Compare commits

...
92 Commits
Author SHA1 Message Date
DeFiDude 14241a3839 Release 1.4.0 2026-11-08 11:52:10 -07:00
DeFiDude 302626c38a api: RNodeStream is an opaque struct; approve the removal and refresh the baseline 2026-11-07 21:21:56 -07:00
DeFiDude ac9ea27752 Replace invalid AGPL license with Reticulum License
This repository is a port of Reticulum, which is licensed under the Reticulum
License. The AGPL-3.0-or-later grant previously in LICENSE was never
effective, because there was no right to place the derived code under AGPL
terms. The Reticulum License now in LICENSE governs every revision in this
repository's history, not only revisions from this commit forward. Additions
and modifications by Ratspeak LLC remain its copyright and are licensed under
the same terms.
2026-11-07 20:49:18 -07:00
DeFiDude 4bf5679bd5 rnode: rewrite the TCP transport behind a shared link trait 2026-11-07 19:25:36 -07:00
DeFiDude 6ce6aa8dba rnode: initialize Android USB serial adapters 2026-11-05 20:06:40 -07:00
DeFiDude fdedbd2c8b docs: escape the rnid metadata file placeholder 2026-11-05 11:08:46 -07:00
DeFiDude 7071bae90e runtime: let an idle link manager sleep until it has work 2026-11-05 02:43:54 -07:00
DeFiDude b217cb3f59 docs: format command help 2026-11-02 11:42:21 -07:00
DeFiDude dc50ce5390 docs: refresh guides and reference help 2026-11-02 11:13:50 -07:00
DeFiDude 5b38cae702 api: record the RNode attempt-failure snapshot 2026-10-31 13:45:25 -06:00
DeFiDude 5a448fdebf rnode: name why a BLE attempt failed and signal a radio that never answers 2026-10-31 12:10:00 -06:00
DeFiDude bf7d16fc36 tests: keep child-spawning tests apart from lock and FIFO tests 2026-10-25 23:14:14 -06:00
DeFiDude 48adcf726e discovery: never announce Backbone clients and read only reachable_on 2026-10-25 21:49:07 -06:00
DeFiDude f1caa4571d docs: record the TCP client's i2p_tunneled option 2026-10-25 21:44:34 -06:00
DeFiDude 30e433a9cb runtime: read AutoInterface devices and I2P peers exactly as Python lists them 2026-10-25 21:11:23 -06:00
DeFiDude b56a427c4a docs: call the RPC key an admin credential 2026-10-25 21:05:17 -06:00
DeFiDude 0267f42001 rnstatus: show the network an auto-connected interface came from 2026-10-25 21:03:24 -06:00
DeFiDude 5ac4820b32 management: answer the status profiling flag as Python does 2026-10-25 20:53:59 -06:00
DeFiDude c3b3fd1c1f interfaces: wait for the real reconnect in local socket tests 2026-10-25 20:49:42 -06:00
DeFiDude 55072d1ca2 discovery: require an explicit reachable address 2026-10-25 19:38:38 -06:00
DeFiDude 06597b5869 tcp: honor I2P-tunneled client socket timeouts 2026-10-25 19:34:27 -06:00
DeFiDude 442196c71a runtime: read AutoInterface device lists from parsed config 2026-10-25 18:46:54 -06:00
DeFiDude 45b49db0c1 i2p: accept SAM reply lines up to Python's 64 KiB limit 2026-10-25 12:41:57 -06:00
DeFiDude 21100300fc i2p: keep the session's private key out of freed memory and debug output 2026-10-25 12:00:48 -06:00
DeFiDude 6aa1d4bbf1 transport: keep each IFAC key in one wiped allocation shared by its interface records 2026-10-25 11:50:58 -06:00
DeFiDude 3311c0a7b1 runtime: wipe the IFAC passphrase in interface options and keep it out of debug output 2026-10-25 11:39:52 -06:00
DeFiDude 6bdc82af93 identity: encode ratchet files into a pre-sized buffer and correct key-file notes 2026-10-25 11:23:44 -06:00
DeFiDude 215250d2b2 tests: control the residue harness and check secrets drop inside each check 2026-10-25 11:18:06 -06:00
DeFiDude 881f7b926d identity: test raw keys that begin like the older envelope format 2026-10-25 11:12:09 -06:00
DeFiDude d1c6d508c9 persistence: retry file readbacks that a signal interrupts 2026-10-25 11:09:40 -06:00
DeFiDude 5366b1d3d3 identity: decode legacy key files without leaving key copies in freed memory 2026-10-25 11:00:38 -06:00
DeFiDude 588fdfc123 ratkey: wipe security key responses that carry an ECDH shared secret 2026-10-25 10:34:56 -06:00
DeFiDude a551770f63 crypto: wipe HKDF output, including IFAC masks, when it is dropped 2026-10-25 10:34:56 -06:00
DeFiDude 416f1ae86c crypto: wipe AES key schedules and CBC state when ciphers are dropped 2026-10-25 10:09:58 -06:00
DeFiDude ad10380bbb crypto: keep plaintext, derived keys and key files out of freed memory 2026-10-25 09:34:02 -06:00
DeFiDude 708b37b017 persistence: verify writes through a wiped buffer and test real write failures 2026-10-25 09:33:48 -06:00
DeFiDude 6d2619cc48 docs: add operator notes for remote management on the transport identity 2026-10-25 07:14:41 -06:00
DeFiDude 8c841a92f1 docs: correct the Python release that gates auto-connect 2026-10-25 07:14:39 -06:00
DeFiDude 56b6bcefa5 docs: reword two discovery comments 2026-10-25 07:14:38 -06:00
DeFiDude efbc495e84 api: make discovery rejection reasons non-exhaustive 2026-10-25 07:14:26 -06:00
DeFiDude 2992377739 tests: check that a wire announce without valid IFAC is never held 2026-10-25 07:13:41 -06:00
DeFiDude 692260e79b status: name the network an auto-connected interface came from 2026-10-25 07:11:57 -06:00
DeFiDude 48e355a943 discovery: never auto-connect to onion or local addresses, or to an endpoint already in use 2026-10-25 07:09:37 -06:00
DeFiDude cd091604d2 management: refuse Resources on remote management Links, as Python does 2026-10-25 07:07:50 -06:00
DeFiDude 08d246ed22 management: filter remote path tables as Python compares destinations and hop limits 2026-10-25 07:07:16 -06:00
DeFiDude 04f9324cd5 transport: count dropped realtime Link packets in the interface's dropped bytes 2026-10-25 07:06:50 -06:00
DeFiDude e16c8b4d39 transport: count a path request only once its tag passes the duplicate check 2026-10-25 07:06:33 -06:00
DeFiDude 4683cb2c2a link: add a clock that keeps counting while the system is suspended 2026-10-25 06:35:18 -06:00
DeFiDude 379312e305 docs: describe I2P discovery generically 2026-10-25 06:24:04 -06:00
DeFiDude b79bcdb38b i2p: keep the server's key in Python's key file, and announce a new address on the interval 2026-10-25 06:23:59 -06:00
DeFiDude 4c6217597a i2p: give configured peers the global ingress settings, as Python does 2026-10-25 06:23:40 -06:00
DeFiDude cb929d5f65 i2p: never tear down a bootstrap-only I2P interface, as Python never detaches one 2026-10-25 06:21:47 -06:00
DeFiDude ef551de12b tests: time out the first connect in the backlog tests, so a slow refusal still fails first 2026-10-25 06:20:05 -06:00
DeFiDude 09ae5d6e26 transport: remember the identity of every validated announce before deciding its path 2026-10-25 06:04:12 -06:00
DeFiDude 9d7b2bd429 api: expose synthesis verification and the client drivers' Python names 2026-10-25 03:40:37 -06:00
DeFiDude f3f72ead60 i2p: announce one discoverable interface at its own b32 and keep peers at Python's defaults 2026-10-25 03:34:53 -06:00
DeFiDude 53515b3d41 docs: note that an I2P interface runs its server only when connectable 2026-10-25 03:21:41 -06:00
DeFiDude 846833a197 docs: describe the hub restart change generically 2026-10-25 03:21:08 -06:00
DeFiDude c44744ecee tests: give tunnel test names, paths and aspects neutral prefixes 2026-10-25 03:20:57 -06:00
DeFiDude 4ea028eb75 tests: run the Unix shared-instance tunnel tests only on Unix 2026-10-25 03:19:47 -06:00
DeFiDude fbbc311192 tunnel: expire handled tunnels after TUNNEL_TIMEOUT as Python does 2026-10-25 03:18:33 -06:00
DeFiDude 1801cf291a local: drop traffic queued while the shared instance was unreachable 2026-10-25 03:11:40 -06:00
DeFiDude 264b00eb3d interfaces: drop traffic queued while a client's connection attempts fail 2026-10-25 03:07:38 -06:00
DeFiDude 2e8fa290dc discovery: announce KISS TCP clients and unset radio parameters as Python does 2026-10-25 03:00:21 -06:00
DeFiDude feb11b0089 discovery: name rsRNS and auto-connect only to the stacks Python 1.5 trusts 2026-10-25 02:51:31 -06:00
DeFiDude 1371918851 transport: process released and replayed announces without re-checking IFAC or recounting bytes 2026-10-25 02:51:05 -06:00
DeFiDude 65d95eed33 status: give Python 1.5 rnstatus and rnpath full interface stats, locally and remotely 2026-10-25 02:50:33 -06:00
DeFiDude 6e412dc9e0 interfaces: open every TCP, Backbone and I2P client connection with a tunnel synthesis 2026-10-24 23:29:20 -06:00
DeFiDude b774544cbb transport: drop multi-hop PLAIN and GROUP packets as Python's packet filter does 2026-10-24 23:10:14 -06:00
DeFiDude af65181e49 transport: accept valid tunnel syntheses and bind tunnels as in Python 2026-10-24 23:06:26 -06:00
DeFiDude acd59b178e transport: never rebind saved paths to accepted clients and load tunnels unbound 2026-10-24 23:00:56 -06:00
DeFiDude 52ab6c02d7 transport: stop sharing interface id 0 and run every configured I2P peer 2026-10-24 22:52:07 -06:00
DeFiDude f9d848866e transport: give interface stat entries a default 2026-10-24 19:02:11 -06:00
DeFiDude 562bc99da7 android-usb: read one max-size packet per bulk transfer 2026-10-22 23:09:12 -06:00
DeFiDude d738238b4e tests: retry the listener signal check when startup was interrupted 2026-10-21 17:33:39 -06:00
DeFiDude e5e8401fc7 link: count the responder's LRPROOF as Link outbound, as in Python 2026-10-21 17:33:39 -06:00
DeFiDude d047641898 link: accept peer identification before the RTT packet, as in Python 2026-10-21 16:08:08 -06:00
DeFiDude 76cfd48b29 tests: skip long backdated timeouts on freshly booted Windows clocks 2026-10-20 23:30:56 -06:00
DeFiDude 42b53c5538 persistence: accept every filesystem and warn on network or RAM storage 2026-10-20 20:27:10 -06:00
DeFiDude 5468316087 ci: pin Rust 1.96.0 instead of floating stable 2026-10-20 20:08:40 -06:00
DeFiDude c4788883f3 api: record RNode rejection, IFAC status and interface enable additions 2026-10-20 18:50:36 -06:00
DeFiDude 8b046794f1 docs: note pending radio and status changes 2026-10-20 17:17:30 -06:00
DeFiDude 85f29bcfd3 config: start an interface only when it is enabled, as upstream 2026-10-20 17:16:28 -06:00
DeFiDude 465ec096a5 status: report IFAC like upstream, only for interfaces that have it 2026-10-20 16:33:12 -06:00
DeFiDude b6f9e788b2 rnode: confirm effective settings on every transport and retry unopenable ports 2026-10-20 15:17:08 -06:00
DeFiDude 1a835f0acc ble: hold native RNode startup until the Android bridge attaches 2026-10-20 12:46:18 -06:00
DeFiDude 506852837c ble: validate effective RNode settings and stop on definitive rejection 2026-10-20 10:27:03 -06:00
DeFiDude 8fcf0b678a ratchet: require prepared namespaces for durable received keys 2026-10-13 17:41:23 -06:00
DeFiDude 817a640ed1 runtime: defer bounded request work with exact endpoint ownership 2026-10-13 00:30:19 -06:00
DeFiDude 4bba059d93 persistence: qualify native Android locking and CI boundaries 2026-10-13 00:07:28 -06:00
DeFiDude 7a33f4297f protocol: enforce capacity, ownership and durable admission boundaries 2026-10-12 23:57:46 -06:00
DeFiDude df94572ff6 tests: retain RNode and cache-miss regression coverage 2026-10-12 23:57:45 -06:00
237 changed files with 27006 additions and 6108 deletions

No files matched your search

+2 -2
View File
@@ -50,7 +50,7 @@ jobs:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: stable
toolchain: 1.96.0
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
cache-bin: false
@@ -74,7 +74,7 @@ jobs:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: stable
toolchain: 1.96.0
components: clippy, rustfmt
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
+50
View File
@@ -2,6 +2,56 @@
## Unreleased
## 1.4.0 - 2026-11-08
- RNode drivers confirm the settings the radio applies once it is on, on every transport, and stop with the rejected setting named (for example TX power below an amplifier's minimum) instead of transmitting at other settings or retrying forever.
- Serial and TCP RNodes keep retrying a port that is missing, busy or not permitted every 5 seconds, as in Python Reticulum, and report which.
- Android Bluetooth RNode sessions wait for the bridge before starting, so a slow reconnect no longer drops a healthy link.
- Interface status reports IFAC like Python Reticulum: `rnstatus-rs` shows the network name and access line only for interfaces that use IFAC.
- Interfaces start only when `enabled` or `interface_enabled` is yes, as in Python Reticulum. A section with neither key is now skipped with a warning instead of starting, so add `enabled = yes` to it. An RNodeMulti subinterface with its own flag follows that flag, so a subinterface set to no never transmits.
- Durable storage works on any filesystem again, as in Python Reticulum, including ZFS, Docker overlays, external drives and network shares. A flush the filesystem lacks is skipped and logged once, and network or RAM-backed storage logs a warning instead of refusing to start.
- A Link accepts the peer's identification as soon as its handshake completes, as in Python Reticulum, so a request a Python client sends right after identifying no longer fails for lack of an identity. Only the receiving side of a Link accepts identification.
- The receiving side of a Link counts its Link proof as sent traffic, as in Python Reticulum, so it no longer answers keepalives before the Link is established and its traffic totals include the proof.
- A connectable I2P interface now starts alongside a Unix-socket shared instance or another connectable I2P interface, and an I2P interface runs one connection for every configured peer, plus its server when connectable, as in Python Reticulum.
- Hub restarts restore saved paths and tunnels as in Python Reticulum.
- Transport hubs now accept tunnel synthesis, so a Python client that reconnects gets its paths back without announcing again, and losing a tunnel's interface no longer drops paths the hub learned through other interfaces, as in Python Reticulum.
- PLAIN and GROUP packets that arrive from more than one hop away, and announces typed PLAIN or GROUP, are dropped before deduplication, as in Python Reticulum.
- TCP, Backbone and I2P client interfaces open every connection with a tunnel synthesis, so a transport hub restores their paths after a reconnect, and traffic queued while a connection was down or failing to open is dropped when it opens, as in Python Reticulum.
- A client of a Unix-socket shared instance drops traffic queued while the instance was unreachable, as in Python Reticulum.
- I2P interfaces announce their own address for discovery, and the peers listed in `peers` keep Python's defaults, sharing only the interface's IFAC, as in Python Reticulum.
- A bootstrap-only I2P interface keeps running once discovered interfaces connect, as in Python Reticulum, which never detaches an I2P interface.
- A connectable I2P interface keeps its I2P address across restarts. Its key is stored in Python Reticulum's key file under `storage/i2p`, readable by its owner only; as in Python Reticulum, a node without `enable_transport` or `static_transport_identity` gets a new address each start.
- Every validated announce refreshes the identity remembered for its destination, including path responses and replays that leave the path unchanged, so a destination's identity stays recallable as in Python Reticulum.
- Python Reticulum 1.5 `rnstatus` and `rnpath` work against `rnsd-rs`, locally and with `-R`: interface stats carry every field they read, including announce and path request counts, violation counters and the transport instance, and remote management answers on the transport identity, as in Python Reticulum.
- `rnstatus-rs -R` and `rnpath-rs -R` take the remote node's transport identity hash, which `rnstatus` shows as the transport instance on a transport node. A node with `enable_transport` off and no `static_transport_identity` gets a new management destination each start, as in Python Reticulum; set `static_transport_identity = yes` on a leaf you manage remotely. `storage/remote_management_identity` is no longer used and can be deleted.
- Announces held during an ingress burst on an IFAC interface are processed when released instead of being dropped, and released or replayed announces no longer count as received traffic again, as in Python Reticulum.
- Interface discovery announces name this stack, `rsRNS`, and its version. `rnsd-rs` auto-connects only to Backbone interfaces announced by Python Reticulum 1.5.2 or later, or to any announced Backbone interface with `autoconnect_unverified_implementations`, and no longer stores or lists discovered TCP client interfaces, as in Python Reticulum.
- Discovery announces a KISS-framed TCP client as a KISS interface and sends and reads unset radio parameters as nil, so Python and `rnsd-rs` read each other's KISS, Weave and RNode announces, as in Python Reticulum.
- `rns_link::clock::ContinuousInstant` reads a monotonic clock that keeps counting while the system is suspended, for deadlines that must hold in real time across a sleep.
- An interface counts a path request in its stats only once its tag passes the duplicate check, as in Python Reticulum 1.5.
- A realtime Link packet dropped at a full transmit queue counts toward the interface's dropped bytes.
- `rnpath -R` filters the remote path and rate tables as Python Reticulum compares them: a destination hash of another length matches nothing, and the hop limit compares as a number instead of wrapping above 255.
- Remote management Links refuse Resources other than requests and responses, as Python Reticulum's do.
- `rnsd-rs` never auto-connects a discovered interface at an onion address, at 127.0.0.1 or 0.0.0.0, or at a host and port that an interface already connects to, as in Python Reticulum.
- Interface stats name the network an auto-connected interface was discovered through (`autoconnect_source`), as in Python Reticulum.
- Decryption, key derivation and identity and ratchet file handling wipe temporary sensitive buffers, and decryption avoids an extra plaintext copy. Returned plaintext remains caller-owned and must be wrapped in `Zeroizing` when it needs wiping on drop. Identity files larger than 1 KiB are refused.
- A 64-byte identity file always loads as a raw key, as in Python Reticulum. About one key in 29,000 began with bytes that were misread as the older envelope format, and its identity failed to load.
- Writing, verifying and recovering state files retries a read that a signal interrupts instead of failing.
- Interface options wipe their IFAC passphrase when dropped, and the debug output of IFAC settings no longer shows it.
- Each interface's IFAC key lives in one allocation that is wiped when dropped, so interface tables no longer leave copies of it in freed memory.
- I2P interfaces no longer leave their private key in freed memory when they read it, store it or exchange it with the SAM bridge. They refuse a key file larger than 16 KiB and, as Python Reticulum's SAM client does, a SAM reply line longer than 64 KiB.
- Remote management answers the profiling flag of `rnstatus -R -z` with empty results, and leaves a status request that is not a list of flags unanswered, as Python Reticulum does.
- `rnstatus-rs` shows the network an auto-connected interface was discovered through on a `Source` line under its name, as Python's `rnstatus` does, and its JSON output carries it as `autoconnect_source`.
- AutoInterface's `devices` and `ignored_devices` take effect, and they and I2P `peers` are read as Python Reticulum reads lists: a quoted name that contains a comma stays one name, and `devices = ,` allows every interface.
- TCP client interfaces read `i2p_tunneled`, as Python Reticulum does, and give a connection tunneled over I2P its longer I2P socket timeouts.
- TCP server and Backbone interfaces are announced for discovery only with `reachable_on` set, and Backbone clients never, as in Python Reticulum. A discoverable server without `reachable_on` logs a warning and is not announced, so set `reachable_on` to keep announcing it. The `discovery_reachable_on` key is no longer read.
- Corrected packet-size limits across interfaces and Links, including IFAC overhead, and reject unsupported Link setups before sending them.
- Added application-controlled acknowledgements so propagation nodes can confirm a message only after safely storing it.
- Prevent stale interface or Link callbacks from acknowledging a different connection after reconnect or cancellation.
- Reject malformed Resource metadata and invalid timeout values without panics or excessive allocation.
- Added checked durable file operations for identities, ratchets, and application storage, with explicit recovery after interrupted writes.
- Updated public interface, Link, and storage APIs. Use the `~1.4.0` compatibility line for these source-breaking APIs.
## 1.3.0 - 2026-10-12
### Added
Generated
+17 -10
View File
@@ -11,6 +11,7 @@ dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"zeroize",
]
[[package]]
@@ -328,6 +329,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
@@ -1624,7 +1626,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"aes",
"cbc",
@@ -1645,9 +1647,10 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"proptest",
"rand 0.8.5",
"rmp-serde",
@@ -1656,6 +1659,7 @@ dependencies = [
"rns-wire",
"serde",
"serde_bytes",
"sha2",
"thiserror 2.0.21",
"tracing",
"windows-sys 0.61.2",
@@ -1664,7 +1668,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bluer",
"btleplug",
@@ -1697,9 +1701,10 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"proptest",
"rand 0.8.5",
"rmpv",
@@ -1708,12 +1713,13 @@ dependencies = [
"rns-wire",
"thiserror 2.0.21",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bzip2",
"hex",
@@ -1723,6 +1729,7 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"serde",
"thiserror 2.0.21",
"tokio",
"tracing",
@@ -1730,7 +1737,7 @@ dependencies = [
[[package]]
name = "rns-ratkey"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"aes",
"bip39",
@@ -1756,7 +1763,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1783,7 +1790,7 @@ dependencies = [
[[package]]
name = "rns-tools"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"base64",
"bytes",
@@ -1810,7 +1817,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1830,7 +1837,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"proptest",
"rns-crypto",
+13 -13
View File
@@ -14,18 +14,18 @@ members = [
]
[workspace.package]
version = "1.3.0"
version = "1.4.0"
edition = "2024"
license = "AGPL-3.0-or-later"
license-file = "LICENSE"
rust-version = "1.89"
[workspace.dependencies]
# Crypto
x25519-dalek = { version = "2", features = ["static_secrets"] }
ed25519-dalek = { version = "2", features = ["hazmat", "rand_core"] }
aes = "0.8"
aes = { version = "0.8", features = ["zeroize"] }
des = "0.8"
cbc = { version = "0.1", features = ["alloc"] }
cbc = { version = "0.1", features = ["alloc", "zeroize"] }
hkdf = "0.12"
hmac = "0.12"
md-5 = "0.10"
@@ -80,12 +80,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
proptest = "1"
# Workspace crates
rns-crypto = { path = "crates/rns-crypto", version = "~1.3.0", default-features = false }
rns-wire = { path = "crates/rns-wire", version = "~1.3.0", default-features = false }
rns-identity = { path = "crates/rns-identity", version = "~1.3.0" }
rns-transport = { path = "crates/rns-transport", version = "~1.3.0" }
rns-link = { path = "crates/rns-link", version = "~1.3.0" }
rns-protocol = { path = "crates/rns-protocol", version = "~1.3.0" }
rns-interface = { path = "crates/rns-interface", version = "~1.3.0" }
rns-runtime = { path = "crates/rns-runtime", version = "~1.3.0" }
rns-ratkey = { path = "crates/rns-ratkey", version = "~1.3.0" }
rns-crypto = { path = "crates/rns-crypto", version = "~1.4.0", default-features = false }
rns-wire = { path = "crates/rns-wire", version = "~1.4.0", default-features = false }
rns-identity = { path = "crates/rns-identity", version = "~1.4.0" }
rns-transport = { path = "crates/rns-transport", version = "~1.4.0" }
rns-link = { path = "crates/rns-link", version = "~1.4.0" }
rns-protocol = { path = "crates/rns-protocol", version = "~1.4.0" }
rns-interface = { path = "crates/rns-interface", version = "~1.4.0" }
rns-runtime = { path = "crates/rns-runtime", version = "~1.4.0" }
rns-ratkey = { path = "crates/rns-ratkey", version = "~1.4.0" }
+26 -653
View File
@@ -1,661 +1,34 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Reticulum License
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Derived from the reference implementation at
https://github.com/markqvist/Reticulum
Preamble
Copyright (c) 2016-2026 Mark Qvist, unless otherwise noted
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
Additions and modifications Copyright (c) 2026 Ratspeak LLC
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
- The Software shall not be used in any kind of system which includes amongst
its functions the ability to purposefully do harm to human beings.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
- The Software shall not be used, directly or indirectly, in the creation of
an artificial intelligence, machine learning or language model training
dataset, including but not limited to any use that contributes to the
training or development of such a model or algorithm.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+85 -44
View File
@@ -5,10 +5,10 @@
**A Rust implementation of Reticulum.**
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![License: Reticulum License](https://img.shields.io/badge/license-Reticulum%20License-blue.svg)](LICENSE)
[![Rust 1.89+](https://img.shields.io/badge/rust-1.89%2B-orange.svg)](https://www.rust-lang.org)
[![Release baseline: Reticulum 1.4.2](https://img.shields.io/badge/release%20baseline-Reticulum%201.4.2-success.svg)](https://reticulum.network/)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#compatibility-notes)
[Reticulum Manual](https://reticulum.network/manual/) |
[Ratspeak](https://github.com/ratspeak/Ratspeak) |
@@ -19,9 +19,12 @@
---
rsReticulum is a Rust implementation of Reticulum. This is not a fork of
Reticulum; it is Reticulum written in a different language, focused on staying
interoperable. It is not the source-of-truth implementation, do not treat it as one.
rsReticulum is a Rust port of
[Reticulum](https://github.com/markqvist/Reticulum), the reference
implementation by Mark Qvist. It was written from the reference source, not from
a specification, and tracks the reference's wire behavior release by release.
The Python reference implementation remains the source of truth. See
[License](#license).
Commands are intentionally namespaced for Rust with `*-rs` command names, so
rsReticulum can live beside other Reticulum tools on `PATH` without worry.
@@ -39,6 +42,18 @@ rsReticulum can live beside other Reticulum tools on `PATH` without worry.
## Build It
This guide describes the 1.4.0 release, [v1.4.0](https://github.com/ratspeak/rsReticulum/releases/tag/v1.4.0), the source line Ratspeak builds from. For the 1.3.0 tools, use [the v1.3.0 README](https://github.com/ratspeak/rsReticulum/blob/v1.3.0/README.md) and that build's `--help`.
From a new working directory:
```bash
git clone https://github.com/ratspeak/rsReticulum.git
git -C rsReticulum checkout --detach 5b38cae702a5b3984adf12a435f6d3012fcf90e1
cd rsReticulum
```
Run the build commands below from that directory. The host crates require Rust 1.89 or newer.
### macOS
Install Rust with `rustup`, then install Apple's command-line build tools:
@@ -50,13 +65,12 @@ xcode-select --install
Build the tools:
```bash
cd rsReticulum
cargo build --release --locked
```
### Linux, Raspberry Pi, and VPS Hosts
##### Install Rust with `rustup`, then install the needed packages:
Install Rust with `rustup`, then install the build packages:
Debian, Ubuntu, and Raspberry Pi OS:
@@ -77,10 +91,9 @@ Arch:
sudo pacman -S --needed base-devel pkgconf
```
##### Build the tools:
Build the tools:
```bash
cd rsReticulum
cargo build --release --locked
```
@@ -92,7 +105,6 @@ Build Tools, install the "Desktop development with C++" workload.
Build from PowerShell:
```powershell
cd rsReticulum
cargo build --release --locked
```
@@ -111,14 +123,14 @@ The `rns-tools` crate builds Rust-namespaced Reticulum utilities:
| rnid-rs | Identity generation, inspection, public/private import/export, hashing, signing, verification, encryption, and decryption. |
| rnprobe-rs | Destination probe utility with loss and round-trip reporting. |
| rncp-rs | File transfer utility with send, listen, and authenticated fetch modes. |
| rnodeconf-rs | RNode inspection, safe configuration, EEPROM backup, and trust utility. |
| rnodeconf-rs | RNode inspection, EEPROM backup, and saved TNC/normal startup configuration. |
| rnsh-rs | Reticulum shell listener/client. |
#### Commands:
Common command forms (use each binary’s `--help` for the complete option list):
```text
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]
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|arxc|atxc|prx|ptx|prxc|ptxc|held|pvs|ivs|flt|txdrp|txdrb]
[--reverse] [--announce-stats] [--link-stats] [--totals] [--json]
[-d|--discovered] [-D] [-m [-I SECONDS]] [FILTER]
[-R <transport_hash> -i <identity_file>]
@@ -132,9 +144,9 @@ 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]
rnodeconf-rs [-i] [--config] [--eeprom-backup|--eeprom-dump] [--version] [PORT]
rnodeconf-rs -T --freq HZ --bw HZ --txp DBM --sf SF --cr CR PORT
rnodeconf-rs -N 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...]
```
@@ -142,14 +154,20 @@ rnsh-rs [-i FILE] [-s NAME] [-N] [-m] [-w SECONDS] <destination_hash> [-- CM
Add the release `bin/` directory or `target/release` to `PATH` if
you want to call them without a path prefix.
`rncp-rs` follows the established listener authentication model: without `-n`,
incoming senders must match `-a <hash>` or an `allowed_identities` file.
`rncp-rs -F` can serve fetch requests to authenticated clients; use
`-j <jail>` to bound file access unless unrestricted fetch paths are
intentional.
`rncp-rs` has a listener authorization limitation in 1.4.0 and 1.3.0: `-a <hash>` and `allowed_identities` are checked when a
peer identifies, but identification is not required before receiving a pushed
file. Do not rely on the allowlist to exclude unidentified senders.
`rnodeconf-rs` in the current build only covers safe inspection/device setting paths, EEPROM
dump/backup, and trusted-key storage.
Without `-n`, fetch requests require an identified peer on the allowlist.
`rncp-rs -F` enables fetch service and leaves push reception enabled. Use
`-j <jail>` to constrain fetched paths to a directory under trusted local
control; it is not an operating-system sandbox.
`rnodeconf-rs` in 1.4.0 and 1.3.0 supports inspection,
EEPROM dump/backup, and saving TNC/normal startup settings. `-T` requires all five
RF values shown above. Firmware installation, signing/trust enrollment and
Bluetooth, Wi-Fi, display and interference-avoidance changes are disabled.
Their options remain in the parser but return an error.
`rnid-rs` tracks the Reticulum 1.4.2 identity utility surface for normal
software identities: public/private import and export, destination hashing,
@@ -157,10 +175,11 @@ software identities: public/private import and export, destination hashing,
hardware-backed `rnid-rs hw` path is a Rust extension behind the `hardware`
feature and should still be treated as experimental.
Common `rnid-rs` flows:
Common `rnid-rs` flows for a POSIX shell. Replace uppercase placeholders with your values. Private exports and imported private data grant control of the identity; keep them out of shared terminals, logs and shell history.
```bash
# Generate and inspect an identity.
mkdir -p ~/.rsReticulum/identities
rnid-rs -g ~/.rsReticulum/identities/mgmt
rnid-rs -i ~/.rsReticulum/identities/mgmt -p
rnid-rs -i ~/.rsReticulum/identities/mgmt -H lxmf.delivery
@@ -172,13 +191,13 @@ rnid-rs -i ~/.rsReticulum/identities/mgmt -X -B
# Write identity files. Without -X, -w writes a public .pub file.
rnid-rs -i ~/.rsReticulum/identities/mgmt -w mgmt.pub
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
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.4.2-compatible .rsg envelopes.
rnid-rs -i ~/.rsReticulum/identities/mgmt -s message.txt
rnid-rs -V message.txt.rsg
rnid-rs -i <signer_hash> -N -V message.txt.rsg
rnid-rs -i "SIGNER_IDENTITY_HASH" -N -V message.txt.rsg
# Encrypt to a public identity, decrypt with the matching private identity.
rnid-rs -i mgmt.pub -e message.txt
@@ -199,13 +218,15 @@ directory is supplied, the default is:
| Linux/macOS | `/etc/rsReticulum/config`, then `~/.config/rsReticulum/config`, then `~/.rsReticulum/config` |
| Windows | `%APPDATA%\rsReticulum\config` |
Generate the annotated starter file:
On Linux/macOS, the first two locations are selected only when their `config` file exists; otherwise the home-directory fallback is used.
Print the annotated starter configuration to standard output:
```bash
rnsd-rs --exampleconfig
```
Minimal TCP client example:
Minimal TCP client example. Replace `reticulum.example.org` and the port with the endpoint supplied by your network operator:
```ini
[reticulum]
@@ -218,17 +239,15 @@ enable_transport = no
[[Default TCP]]
type = TCPClientInterface
enabled = yes
target_host = rns.ratspeak.org
target_host = reticulum.example.org
target_port = 4242
```
Existing Python Reticulum configs should work if every requested interface
is implemented here. Unknown or not-yet-wired interfaces should be removed or
disabled until support lands.
Review an imported Python or older Rust config before starting it. Each interface needs a supported type and an explicit `enabled = yes` or `interface_enabled = yes`. For an explicit IFAC size, use `ifac_size_unit = bits` with `ifac_size`, or the separate `ifac_size_bytes` key. Unmarked values from 1 to 64 are rejected as ambiguous; larger valid values are interpreted as bits. See the [configuration migration](api/migrations/capacity-and-receipts.md#explicit-ifac-units). The published 1.3.0 tools use the older byte convention. Keep unsupported interfaces disabled.
The default shared-instance data/control ports are `37428`/`37429`. Ratspeak
uses app-private `37430`/`37431` ports. If you run two daemons at the same
time, give one config a distinct port pair to avoid confliction, like:
time, give one config a distinct port pair to avoid a port conflict:
```ini
[reticulum]
@@ -236,15 +255,21 @@ shared_instance_port = 37432
instance_control_port = 37433
```
Programs use the control port with the instance's RPC key: `rpc_key` under
`[reticulum]` when it is set, otherwise a key derived from the transport
identity. That key is an admin credential: a program that has it can read the
daemon's network state, drop its paths and block identities, so treat it like
a password and give it only to programs you trust.
## Interface Support
###### Note: This is alpha, if something doesn't work, open an issue with enough context/information to help contribute to fixing it.
This stack is experimental. Include the source revision or binary version, platform, interface type and relevant logs when reporting a problem.
| Interface | Current behavior |
| --- | --- |
| TCP client/server | Config-backed IPv4 and IPv6 paths. |
| UDP | Config-backed unicast and multicast paths. |
| Auto | Config-backed UDP discovery plus TCP fallback. |
| UDP | Unicast and IPv4 broadcast datagrams; this driver does not join multicast groups. |
| Auto | IPv6 multicast discovery with unicast UDP data on the local network. |
| Local shared instance | Config-backed TCP loopback or Unix socket depending on platform. |
| I2P | Config-backed SAM v3.1 path. |
| Pipe | Config-backed subprocess stdio pipe. |
@@ -267,8 +292,8 @@ different path or interface; loss of the selected interface closes that Link.
Reliable Link control uses a bounded ordered queue, while realtime media has a
separate bounded best-effort path that cannot overtake retained control
traffic. Initiator packet proofs use the temporary signing key advertised in
the Link Request, and responder packet proofs use the accepting destination
traffic. A proof sent by the initiator uses its temporary signing key from
the Link Request; a proof sent by the responder uses the accepting destination
identity.
## Compatibility Notes
@@ -277,15 +302,17 @@ 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 release baseline is Reticulum 1.4.2. The complete byte-exact corpus,
The release baseline for 1.3.0 and 1.4.0 is Python Reticulum 1.4.2. The complete byte-exact corpus,
utility vectors, source-truth oracles, and live Python interoperability matrix
are pinned to its exact source commit. Historical 1.3.8 audits and fixtures
retain their original provenance as backward-compatibility evidence. RNS 1.5.0
is intentionally deferred and is not a current support claim.
was not part of that complete release gate. The current source includes
selected later Python compatibility changes; those do not establish complete
parity with a later Python release.
Known gaps and intentional limits:
- `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented. There is on-going work in progress for supporting these.
- `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented.
- `rnodeconf-rs` is partial; safe inspection/configuration and EEPROM
dump/backup are furthest along. Firmware flashing, autoinstall/update, ROM
bootstrap, destructive EEPROM wipe, and full signing-key management are not
@@ -295,8 +322,14 @@ Known gaps and intentional limits:
- `rnpath-rs` remote mode is read-only for table/rates, including destination
filters, apart from the remote blackhole-list query path. Remote mutations
and remote active path requests are full gaps.
- Interface discovery announces name this stack `rsRNS` and its version. Python
Reticulum 1.5.5 and later auto-connects only to Backbone interfaces
announced by Python Reticulum 1.5.2 or later, so a Python node auto-connects
to an `rsRNS` interface only with `autoconnect_unverified_implementations =
yes` in its `[reticulum]` section. `rnsd-rs` follows the same rule, and the
same option lets it auto-connect to any announced Backbone interface.
- `rncp-rs` implements the listener `-b` announce interval. `-P/--phy-rates`
is not supported for the time being.
is not supported.
- `rns-ratkey` hardware identity support is feature-gated and still has known
hardware-verification gaps before it should be described as release-ready.
@@ -309,4 +342,12 @@ PRs are closed for now until I have time to catch up on everything. I'm tired.
## License
GNU Affero General Public License v3.0 or later. See [LICENSE](LICENSE).
rsReticulum is licensed under the [Reticulum License](LICENSE), the license of
the reference implementation it is ported from. Copyright (c) 2016-2026 Mark
Qvist, unless otherwise noted; additions and modifications Copyright (c) 2026
Ratspeak LLC.
The license is permissive with two conditions: no use in systems built to
purposefully harm people, and no use in or contribution to AI or language-model
training. The copyright and permission notice must stay in every copy.
[LICENSE](LICENSE) is the binding text.
+6
View File
@@ -1,5 +1,9 @@
# Rust API
This guide describes the 1.4.0 API, published as v1.4.0. For the 1.3.0
tools and libraries, use the documentation at that tag. The [1.4 migration
guide](migrations/1.4.md) covers source and configuration changes.
Application code should begin with `rns_runtime::prelude`. It collects the
runtime handle and the commonly used identity, destination, packet, Link,
request, Channel, Resource, interface, and shutdown types without wrapping or
@@ -69,6 +73,8 @@ endpoint, not the identity of the packet socket. Selecting a trustworthy matchin
pair remains the application's responsibility. These policies do not move
AutoInterface's interoperable UDP ports or alter Reticulum wire formats.
The [capacity, IFAC and receipt migration guide](migrations/capacity-and-receipts.md) describes the current 1.4 source boundary, including custom-driver ownership and application-controlled admission.
## Stability
The 1.3 line changes the six discovery coordinate fields to `Option<f64>` so
+17 -8
View File
@@ -11,6 +11,7 @@ dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"zeroize",
]
[[package]]
@@ -225,6 +226,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
@@ -1170,13 +1172,15 @@ dependencies = [
name = "rns-application-api-fixture"
version = "0.0.0"
dependencies = [
"rns-identity",
"rns-protocol",
"rns-runtime",
"rns-transport",
]
[[package]]
name = "rns-crypto"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"aes",
"cbc",
@@ -1194,9 +1198,10 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"rand",
"rmp-serde",
"rmpv",
@@ -1204,6 +1209,7 @@ dependencies = [
"rns-wire",
"serde",
"serde_bytes",
"sha2",
"thiserror 2.0.20",
"tracing",
"windows-sys 0.61.2",
@@ -1212,7 +1218,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bluer",
"btleplug",
@@ -1245,9 +1251,10 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"rand",
"rmpv",
"rns-crypto",
@@ -1255,12 +1262,13 @@ dependencies = [
"rns-wire",
"thiserror 2.0.20",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bzip2",
"hex",
@@ -1269,6 +1277,7 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"serde",
"thiserror 2.0.20",
"tokio",
"tracing",
@@ -1276,7 +1285,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1303,7 +1312,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1322,7 +1331,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"rns-crypto",
"sha2",
+2
View File
@@ -11,5 +11,7 @@ default = []
all = ["rns-runtime/ble", "rns-runtime/rnode-tcp", "rns-runtime/serial"]
[dependencies]
rns-protocol = { path = "../../crates/rns-protocol" }
rns-identity = { path = "../../crates/rns-identity" }
rns-transport = { path = "../../crates/rns-transport" }
rns-runtime = { path = "../../crates/rns-runtime", default-features = false }
+29 -1
View File
@@ -134,7 +134,7 @@ pub mod shared_ownership {
}
}
/// The 1.4 discovery API distinguishes unknown components from true zeros.
/// The 1.3 discovery API distinguishes unknown components from true zeros.
pub mod nullable_discovery {
use rns_transport::discovery::DiscoveryInterfaceConfig;
use rns_transport::discovery::app_data::DiscoveryInfo;
@@ -163,3 +163,31 @@ pub mod nullable_discovery {
[info.latitude, info.longitude, info.height]
}
}
/// Application admission carries non-cloneable authority separately from bytes.
pub mod application_packet_admission {
use rns_runtime::link_manager::{
InboundLinkPacket, LinkPacketReceiptOutcome, LinkPacketRejection,
};
pub async fn accept(packet: InboundLinkPacket) -> Option<LinkPacketReceiptOutcome> {
let (payload, receipt) = packet.into_parts();
let outcome = receipt?.accept().await.ok();
drop(payload);
outcome
}
pub fn compile_surface() {
let _ = LinkPacketRejection::InvalidPropagationStamp;
let _ = rns_runtime::link_manager::LinkManager::set_ordinary_packet_proof_strategy;
let _ = rns_runtime::interface_factory::InterfacePostInit::try_from_section;
let _ = rns_runtime::config::ifac::parse_ifac_size;
let _ = rns_runtime::config::ifac_lock::ConfigWriteLock::acquire;
let _ = rns_identity::persistence::durable_write;
let _ = rns_identity::persistence::durable_reconcile_hash;
let _ = rns_transport::messages::InterfacePacketCapacity::new(500, 508, false);
let _ = rns_transport::messages::InterfaceTransportSender::new;
let _ = rns_transport::link_messages::dispatch_link_request;
let _ = rns_transport::link_messages::LinkRequestDispatchError::NoInterface;
let _ = rns_transport::ifac::try_ifac_sign;
let _ = rns_protocol::resource_control::check_control_frame;
}
}
+186
View File
@@ -0,0 +1,186 @@
# Migrating to the 1.4 source API
The 1.4 line is published as v1.4.0 and is the source line Ratspeak builds
from. These APIs and migration commands require a 1.4 build.
The 1.4 source line introduces explicit interface-capacity ownership and durable
application admission. Existing published releases are unchanged. Migrate
Reticulum dependents together to ~1.4.0; a source version alone is not publication.
Follow [capacity, IFAC configuration, receipts and timing](capacity-and-receipts.md)
for the full API and configuration transition. In particular:
- Replace `InterfacePostInit::from_section` with fallible `try_from_section`,
and propagate semantic configuration errors before spawning interfaces.
- `LinkManager::set_link_packet_channel` returns a result. The legacy tuple
receiver cannot enable ProveApp; use the bounded typed packet channel and
exact endpoint binding for application-controlled receipts.
- Custom interface handles and entries must supply exact owner and typed packet
capacity facts. Construct their bound sender before producer tasks start.
Link endpoint bindings retain the interface owner captured from the admitted
request/proof, rather than looking up whichever interface currently has an ID.
- Request admission and proof validation are separate. Retain one attempt-owned
result and deadline; cancelled/refused attempts cannot change a replacement.
- `rns_interface::rnode::RNodeStream` is an opaque struct; its `Serial` and `Tcp`
variants are no longer public. Open streams with `open_serial` or
`connect_tcp`; `try_clone`, `description`, and the `Read`/`Write`
implementations are unchanged.
Build `InterfaceStatRpcEntry` with `..Default::default()` and `InterfaceEntry`
with `..InterfaceEntry::new(...)`, so fields added on the 1.4 line stay
source compatible.
`rns_link::mtu_discovery::SignallingData` remains a public re-export of the
shared `rns_wire::link_signalling::SignallingData`; existing imports and checked
handshake callers can continue using that alias. Cargo-public-api renders
canonical type paths from rns-wire, so its twelve moved snapshot lines are
explicitly recorded despite preserved source identity. `new/pack/unpack` remain
low-level representation helpers; use checked signalling APIs for admission.
`rpc::InterfaceStatEntry::ifac_size` is now `Option<usize>`, `None` when the
interface has no IFAC, and the entry gains `ifac_signature` and `ifac_netname`,
as in Python's interface stats. Interface sections start only when
`interface_enabled` or `enabled` is true; add `enabled = yes` to sections that
relied on the old default. `ConfigSection::interface_enabled`, `has_enable_key`
and `invalid_enable_key` expose that rule to embedders.
Strict persistence accepts every filesystem; `DurabilityUnsupported` no longer
reports an unqualified filesystem. `persistence::storage_risk` classifies network
or user-space (`Remote`) and RAM-backed (`Volatile`) storage so applications can
warn their users.
`I2PServerConfig` gains `b32`, which receives the server's b32 address when
SAM creates its session, and `key_path`, the file that keeps the server's
private key, and so its address, across sessions; the runtime sets it to
Python's key file under `storage/i2p`. `i2p::destination_b32` derives the
address from a SAM private key; build the config with `new`.
`discovery::announcer::Announcer::reconfigure` replaces a registered
interface's config but keeps its announce interval.
`TunnelEntry::interface_id` is now `Option<InterfaceId>`, `None` while the
tunnel is unbound, instead of the id-0 sentinel. `spawn_local_server` and
`spawn_i2p_server` take the listener's allocated `InterfaceId`, which their
accepted clients report as `parent_id`. `InterfaceEntry::parent_id` carries it
into transport; set it from `InterfaceHandle::parent_id`. Persisted tunnels now
load unbound into the tunnel table, so `TransportActor::pending_tunnel_entries`
is gone.
`TunnelSynthesisData::unpack` accepts exactly 176 bytes, and `is_signed` is
the check transport applies before admitting one. The TCP, Backbone and I2P
client configs' `python_name` is the Python `str()` their syntheses hash. Announces join the
tunnel named by their interface's latest synthesis, which `handle_tunnel` and
`TunnelTable::insert` record and `TunnelTable::void_interface` clears; writing
`interface_id` directly no longer rebinds an interface. `handle_tunnel` no
longer takes a timeout: a tunnel expires `TUNNEL_TIMEOUT` after its synthesis,
as in Python. `TunnelTable::cull_expired` and `cull_expired_batch` also drop
tunnels set to expire more than twice `TUNNEL_TIMEOUT` ahead.
`TcpClientConfig`, `BackboneClientConfig` and `I2PClientConfig` gain
`tunnel_identity`. With a `TunnelIdentity` set, the client opens every
connection with a tunnel synthesis signed by it; the runtime sets it from
`ReticulumHandle::transport_identity`. Build these configs with `new` so the
field defaults to `None`. A KISS-framed TCP client never synthesizes. Every
TCP, Backbone and I2P client, the shared-instance TCP client included, drops
its queued traffic when a connection opens after an outage or a failed
attempt, and the Unix shared-instance client drops it when it reconnects.
`TcpClientConfig` gains `i2p_tunneled`, which gives a TCP connection tunneled
over I2P Python's longer I2P socket timeouts; the runtime reads it from the
interface's `i2p_tunneled` key. Build the config with `new` so it defaults to
`false`.
Interface stats carry Python 1.5's per-interface counters.
`IngressController` counts announces and path requests received and sent;
`InterfaceEntry` gains `protocol_violations`, `ifac_violations`,
`packet_filter_hits` and `tx_dropped_bytes`; `InterfaceStatRpcEntry` reports
all of them plus `parent_id`; `rpc::InterfaceStatEntry` carries them, the
listener's name, and now implements `Default`. Build it with
`..Default::default()`. The control port and remote management answer with
one Python-shaped stats dict, so `remote_management_schema` is removed:
decode a `/status` answer as `[stats, link_count?]`, and a `/path` answer with
`rpc::decode_response_for_request`. Remote management answers on the transport
identity, so `rnstatus -R` and `rnpath -R` take its hash. A node with
`enable_transport` off and no `static_transport_identity` gets a new management
destination each start, as in Python. The runtime no longer reads
`storage/remote_management_identity`, and leaves the file in place for the
operator to delete.
Interface discovery carries Python 1.5's implementation keys.
`DiscoveryInfo` gains `impl_name` and `impl_version`; build it with
`..Default::default()`. `discovery::autoconnect::qualifies` applies Python's
auto-connect rule, with `ReticulumConfig::autoconnect_unverified_implementations`
as its opt-in. The receiver no longer stores types that are never listed, so
`discovery::Reason` gains `UnlistedType` and becomes `#[non_exhaustive]`, so a
match needs a wildcard arm.
`rns_link::clock::ContinuousInstant` reads a monotonic clock that keeps
counting while the system is suspended: `CLOCK_BOOTTIME` on Linux and Android,
`CLOCK_MONOTONIC_RAW` on Apple platforms and the performance counter on
Windows, with `std::time::Instant` as a best-effort fallback elsewhere. Use it
for a deadline that must hold in real time across a sleep. Check that deadline
on a regular tick and when the runtime resumes; do not assume an outstanding
async timer enforces the same suspend-inclusive deadline on every platform.
Readings are process-local and do not convert to or from `std::time::Instant`.
rns-link gains the target dependencies `libc` (unix) and `windows-sys`
(Windows), so dependents that build with `--locked` refresh their lock files.
`hkdf::derive_key_64` returns `Zeroizing<[u8; 64]>` and `hkdf::hkdf_sha256`
returns `Zeroizing<Vec<u8>>`, so derived keys are wiped when they are dropped.
Pass `&key[..]` where a slice is expected and compare `&okm[..]` with a plain
`Vec`; the bytes are unchanged. `Zeroizing<[u8; 64]>` is not `Copy`, so code
that copied the key borrows it instead. `token::decrypt` still returns
`Vec<u8>` and wipes its buffer when decryption fails; wrap a secret plaintext
in `Zeroizing`. `Identity::from_file` reads at most 1025 bytes and refuses a
file larger than 1 KiB.
`InterfacePostInit::ifac_passphrase` is `Option<Zeroizing<String>>`, so the
passphrase is wiped when the options are dropped: read it with
`.as_deref().map(String::as_str)` and wrap a new one in `Zeroizing::new`.
`RuntimeInterfaceIfacConfig` prints `<redacted>` in place of its passphrase.
`InterfaceEntry::ifac_key` is `Option<rns_identity::ifac::IfacKey>`, one
allocation that clones share and that is wiped when the last one drops, so
interface tables never copy the key. `with_ifac` still takes the key bytes;
otherwise set `Some(key.into())` or `IfacKey::derive(network_name,
passphrase)`, and read the bytes through `&*key`.
rns-crypto re-exports `zeroize` for crates that hold its wiped types without
depending on it, and `rns_identity::persistence::read_secret_file` reads a
bounded secret file into one wiped buffer. An I2P interface refuses a key file
larger than 16 KiB and a SAM reply line longer than 64 KiB, and
`I2PServerConfig` prints `<redacted>` in place of a configured key.
rns-crypto enables the `zeroize` features of `aes` and `cbc`, so AES key
schedules and CBC state are wiped when dropped; dependents that build with
`--locked` refresh their lock files.
The compatibility floor remains unchanged. Its cumulative exact-removal list
also retains the already-reviewed [1.3 migration](1.3.md) for discovery ownership
and nullable coordinates; it is not reclassified as a new 1.4 change. Additive
struct fields can require literal-construction updates even when no old public
line disappears. No whole-crate waiver or baseline reset is used.
Disk-backed Destination handlers can use
`LinkManager::register_deferred_request_handler` after installing an exact
endpoint dispatch handle. Existing synchronous handlers remain supported. The
new callback receives `DestinationRequest` and a one-shot
`DeferredRequestResponder`; move both into the actual bounded worker and return
promptly. Read `response_byte_limit()` before allocating or retiring stored
items. Check `is_cancelled()` before work, and retain the responder until the
worker has actually stopped. `respond(RequestOutcome)` returns a typed completion
receiver: `Sent` means the packet was queued or the response Resource started,
not that the remote application accepted it.
Admission reserves one of four process-wide slots and a conservative share of
256 MiB before invoking the callback. Charge is sixteen times request capacity,
eight times the effective response capacity, plus 16 MiB of construction scratch.
The token may report a smaller limit than registration requested. This accounts
for the bounded handler's planning structures and current response/Resource
construction; arbitrary application allocations are outside this contract.
Response allocation capacity, including optional follow-up Resource metadata,
must fit the token. Requests expire after 120 seconds. Refused admission never
invokes the callback. Dropping a manager revokes response authority while a live
worker retains its reservation; completed response Resources retain that same
reservation until terminal cleanup.
Deferred handlers require exact endpoint ownership. Queued response packets and
Resource advertisement, part, request, hash-map update and cancellation commands
carry `SendLinkEndpointExact` authority. The actor rejects an old token even when
a replacement uses the same Link ID, interface and role. Existing legacy send
commands remain available; they do not acquire this generation-bound guarantee.
+120
View File
@@ -0,0 +1,120 @@
# Capacity, IFAC configuration, and application packet receipts
These changes are part of the 1.4.0 line, published as v1.4.0 and used by
Ratspeak. They are not in the 1.3.0 tools. The migration command below
requires a 1.4 build.
## Interface ownership and packet capacity
`InterfaceHandle` and `InterfaceEntry` carry an `InterfaceOwner` and an
`InterfacePacketCapacity`. The historical `mtu` field remains available for
statistics. Admission uses the separate clear-packet and IFAC-bearing wire
budgets, and `link_mtu_upgrade` explicitly controls upgrade permission.
Custom drivers must create `InterfaceTransportSender` before starting any task
or callback that can publish input or cleanup events. Copy its `owner()` into
the handle, and retain clones of that sender across carrier reconnects. Each
accepted child and replacement registration needs a fresh sender and owner.
Send inbound packets and driver-originated deregistration through this sender;
raw unowned events are refused. Do not wrap messages twice. Coordinated IFAC or
capacity changes use a new owner revision and rebind producers; ordinary
bitrate/online changes do not establish a new capacity promise.
Async driver sends wait until the actor accepts that owner registration. This
keeps the first packet of a newly accepted connection from racing registration;
retiring the owner releases pending sends with an error. Custom actor harnesses
must explicitly mark the owner registered when they accept its registration.
The conservative custom-driver default is `InterfacePacketCapacity::base(mtu)`.
Explicitly declare additional IFAC headroom or upgrade support only when the
whole-packet driver guarantee supports it. Framing and BLE fragmentation are
outside these budgets. TCP fixed MTUs must fit the actual wire budget after IFAC.
Active IFAC also limits the complete wire packet to HKDF-SHA256's 8160-byte
expansion limit; subtract the configured tag size for its clear-packet ceiling.
General Links require at least 500 clear packet bytes. An interface with less
capacity can still carry fitting non-Link traffic, but reports
`LinkCapacityUnavailable` for general Links. RNode's 508-byte wire budget carries
500 clear bytes with IFAC tags up to eight bytes. Larger tags are never silently
weakened. Current local endpoints remain capped at 500; safe transit can preserve
larger peer offers. Legacy or zero Link signalling means 500; nonzero values below
500, malformed shapes, disabled endpoint modes, and proofs above the original
offer are rejected before endpoint state changes.
Initiators send `SendLinkRequest` with a per-attempt oneshot result, or call
`link_messages::dispatch_link_request`. The result preserves typed capacity
errors before waiting for a proof. Keep one establishment deadline around both
admission and proof waiting. Drop the result receiver when cancelling: an actor
that has not dispatched that attempt then emits no request. This acknowledgement
means local driver admission, not peer receipt. It does not replace signature
verification or the exact interface owner retained from the request/proof path.
## Explicit IFAC units
Use `ifac_size_unit = bits` with `ifac_size` to state the unit explicitly.
Valid bit values are multiples of eight from 8 to 512. Without the unit key,
values from 1 to 64 are rejected as ambiguous; valid values from 72 to 512
are accepted as bits. The byte escape hatch is `ifac_size_bytes`, from 1 to 64;
it cannot coexist with either bits field. Migrate ambiguous old values using
their known source convention; the parser does not infer that convention.
Omitting all size keys retains the interface class default. Explicit malformed
sizes remain errors even when credentials are absent. Disabled interfaces may
retain old settings, but must be migrated before enabling them.
`InterfacePostInit::try_from_section` replaces the infallible constructor. Use
the shared `config::ifac::parse_ifac_size` decoder rather than another parser.
`validate_config_capacity` checks explicit driver promises before spawn.
Malformed file syntax still fails the file; semantic errors isolate the affected
enabled interface.
Preview an explicitly selected migration without starting the network:
```sh
rnsd-rs -c /path/to/config-directory config ifac-units --source-units bytes --interface Radio
```
Use `--source-units bits` when that is the known source convention. Add `--write`
to publish the reviewed plan. Publication checks that the source is unchanged,
takes the shared OS-backed config lock, and retains a unique private backup.
An older binary requires restoring its original configuration before rollback.
## Ordinary Link packet proofs
Ordinary `DATA` with context `None` follows explicit `ProofStrategy` policy.
`ProveNone` delivers without a proof. `ProveAll` preserves automatic proofs and
delivers independently of proof queue admission. `ProveApp` requires both an
exact endpoint dispatch handle and the bounded typed inbound channel; it cannot
use the legacy tuple channel. Configuration setters return a result.
For application-controlled admission, receive `InboundLinkPacket`, retain its
`Bytes` and non-cloneable `LinkPacketReceipt` through validation and persistence,
then consume the receipt with `accept()`. Awaiting its result distinguishes local
driver admission (`Sent`) from expiration, closed ownership, dropping, or failure.
`Sent` does not mean physical radio transmission or remote delivery. Dropping the
receipt produces no proof. `reject_and_close(InvalidPropagationStamp)` orders the
protocol rejection before teardown when it can be admitted. Use
`close_without_proof()` for a storage/quota failure that requires teardown without
claiming an invalid propagation stamp; it retains the same exact-owner checks.
Authority is tied to the exact Link generation. Expired, closed, or replaced
owners cannot send a late proof. Payload clones retain admission credits until
they are actually dropped, even if the receipt expires. Limits are 64 packets
and 2 MiB per Link, and 256 packets and 8 MiB process-wide for this ordinary
application-controlled ingress. Resource, Channel, RPC, Direct, and voice
protocol owners retain their own admission rules.
## Durable storage and local timing
`rns_identity::persistence::durable_write` returns a privately constructed receipt
only after exact verification and the native platform barriers succeed. It is
separate from the existing cache writer. Errors distinguish pre-publication
failure from `CommitUncertain`; keep recovery material and withhold higher-level
acceptance on uncertainty. `durable_reconcile` and bounded streaming
`durable_reconcile_hash` renew barriers as well as verifying bytes. A receipt
attests those calls, not hardware infallibility or the provenance of a message.
Directory migration still requires an application journal and native recovery.
Use `Link::try_extend_establishment_timeout` for checked timeout extension.
Invalid floating-point times and unrepresentable deadlines are rejected before
transport side effects. Channel RTTs have a finite local ceiling and its sending
window remains bounded even when public tuning fields contain extreme values.
+109 -45
View File
@@ -4,7 +4,7 @@
"packages": [
{
"name": "rns-crypto",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -34,7 +34,9 @@
"requirement": "^0.8",
"optional": false,
"defaultFeatures": true,
"features": [],
"features": [
"zeroize"
],
"sourceKind": "registry"
},
{
@@ -46,7 +48,8 @@
"optional": false,
"defaultFeatures": true,
"features": [
"alloc"
"alloc",
"zeroize"
],
"sourceKind": "registry"
},
@@ -173,7 +176,7 @@
},
{
"name": "rns-identity",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
@@ -239,7 +242,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -252,7 +255,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -284,6 +287,17 @@
"features": [],
"sourceKind": "registry"
},
{
"name": "sha2",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.10",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "thiserror",
"rename": null,
@@ -319,6 +333,17 @@
],
"sourceKind": "registry"
},
{
"name": "libc",
"rename": null,
"kind": null,
"target": "cfg(unix)",
"requirement": "^0.2",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "windows-sys",
"rename": null,
@@ -336,7 +361,7 @@
},
{
"name": "rns-interface",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -452,7 +477,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -465,7 +490,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -476,7 +501,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -487,7 +512,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -696,7 +721,7 @@
},
{
"name": "rns-link",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -759,7 +784,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [],
@@ -770,7 +795,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -781,7 +806,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [],
@@ -821,12 +846,36 @@
"derive"
],
"sourceKind": "registry"
},
{
"name": "libc",
"rename": null,
"kind": null,
"target": "cfg(unix)",
"requirement": "^0.2",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "windows-sys",
"rename": null,
"kind": null,
"target": "cfg(windows)",
"requirement": "^0.61",
"optional": false,
"defaultFeatures": true,
"features": [
"Win32_System_Performance"
],
"sourceKind": "registry"
}
]
},
{
"name": "rns-protocol",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
@@ -892,7 +941,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -905,7 +954,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -916,7 +965,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -924,6 +973,19 @@
],
"sourceKind": "path"
},
{
"name": "serde",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [
"derive"
],
"sourceKind": "registry"
},
{
"name": "thiserror",
"rename": null,
@@ -963,7 +1025,7 @@
},
{
"name": "rns-ratkey",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -993,7 +1055,9 @@
"requirement": "^0.8",
"optional": false,
"defaultFeatures": true,
"features": [],
"features": [
"zeroize"
],
"sourceKind": "registry"
},
{
@@ -1078,7 +1142,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1091,7 +1155,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1197,7 +1261,7 @@
},
{
"name": "rns-runtime",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -1312,7 +1376,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1325,7 +1389,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1336,7 +1400,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1347,7 +1411,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1358,7 +1422,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1369,7 +1433,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1380,7 +1444,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1475,7 +1539,7 @@
},
{
"name": "rns-tools",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -1586,7 +1650,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1599,7 +1663,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1610,7 +1674,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1621,7 +1685,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": true,
"defaultFeatures": true,
"features": [
@@ -1634,7 +1698,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [
@@ -1647,7 +1711,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1658,7 +1722,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1751,7 +1815,7 @@
},
{
"name": "rns-transport",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -1831,7 +1895,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1844,7 +1908,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -1855,7 +1919,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [
@@ -1926,7 +1990,7 @@
},
{
"name": "rns-wire",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {
@@ -1955,7 +2019,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": false,
"features": [],
+3 -2
View File
@@ -1,4 +1,5 @@
pub mod rns_crypto
pub use rns_crypto::zeroize
pub mod rns_crypto::aes_cbc
pub enum rns_crypto::aes_cbc::AesCbcError
pub rns_crypto::aes_cbc::AesCbcError::DecryptionFailed
@@ -33,8 +34,8 @@ pub mod rns_crypto::hkdf
pub enum rns_crypto::hkdf::HkdfError
pub rns_crypto::hkdf::HkdfError::ExpansionFailed
pub rns_crypto::hkdf::HkdfError::OutputTooLong(usize)
pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<[u8; 64], rns_crypto::hkdf::HkdfError>
pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::hkdf::HkdfError>
pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<zeroize::Zeroizing<[u8; 64]>, rns_crypto::hkdf::HkdfError>
pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, rns_crypto::hkdf::HkdfError>
pub mod rns_crypto::hmac
pub fn rns_crypto::hmac::hmac_sha256(&[u8], &[u8]) -> [u8; 32]
pub fn rns_crypto::hmac::hmac_verify(&[u8], &[u8], &[u8; 32]) -> bool
+57
View File
@@ -38,6 +38,7 @@ pub fn rns_identity::announce_state::RatchetControlState::new([u8; 16], [u8; 16]
pub fn rns_identity::announce_state::RatchetControlState::prepare_announce(&self, u64) -> core::io::error::Result<core::option::Option<Self>>
pub fn rns_identity::announce_state::RatchetControlState::rotation_due(&self, u64, u64) -> bool
pub fn rns_identity::announce_state::RatchetControlState::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::announce_state::RatchetControlState::save_verified_durable(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::announce_state::RatchetControlState::with_rotation_at(&self, u64) -> Self
pub mod rns_identity::destination
#[repr(u8)] pub enum rns_identity::destination::AllowPolicy
@@ -247,9 +248,23 @@ pub mod rns_identity::ifac
pub enum rns_identity::ifac::IfacError
pub rns_identity::ifac::IfacError::HkdfFailed(rns_crypto::hkdf::HkdfError)
pub rns_identity::ifac::IfacError::InvalidSalt
pub struct rns_identity::ifac::IfacKey(_)
impl rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::derive(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<Self, rns_identity::ifac::IfacError>
impl core::cmp::Eq for rns_identity::ifac::IfacKey
impl core::cmp::PartialEq for rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::eq(&self, &Self) -> bool
impl core::convert::From<[u8; 64]> for rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::from([u8; 64]) -> Self
impl core::fmt::Debug for rns_identity::ifac::IfacKey
pub fn rns_identity::ifac::IfacKey::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
impl core::ops::deref::Deref for rns_identity::ifac::IfacKey
pub type rns_identity::ifac::IfacKey::Target = [u8; 64]
pub fn rns_identity::ifac::IfacKey::deref(&self) -> &[u8; 64]
pub const rns_identity::ifac::IFAC_SALT: &str
pub fn rns_identity::ifac::derive_ifac_identity(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<(rns_identity::identity::Identity, [u8; 64], [u8; 64]), rns_identity::ifac::IfacError>
pub fn rns_identity::ifac::derive_ifac_key(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<[u8; 64], rns_identity::ifac::IfacError>
pub fn rns_identity::ifac::ifac_signature(&[u8; 64]) -> core::option::Option<[u8; 64]>
pub fn rns_identity::ifac::split_ifac_key(&[u8; 64]) -> (&[u8], &[u8])
pub mod rns_identity::known_destinations
pub struct rns_identity::known_destinations::KnownDestination
@@ -283,9 +298,49 @@ pub fn rns_identity::known_destinations::KnownDestinations::default() -> Self
pub mod rns_identity::name_hash
pub fn rns_identity::name_hash::name_hash(&str) -> [u8; 10]
pub mod rns_identity::persistence
pub enum rns_identity::persistence::DurableCleanupOutcome
pub rns_identity::persistence::DurableCleanupOutcome::AlreadyAbsent
pub rns_identity::persistence::DurableCleanupOutcome::Removed
pub enum rns_identity::persistence::DurableCommitPhase
pub rns_identity::persistence::DurableCommitPhase::CommitUncertain
pub rns_identity::persistence::DurableCommitPhase::NotCommitted
pub enum rns_identity::persistence::DurableErrorKind
pub rns_identity::persistence::DurableErrorKind::DurabilityUnsupported
pub rns_identity::persistence::DurableErrorKind::InvalidInput
pub rns_identity::persistence::DurableErrorKind::Io
pub rns_identity::persistence::DurableErrorKind::Verification
#[non_exhaustive] pub enum rns_identity::persistence::StorageRisk
pub rns_identity::persistence::StorageRisk::Remote
pub rns_identity::persistence::StorageRisk::Volatile
impl core::fmt::Display for rns_identity::persistence::StorageRisk
pub fn rns_identity::persistence::StorageRisk::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_identity::persistence::DurableDirectoryReceipt
impl rns_identity::persistence::DurableDirectoryReceipt
pub fn rns_identity::persistence::DurableDirectoryReceipt::path(&self) -> &std::path::Path
pub struct rns_identity::persistence::DurableFileReceipt
impl rns_identity::persistence::DurableFileReceipt
pub fn rns_identity::persistence::DurableFileReceipt::content_hash(&self) -> [u8; 32]
pub fn rns_identity::persistence::DurableFileReceipt::is_empty(&self) -> bool
pub fn rns_identity::persistence::DurableFileReceipt::len(&self) -> usize
pub fn rns_identity::persistence::DurableFileReceipt::path(&self) -> &std::path::Path
pub struct rns_identity::persistence::DurableWriteError
pub rns_identity::persistence::DurableWriteError::kind: rns_identity::persistence::DurableErrorKind
pub rns_identity::persistence::DurableWriteError::phase: rns_identity::persistence::DurableCommitPhase
pub rns_identity::persistence::DurableWriteError::recovery_paths: alloc::vec::Vec<std::path::PathBuf>
pub fn rns_identity::persistence::atomic_write(&std::path::Path, &[u8]) -> core::io::error::Result<()>
pub fn rns_identity::persistence::durable_create_dir_all(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_reconcile(&std::path::Path, &[u8]) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_reconcile_directory(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_reconcile_hash(&std::path::Path, [u8; 32], usize) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_remove(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableCleanupOutcome, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_rename_directory(&std::path::Path, &std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::durable_write(&std::path::Path, &[u8]) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::read_file(&std::path::Path) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::read_file_bounded(&std::path::Path, usize) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::read_secret_file(&std::path::Path, usize) -> core::io::error::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::storage_risk(&std::path::Path) -> core::io::error::Result<core::option::Option<rns_identity::persistence::StorageRisk>>
pub fn rns_identity::persistence::try_lock_exclusive(&std::fs::File) -> core::io::error::Result<()>
pub fn rns_identity::persistence::validate_durable_storage_directory(&std::path::Path) -> core::result::Result<(), rns_identity::persistence::DurableWriteError>
pub mod rns_identity::ratchet
pub enum rns_identity::ratchet::RatchetRingFormat
pub rns_identity::ratchet::RatchetRingFormat::Canonical
@@ -335,6 +390,7 @@ pub fn rns_identity::ratchet::RatchetRing::rotate(&mut self) -> [u8; 32]
pub fn rns_identity::ratchet::RatchetRing::rotate_at(&mut self, f64) -> [u8; 32]
pub fn rns_identity::ratchet::RatchetRing::save(&self, &std::path::Path, &[u8; 64]) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::RatchetRing::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::RatchetRing::save_verified_durable(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::RatchetRing::set_ratchet_interval(&mut self, u64) -> bool
pub fn rns_identity::ratchet::RatchetRing::set_retained_ratchets(&mut self, usize) -> bool
impl core::default::Default for rns_identity::ratchet::RatchetRing
@@ -354,6 +410,7 @@ pub fn rns_identity::ratchet::ReceivedRatchet::new([u8; 32]) -> Self
pub fn rns_identity::ratchet::ReceivedRatchet::new_at([u8; 32], f64) -> Self
pub fn rns_identity::ratchet::ReceivedRatchet::ratchet_id(&self) -> alloc::vec::Vec<u8>
pub fn rns_identity::ratchet::ReceivedRatchet::save(&self, &std::path::Path) -> core::io::error::Result<()>
pub fn rns_identity::ratchet::ReceivedRatchet::save_durable(&self, &std::path::Path) -> core::io::error::Result<()>
pub struct rns_identity::ratchet::ReceivedRatchetStore
impl rns_identity::ratchet::ReceivedRatchetStore
pub fn rns_identity::ratchet::ReceivedRatchetStore::clean_expired(&mut self)
+49 -15
View File
@@ -121,8 +121,10 @@ pub rns_interface::backbone::BackboneClientConfig::name: alloc::string::String
pub rns_interface::backbone::BackboneClientConfig::prefer_ipv6: bool
pub rns_interface::backbone::BackboneClientConfig::target_host: alloc::string::String
pub rns_interface::backbone::BackboneClientConfig::target_port: u16
pub rns_interface::backbone::BackboneClientConfig::tunnel_identity: core::option::Option<rns_interface::traits::TunnelIdentity>
impl rns_interface::backbone::BackboneClientConfig
pub fn rns_interface::backbone::BackboneClientConfig::new(&str, &str, u16) -> Self
pub fn rns_interface::backbone::BackboneClientConfig::python_name(&self) -> alloc::string::String
pub struct rns_interface::backbone::BackboneServerConfig
pub rns_interface::backbone::BackboneServerConfig::block_fast_flapping: bool
pub rns_interface::backbone::BackboneServerConfig::device: core::option::Option<alloc::string::String>
@@ -454,9 +456,13 @@ pub rns_interface::i2p::I2PClientConfig::peer_destination: alloc::string::String
pub rns_interface::i2p::I2PClientConfig::reconnect_delay: u64
pub rns_interface::i2p::I2PClientConfig::sam_host: alloc::string::String
pub rns_interface::i2p::I2PClientConfig::sam_port: u16
pub rns_interface::i2p::I2PClientConfig::tunnel_identity: core::option::Option<rns_interface::traits::TunnelIdentity>
impl rns_interface::i2p::I2PClientConfig
pub fn rns_interface::i2p::I2PClientConfig::new(&str, &str) -> Self
pub fn rns_interface::i2p::I2PClientConfig::python_name(&self) -> alloc::string::String
pub struct rns_interface::i2p::I2PServerConfig
pub rns_interface::i2p::I2PServerConfig::b32: core::option::Option<tokio::sync::watch::Sender<core::option::Option<alloc::string::String>>>
pub rns_interface::i2p::I2PServerConfig::key_path: core::option::Option<std::path::PathBuf>
pub rns_interface::i2p::I2PServerConfig::keyfile: core::option::Option<alloc::string::String>
pub rns_interface::i2p::I2PServerConfig::mode: rns_interface::traits::InterfaceMode
pub rns_interface::i2p::I2PServerConfig::name: alloc::string::String
@@ -465,6 +471,8 @@ pub rns_interface::i2p::I2PServerConfig::sam_host: alloc::string::String
pub rns_interface::i2p::I2PServerConfig::sam_port: u16
impl rns_interface::i2p::I2PServerConfig
pub fn rns_interface::i2p::I2PServerConfig::new(&str) -> Self
impl core::fmt::Debug for rns_interface::i2p::I2PServerConfig
pub fn rns_interface::i2p::I2PServerConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub const rns_interface::i2p::BITRATE_GUESS: u64
pub const rns_interface::i2p::DEFAULT_SAM_ADDRESS: &str
pub const rns_interface::i2p::DEFAULT_SAM_PORT: u16
@@ -478,11 +486,12 @@ pub const rns_interface::i2p::RECONNECT_WAIT: u64
pub const rns_interface::i2p::RECONNECT_WAIT_MAX: u64
pub const rns_interface::i2p::SAM_VERSION: &str
pub const rns_interface::i2p::TUNNEL_KEEPALIVE: u64
pub fn rns_interface::i2p::destination_b32(&str) -> core::option::Option<alloc::string::String>
pub fn rns_interface::i2p::parse_sam_reply(&str) -> alloc::vec::Vec<(alloc::string::String, alloc::string::String)>
pub fn rns_interface::i2p::sam_reply_get<'a>(&'a [(alloc::string::String, alloc::string::String)], &str) -> core::option::Option<&'a str>
pub fn rns_interface::i2p::sam_reply_has_token(&[(alloc::string::String, alloc::string::String)], &str) -> bool
pub async fn rns_interface::i2p::spawn_i2p_client(rns_interface::i2p::I2PClientConfig, rns_interface::traits::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub async fn rns_interface::i2p::spawn_i2p_server(rns_interface::i2p::I2PServerConfig, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub async fn rns_interface::i2p::spawn_i2p_server(rns_interface::i2p::I2PServerConfig, rns_interface::traits::InterfaceId, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub mod rns_interface::kiss
pub struct rns_interface::kiss::KissDeframer
impl rns_interface::kiss::KissDeframer
@@ -560,7 +569,7 @@ pub fn rns_interface::local::python_shared_socket_name(&str) -> alloc::string::S
pub fn rns_interface::local::socket_path(core::option::Option<&std::path::Path>) -> std::path::PathBuf
pub fn rns_interface::local::socket_path_for(&str) -> alloc::string::String
pub async fn rns_interface::local::spawn_local_client(rns_interface::local::LocalClientConfig, rns_interface::traits::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub async fn rns_interface::local::spawn_local_server(rns_interface::local::LocalServerConfig, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub async fn rns_interface::local::spawn_local_server(rns_interface::local::LocalServerConfig, rns_interface::traits::InterfaceId, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>
pub mod rns_interface::pipe
pub struct rns_interface::pipe::PipeInterfaceConfig
pub rns_interface::pipe::PipeInterfaceConfig::command: alloc::string::String
@@ -658,6 +667,11 @@ pub rns_interface::rnode::RNodeFirmwareCompatibility::Unsupported
pub rns_interface::rnode::RNodeObservedRadioState::Off
pub rns_interface::rnode::RNodeObservedRadioState::On
pub rns_interface::rnode::RNodeObservedRadioState::Unknown
#[non_exhaustive] pub enum rns_interface::rnode::RNodePortFailureClass
pub rns_interface::rnode::RNodePortFailureClass::AccessDenied
pub rns_interface::rnode::RNodePortFailureClass::InUse
pub rns_interface::rnode::RNodePortFailureClass::NotFound
pub rns_interface::rnode::RNodePortFailureClass::Unavailable
pub enum rns_interface::rnode::RNodeResponse
pub rns_interface::rnode::RNodeResponse::None
pub rns_interface::rnode::RNodeResponse::Packet(rns_transport::messages::TransportMessage)
@@ -671,9 +685,11 @@ pub rns_interface::rnode::RNodeRuntimePhase::ShuttingDown
pub rns_interface::rnode::RNodeRuntimePhase::Stopped
#[non_exhaustive] pub enum rns_interface::rnode::RNodeRuntimeReason
pub rns_interface::rnode::RNodeRuntimeReason::CapabilityAdmissionRejected
pub rns_interface::rnode::RNodeRuntimeReason::ConfigurationRejected
pub rns_interface::rnode::RNodeRuntimeReason::ConnectionAttemptFailed
pub rns_interface::rnode::RNodeRuntimeReason::ConnectionLost
pub rns_interface::rnode::RNodeRuntimeReason::DeviceReset
pub rns_interface::rnode::RNodeRuntimeReason::DeviceUnresponsive
pub rns_interface::rnode::RNodeRuntimeReason::DriverTerminated
pub rns_interface::rnode::RNodeRuntimeReason::RadioInitialisationFault
pub rns_interface::rnode::RNodeRuntimeReason::StopRequested
@@ -681,19 +697,6 @@ pub rns_interface::rnode::RNodeRuntimeReason::TransportConsumerClosed
#[non_exhaustive] pub enum rns_interface::rnode::RNodeSpawnError
pub rns_interface::rnode::RNodeSpawnError::CapabilityAdmission(rns_interface::rnode::RNodeCapabilityAdmissionError)
pub rns_interface::rnode::RNodeSpawnError::Interface(rns_interface::traits::InterfaceError)
pub enum rns_interface::rnode::RNodeStream
pub rns_interface::rnode::RNodeStream::Serial(alloc::boxed::Box<dyn serialport::SerialPort>)
pub rns_interface::rnode::RNodeStream::Tcp(std::net::tcp::TcpStream)
impl rns_interface::rnode::RNodeStream
pub fn rns_interface::rnode::RNodeStream::connect_tcp(&str) -> core::io::error::Result<Self>
pub fn rns_interface::rnode::RNodeStream::description(&self) -> alloc::string::String
pub fn rns_interface::rnode::RNodeStream::open_serial(&str, u32) -> core::io::error::Result<Self>
pub fn rns_interface::rnode::RNodeStream::try_clone(&self) -> core::io::error::Result<Self>
impl alloc::io::read::Read for rns_interface::rnode::RNodeStream
pub fn rns_interface::rnode::RNodeStream::read(&mut self, &mut [u8]) -> core::io::error::Result<usize>
impl core::io::write::Write for rns_interface::rnode::RNodeStream
pub fn rns_interface::rnode::RNodeStream::flush(&mut self) -> core::io::error::Result<()>
pub fn rns_interface::rnode::RNodeStream::write(&mut self, &[u8]) -> core::io::error::Result<usize>
#[non_exhaustive] pub enum rns_interface::rnode::RNodeTransmitFlowState
pub rns_interface::rnode::RNodeTransmitFlowState::Blocked
pub rns_interface::rnode::RNodeTransmitFlowState::Permitted
@@ -703,6 +706,9 @@ pub rns_interface::rnode::RNodeTransportClass::Ble
pub rns_interface::rnode::RNodeTransportClass::Serial
pub rns_interface::rnode::RNodeTransportClass::Tcp
pub rns_interface::rnode::RNodeTransportClass::Usb
#[non_exhaustive] pub struct rns_interface::rnode::RNodeAttemptFailure
pub rns_interface::rnode::RNodeAttemptFailure::consecutive: u32
pub rns_interface::rnode::RNodeAttemptFailure::reason: rns_interface::rnode::RNodeRuntimeReason
pub struct rns_interface::rnode::RNodeConfig
pub rns_interface::rnode::RNodeConfig::bandwidth: u32
pub rns_interface::rnode::RNodeConfig::baud_rate: u32
@@ -751,11 +757,14 @@ pub fn rns_interface::rnode::RNodeRadioSettings::from(&rns_interface::rnode::RNo
pub rns_interface::rnode::RNodeRuntimeSnapshot::capability: rns_interface::rnode::RNodeCapabilityState
pub rns_interface::rnode::RNodeRuntimeSnapshot::capability_admission_failure: core::option::Option<rns_interface::rnode::RNodeCapabilityAdmissionFailureClass>
pub rns_interface::rnode::RNodeRuntimeSnapshot::configuration: rns_interface::rnode::RNodeConfigurationState
pub rns_interface::rnode::RNodeRuntimeSnapshot::configuration_rejection: core::option::Option<rns_interface::rnode_protocol::RNodeReadinessEvidence>
pub rns_interface::rnode::RNodeRuntimeSnapshot::connection_generation: u64
pub rns_interface::rnode::RNodeRuntimeSnapshot::detection: rns_interface::rnode::RNodeDetectionState
pub rns_interface::rnode::RNodeRuntimeSnapshot::disconnect_total: u64
pub rns_interface::rnode::RNodeRuntimeSnapshot::firmware_compatibility: rns_interface::rnode::RNodeFirmwareCompatibility
pub rns_interface::rnode::RNodeRuntimeSnapshot::last_attempt_failure: core::option::Option<rns_interface::rnode::RNodeAttemptFailure>
pub rns_interface::rnode::RNodeRuntimeSnapshot::phase: rns_interface::rnode::RNodeRuntimePhase
pub rns_interface::rnode::RNodeRuntimeSnapshot::port_failure: core::option::Option<rns_interface::rnode::RNodePortFailureClass>
pub rns_interface::rnode::RNodeRuntimeSnapshot::radio: rns_interface::rnode::RNodeObservedRadioState
pub rns_interface::rnode::RNodeRuntimeSnapshot::reason: core::option::Option<rns_interface::rnode::RNodeRuntimeReason>
pub rns_interface::rnode::RNodeRuntimeSnapshot::reconnect_attempt: u64
@@ -768,6 +777,17 @@ pub const fn rns_interface::rnode::RNodeStartupOptions::require_capability_admis
pub const fn rns_interface::rnode::RNodeStartupOptions::with_persisted_bluetooth_enabled(self) -> Self
impl core::default::Default for rns_interface::rnode::RNodeStartupOptions
pub fn rns_interface::rnode::RNodeStartupOptions::default() -> Self
pub struct rns_interface::rnode::RNodeStream
impl rns_interface::rnode::RNodeStream
pub fn rns_interface::rnode::RNodeStream::connect_tcp(&str) -> core::io::error::Result<Self>
pub fn rns_interface::rnode::RNodeStream::description(&self) -> alloc::string::String
pub fn rns_interface::rnode::RNodeStream::open_serial(&str, u32) -> core::io::error::Result<Self>
pub fn rns_interface::rnode::RNodeStream::try_clone(&self) -> core::io::error::Result<Self>
impl alloc::io::read::Read for rns_interface::rnode::RNodeStream
pub fn rns_interface::rnode::RNodeStream::read(&mut self, &mut [u8]) -> core::io::error::Result<usize>
impl core::io::write::Write for rns_interface::rnode::RNodeStream
pub fn rns_interface::rnode::RNodeStream::flush(&mut self) -> core::io::error::Result<()>
pub fn rns_interface::rnode::RNodeStream::write(&mut self, &[u8]) -> core::io::error::Result<usize>
#[non_exhaustive] pub struct rns_interface::rnode::SpawnedRNodeInterface
pub rns_interface::rnode::SpawnedRNodeInterface::driver: rns_interface::rnode::RNodeDriverHandle
pub rns_interface::rnode::SpawnedRNodeInterface::interface: rns_interface::traits::InterfaceHandle
@@ -1070,6 +1090,8 @@ pub rns_interface::rnode_protocol::RNodeReadinessBlocker::RadioInitialisationFau
pub rns_interface::rnode_protocol::RNodeReadinessBlocker::UnsupportedFirmware
pub rns_interface::rnode_protocol::RNodeReadinessBlocker::UnsupportedFirmware::minimum: rns_interface::rnode_protocol::RNodeFirmwareVersion
pub rns_interface::rnode_protocol::RNodeReadinessBlocker::UnsupportedFirmware::observed: rns_interface::rnode_protocol::RNodeFirmwareVersion
impl rns_interface::rnode_protocol::RNodeReadinessBlocker
pub const fn rns_interface::rnode_protocol::RNodeReadinessBlocker::rejected_evidence(self) -> core::option::Option<rns_interface::rnode_protocol::RNodeReadinessEvidence>
pub enum rns_interface::rnode_protocol::RNodeReadinessEvidence
pub rns_interface::rnode_protocol::RNodeReadinessEvidence::Bandwidth
pub rns_interface::rnode_protocol::RNodeReadinessEvidence::CodingRate
@@ -1100,12 +1122,14 @@ pub rns_interface::rnode_protocol::RNodeProtocolEvidence::tx_power: core::option
pub struct rns_interface::rnode_protocol::RNodeProtocolState
impl rns_interface::rnode_protocol::RNodeProtocolState
pub fn rns_interface::rnode_protocol::RNodeProtocolState::apply_frame(&mut self, u8, &[u8]) -> rns_interface::rnode_protocol::RNodeProtocolEffect
pub fn rns_interface::rnode_protocol::RNodeProtocolState::definitive_rejection(&self) -> core::option::Option<rns_interface::rnode_protocol::RNodeReadinessEvidence>
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::detection_observed(&self) -> bool
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::evidence(&self) -> rns_interface::rnode_protocol::RNodeProtocolEvidence
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::flow_permission_observed(&self) -> bool
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::new(rns_interface::rnode_protocol::RNodeProtocolTarget) -> Self
pub fn rns_interface::rnode_protocol::RNodeProtocolState::readiness(&self) -> rns_interface::rnode_protocol::RNodeReadiness
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::target(&self) -> rns_interface::rnode_protocol::RNodeProtocolTarget
pub const fn rns_interface::rnode_protocol::RNodeProtocolState::with_effective_settings(rns_interface::rnode_protocol::RNodeProtocolTarget) -> Self
pub struct rns_interface::rnode_protocol::RNodeProtocolTarget
pub rns_interface::rnode_protocol::RNodeProtocolTarget::bandwidth: u32
pub rns_interface::rnode_protocol::RNodeProtocolTarget::coding_rate: u8
@@ -1142,14 +1166,17 @@ pub mod rns_interface::tcp
pub struct rns_interface::tcp::TcpClientConfig
pub rns_interface::tcp::TcpClientConfig::connect_timeout_secs: u64
pub rns_interface::tcp::TcpClientConfig::fixed_mtu: core::option::Option<u32>
pub rns_interface::tcp::TcpClientConfig::i2p_tunneled: bool
pub rns_interface::tcp::TcpClientConfig::kiss_framing: bool
pub rns_interface::tcp::TcpClientConfig::max_reconnect_tries: core::option::Option<usize>
pub rns_interface::tcp::TcpClientConfig::mode: rns_interface::traits::InterfaceMode
pub rns_interface::tcp::TcpClientConfig::name: alloc::string::String
pub rns_interface::tcp::TcpClientConfig::target_host: alloc::string::String
pub rns_interface::tcp::TcpClientConfig::target_port: u16
pub rns_interface::tcp::TcpClientConfig::tunnel_identity: core::option::Option<rns_interface::traits::TunnelIdentity>
impl rns_interface::tcp::TcpClientConfig
pub fn rns_interface::tcp::TcpClientConfig::new(&str, &str, u16) -> Self
pub fn rns_interface::tcp::TcpClientConfig::python_name(&self) -> alloc::string::String
pub struct rns_interface::tcp::TcpInterfaceState
pub rns_interface::tcp::TcpInterfaceState::detached: core::sync::atomic::AtomicBool
pub rns_interface::tcp::TcpInterfaceState::online: core::sync::atomic::AtomicBool
@@ -1217,11 +1244,18 @@ pub rns_interface::traits::InterfaceHandle::mode: rns_interface::traits::Interfa
pub rns_interface::traits::InterfaceHandle::mtu: u32
pub rns_interface::traits::InterfaceHandle::name: alloc::string::String
pub rns_interface::traits::InterfaceHandle::online: alloc::sync::Arc<core::sync::atomic::AtomicBool>
pub rns_interface::traits::InterfaceHandle::owner: rns_transport::interface_ownership::InterfaceOwner
pub rns_interface::traits::InterfaceHandle::packet_capacity: rns_transport::interface_ownership::InterfacePacketCapacity
pub rns_interface::traits::InterfaceHandle::parent_id: core::option::Option<rns_interface::traits::InterfaceId>
pub rns_interface::traits::InterfaceHandle::read_task: tokio::runtime::task::join::JoinHandle<()>
pub rns_interface::traits::InterfaceHandle::rxb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
pub rns_interface::traits::InterfaceHandle::tx: tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>
pub rns_interface::traits::InterfaceHandle::txb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
pub struct rns_interface::traits::TunnelIdentity(pub alloc::sync::Arc<rns_identity::identity::Identity>)
impl rns_interface::traits::TunnelIdentity
pub fn rns_interface::traits::TunnelIdentity::synthesis(&self, &str) -> core::option::Option<bytes::bytes::Bytes>
impl core::fmt::Debug for rns_interface::traits::TunnelIdentity
pub fn rns_interface::traits::TunnelIdentity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub const rns_interface::traits::AR_FREQ_DECAY: f64
pub const rns_interface::traits::AR_MINFREQ_HZ: f64
pub const rns_interface::traits::DEFAULT_AR_GRACE: u32
+37 -12
View File
@@ -1,4 +1,27 @@
pub mod rns_link
pub mod rns_link::clock
pub struct rns_link::clock::ContinuousInstant(_)
impl rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::checked_add(self, core::time::Duration) -> core::option::Option<Self>
pub fn rns_link::clock::ContinuousInstant::checked_duration_since(self, Self) -> core::option::Option<core::time::Duration>
pub fn rns_link::clock::ContinuousInstant::checked_sub(self, core::time::Duration) -> core::option::Option<Self>
pub fn rns_link::clock::ContinuousInstant::duration_since(self, Self) -> core::time::Duration
pub fn rns_link::clock::ContinuousInstant::elapsed(self) -> core::time::Duration
pub fn rns_link::clock::ContinuousInstant::now() -> Self
pub fn rns_link::clock::ContinuousInstant::saturating_duration_since(self, Self) -> core::time::Duration
impl core::ops::arith::Add<core::time::Duration> for rns_link::clock::ContinuousInstant
pub type rns_link::clock::ContinuousInstant::Output = rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::add(self, core::time::Duration) -> Self
impl core::ops::arith::AddAssign<core::time::Duration> for rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::add_assign(&mut self, core::time::Duration)
impl core::ops::arith::Sub for rns_link::clock::ContinuousInstant
pub type rns_link::clock::ContinuousInstant::Output = core::time::Duration
pub fn rns_link::clock::ContinuousInstant::sub(self, Self) -> core::time::Duration
impl core::ops::arith::Sub<core::time::Duration> for rns_link::clock::ContinuousInstant
pub type rns_link::clock::ContinuousInstant::Output = rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::sub(self, core::time::Duration) -> Self
impl core::ops::arith::SubAssign<core::time::Duration> for rns_link::clock::ContinuousInstant
pub fn rns_link::clock::ContinuousInstant::sub_assign(&mut self, core::time::Duration)
pub mod rns_link::constants
pub const rns_link::constants::ACCEPT_ALL: u8
pub const rns_link::constants::ACCEPT_APP: u8
@@ -49,6 +72,7 @@ pub enum rns_link::handshake::HandshakeError
pub rns_link::handshake::HandshakeError::InvalidLength(usize)
pub rns_link::handshake::HandshakeError::InvalidSignature
pub rns_link::handshake::HandshakeError::KeyDerivation(rns_link::key_derivation::LinkKeyError)
pub rns_link::handshake::HandshakeError::Signalling(rns_wire::link_signalling::LinkSignallingError)
pub rns_link::handshake::HandshakeError::TooShort
pub rns_link::handshake::HandshakeError::UnsupportedMode(u8)
pub struct rns_link::handshake::EphemeralKeys
@@ -64,20 +88,20 @@ impl zeroize::Zeroize for rns_link::handshake::EphemeralKeys
pub fn rns_link::handshake::EphemeralKeys::zeroize(&mut self)
pub struct rns_link::handshake::LinkProofData
pub rns_link::handshake::LinkProofData::responder_x25519_pub: [u8; 32]
pub rns_link::handshake::LinkProofData::signalling: rns_link::mtu_discovery::SignallingData
pub rns_link::handshake::LinkProofData::signalling: rns_wire::link_signalling::SignallingData
pub rns_link::handshake::LinkProofData::signature: [u8; 64]
impl rns_link::handshake::LinkProofData
pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self
pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_wire::link_signalling::SignallingData) -> Self
pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_wire::link_signalling::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
pub fn rns_link::handshake::LinkProofData::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_link::handshake::LinkProofData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
pub fn rns_link::handshake::LinkProofData::validate(&self, &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 16], &[u8; 32]) -> bool
pub struct rns_link::handshake::LinkRequestData
pub rns_link::handshake::LinkRequestData::peer_ed25519_pub: [u8; 32]
pub rns_link::handshake::LinkRequestData::peer_x25519_pub: [u8; 32]
pub rns_link::handshake::LinkRequestData::signalling: rns_link::mtu_discovery::SignallingData
pub rns_link::handshake::LinkRequestData::signalling: rns_wire::link_signalling::SignallingData
impl rns_link::handshake::LinkRequestData
pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_link::mtu_discovery::SignallingData) -> alloc::vec::Vec<u8>
pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_wire::link_signalling::SignallingData) -> alloc::vec::Vec<u8>
pub fn rns_link::handshake::LinkRequestData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
pub fn rns_link::handshake::compute_link_id(&[u8; 16], &[u8]) -> [u8; 16]
pub fn rns_link::handshake::compute_link_id_from_raw(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
@@ -287,6 +311,7 @@ pub fn rns_link::link::Link::track_incoming_resource(&mut self, [u8; 32])
pub fn rns_link::link::Link::track_outgoing_resource(&mut self, [u8; 32])
pub fn rns_link::link::Link::track_phy_stats(&mut self, bool)
pub fn rns_link::link::Link::traffic_stats(&self) -> (u64, u64, u64, u64)
pub fn rns_link::link::Link::try_extend_establishment_timeout(&mut self, f64) -> core::result::Result<(), rns_link::link::TimeoutError>
pub fn rns_link::link::Link::untrack_resource(&mut self, &[u8; 32])
pub fn rns_link::link::Link::update_outgoing_resource_state(&mut self, usize, rns_link::link::OutboundResourceState)
pub fn rns_link::link::Link::update_pending_request_id(&mut self, &[u8; 16], [u8; 16]) -> bool
@@ -301,19 +326,19 @@ pub struct rns_link::link::LinkPhyStats
pub rns_link::link::LinkPhyStats::q: core::option::Option<f64>
pub rns_link::link::LinkPhyStats::rssi: core::option::Option<f64>
pub rns_link::link::LinkPhyStats::snr: core::option::Option<f64>
pub struct rns_link::link::TimeoutError
pub type rns_link::link::LinkCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync)>
pub type rns_link::link::PacketCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8]) + core::marker::Send + core::marker::Sync)>
pub type rns_link::link::ParsedRequestData = ([u8; 16], [u8; 16], f64, alloc::vec::Vec<u8>)
pub type rns_link::link::RemoteIdentifiedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link, &[u8; 64]) + core::marker::Send + core::marker::Sync)>
pub type rns_link::link::ResourceCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(bool) -> bool + core::marker::Send + core::marker::Sync)>
pub mod rns_link::mtu_discovery
pub struct rns_link::mtu_discovery::SignallingData
pub rns_link::mtu_discovery::SignallingData::mode: u8
pub rns_link::mtu_discovery::SignallingData::mtu: u32
impl rns_link::mtu_discovery::SignallingData
pub fn rns_link::mtu_discovery::SignallingData::new(u8, u32) -> Self
pub fn rns_link::mtu_discovery::SignallingData::pack(&self) -> [u8; 3]
pub fn rns_link::mtu_discovery::SignallingData::unpack(&[u8]) -> core::option::Option<Self>
pub use rns_link::mtu_discovery::LinkMtu
pub use rns_link::mtu_discovery::LinkSignalling
pub use rns_link::mtu_discovery::LinkSignallingError
pub use rns_link::mtu_discovery::SignallingData
pub use rns_link::mtu_discovery::parse_proof_signalling
pub use rns_link::mtu_discovery::parse_request_signalling
pub mod rns_link::request
pub enum rns_link::request::RequestState
pub rns_link::request::RequestState::Delivered
+14
View File
@@ -129,6 +129,7 @@ pub const rns_protocol::channel::FAST_RATE_THRESHOLD: usize
pub const rns_protocol::channel::MAX_TRIES: usize
pub const rns_protocol::channel::MIN_TIMEOUT_BASE: f64
pub const rns_protocol::channel::RTT_FAST: f64
pub const rns_protocol::channel::RTT_MAX: f64
pub const rns_protocol::channel::RTT_MEDIUM: f64
pub const rns_protocol::channel::RTT_SLOW: f64
pub const rns_protocol::channel::SEQ_MAX: u16
@@ -206,6 +207,10 @@ pub enum rns_protocol::resource::CancelType
pub rns_protocol::resource::CancelType::Icl
pub rns_protocol::resource::CancelType::Rcl
pub enum rns_protocol::resource::ResourceError
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::context: rns_wire::context::PacketContext
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::encoded_len: usize
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::mtu: usize
pub rns_protocol::resource::ResourceError::Corrupt
pub rns_protocol::resource::ResourceError::DecompressionFailed
pub rns_protocol::resource::ResourceError::DecryptFailed
@@ -483,14 +488,23 @@ pub rns_protocol::resource_adv::ResourceAdvertisement::segment_index: usize
pub rns_protocol::resource_adv::ResourceAdvertisement::total_segments: usize
pub rns_protocol::resource_adv::ResourceAdvertisement::transfer_size: usize
impl rns_protocol::resource_adv::ResourceAdvertisement
pub fn rns_protocol::resource_adv::ResourceAdvertisement::encoded_len(&self) -> core::result::Result<usize, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::get_map_hashes(&self) -> alloc::vec::Vec<[u8; 4]>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::new(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize) -> Self
pub fn rns_protocol::resource_adv::ResourceAdvertisement::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::pack_into<W: core::io::write::Write>(&self, W) -> core::result::Result<(), rmp_serde::encode::Error>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::unpack(&[u8]) -> core::result::Result<Self, alloc::string::String>
pub fn rns_protocol::resource_adv::ResourceAdvertisement::with_metadata_size(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize, usize) -> Self
pub const rns_protocol::resource_adv::OVERHEAD: usize
pub fn rns_protocol::resource_adv::collision_guard_size(usize) -> usize
pub fn rns_protocol::resource_adv::hashmap_max_len(usize) -> usize
pub mod rns_protocol::resource_control
pub const rns_protocol::resource_control::HASHMAP_STRIDE: usize
pub fn rns_protocol::resource_control::check_advertisement(&rns_protocol::resource_adv::ResourceAdvertisement, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_control::check_control_frame(rns_wire::context::PacketContext, usize, bool, usize, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_control::encode_hashmap_update(&[u8; 32], usize, &[u8]) -> alloc::vec::Vec<u8>
pub fn rns_protocol::resource_control::encrypted_len(usize) -> core::result::Result<usize, rns_protocol::resource::ResourceError>
pub fn rns_protocol::resource_control::preflight_outbound(usize, core::option::Option<usize>, core::option::Option<&[u8]>, bool, bool, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
pub mod rns_protocol::rnsh
pub enum rns_protocol::rnsh::RnshCodecError
pub rns_protocol::rnsh::RnshCodecError::Decode(alloc::string::String)
+135 -53
View File
@@ -38,6 +38,57 @@ pub fn rns_runtime::buffer_stream::LinkSessionBufferWriter::poll_write(core::pin
pub const rns_runtime::buffer_stream::DEFAULT_CLOSE_TIMEOUT: core::time::Duration
pub const rns_runtime::buffer_stream::DEFAULT_READER_CAPACITY: usize
pub mod rns_runtime::config
pub mod rns_runtime::config::ifac
pub enum rns_runtime::config::ifac::IfacConfigError
pub rns_runtime::config::ifac::IfacConfigError::IfacUnitsRequired
pub rns_runtime::config::ifac::IfacConfigError::Invalid
pub rns_runtime::config::ifac::IfacConfigError::Invalid::field: &'static str
pub rns_runtime::config::ifac::IfacConfigError::Invalid::reason: &'static str
pub enum rns_runtime::config::ifac::IfacMigrationError
pub rns_runtime::config::ifac::IfacMigrationError::EmptySelection
pub rns_runtime::config::ifac::IfacMigrationError::Invalid
pub rns_runtime::config::ifac::IfacMigrationError::Invalid::error: rns_runtime::config::ifac::IfacConfigError
pub rns_runtime::config::ifac::IfacMigrationError::Invalid::interface: alloc::string::String
pub rns_runtime::config::ifac::IfacMigrationError::NotFound(alloc::string::String)
pub rns_runtime::config::ifac::IfacMigrationError::SourceMismatch
pub rns_runtime::config::ifac::IfacMigrationError::Syntax(rns_runtime::config::ConfigError)
pub enum rns_runtime::config::ifac::IfacSourceUnits
pub rns_runtime::config::ifac::IfacSourceUnits::Bits
pub rns_runtime::config::ifac::IfacSourceUnits::Bytes
pub struct rns_runtime::config::ifac::IfacMigrationPlan
impl rns_runtime::config::ifac::IfacMigrationPlan
pub fn rns_runtime::config::ifac::IfacMigrationPlan::changes(&self) -> &[rns_runtime::config::ifac::IfacUnitChange]
pub fn rns_runtime::config::ifac::IfacMigrationPlan::is_unchanged(&self) -> bool
pub fn rns_runtime::config::ifac::IfacMigrationPlan::proposed_config(&self) -> &str
pub fn rns_runtime::config::ifac::IfacMigrationPlan::source_hash(&self) -> [u8; 32]
pub fn rns_runtime::config::ifac::IfacMigrationPlan::source_matches(&self, &str) -> bool
impl core::fmt::Debug for rns_runtime::config::ifac::IfacMigrationPlan
pub fn rns_runtime::config::ifac::IfacMigrationPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_runtime::config::ifac::IfacUnitChange
pub rns_runtime::config::ifac::IfacUnitChange::effective_bytes: usize
pub rns_runtime::config::ifac::IfacUnitChange::interface: alloc::string::String
pub rns_runtime::config::ifac::IfacUnitChange::previous_value: usize
pub struct rns_runtime::config::ifac::PropertySpan
pub rns_runtime::config::ifac::PropertySpan::key: alloc::string::String
pub rns_runtime::config::ifac::PropertySpan::path: alloc::vec::Vec<alloc::string::String>
pub rns_runtime::config::ifac::PropertySpan::range: core::ops::range::Range<usize>
pub rns_runtime::config::ifac::PropertySpan::section: alloc::string::String
pub struct rns_runtime::config::ifac::SectionSpan
pub rns_runtime::config::ifac::SectionSpan::header_end: usize
pub rns_runtime::config::ifac::SectionSpan::path: alloc::vec::Vec<alloc::string::String>
pub rns_runtime::config::ifac::SectionSpan::range: core::ops::range::Range<usize>
pub rns_runtime::config::ifac::SectionSpan::section: alloc::string::String
pub const rns_runtime::config::ifac::SIZE_KEYS: &[&str]
pub fn rns_runtime::config::ifac::migration_candidates(&rns_runtime::config::Config) -> alloc::vec::Vec<rns_runtime::config::ifac::IfacUnitChange>
pub fn rns_runtime::config::ifac::parse_ifac_size(&rns_runtime::config::ConfigSection) -> core::result::Result<core::option::Option<usize>, rns_runtime::config::ifac::IfacConfigError>
pub fn rns_runtime::config::ifac::plan_ifac_unit_migration(&str, &[alloc::string::String], rns_runtime::config::ifac::IfacSourceUnits) -> core::result::Result<rns_runtime::config::ifac::IfacMigrationPlan, rns_runtime::config::ifac::IfacMigrationError>
pub fn rns_runtime::config::ifac::property_spans(&str) -> core::result::Result<alloc::vec::Vec<rns_runtime::config::ifac::PropertySpan>, rns_runtime::config::ConfigError>
pub fn rns_runtime::config::ifac::section_spans(&str) -> core::result::Result<alloc::vec::Vec<rns_runtime::config::ifac::SectionSpan>, rns_runtime::config::ConfigError>
pub fn rns_runtime::config::ifac::validate_ifac_update(core::option::Option<&str>, &str) -> core::result::Result<(), rns_runtime::config::ifac::IfacMigrationError>
pub mod rns_runtime::config::ifac_lock
pub struct rns_runtime::config::ifac_lock::ConfigWriteLock
impl rns_runtime::config::ifac_lock::ConfigWriteLock
pub fn rns_runtime::config::ifac_lock::ConfigWriteLock::acquire(&std::path::Path) -> core::io::error::Result<Self>
pub enum rns_runtime::config::ConfigError
pub rns_runtime::config::ConfigError::InvalidValue
pub rns_runtime::config::ConfigError::InvalidValue::key: alloc::string::String
@@ -78,6 +129,9 @@ pub fn rns_runtime::config::ConfigSection::get_int(&self, &str) -> core::option:
pub fn rns_runtime::config::ConfigSection::get_list(&self, &str) -> core::option::Option<alloc::vec::Vec<alloc::string::String>>
pub fn rns_runtime::config::ConfigSection::get_uint(&self, &str) -> core::option::Option<u64>
pub fn rns_runtime::config::ConfigSection::has(&self, &str) -> bool
pub fn rns_runtime::config::ConfigSection::has_enable_key(&self) -> bool
pub fn rns_runtime::config::ConfigSection::interface_enabled(&self) -> bool
pub fn rns_runtime::config::ConfigSection::invalid_enable_key(&self) -> core::option::Option<&'static str>
pub fn rns_runtime::config::ConfigSection::new() -> Self
pub fn rns_runtime::config::ConfigSection::set(&mut self, &str, &str)
pub fn rns_runtime::config::ConfigSection::set_list(&mut self, &str, alloc::vec::Vec<alloc::string::String>)
@@ -118,6 +172,7 @@ pub rns_runtime::destination_runtime::DestinationRuntimeError::Destination(rns_i
pub rns_runtime::destination_runtime::DestinationRuntimeError::InvalidEventCapacity
pub rns_runtime::destination_runtime::DestinationRuntimeError::LinkSend(rns_runtime::link_manager::LinkSendError)
pub rns_runtime::destination_runtime::DestinationRuntimeError::ManagerUnavailable
pub rns_runtime::destination_runtime::DestinationRuntimeError::OrdinaryPacketConfiguration(rns_runtime::link_manager::LinkPacketConfigurationError)
pub struct rns_runtime::destination_runtime::DestinationEvents
pub rns_runtime::destination_runtime::DestinationEvents::channel_messages: tokio::sync::mpsc::bounded::Receiver<rns_runtime::link_manager::LinkChannelMessage>
pub rns_runtime::destination_runtime::DestinationEvents::link_packet_proofs: tokio::sync::mpsc::bounded::Receiver<rns_runtime::link_manager::LinkPacketProof>
@@ -278,14 +333,14 @@ pub rns_runtime::interface_factory::InterfacePostInit::announces_from_internal:
pub rns_runtime::interface_factory::InterfacePostInit::bitrate: core::option::Option<u64>
pub rns_runtime::interface_factory::InterfacePostInit::default_ifac_size: usize
pub rns_runtime::interface_factory::InterfacePostInit::ifac_network_name: core::option::Option<alloc::string::String>
pub rns_runtime::interface_factory::InterfacePostInit::ifac_passphrase: core::option::Option<alloc::string::String>
pub rns_runtime::interface_factory::InterfacePostInit::ifac_passphrase: core::option::Option<zeroize::Zeroizing<alloc::string::String>>
pub rns_runtime::interface_factory::InterfacePostInit::ifac_size: core::option::Option<usize>
pub rns_runtime::interface_factory::InterfacePostInit::ingress_control: bool
pub rns_runtime::interface_factory::InterfacePostInit::ingress_overrides: rns_transport::ingress::IngressOverrides
pub rns_runtime::interface_factory::InterfacePostInit::outgoing: bool
pub rns_runtime::interface_factory::InterfacePostInit::recursive_prs: bool
impl rns_runtime::interface_factory::InterfacePostInit
pub fn rns_runtime::interface_factory::InterfacePostInit::from_section(&rns_runtime::config::ConfigSection) -> Self
pub fn rns_runtime::interface_factory::InterfacePostInit::try_from_section(&rns_runtime::config::ConfigSection) -> core::result::Result<Self, rns_runtime::interface_factory::InterfaceFactoryError>
pub fn rns_runtime::interface_factory::InterfacePostInit::with_default_ifac_size(self, usize) -> Self
pub struct rns_runtime::interface_factory::KissSerialConfig
pub rns_runtime::interface_factory::KissSerialConfig::baud_rate: u32
@@ -362,6 +417,7 @@ pub rns_runtime::interface_factory::SerialInterfaceConfig::port: alloc::string::
pub rns_runtime::interface_factory::SerialInterfaceConfig::stop_bits: u8
pub fn rns_runtime::interface_factory::default_ifac_size_for(&rns_runtime::interface_factory::InterfaceConfig) -> usize
pub fn rns_runtime::interface_factory::synthesize_interface(&str, &rns_runtime::config::ConfigSection) -> core::result::Result<rns_runtime::interface_factory::InterfaceConfig, rns_runtime::interface_factory::InterfaceFactoryError>
pub fn rns_runtime::interface_factory::validate_config_capacity(&rns_runtime::interface_factory::InterfaceConfig, &rns_runtime::interface_factory::InterfacePostInit) -> core::result::Result<(), rns_runtime::interface_factory::InterfaceFactoryError>
pub mod rns_runtime::jobs
pub enum rns_runtime::jobs::Job
pub rns_runtime::jobs::Job::CleanCache
@@ -397,6 +453,7 @@ pub rns_runtime::link_client::LinkClientError::LinkCrypto(alloc::string::String)
pub rns_runtime::link_client::LinkClientError::NoSigningKey
pub rns_runtime::link_client::LinkClientError::ProofInvalid(alloc::string::String)
pub rns_runtime::link_client::LinkClientError::PubkeyNotDiscovered
pub rns_runtime::link_client::LinkClientError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::link_client::LinkClientError::Timeout(&'static str)
pub rns_runtime::link_client::LinkClientError::TransportUnavailable
pub rns_runtime::link_client::LinkClientError::UnexpectedResponse(alloc::string::String)
@@ -411,6 +468,15 @@ pub rns_runtime::link_manager::ChannelSendError::LinkNotActive
pub rns_runtime::link_manager::ChannelSendError::LinkNotFound
pub rns_runtime::link_manager::ChannelSendError::NoSessionKeys
pub rns_runtime::link_manager::ChannelSendError::TransportUnavailable
pub enum rns_runtime::link_manager::DeferredResponseError
pub rns_runtime::link_manager::DeferredResponseError::Closed
pub rns_runtime::link_manager::DeferredResponseError::TooLarge
pub enum rns_runtime::link_manager::DeferredResponseOutcome
pub rns_runtime::link_manager::DeferredResponseOutcome::Closed
pub rns_runtime::link_manager::DeferredResponseOutcome::Dropped
pub rns_runtime::link_manager::DeferredResponseOutcome::Expired
pub rns_runtime::link_manager::DeferredResponseOutcome::Sent
pub rns_runtime::link_manager::DeferredResponseOutcome::Unavailable
pub enum rns_runtime::link_manager::DestinationControlError
pub rns_runtime::link_manager::DestinationControlError::Destination(rns_identity::destination::DestinationError)
pub rns_runtime::link_manager::DestinationControlError::DestinationUnavailable
@@ -486,6 +552,18 @@ pub rns_runtime::link_manager::LinkManagerCommand::SetDefaultAppData
pub rns_runtime::link_manager::LinkManagerCommand::SetDefaultAppData::app_data: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::link_manager::LinkManagerCommand::SetDefaultAppData::result_tx: core::option::Option<tokio::sync::oneshot::Sender<core::result::Result<(), rns_runtime::link_manager::DestinationControlError>>>
pub rns_runtime::link_manager::LinkManagerCommand::Shutdown
pub enum rns_runtime::link_manager::LinkPacketConfigurationError
pub rns_runtime::link_manager::LinkPacketConfigurationError::ExactDispatchRequired
pub rns_runtime::link_manager::LinkPacketConfigurationError::LegacyChannel
pub rns_runtime::link_manager::LinkPacketConfigurationError::TypedChannelRequired
pub enum rns_runtime::link_manager::LinkPacketReceiptOutcome
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Closed
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Dropped
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Expired
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Sent
pub rns_runtime::link_manager::LinkPacketReceiptOutcome::Unavailable
pub enum rns_runtime::link_manager::LinkPacketRejection
pub rns_runtime::link_manager::LinkPacketRejection::InvalidPropagationStamp
pub enum rns_runtime::link_manager::LinkPayloadSendReceipt
pub rns_runtime::link_manager::LinkPayloadSendReceipt::Packet(rns_runtime::link_manager::LinkPacketSendReceipt)
pub rns_runtime::link_manager::LinkPayloadSendReceipt::Resource(rns_runtime::link_manager::LinkResourceSendReceipt)
@@ -535,6 +613,13 @@ pub struct rns_runtime::link_manager::ChannelSendReceipt
pub rns_runtime::link_manager::ChannelSendReceipt::link_id: [u8; 16]
pub rns_runtime::link_manager::ChannelSendReceipt::packet_hash: [u8; 32]
pub rns_runtime::link_manager::ChannelSendReceipt::sequence: u16
pub struct rns_runtime::link_manager::DeferredRequestResponder
impl rns_runtime::link_manager::DeferredRequestResponder
pub fn rns_runtime::link_manager::DeferredRequestResponder::is_cancelled(&self) -> bool
pub fn rns_runtime::link_manager::DeferredRequestResponder::respond(self, rns_runtime::link_manager::RequestOutcome) -> core::result::Result<tokio::sync::oneshot::Receiver<rns_runtime::link_manager::DeferredResponseOutcome>, rns_runtime::link_manager::DeferredResponseError>
pub fn rns_runtime::link_manager::DeferredRequestResponder::response_byte_limit(&self) -> usize
impl core::ops::drop::Drop for rns_runtime::link_manager::DeferredRequestResponder
pub fn rns_runtime::link_manager::DeferredRequestResponder::drop(&mut self)
pub struct rns_runtime::link_manager::DestinationAnnounceOptions
pub rns_runtime::link_manager::DestinationAnnounceOptions::app_data: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::link_manager::DestinationAnnounceOptions::attached_interface: core::option::Option<rns_transport::messages::InterfaceId>
@@ -551,6 +636,14 @@ pub rns_runtime::link_manager::DestinationRequest::path: alloc::string::String
pub rns_runtime::link_manager::DestinationRequest::remote_identity: core::option::Option<rns_identity::identity::Identity>
pub rns_runtime::link_manager::DestinationRequest::request_id: [u8; 16]
pub rns_runtime::link_manager::DestinationRequest::requested_at: f64
pub struct rns_runtime::link_manager::InboundLinkPacket
impl rns_runtime::link_manager::InboundLinkPacket
pub fn rns_runtime::link_manager::InboundLinkPacket::destination_hash(&self) -> [u8; 16]
pub fn rns_runtime::link_manager::InboundLinkPacket::into_parts(self) -> (bytes::bytes::Bytes, core::option::Option<rns_runtime::link_manager::LinkPacketReceipt>)
pub fn rns_runtime::link_manager::InboundLinkPacket::link_id(&self) -> [u8; 16]
pub fn rns_runtime::link_manager::InboundLinkPacket::packet_hash(&self) -> [u8; 32]
pub fn rns_runtime::link_manager::InboundLinkPacket::payload(&self) -> &bytes::bytes::Bytes
pub fn rns_runtime::link_manager::InboundLinkPacket::role(&self) -> rns_link::link::LinkRole
pub struct rns_runtime::link_manager::LinkChannelMessage
pub rns_runtime::link_manager::LinkChannelMessage::link_id: [u8; 16]
pub rns_runtime::link_manager::LinkChannelMessage::msg_type: u16
@@ -574,8 +667,11 @@ pub fn rns_runtime::link_manager::LinkManager::get_link_mut(&mut self, &[u8; 16]
pub fn rns_runtime::link_manager::LinkManager::link_identities_handle(&self) -> alloc::sync::Arc<std::sync::poison::mutex::Mutex<std::collections::hash::map::HashMap<[u8; 16], [u8; 16]>>>
pub fn rns_runtime::link_manager::LinkManager::link_interface(&self, &[u8; 16]) -> core::option::Option<rns_transport::messages::InterfaceId>
pub fn rns_runtime::link_manager::LinkManager::new(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Receiver<rns_transport::link_messages::DestinationEvent>, [u8; 16], core::option::Option<rns_crypto::ed25519::Ed25519PrivateKey>) -> Self
pub fn rns_runtime::link_manager::LinkManager::ordinary_packet_overload_count(&self) -> u64
pub fn rns_runtime::link_manager::LinkManager::ordinary_packet_proof_strategy(&self) -> rns_identity::destination::ProofStrategy
pub fn rns_runtime::link_manager::LinkManager::process_destination_packet(&self, &[u8], &rns_identity::identity::Identity) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_runtime::link_manager::LinkManager::register_channel_message_type(&mut self, u16) -> core::result::Result<(), rns_protocol::channel::ChannelError>
pub fn rns_runtime::link_manager::LinkManager::register_deferred_request_handler<F>(&mut self, &str, rns_identity::destination::AllowPolicy, core::option::Option<alloc::vec::Vec<[u8; 16]>>, bool, usize, F) -> bool where F: core::ops::function::Fn(rns_runtime::link_manager::DestinationRequest, rns_runtime::link_manager::DeferredRequestResponder) + core::marker::Send + 'static
pub fn rns_runtime::link_manager::LinkManager::register_request_handler<F>(&mut self, &str, rns_identity::destination::AllowPolicy, core::option::Option<alloc::vec::Vec<[u8; 16]>>, bool, F) -> bool where F: core::ops::function::Fn(rns_runtime::link_manager::DestinationRequest) -> rns_runtime::link_manager::RequestOutcome + core::marker::Send + 'static
pub async fn rns_runtime::link_manager::LinkManager::run(self)
pub async fn rns_runtime::link_manager::LinkManager::run_with_commands(self, tokio::sync::mpsc::bounded::Receiver<rns_runtime::link_manager::LinkManagerCommand>)
@@ -589,14 +685,16 @@ pub fn rns_runtime::link_manager::LinkManager::set_accounting_event_channel(&mut
pub fn rns_runtime::link_manager::LinkManager::set_announce_handler<F>(&mut self, F) where F: core::ops::function::FnMut() + core::marker::Send + 'static
pub fn rns_runtime::link_manager::LinkManager::set_channel_message_channel(&mut self, tokio::sync::mpsc::bounded::Sender<rns_runtime::link_manager::LinkChannelMessage>)
pub fn rns_runtime::link_manager::LinkManager::set_destination_delivery_proof_channel(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<rns_runtime::link_manager::DestinationDeliveryProof>)
pub fn rns_runtime::link_manager::LinkManager::set_inbound_link_packet_channel(&mut self, tokio::sync::mpsc::bounded::Sender<rns_runtime::link_manager::InboundLinkPacket>) -> core::result::Result<(), rns_runtime::link_manager::LinkPacketConfigurationError>
pub fn rns_runtime::link_manager::LinkManager::set_inbound_raw_channel(&mut self, tokio::sync::mpsc::bounded::Sender<alloc::vec::Vec<u8>>)
pub fn rns_runtime::link_manager::LinkManager::set_link_closed_channel(&mut self, tokio::sync::mpsc::bounded::Sender<[u8; 16]>)
pub fn rns_runtime::link_manager::LinkManager::set_link_endpoint_dispatch_handle(&mut self, rns_transport::link_endpoint_dispatch::LinkEndpointDispatchHandle)
pub fn rns_runtime::link_manager::LinkManager::set_link_established_channel(&mut self, tokio::sync::mpsc::bounded::Sender<[u8; 16]>)
pub fn rns_runtime::link_manager::LinkManager::set_link_identified_channel(&mut self, tokio::sync::mpsc::bounded::Sender<([u8; 16], [u8; 16])>)
pub fn rns_runtime::link_manager::LinkManager::set_link_identity_gate<F>(&mut self, F) where F: core::ops::function::Fn([u8; 16], [u8; 16]) -> bool + core::marker::Send + 'static
pub fn rns_runtime::link_manager::LinkManager::set_link_packet_channel(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<(alloc::vec::Vec<u8>, [u8; 16])>)
pub fn rns_runtime::link_manager::LinkManager::set_link_packet_channel(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<(alloc::vec::Vec<u8>, [u8; 16])>) -> core::result::Result<(), rns_runtime::link_manager::LinkPacketConfigurationError>
pub fn rns_runtime::link_manager::LinkManager::set_link_packet_proof_channel(&mut self, tokio::sync::mpsc::bounded::Sender<rns_runtime::link_manager::LinkPacketProof>)
pub fn rns_runtime::link_manager::LinkManager::set_ordinary_packet_proof_strategy(&mut self, rns_identity::destination::ProofStrategy) -> core::result::Result<(), rns_runtime::link_manager::LinkPacketConfigurationError>
pub fn rns_runtime::link_manager::LinkManager::set_outbound_resource_proof_channel(&mut self, tokio::sync::mpsc::bounded::Sender<rns_runtime::link_manager::LinkResourceProof>)
pub fn rns_runtime::link_manager::LinkManager::set_request_handler<F>(&mut self, F) where F: core::ops::function::Fn([u8; 16], [u8; 16], alloc::vec::Vec<u8>) -> core::option::Option<alloc::vec::Vec<u8>> + core::marker::Send + 'static
pub fn rns_runtime::link_manager::LinkManager::set_request_handler_ex<F>(&mut self, F) where F: core::ops::function::Fn([u8; 16], [u8; 16], alloc::vec::Vec<u8>) -> rns_runtime::link_manager::RequestOutcome + core::marker::Send + 'static
@@ -616,6 +714,14 @@ pub fn rns_runtime::link_manager::LinkManager::with_destination(tokio::sync::mps
pub struct rns_runtime::link_manager::LinkPacketProof
pub rns_runtime::link_manager::LinkPacketProof::link_id: [u8; 16]
pub rns_runtime::link_manager::LinkPacketProof::packet_hash: [u8; 32]
pub struct rns_runtime::link_manager::LinkPacketReceipt
impl rns_runtime::link_manager::LinkPacketReceipt
pub fn rns_runtime::link_manager::LinkPacketReceipt::accept(self) -> tokio::sync::oneshot::Receiver<rns_runtime::link_manager::LinkPacketReceiptOutcome>
pub fn rns_runtime::link_manager::LinkPacketReceipt::close_without_proof(self) -> tokio::sync::oneshot::Receiver<rns_runtime::link_manager::LinkPacketReceiptOutcome>
pub fn rns_runtime::link_manager::LinkPacketReceipt::drop_without_proof(self)
pub fn rns_runtime::link_manager::LinkPacketReceipt::reject_and_close(self, rns_runtime::link_manager::LinkPacketRejection) -> tokio::sync::oneshot::Receiver<rns_runtime::link_manager::LinkPacketReceiptOutcome>
impl core::ops::drop::Drop for rns_runtime::link_manager::LinkPacketReceipt
pub fn rns_runtime::link_manager::LinkPacketReceipt::drop(&mut self)
pub struct rns_runtime::link_manager::LinkPacketSendReceipt
pub rns_runtime::link_manager::LinkPacketSendReceipt::link_id: [u8; 16]
pub rns_runtime::link_manager::LinkPacketSendReceipt::packet_hash: [u8; 32]
@@ -657,6 +763,7 @@ pub rns_runtime::link_session::LinkSessionError::PayloadTooLarge::actual: usize
pub rns_runtime::link_session::LinkSessionError::PayloadTooLarge::max: usize
pub rns_runtime::link_session::LinkSessionError::ProofInvalid(alloc::string::String)
pub rns_runtime::link_session::LinkSessionError::PublicKeyUnavailable
pub rns_runtime::link_session::LinkSessionError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::link_session::LinkSessionError::RequestRequiresResource
pub rns_runtime::link_session::LinkSessionError::RequestRequiresResource::actual: usize
pub rns_runtime::link_session::LinkSessionError::RequestRequiresResource::max: usize
@@ -697,6 +804,7 @@ pub rns_runtime::link_session::LinkSessionResourceDirection::Inbound
pub rns_runtime::link_session::LinkSessionResourceDirection::Outbound
pub enum rns_runtime::link_session::LinkSessionResourceError
pub rns_runtime::link_session::LinkSessionResourceError::Cancelled
pub rns_runtime::link_session::LinkSessionResourceError::Control(rns_protocol::resource::ResourceError)
pub rns_runtime::link_session::LinkSessionResourceError::Failed(alloc::string::String)
pub rns_runtime::link_session::LinkSessionResourceError::InvalidAdvertisement(alloc::string::String)
pub rns_runtime::link_session::LinkSessionResourceError::LinkCrypto
@@ -860,6 +968,7 @@ pub use rns_runtime::prelude::RNodeConfigurationState
pub use rns_runtime::prelude::RNodeDetectionState
pub use rns_runtime::prelude::RNodeFirmwareCompatibility
pub use rns_runtime::prelude::RNodeObservedRadioState
pub use rns_runtime::prelude::RNodePortFailureClass
pub use rns_runtime::prelude::RNodeRuntimePhase
pub use rns_runtime::prelude::RNodeRuntimeReason
pub use rns_runtime::prelude::RNodeRuntimeSnapshot
@@ -890,6 +999,7 @@ pub rns_runtime::prelude::DestinationRuntimeError::Destination(rns_identity::des
pub rns_runtime::prelude::DestinationRuntimeError::InvalidEventCapacity
pub rns_runtime::prelude::DestinationRuntimeError::LinkSend(rns_runtime::link_manager::LinkSendError)
pub rns_runtime::prelude::DestinationRuntimeError::ManagerUnavailable
pub rns_runtime::prelude::DestinationRuntimeError::OrdinaryPacketConfiguration(rns_runtime::link_manager::LinkPacketConfigurationError)
pub enum rns_runtime::prelude::LinkConnectError
pub rns_runtime::prelude::LinkConnectError::Control(rns_runtime::reticulum::ControlError)
pub rns_runtime::prelude::LinkConnectError::IdentityUnavailable(alloc::string::String)
@@ -916,6 +1026,7 @@ pub rns_runtime::prelude::LinkSessionError::PayloadTooLarge::actual: usize
pub rns_runtime::prelude::LinkSessionError::PayloadTooLarge::max: usize
pub rns_runtime::prelude::LinkSessionError::ProofInvalid(alloc::string::String)
pub rns_runtime::prelude::LinkSessionError::PublicKeyUnavailable
pub rns_runtime::prelude::LinkSessionError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::prelude::LinkSessionError::RequestRequiresResource
pub rns_runtime::prelude::LinkSessionError::RequestRequiresResource::actual: usize
pub rns_runtime::prelude::LinkSessionError::RequestRequiresResource::max: usize
@@ -953,6 +1064,7 @@ pub rns_runtime::prelude::LinkSessionEvent::ResourceStarted::total_segments: usi
pub rns_runtime::prelude::LinkSessionEvent::Stale
pub enum rns_runtime::prelude::LinkSessionResourceError
pub rns_runtime::prelude::LinkSessionResourceError::Cancelled
pub rns_runtime::prelude::LinkSessionResourceError::Control(rns_protocol::resource::ResourceError)
pub rns_runtime::prelude::LinkSessionResourceError::Failed(alloc::string::String)
pub rns_runtime::prelude::LinkSessionResourceError::InvalidAdvertisement(alloc::string::String)
pub rns_runtime::prelude::LinkSessionResourceError::LinkCrypto
@@ -1322,6 +1434,7 @@ pub enum rns_runtime::probe::ProbeError
pub rns_runtime::probe::ProbeError::EncryptError(alloc::string::String)
pub rns_runtime::probe::ProbeError::Internal(alloc::string::String)
pub rns_runtime::probe::ProbeError::InvalidName
pub rns_runtime::probe::ProbeError::InvalidTimeout
pub rns_runtime::probe::ProbeError::MtuExceeded(usize, usize)
pub rns_runtime::probe::ProbeError::NoIdentity
pub rns_runtime::probe::ProbeError::PacketTimeout
@@ -1333,61 +1446,13 @@ pub rns_runtime::probe::ProbeOutcome::hops: u8
pub rns_runtime::probe::ProbeOutcome::interface: core::option::Option<alloc::string::String>
pub rns_runtime::probe::ProbeOutcome::rtt: core::time::Duration
pub rns_runtime::probe::ProbeOutcome::via: core::option::Option<[u8; 16]>
pub fn rns_runtime::probe::checked_probe_timeout(f64) -> core::result::Result<core::time::Duration, rns_runtime::probe::ProbeError>
pub fn rns_runtime::probe::default_probe_app_name() -> &'static str
pub fn rns_runtime::probe::parse_dest_hash(&str) -> core::result::Result<[u8; 16], rns_runtime::probe::ProbeError>
pub async fn rns_runtime::probe::probe_once(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, [u8; 16], &str, usize, core::option::Option<core::time::Duration>, core::option::Option<core::time::Duration>, bool) -> core::result::Result<rns_runtime::probe::ProbeOutcome, rns_runtime::probe::ProbeError>
pub async fn rns_runtime::probe::spawn_probe_responder(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, rns_identity::identity::Identity, &str) -> core::result::Result<[u8; 16], rns_runtime::probe::ProbeError>
pub mod rns_runtime::remote_management
pub async fn rns_runtime::remote_management::start_remote_management(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, &rns_identity::identity::Identity, alloc::vec::Vec<[u8; 16]>) -> core::result::Result<[u8; 16], alloc::string::String>
pub mod rns_runtime::remote_management_schema
pub struct rns_runtime::remote_management_schema::InterfaceStats
pub rns_runtime::remote_management_schema::InterfaceStats::announce_queue: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::bitrate: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::blocked_ips: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::burst_activated: f64
pub rns_runtime::remote_management_schema::InterfaceStats::burst_active: bool
pub rns_runtime::remote_management_schema::InterfaceStats::clients: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::hash: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::InterfaceStats::held_announces: u64
pub rns_runtime::remote_management_schema::InterfaceStats::ifac_netname: core::option::Option<alloc::string::String>
pub rns_runtime::remote_management_schema::InterfaceStats::ifac_signature: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::InterfaceStats::ifac_size: core::option::Option<u64>
pub rns_runtime::remote_management_schema::InterfaceStats::incoming_announce_frequency: f64
pub rns_runtime::remote_management_schema::InterfaceStats::incoming_pr_frequency: f64
pub rns_runtime::remote_management_schema::InterfaceStats::mode: u8
pub rns_runtime::remote_management_schema::InterfaceStats::name: alloc::string::String
pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_announce_frequency: f64
pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_pr_frequency: f64
pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_activated: f64
pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_active: bool
pub rns_runtime::remote_management_schema::InterfaceStats::rxb: u64
pub rns_runtime::remote_management_schema::InterfaceStats::rxs: u64
pub rns_runtime::remote_management_schema::InterfaceStats::short_name: alloc::string::String
pub rns_runtime::remote_management_schema::InterfaceStats::status: bool
pub rns_runtime::remote_management_schema::InterfaceStats::txb: u64
pub rns_runtime::remote_management_schema::InterfaceStats::txs: u64
pub rns_runtime::remote_management_schema::InterfaceStats::type_: alloc::string::String
pub struct rns_runtime::remote_management_schema::PathEntry
pub rns_runtime::remote_management_schema::PathEntry::expires: f64
pub rns_runtime::remote_management_schema::PathEntry::hash: alloc::vec::Vec<u8>
pub rns_runtime::remote_management_schema::PathEntry::hops: u8
pub rns_runtime::remote_management_schema::PathEntry::interface: alloc::string::String
pub rns_runtime::remote_management_schema::PathEntry::timestamp: f64
pub rns_runtime::remote_management_schema::PathEntry::via: core::option::Option<alloc::vec::Vec<u8>>
pub struct rns_runtime::remote_management_schema::RateEntry
pub rns_runtime::remote_management_schema::RateEntry::hash: alloc::vec::Vec<u8>
pub rns_runtime::remote_management_schema::RateEntry::rate: f64
pub struct rns_runtime::remote_management_schema::TransportStats
pub rns_runtime::remote_management_schema::TransportStats::interfaces: alloc::vec::Vec<rns_runtime::remote_management_schema::InterfaceStats>
pub rns_runtime::remote_management_schema::TransportStats::network_id: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::TransportStats::probe_responder: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::TransportStats::rss: core::option::Option<u64>
pub rns_runtime::remote_management_schema::TransportStats::rxb: u64
pub rns_runtime::remote_management_schema::TransportStats::rxs: u64
pub rns_runtime::remote_management_schema::TransportStats::transport_id: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::remote_management_schema::TransportStats::transport_uptime: core::option::Option<f64>
pub rns_runtime::remote_management_schema::TransportStats::txb: u64
pub rns_runtime::remote_management_schema::TransportStats::txs: u64
pub mod rns_runtime::resource_source
pub enum rns_runtime::resource_source::ResourceSourceError
pub rns_runtime::resource_source::ResourceSourceError::Io(core::io::error::Error)
@@ -1567,6 +1632,7 @@ impl core::fmt::Debug for rns_runtime::reticulum::RecalledDestination
pub fn rns_runtime::reticulum::RecalledDestination::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_runtime::reticulum::ReticulumConfig
pub rns_runtime::reticulum::ReticulumConfig::autoconnect_discovered_interfaces: usize
pub rns_runtime::reticulum::ReticulumConfig::autoconnect_unverified_implementations: bool
pub rns_runtime::reticulum::ReticulumConfig::blackhole_sources: alloc::vec::Vec<[u8; 16]>
pub rns_runtime::reticulum::ReticulumConfig::blackhole_update_interval: f64
pub rns_runtime::reticulum::ReticulumConfig::bootstrap_configs: alloc::vec::Vec<std::path::PathBuf>
@@ -1682,6 +1748,8 @@ pub struct rns_runtime::reticulum::RuntimeInterfaceIfacConfig
pub rns_runtime::reticulum::RuntimeInterfaceIfacConfig::ifac_size: core::option::Option<usize>
pub rns_runtime::reticulum::RuntimeInterfaceIfacConfig::network_name: core::option::Option<alloc::string::String>
pub rns_runtime::reticulum::RuntimeInterfaceIfacConfig::passphrase: core::option::Option<alloc::string::String>
impl core::fmt::Debug for rns_runtime::reticulum::RuntimeInterfaceIfacConfig
pub fn rns_runtime::reticulum::RuntimeInterfaceIfacConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_runtime::reticulum::SendOptions
pub rns_runtime::reticulum::SendOptions::attached_interface: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_runtime::reticulum::SendOptions::create_receipt: bool
@@ -1743,6 +1811,7 @@ pub rns_runtime::rncp::RncpError::NoIdentity
pub rns_runtime::rncp::RncpError::NoSigningKey
pub rns_runtime::rncp::RncpError::PathTimeout
pub rns_runtime::rncp::RncpError::ProofInvalid(alloc::string::String)
pub rns_runtime::rncp::RncpError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::rncp::RncpError::ResourceCreate(alloc::string::String)
pub rns_runtime::rncp::RncpError::ResourceFailed(alloc::string::String)
pub rns_runtime::rncp::RncpError::Timeout(&'static str)
@@ -1840,6 +1909,7 @@ pub rns_runtime::rnsh::RnshError::PathTimeout
pub rns_runtime::rnsh::RnshError::Process(alloc::string::String)
pub rns_runtime::rnsh::RnshError::ProofInvalid(alloc::string::String)
pub rns_runtime::rnsh::RnshError::Remote(alloc::string::String)
pub rns_runtime::rnsh::RnshError::RequestDispatch(rns_transport::link_messages::LinkRequestDispatchError)
pub rns_runtime::rnsh::RnshError::Timeout(&'static str)
pub rns_runtime::rnsh::RnshError::TransportUnavailable
impl core::convert::From<rns_protocol::channel::ChannelError> for rns_runtime::rnsh::RnshError
@@ -1961,6 +2031,9 @@ pub rns_runtime::rpc::InterfaceStatEntry::announce_queue: core::option::Option<u
pub rns_runtime::rpc::InterfaceStatEntry::announce_rate_grace: core::option::Option<u32>
pub rns_runtime::rpc::InterfaceStatEntry::announce_rate_penalty: core::option::Option<f64>
pub rns_runtime::rpc::InterfaceStatEntry::announce_rate_target: core::option::Option<f64>
pub rns_runtime::rpc::InterfaceStatEntry::announces_received: u64
pub rns_runtime::rpc::InterfaceStatEntry::announces_sent: u64
pub rns_runtime::rpc::InterfaceStatEntry::autoconnect_source: core::option::Option<alloc::string::String>
pub rns_runtime::rpc::InterfaceStatEntry::bitrate: u64
pub rns_runtime::rpc::InterfaceStatEntry::blocked_ips: core::option::Option<u64>
pub rns_runtime::rpc::InterfaceStatEntry::burst_activated: f64
@@ -1968,7 +2041,10 @@ pub rns_runtime::rpc::InterfaceStatEntry::burst_active: bool
pub rns_runtime::rpc::InterfaceStatEntry::clients: core::option::Option<u64>
pub rns_runtime::rpc::InterfaceStatEntry::held_announces: u64
pub rns_runtime::rpc::InterfaceStatEntry::id: u64
pub rns_runtime::rpc::InterfaceStatEntry::ifac_size: usize
pub rns_runtime::rpc::InterfaceStatEntry::ifac_netname: core::option::Option<alloc::string::String>
pub rns_runtime::rpc::InterfaceStatEntry::ifac_signature: core::option::Option<alloc::vec::Vec<u8>>
pub rns_runtime::rpc::InterfaceStatEntry::ifac_size: core::option::Option<usize>
pub rns_runtime::rpc::InterfaceStatEntry::ifac_violations: u64
pub rns_runtime::rpc::InterfaceStatEntry::incoming_announce_frequency: f64
pub rns_runtime::rpc::InterfaceStatEntry::incoming_pr_frequency: f64
pub rns_runtime::rpc::InterfaceStatEntry::mode: alloc::string::String
@@ -1977,12 +2053,18 @@ pub rns_runtime::rpc::InterfaceStatEntry::name: alloc::string::String
pub rns_runtime::rpc::InterfaceStatEntry::online: bool
pub rns_runtime::rpc::InterfaceStatEntry::outgoing_announce_frequency: f64
pub rns_runtime::rpc::InterfaceStatEntry::outgoing_pr_frequency: f64
pub rns_runtime::rpc::InterfaceStatEntry::packet_filter_hits: u64
pub rns_runtime::rpc::InterfaceStatEntry::parent_interface_name: core::option::Option<alloc::string::String>
pub rns_runtime::rpc::InterfaceStatEntry::path_requests_received: u64
pub rns_runtime::rpc::InterfaceStatEntry::path_requests_sent: u64
pub rns_runtime::rpc::InterfaceStatEntry::pr_burst_activated: f64
pub rns_runtime::rpc::InterfaceStatEntry::pr_burst_active: bool
pub rns_runtime::rpc::InterfaceStatEntry::protocol_violations: u64
pub rns_runtime::rpc::InterfaceStatEntry::role: alloc::string::String
pub rns_runtime::rpc::InterfaceStatEntry::rx_bytes: u64
pub rns_runtime::rpc::InterfaceStatEntry::rx_rate: u64
pub rns_runtime::rpc::InterfaceStatEntry::tx_bytes: u64
pub rns_runtime::rpc::InterfaceStatEntry::tx_dropped_bytes: u64
pub rns_runtime::rpc::InterfaceStatEntry::tx_drops: u64
pub rns_runtime::rpc::InterfaceStatEntry::tx_rate: u64
pub struct rns_runtime::rpc::PathTableEntry
+251 -6
View File
@@ -55,7 +55,6 @@ pub rns_transport::actor::TransportActor::path_waiters: std::collections::hash::
pub rns_transport::actor::TransportActor::pending_discovery_prs: alloc::collections::vec_deque::VecDeque<rns_transport::actor::PendingDiscoveryPathRequest>
pub rns_transport::actor::TransportActor::pending_local_path_requests: std::collections::hash::map::HashMap<[u8; 16], rns_transport::messages::InterfaceId>
pub rns_transport::actor::TransportActor::pending_path_entries: alloc::vec::Vec<rns_transport::persistence::PersistedPathEntry>
pub rns_transport::actor::TransportActor::pending_tunnel_entries: alloc::vec::Vec<rns_transport::persistence::PersistedTunnelEntry>
pub rns_transport::actor::TransportActor::rate_table: rns_transport::rate_limit::RateTable
pub rns_transport::actor::TransportActor::receipt_msg_ids: std::collections::hash::map::HashMap<[u8; 16], alloc::string::String>
pub rns_transport::actor::TransportActor::receipt_proof_txs: std::collections::hash::map::HashMap<[u8; 16], tokio::sync::mpsc::unbounded::UnboundedSender<rns_transport::link_messages::DestinationEvent>>
@@ -306,6 +305,7 @@ pub fn rns_transport::discovery::announcer::Announcer::is_empty(&self) -> bool
pub fn rns_transport::discovery::announcer::Announcer::len(&self) -> usize
pub fn rns_transport::discovery::announcer::Announcer::new(alloc::sync::Arc<dyn rns_transport::discovery::stamper::DiscoveryStamper>) -> Self
pub fn rns_transport::discovery::announcer::Announcer::prepare(&mut self, f64, core::option::Option<rns_transport::discovery::announcer::EncryptFn<'_>>) -> (alloc::vec::Vec<rns_transport::discovery::announcer::PreparedAnnounce>, alloc::vec::Vec<(rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::SkipReason)>)
pub fn rns_transport::discovery::announcer::Announcer::reconfigure(&mut self, rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::DiscoveryInterfaceConfig) -> bool
pub fn rns_transport::discovery::announcer::Announcer::register(&mut self, rns_transport::messages::InterfaceId, [u8; 16], rns_transport::discovery::announcer::DiscoveryInterfaceConfig)
pub fn rns_transport::discovery::announcer::Announcer::tick(&mut self, f64, core::option::Option<rns_transport::discovery::announcer::EncryptFn<'_>>) -> (alloc::vec::Vec<rns_transport::discovery::announcer::AnnounceRequest>, alloc::vec::Vec<(rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::SkipReason)>)
pub struct rns_transport::discovery::announcer::DiscoveryInterfaceConfig
@@ -360,6 +360,8 @@ pub rns_transport::discovery::app_data::DiscoveryInfo::frequency: core::option::
pub rns_transport::discovery::app_data::DiscoveryInfo::height: core::option::Option<f64>
pub rns_transport::discovery::app_data::DiscoveryInfo::ifac_netkey: core::option::Option<alloc::string::String>
pub rns_transport::discovery::app_data::DiscoveryInfo::ifac_netname: core::option::Option<alloc::string::String>
pub rns_transport::discovery::app_data::DiscoveryInfo::impl_name: core::option::Option<alloc::string::String>
pub rns_transport::discovery::app_data::DiscoveryInfo::impl_version: core::option::Option<alloc::string::String>
pub rns_transport::discovery::app_data::DiscoveryInfo::interface_type: alloc::string::String
pub rns_transport::discovery::app_data::DiscoveryInfo::latitude: core::option::Option<f64>
pub rns_transport::discovery::app_data::DiscoveryInfo::longitude: core::option::Option<f64>
@@ -381,6 +383,8 @@ pub fn rns_transport::discovery::app_data::sanitize_name(&str) -> alloc::string:
pub fn rns_transport::discovery::app_data::split_flags(&[u8]) -> core::result::Result<(u8, &[u8]), rns_transport::discovery::app_data::AppDataError>
pub fn rns_transport::discovery::app_data::split_stamp(&[u8]) -> core::result::Result<(&[u8], &[u8]), rns_transport::discovery::app_data::AppDataError>
pub type rns_transport::discovery::app_data::DiscoveryEncryptor<'a> = (dyn core::ops::function::Fn(&[u8]) -> core::option::Option<alloc::vec::Vec<u8>> + 'a)
pub mod rns_transport::discovery::autoconnect
pub fn rns_transport::discovery::autoconnect::qualifies(&rns_transport::discovery::app_data::DiscoveryInfo, bool) -> bool
pub mod rns_transport::discovery::blackhole_manifest
pub enum rns_transport::discovery::blackhole_manifest::ManifestError
pub rns_transport::discovery::blackhole_manifest::ManifestError::BadField(&'static str)
@@ -432,9 +436,12 @@ pub const rns_transport::discovery::constants::key::REACHABLE_ON: u8
pub const rns_transport::discovery::constants::key::SPREADING_FACTOR: u8
pub const rns_transport::discovery::constants::key::TRANSPORT: u8
pub const rns_transport::discovery::constants::key::TRANSPORT_ID: u8
pub const rns_transport::discovery::constants::key::TRANSPORT_IMPL: u8
pub const rns_transport::discovery::constants::key::TRANSPORT_VERS: u8
pub const rns_transport::discovery::constants::ANNOUNCE_JOB_INTERVAL_SECS: u64
pub const rns_transport::discovery::constants::APP_NAME: &str
pub const rns_transport::discovery::constants::AUTOCONNECT_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::constants::AUTOCONNECT_MINIMUM_VERSIONS: &[(&str, core::option::Option<&str>)]
pub const rns_transport::discovery::constants::BLACKHOLE_ASPECTS: &[&str]
pub const rns_transport::discovery::constants::BLACKHOLE_ASPECT_FILTER: &str
pub const rns_transport::discovery::constants::BLACKHOLE_INITIAL_WAIT_SECS: u64
@@ -444,10 +451,13 @@ pub const rns_transport::discovery::constants::BLACKHOLE_UPDATE_INTERVAL_SECS: u
pub const rns_transport::discovery::constants::DEFAULT_STAMP_VALUE: u8
pub const rns_transport::discovery::constants::DETACH_THRESHOLD_TICKS: u64
pub const rns_transport::discovery::constants::DISCOVERABLE_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::constants::DISCOVERED_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::constants::DISCOVERY_ASPECTS: &[&str]
pub const rns_transport::discovery::constants::DISCOVERY_ASPECT_FILTER: &str
pub const rns_transport::discovery::constants::FLAG_ENCRYPTED: u8
pub const rns_transport::discovery::constants::FLAG_SIGNED: u8
pub const rns_transport::discovery::constants::IMPLEMENTATION_NAME: &str
pub const rns_transport::discovery::constants::IMPLEMENTATION_VERSION: &str
pub const rns_transport::discovery::constants::MONITOR_INTERVAL_SECS: u64
pub const rns_transport::discovery::constants::STAMP_SIZE: usize
pub const rns_transport::discovery::constants::THRESHOLD_REMOVE_SECS: u64
@@ -472,11 +482,13 @@ pub const rns_transport::discovery::key::REACHABLE_ON: u8
pub const rns_transport::discovery::key::SPREADING_FACTOR: u8
pub const rns_transport::discovery::key::TRANSPORT: u8
pub const rns_transport::discovery::key::TRANSPORT_ID: u8
pub const rns_transport::discovery::key::TRANSPORT_IMPL: u8
pub const rns_transport::discovery::key::TRANSPORT_VERS: u8
pub mod rns_transport::discovery::receiver
pub enum rns_transport::discovery::receiver::Outcome
pub rns_transport::discovery::receiver::Outcome::Accepted
pub rns_transport::discovery::receiver::Outcome::Rejected(rns_transport::discovery::receiver::Reason)
pub enum rns_transport::discovery::receiver::Reason
#[non_exhaustive] pub enum rns_transport::discovery::receiver::Reason
pub rns_transport::discovery::receiver::Reason::DecodeFailed
pub rns_transport::discovery::receiver::Reason::DecryptFailed
pub rns_transport::discovery::receiver::Reason::EncryptedWithoutKey
@@ -485,6 +497,7 @@ pub rns_transport::discovery::receiver::Reason::MissingAppData
pub rns_transport::discovery::receiver::Reason::StampInvalid
pub rns_transport::discovery::receiver::Reason::StorageFailed
pub rns_transport::discovery::receiver::Reason::UnauthorizedSource
pub rns_transport::discovery::receiver::Reason::UnlistedType
pub rns_transport::discovery::receiver::Reason::ValidationBusy
pub struct rns_transport::discovery::receiver::ReceiverConfig
pub rns_transport::discovery::receiver::ReceiverConfig::decryptor: core::option::Option<alloc::sync::Arc<dyn rns_transport::discovery::receiver::DiscoveryDecryptor>>
@@ -575,7 +588,7 @@ pub rns_transport::discovery::ManifestError::NotAMap
pub enum rns_transport::discovery::Outcome
pub rns_transport::discovery::Outcome::Accepted
pub rns_transport::discovery::Outcome::Rejected(rns_transport::discovery::receiver::Reason)
pub enum rns_transport::discovery::Reason
#[non_exhaustive] pub enum rns_transport::discovery::Reason
pub rns_transport::discovery::Reason::DecodeFailed
pub rns_transport::discovery::Reason::DecryptFailed
pub rns_transport::discovery::Reason::EncryptedWithoutKey
@@ -584,6 +597,7 @@ pub rns_transport::discovery::Reason::MissingAppData
pub rns_transport::discovery::Reason::StampInvalid
pub rns_transport::discovery::Reason::StorageFailed
pub rns_transport::discovery::Reason::UnauthorizedSource
pub rns_transport::discovery::Reason::UnlistedType
pub rns_transport::discovery::Reason::ValidationBusy
pub enum rns_transport::discovery::SkipReason
pub rns_transport::discovery::SkipReason::EncryptionFailed
@@ -605,6 +619,7 @@ pub fn rns_transport::discovery::announcer::Announcer::is_empty(&self) -> bool
pub fn rns_transport::discovery::announcer::Announcer::len(&self) -> usize
pub fn rns_transport::discovery::announcer::Announcer::new(alloc::sync::Arc<dyn rns_transport::discovery::stamper::DiscoveryStamper>) -> Self
pub fn rns_transport::discovery::announcer::Announcer::prepare(&mut self, f64, core::option::Option<rns_transport::discovery::announcer::EncryptFn<'_>>) -> (alloc::vec::Vec<rns_transport::discovery::announcer::PreparedAnnounce>, alloc::vec::Vec<(rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::SkipReason)>)
pub fn rns_transport::discovery::announcer::Announcer::reconfigure(&mut self, rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::DiscoveryInterfaceConfig) -> bool
pub fn rns_transport::discovery::announcer::Announcer::register(&mut self, rns_transport::messages::InterfaceId, [u8; 16], rns_transport::discovery::announcer::DiscoveryInterfaceConfig)
pub fn rns_transport::discovery::announcer::Announcer::tick(&mut self, f64, core::option::Option<rns_transport::discovery::announcer::EncryptFn<'_>>) -> (alloc::vec::Vec<rns_transport::discovery::announcer::AnnounceRequest>, alloc::vec::Vec<(rns_transport::messages::InterfaceId, rns_transport::discovery::announcer::SkipReason)>)
pub struct rns_transport::discovery::BlackholeManifestEntry
@@ -684,6 +699,7 @@ pub fn rns_transport::discovery::receiver::ReceiverConfig::process_event(&self,
pub const rns_transport::discovery::ANNOUNCE_JOB_INTERVAL_SECS: u64
pub const rns_transport::discovery::APP_NAME: &str
pub const rns_transport::discovery::AUTOCONNECT_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::AUTOCONNECT_MINIMUM_VERSIONS: &[(&str, core::option::Option<&str>)]
pub const rns_transport::discovery::BLACKHOLE_ASPECTS: &[&str]
pub const rns_transport::discovery::BLACKHOLE_ASPECT_FILTER: &str
pub const rns_transport::discovery::BLACKHOLE_INITIAL_WAIT: core::time::Duration
@@ -697,10 +713,13 @@ pub const rns_transport::discovery::BLACKHOLE_UPDATE_INTERVAL_SECS: u64
pub const rns_transport::discovery::DEFAULT_STAMP_VALUE: u8
pub const rns_transport::discovery::DETACH_THRESHOLD_TICKS: u64
pub const rns_transport::discovery::DISCOVERABLE_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::DISCOVERED_INTERFACE_TYPES: &[&str]
pub const rns_transport::discovery::DISCOVERY_ASPECTS: &[&str]
pub const rns_transport::discovery::DISCOVERY_ASPECT_FILTER: &str
pub const rns_transport::discovery::FLAG_ENCRYPTED: u8
pub const rns_transport::discovery::FLAG_SIGNED: u8
pub const rns_transport::discovery::IMPLEMENTATION_NAME: &str
pub const rns_transport::discovery::IMPLEMENTATION_VERSION: &str
pub const rns_transport::discovery::MONITOR_INTERVAL_SECS: u64
pub const rns_transport::discovery::STAMP_SIZE: usize
pub const rns_transport::discovery::THRESHOLD_REMOVE_SECS: u64
@@ -738,9 +757,15 @@ pub fn rns_transport::hashlist::PacketHashlist::new_with_capacity(usize) -> Self
impl core::default::Default for rns_transport::hashlist::PacketHashlist
pub fn rns_transport::hashlist::PacketHashlist::default() -> Self
pub mod rns_transport::ifac
pub enum rns_transport::ifac::IfacSignError
pub rns_transport::ifac::IfacSignError::InvalidTagSize
pub rns_transport::ifac::IfacSignError::PacketTooLarge
pub rns_transport::ifac::IfacSignError::ShortPacket
pub const rns_transport::ifac::MAX_IFAC_WIRE_BYTES: usize
pub fn rns_transport::ifac::has_ifac_flag(&[u8]) -> bool
pub fn rns_transport::ifac::ifac_sign(&[u8], &[u8; 64], usize) -> alloc::vec::Vec<u8>
pub fn rns_transport::ifac::ifac_verify(&[u8], &[u8; 64], usize) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_transport::ifac::try_ifac_sign(&[u8], &[u8; 64], usize) -> core::result::Result<alloc::vec::Vec<u8>, rns_transport::ifac::IfacSignError>
pub mod rns_transport::ingress
pub struct rns_transport::ingress::HeldAnnounce
pub rns_transport::ingress::HeldAnnounce::destination_hash: [u8; 16]
@@ -750,6 +775,8 @@ pub rns_transport::ingress::HeldAnnounce::receiving_interface_id: u64
pub struct rns_transport::ingress::IngressController
impl rns_transport::ingress::IngressController
pub fn rns_transport::ingress::IngressController::age(&self) -> f64
pub fn rns_transport::ingress::IngressController::announces_received(&self) -> u64
pub fn rns_transport::ingress::IngressController::announces_sent(&self) -> u64
pub fn rns_transport::ingress::IngressController::burst_activated(&self) -> std::time::Instant
pub fn rns_transport::ingress::IngressController::burst_freq(&self) -> f64
pub fn rns_transport::ingress::IngressController::burst_freq_new(&self) -> f64
@@ -768,6 +795,8 @@ pub fn rns_transport::ingress::IngressController::is_pr_burst_active(&self) -> b
pub fn rns_transport::ingress::IngressController::new() -> Self
pub fn rns_transport::ingress::IngressController::outgoing_announce_frequency(&self) -> f64
pub fn rns_transport::ingress::IngressController::outgoing_pr_frequency(&self) -> f64
pub fn rns_transport::ingress::IngressController::path_requests_received(&self) -> u64
pub fn rns_transport::ingress::IngressController::path_requests_sent(&self) -> u64
pub fn rns_transport::ingress::IngressController::pr_burst_activated(&self) -> std::time::Instant
pub fn rns_transport::ingress::IngressController::pr_burst_freq(&self) -> f64
pub fn rns_transport::ingress::IngressController::pr_burst_freq_new(&self) -> f64
@@ -779,9 +808,12 @@ pub fn rns_transport::ingress::IngressController::should_egress_limit_pr(&mut se
pub fn rns_transport::ingress::IngressController::should_ingress_limit(&mut self) -> bool
pub fn rns_transport::ingress::IngressController::should_ingress_limit_pr(&mut self) -> bool
pub fn rns_transport::ingress::IngressController::try_release_held(&mut self) -> core::option::Option<rns_transport::ingress::HeldAnnounce>
pub fn rns_transport::ingress::IngressController::try_with_overrides(&rns_transport::ingress::IngressOverrides) -> core::result::Result<Self, rns_transport::ingress::IngressOverrideError>
pub fn rns_transport::ingress::IngressController::with_overrides(&rns_transport::ingress::IngressOverrides) -> Self
impl core::default::Default for rns_transport::ingress::IngressController
pub fn rns_transport::ingress::IngressController::default() -> Self
pub struct rns_transport::ingress::IngressOverrideError
pub rns_transport::ingress::IngressOverrideError::field: &'static str
pub struct rns_transport::ingress::IngressOverrides
pub rns_transport::ingress::IngressOverrides::burst_freq: core::option::Option<f64>
pub rns_transport::ingress::IngressOverrides::burst_freq_new: core::option::Option<f64>
@@ -797,6 +829,60 @@ pub rns_transport::ingress::IngressOverrides::pr_burst_freq: core::option::Optio
pub rns_transport::ingress::IngressOverrides::pr_burst_freq_new: core::option::Option<f64>
impl rns_transport::ingress::IngressOverrides
pub fn rns_transport::ingress::IngressOverrides::is_empty(&self) -> bool
pub fn rns_transport::ingress::IngressOverrides::validate(&self) -> core::result::Result<(), rns_transport::ingress::IngressOverrideError>
pub mod rns_transport::interface_ownership
pub enum rns_transport::interface_ownership::InterfaceCapacityError
pub rns_transport::interface_ownership::InterfaceCapacityError::Empty
pub rns_transport::interface_ownership::InterfaceCapacityError::IfacExceedsWire
pub rns_transport::interface_ownership::InterfaceCapacityError::IfacExceedsWire::ifac_bytes: usize
pub rns_transport::interface_ownership::InterfaceCapacityError::IfacExceedsWire::wire_bytes: u32
pub rns_transport::interface_ownership::InterfaceCapacityError::InvalidIfac
pub rns_transport::interface_ownership::InterfaceCapacityError::LinkCapacityUnavailable
pub rns_transport::interface_ownership::InterfaceCapacityError::LinkCapacityUnavailable::clear_mtu: u32
pub rns_transport::interface_ownership::InterfaceCapacityError::LinkCapacityUnavailable::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::interface_ownership::InterfaceCapacityError::LinkCapacityUnavailable::required: u32
pub struct rns_transport::interface_ownership::InterfaceOwner
impl rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::epoch(&self) -> u64
pub fn rns_transport::interface_ownership::InterfaceOwner::id(&self) -> rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwner::is_current(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::is_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::mark_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::new() -> Self
pub fn rns_transport::interface_ownership::InterfaceOwner::next_revision(&self) -> core::option::Option<Self>
pub fn rns_transport::interface_ownership::InterfaceOwner::revision(&self) -> u64
impl core::cmp::Eq for rns_transport::interface_ownership::InterfaceOwner
impl core::cmp::PartialEq for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::eq(&self, &Self) -> bool
impl core::default::Default for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::default() -> Self
pub struct rns_transport::interface_ownership::InterfaceOwnerId
impl rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwnerId::matches(self, &rns_transport::interface_ownership::InterfaceOwner) -> bool
pub struct rns_transport::interface_ownership::InterfacePacketCapacity
pub rns_transport::interface_ownership::InterfacePacketCapacity::link_mtu_upgrade: bool
pub rns_transport::interface_ownership::InterfacePacketCapacity::max_clear_packet_bytes: u32
pub rns_transport::interface_ownership::InterfacePacketCapacity::max_wire_packet_bytes: u32
impl rns_transport::interface_ownership::InterfacePacketCapacity
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::base(u32) -> Self
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::effective_clear_mtu(self, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::link_ceiling(self, rns_transport::messages::InterfaceId, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::new(u32, u32, bool) -> Self
pub struct rns_transport::interface_ownership::InterfaceTransportSender
impl rns_transport::interface_ownership::InterfaceTransportSender
pub fn rns_transport::interface_ownership::InterfaceTransportSender::actor_sender(&self) -> tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::bind(rns_transport::messages::InterfaceId, rns_transport::interface_ownership::InterfaceOwner, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::capacity(&self) -> usize
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::closed(&self)
pub fn rns_transport::interface_ownership::InterfaceTransportSender::event(&self, rns_transport::messages::TransportMessage) -> rns_transport::messages::TransportMessage
pub fn rns_transport::interface_ownership::InterfaceTransportSender::interface_id(&self) -> rns_transport::messages::InterfaceId
pub fn rns_transport::interface_ownership::InterfaceTransportSender::is_closed(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceTransportSender::max_capacity(&self) -> usize
pub fn rns_transport::interface_ownership::InterfaceTransportSender::new(rns_transport::messages::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::owner(&self) -> rns_transport::interface_ownership::InterfaceOwner
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::ready(&self) -> bool
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::SendError<rns_transport::messages::TransportMessage>>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::try_send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::TrySendError<rns_transport::messages::TransportMessage>>
pub mod rns_transport::link_endpoint_dispatch
#[non_exhaustive] pub enum rns_transport::link_endpoint_dispatch::LinkEndpointDispatchError
pub rns_transport::link_endpoint_dispatch::LinkEndpointDispatchError::Closed
@@ -841,6 +927,7 @@ pub rns_transport::link_messages::DestinationEvent::DeliveryProof::msg_id: alloc
pub rns_transport::link_messages::DestinationEvent::DeliveryProof::rtt: core::option::Option<core::time::Duration>
pub rns_transport::link_messages::DestinationEvent::InboundPacket
pub rns_transport::link_messages::DestinationEvent::InboundPacket::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::link_messages::DestinationEvent::InboundPacket::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwnerId>
pub rns_transport::link_messages::DestinationEvent::InboundPacket::metrics: rns_transport::link_messages::PacketMetrics
pub rns_transport::link_messages::DestinationEvent::InboundPacket::raw: bytes::bytes::Bytes
pub rns_transport::link_messages::DestinationEvent::LinkClosed
@@ -849,8 +936,14 @@ pub rns_transport::link_messages::DestinationEvent::LinkEstablished
pub rns_transport::link_messages::DestinationEvent::LinkEstablished::link_id: [u8; 16]
pub rns_transport::link_messages::DestinationEvent::LinkRequest
pub rns_transport::link_messages::DestinationEvent::LinkRequest::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::link_messages::DestinationEvent::LinkRequest::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwnerId>
pub rns_transport::link_messages::DestinationEvent::LinkRequest::metrics: rns_transport::link_messages::PacketMetrics
pub rns_transport::link_messages::DestinationEvent::LinkRequest::raw: bytes::bytes::Bytes
pub enum rns_transport::link_messages::LinkRequestDispatchError
pub rns_transport::link_messages::LinkRequestDispatchError::Capacity(rns_transport::interface_ownership::InterfaceCapacityError)
pub rns_transport::link_messages::LinkRequestDispatchError::InvalidRequest
pub rns_transport::link_messages::LinkRequestDispatchError::NoInterface
pub rns_transport::link_messages::LinkRequestDispatchError::TransportUnavailable
pub struct rns_transport::link_messages::AnnounceRequest
pub rns_transport::link_messages::AnnounceRequest::app_name: alloc::string::String
pub rns_transport::link_messages::AnnounceRequest::attached_interface: core::option::Option<rns_transport::messages::InterfaceId>
@@ -868,6 +961,7 @@ pub struct rns_transport::link_messages::PacketMetrics
pub rns_transport::link_messages::PacketMetrics::q: core::option::Option<f32>
pub rns_transport::link_messages::PacketMetrics::rssi: core::option::Option<f32>
pub rns_transport::link_messages::PacketMetrics::snr: core::option::Option<f32>
pub async fn rns_transport::link_messages::dispatch_link_request(&tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, rns_transport::messages::OutboundRequest) -> core::result::Result<(), rns_transport::link_messages::LinkRequestDispatchError>
pub mod rns_transport::link_table
pub struct rns_transport::link_table::ExpiredLink
pub rns_transport::link_table::ExpiredLink::destination_hash: [u8; 16]
@@ -879,13 +973,17 @@ pub rns_transport::link_table::ExpiredLink::taken_hops: u8
impl core::convert::From<&rns_transport::link_table::LinkEntry> for rns_transport::link_table::ExpiredLink
pub fn rns_transport::link_table::ExpiredLink::from(&rns_transport::link_table::LinkEntry) -> Self
pub struct rns_transport::link_table::LinkEntry
pub rns_transport::link_table::LinkEntry::accepted_mtu_ceiling: u32
pub rns_transport::link_table::LinkEntry::destination_hash: [u8; 16]
pub rns_transport::link_table::LinkEntry::established: bool
pub rns_transport::link_table::LinkEntry::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::link_table::LinkEntry::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwner>
pub rns_transport::link_table::LinkEntry::next_hop: core::option::Option<[u8; 16]>
pub rns_transport::link_table::LinkEntry::proof_timeout: f64
pub rns_transport::link_table::LinkEntry::receiving_interface: rns_transport::messages::InterfaceId
pub rns_transport::link_table::LinkEntry::receiving_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwner>
pub rns_transport::link_table::LinkEntry::remaining_hops: u8
pub rns_transport::link_table::LinkEntry::requested_mode: u8
pub rns_transport::link_table::LinkEntry::taken_hops: u8
pub rns_transport::link_table::LinkEntry::timestamp: f64
pub rns_transport::link_table::LinkEntry::validated: bool
@@ -904,9 +1002,26 @@ pub fn rns_transport::link_table::LinkTable::iter(&self) -> impl core::iter::tra
pub fn rns_transport::link_table::LinkTable::len(&self) -> usize
pub fn rns_transport::link_table::LinkTable::new() -> Self
pub fn rns_transport::link_table::LinkTable::remove(&mut self, &[u8; 16]) -> core::option::Option<rns_transport::link_table::LinkEntry>
pub fn rns_transport::link_table::LinkTable::remove_interface(&mut self, rns_transport::messages::InterfaceId)
impl core::default::Default for rns_transport::link_table::LinkTable
pub fn rns_transport::link_table::LinkTable::default() -> Self
pub mod rns_transport::link_transit
pub enum rns_transport::link_transit::LinkTransitError
pub rns_transport::link_transit::LinkTransitError::Capacity(rns_transport::interface_ownership::InterfaceCapacityError)
pub rns_transport::link_transit::LinkTransitError::InvalidSignalling(rns_wire::link_signalling::LinkSignallingError)
pub rns_transport::link_transit::LinkTransitError::StaleInterface
pub rns_transport::link_transit::LinkTransitError::UnsupportedTransitModeTransform
pub mod rns_transport::messages
pub enum rns_transport::messages::InterfaceCapacityError
pub rns_transport::messages::InterfaceCapacityError::Empty
pub rns_transport::messages::InterfaceCapacityError::IfacExceedsWire
pub rns_transport::messages::InterfaceCapacityError::IfacExceedsWire::ifac_bytes: usize
pub rns_transport::messages::InterfaceCapacityError::IfacExceedsWire::wire_bytes: u32
pub rns_transport::messages::InterfaceCapacityError::InvalidIfac
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable::clear_mtu: u32
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::messages::InterfaceCapacityError::LinkCapacityUnavailable::required: u32
pub enum rns_transport::messages::InterfaceRole
pub rns_transport::messages::InterfaceRole::LocalClient
pub rns_transport::messages::InterfaceRole::Normal
@@ -979,6 +1094,10 @@ pub rns_transport::messages::TransportMessage::DeregisterDestination::hash: [u8;
pub rns_transport::messages::TransportMessage::DeregisterInterface
pub rns_transport::messages::TransportMessage::DeregisterInterface::id: rns_transport::messages::InterfaceId
pub rns_transport::messages::TransportMessage::Inbound(rns_transport::messages::InboundPacket)
pub rns_transport::messages::TransportMessage::InterfaceEvent
pub rns_transport::messages::TransportMessage::InterfaceEvent::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::messages::TransportMessage::InterfaceEvent::message: alloc::boxed::Box<rns_transport::messages::TransportMessage>
pub rns_transport::messages::TransportMessage::InterfaceEvent::owner: rns_transport::interface_ownership::InterfaceOwner
pub rns_transport::messages::TransportMessage::Outbound(rns_transport::messages::OutboundRequest)
pub rns_transport::messages::TransportMessage::OutboundAttached
pub rns_transport::messages::TransportMessage::OutboundAttached::interface_id: rns_transport::messages::InterfaceId
@@ -1004,6 +1123,7 @@ pub rns_transport::messages::TransportMessage::RegisterLink
pub rns_transport::messages::TransportMessage::RegisterLink::destination_hash: [u8; 16]
pub rns_transport::messages::TransportMessage::RegisterLink::initiator: bool
pub rns_transport::messages::TransportMessage::RegisterLink::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::messages::TransportMessage::RegisterLink::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwnerId>
pub rns_transport::messages::TransportMessage::RegisterLink::link_id: [u8; 16]
pub rns_transport::messages::TransportMessage::RegisterLink::next_hop: core::option::Option<[u8; 16]>
pub rns_transport::messages::TransportMessage::RegisterLink::remaining_hops: u8
@@ -1045,6 +1165,13 @@ pub rns_transport::messages::TransportMessage::SendLinkEndpointBestEffort::link_
pub rns_transport::messages::TransportMessage::SendLinkEndpointBestEffort::request: rns_transport::messages::OutboundRequest
pub rns_transport::messages::TransportMessage::SendLinkEndpointBestEffort::result_tx: tokio::sync::oneshot::Sender<rns_transport::messages::LinkEndpointSendResult>
pub rns_transport::messages::TransportMessage::SendLinkEndpointBestEffort::role: rns_transport::messages::LinkEndpointRole
pub rns_transport::messages::TransportMessage::SendLinkEndpointExact
pub rns_transport::messages::TransportMessage::SendLinkEndpointExact::authority: rns_transport::link_endpoint_dispatch::LinkEndpointDispatchToken
pub rns_transport::messages::TransportMessage::SendLinkEndpointExact::request: rns_transport::messages::OutboundRequest
pub rns_transport::messages::TransportMessage::SendLinkEndpointExact::result_tx: tokio::sync::oneshot::Sender<rns_transport::messages::LinkEndpointSendResult>
pub rns_transport::messages::TransportMessage::SendLinkRequest
pub rns_transport::messages::TransportMessage::SendLinkRequest::request: rns_transport::messages::OutboundRequest
pub rns_transport::messages::TransportMessage::SendLinkRequest::result_tx: tokio::sync::oneshot::Sender<core::result::Result<(), rns_transport::link_messages::LinkRequestDispatchError>>
pub rns_transport::messages::TransportMessage::SendPacket
pub rns_transport::messages::TransportMessage::SendPacket::attached_interface: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_transport::messages::TransportMessage::SendPacket::receipt: core::option::Option<rns_transport::messages::TrackedReceiptRegistration>
@@ -1235,8 +1362,9 @@ pub rns_transport::messages::InterfaceEntry::announce_rate_target: core::option:
pub rns_transport::messages::InterfaceEntry::announces_from_internal: bool
pub rns_transport::messages::InterfaceEntry::bitrate: u64
pub rns_transport::messages::InterfaceEntry::direction: rns_transport::constants::InterfaceDirection
pub rns_transport::messages::InterfaceEntry::ifac_key: core::option::Option<[u8; 64]>
pub rns_transport::messages::InterfaceEntry::ifac_key: core::option::Option<rns_identity::ifac::IfacKey>
pub rns_transport::messages::InterfaceEntry::ifac_size: usize
pub rns_transport::messages::InterfaceEntry::ifac_violations: u64
pub rns_transport::messages::InterfaceEntry::ingress: rns_transport::ingress::IngressController
pub rns_transport::messages::InterfaceEntry::inspection: core::option::Option<rns_transport::messages::InterfaceInspectionSource>
pub rns_transport::messages::InterfaceEntry::mode: rns_transport::constants::InterfaceMode
@@ -1244,18 +1372,29 @@ pub rns_transport::messages::InterfaceEntry::mtu: u32
pub rns_transport::messages::InterfaceEntry::multipoint: bool
pub rns_transport::messages::InterfaceEntry::name: alloc::string::String
pub rns_transport::messages::InterfaceEntry::online: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicBool>>
pub rns_transport::messages::InterfaceEntry::owner: rns_transport::interface_ownership::InterfaceOwner
pub rns_transport::messages::InterfaceEntry::packet_capacity: rns_transport::interface_ownership::InterfacePacketCapacity
pub rns_transport::messages::InterfaceEntry::packet_filter_hits: u64
pub rns_transport::messages::InterfaceEntry::parent_id: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_transport::messages::InterfaceEntry::protocol_violations: u64
pub rns_transport::messages::InterfaceEntry::recursive_prs: bool
pub rns_transport::messages::InterfaceEntry::role: rns_transport::messages::InterfaceRole
pub rns_transport::messages::InterfaceEntry::rxb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
pub rns_transport::messages::InterfaceEntry::tx: tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>
pub rns_transport::messages::InterfaceEntry::tx_dropped_bytes: u64
pub rns_transport::messages::InterfaceEntry::tx_drops: alloc::sync::Arc<core::sync::atomic::AtomicU64>
pub rns_transport::messages::InterfaceEntry::txb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
impl rns_transport::messages::InterfaceEntry
pub fn rns_transport::messages::InterfaceEntry::accepts_clear_packet(&self, usize) -> bool
pub fn rns_transport::messages::InterfaceEntry::active_ifac_bytes(&self) -> usize
pub fn rns_transport::messages::InterfaceEntry::effective_clear_mtu(&self) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub fn rns_transport::messages::InterfaceEntry::new(alloc::string::String, rns_transport::constants::InterfaceMode, rns_transport::constants::InterfaceDirection, u64, u32, tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_announce_rate(self, f64, u32, f64) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_counters(self, alloc::sync::Arc<core::sync::atomic::AtomicBool>, alloc::sync::Arc<core::sync::atomic::AtomicU64>, alloc::sync::Arc<core::sync::atomic::AtomicU64>) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_ifac(self, [u8; 64], usize) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_multipoint(self, bool) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_owner(self, rns_transport::interface_ownership::InterfaceOwner) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_packet_capacity(self, rns_transport::interface_ownership::InterfacePacketCapacity) -> Self
pub fn rns_transport::messages::InterfaceEntry::with_role(self, rns_transport::messages::InterfaceRole) -> Self
impl core::fmt::Debug for rns_transport::messages::InterfaceEntry
pub fn rns_transport::messages::InterfaceEntry::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
@@ -1268,12 +1407,41 @@ pub fn rns_transport::messages::InterfaceInspectionSource::new<F>(F) -> Self whe
pub fn rns_transport::messages::InterfaceInspectionSource::snapshot(&self) -> rns_transport::messages::InterfaceInspectionSnapshot
impl core::fmt::Debug for rns_transport::messages::InterfaceInspectionSource
pub fn rns_transport::messages::InterfaceInspectionSource::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct rns_transport::messages::InterfaceOwner
impl rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::epoch(&self) -> u64
pub fn rns_transport::interface_ownership::InterfaceOwner::id(&self) -> rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwner::is_current(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::is_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::mark_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::new() -> Self
pub fn rns_transport::interface_ownership::InterfaceOwner::next_revision(&self) -> core::option::Option<Self>
pub fn rns_transport::interface_ownership::InterfaceOwner::revision(&self) -> u64
impl core::cmp::Eq for rns_transport::interface_ownership::InterfaceOwner
impl core::cmp::PartialEq for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::eq(&self, &Self) -> bool
impl core::default::Default for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::default() -> Self
pub struct rns_transport::messages::InterfaceOwnerId
impl rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwnerId::matches(self, &rns_transport::interface_ownership::InterfaceOwner) -> bool
pub struct rns_transport::messages::InterfacePacketCapacity
pub rns_transport::messages::InterfacePacketCapacity::link_mtu_upgrade: bool
pub rns_transport::messages::InterfacePacketCapacity::max_clear_packet_bytes: u32
pub rns_transport::messages::InterfacePacketCapacity::max_wire_packet_bytes: u32
impl rns_transport::interface_ownership::InterfacePacketCapacity
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::base(u32) -> Self
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::effective_clear_mtu(self, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::link_ceiling(self, rns_transport::messages::InterfaceId, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::new(u32, u32, bool) -> Self
pub struct rns_transport::messages::InterfaceStatRpcEntry
pub rns_transport::messages::InterfaceStatRpcEntry::announce_cap: f64
pub rns_transport::messages::InterfaceStatRpcEntry::announce_queue: core::option::Option<u64>
pub rns_transport::messages::InterfaceStatRpcEntry::announce_rate_grace: core::option::Option<u32>
pub rns_transport::messages::InterfaceStatRpcEntry::announce_rate_penalty: core::option::Option<f64>
pub rns_transport::messages::InterfaceStatRpcEntry::announce_rate_target: core::option::Option<f64>
pub rns_transport::messages::InterfaceStatRpcEntry::announces_received: u64
pub rns_transport::messages::InterfaceStatRpcEntry::announces_sent: u64
pub rns_transport::messages::InterfaceStatRpcEntry::bitrate: u64
pub rns_transport::messages::InterfaceStatRpcEntry::blocked_ips: core::option::Option<u64>
pub rns_transport::messages::InterfaceStatRpcEntry::burst_activated: f64
@@ -1282,6 +1450,7 @@ pub rns_transport::messages::InterfaceStatRpcEntry::clients: core::option::Optio
pub rns_transport::messages::InterfaceStatRpcEntry::held_announces: u64
pub rns_transport::messages::InterfaceStatRpcEntry::id: rns_transport::messages::InterfaceId
pub rns_transport::messages::InterfaceStatRpcEntry::ifac_size: usize
pub rns_transport::messages::InterfaceStatRpcEntry::ifac_violations: u64
pub rns_transport::messages::InterfaceStatRpcEntry::incoming_announce_frequency: f64
pub rns_transport::messages::InterfaceStatRpcEntry::incoming_pr_frequency: f64
pub rns_transport::messages::InterfaceStatRpcEntry::mode: alloc::string::String
@@ -1290,16 +1459,38 @@ pub rns_transport::messages::InterfaceStatRpcEntry::name: alloc::string::String
pub rns_transport::messages::InterfaceStatRpcEntry::online: bool
pub rns_transport::messages::InterfaceStatRpcEntry::outgoing_announce_frequency: f64
pub rns_transport::messages::InterfaceStatRpcEntry::outgoing_pr_frequency: f64
pub rns_transport::messages::InterfaceStatRpcEntry::packet_filter_hits: u64
pub rns_transport::messages::InterfaceStatRpcEntry::parent_id: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_transport::messages::InterfaceStatRpcEntry::path_requests_received: u64
pub rns_transport::messages::InterfaceStatRpcEntry::path_requests_sent: u64
pub rns_transport::messages::InterfaceStatRpcEntry::pr_burst_activated: f64
pub rns_transport::messages::InterfaceStatRpcEntry::pr_burst_active: bool
pub rns_transport::messages::InterfaceStatRpcEntry::protocol_violations: u64
pub rns_transport::messages::InterfaceStatRpcEntry::role: alloc::string::String
pub rns_transport::messages::InterfaceStatRpcEntry::rx_bytes: u64
pub rns_transport::messages::InterfaceStatRpcEntry::rx_rate: u64
pub rns_transport::messages::InterfaceStatRpcEntry::tx_bytes: u64
pub rns_transport::messages::InterfaceStatRpcEntry::tx_dropped_bytes: u64
pub rns_transport::messages::InterfaceStatRpcEntry::tx_drops: u64
pub rns_transport::messages::InterfaceStatRpcEntry::tx_rate: u64
pub struct rns_transport::messages::InterfaceTransportSender
impl rns_transport::interface_ownership::InterfaceTransportSender
pub fn rns_transport::interface_ownership::InterfaceTransportSender::actor_sender(&self) -> tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::bind(rns_transport::messages::InterfaceId, rns_transport::interface_ownership::InterfaceOwner, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::capacity(&self) -> usize
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::closed(&self)
pub fn rns_transport::interface_ownership::InterfaceTransportSender::event(&self, rns_transport::messages::TransportMessage) -> rns_transport::messages::TransportMessage
pub fn rns_transport::interface_ownership::InterfaceTransportSender::interface_id(&self) -> rns_transport::messages::InterfaceId
pub fn rns_transport::interface_ownership::InterfaceTransportSender::is_closed(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceTransportSender::max_capacity(&self) -> usize
pub fn rns_transport::interface_ownership::InterfaceTransportSender::new(rns_transport::messages::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::owner(&self) -> rns_transport::interface_ownership::InterfaceOwner
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::ready(&self) -> bool
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::SendError<rns_transport::messages::TransportMessage>>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::try_send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::TrySendError<rns_transport::messages::TransportMessage>>
pub struct rns_transport::messages::LinkEndpointBinding
pub rns_transport::messages::LinkEndpointBinding::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::messages::LinkEndpointBinding::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwnerId>
pub rns_transport::messages::LinkEndpointBinding::link_id: [u8; 16]
pub rns_transport::messages::LinkEndpointBinding::role: rns_transport::messages::LinkEndpointRole
pub struct rns_transport::messages::LinkEndpointLifecycleEvent
@@ -1660,7 +1851,7 @@ pub fn rns_transport::traffic::TrafficCounter::default() -> Self
pub mod rns_transport::tunnel
pub struct rns_transport::tunnel::TunnelEntry
pub rns_transport::tunnel::TunnelEntry::expires: f64
pub rns_transport::tunnel::TunnelEntry::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::tunnel::TunnelEntry::interface_id: core::option::Option<rns_transport::messages::InterfaceId>
pub rns_transport::tunnel::TunnelEntry::tunnel_id: [u8; 32]
pub rns_transport::tunnel::TunnelEntry::tunnel_paths: std::collections::hash::map::HashMap<[u8; 16], rns_transport::tunnel::TunnelPath>
pub struct rns_transport::tunnel::TunnelPath
@@ -1676,6 +1867,7 @@ pub rns_transport::tunnel::TunnelSynthesisData::public_key: [u8; 64]
pub rns_transport::tunnel::TunnelSynthesisData::random_hash: [u8; 16]
pub rns_transport::tunnel::TunnelSynthesisData::signature: [u8; 64]
impl rns_transport::tunnel::TunnelSynthesisData
pub fn rns_transport::tunnel::TunnelSynthesisData::is_signed(&self) -> bool
pub fn rns_transport::tunnel::TunnelSynthesisData::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_transport::tunnel::TunnelSynthesisData::tunnel_id(&self) -> [u8; 32]
pub fn rns_transport::tunnel::TunnelSynthesisData::unpack(&[u8]) -> core::option::Option<Self>
@@ -1694,9 +1886,62 @@ pub fn rns_transport::tunnel::TunnelTable::len(&self) -> usize
pub fn rns_transport::tunnel::TunnelTable::new() -> Self
pub fn rns_transport::tunnel::TunnelTable::remove(&mut self, &[u8; 32]) -> core::option::Option<rns_transport::tunnel::TunnelEntry>
pub fn rns_transport::tunnel::TunnelTable::tunnel_paths(&self) -> impl core::iter::traits::iterator::Iterator<Item = (&[u8; 16], &rns_transport::tunnel::TunnelPath)>
pub fn rns_transport::tunnel::TunnelTable::void_interface(&mut self, rns_transport::messages::InterfaceId) -> usize
impl core::default::Default for rns_transport::tunnel::TunnelTable
pub fn rns_transport::tunnel::TunnelTable::default() -> Self
pub fn rns_transport::tunnel::build_tunnel_synthesis_packet(&rns_identity::identity::Identity, [u8; 32]) -> core::option::Option<alloc::vec::Vec<u8>>
pub fn rns_transport::tunnel::handle_tunnel(&mut rns_transport::tunnel::TunnelTable, [u8; 32], rns_transport::messages::InterfaceId, f64)
pub fn rns_transport::tunnel::handle_tunnel(&mut rns_transport::tunnel::TunnelTable, [u8; 32], rns_transport::messages::InterfaceId)
pub fn rns_transport::tunnel::interface_hash(&str) -> [u8; 32]
pub enum rns_transport::InterfaceCapacityError
pub rns_transport::InterfaceCapacityError::Empty
pub rns_transport::InterfaceCapacityError::IfacExceedsWire
pub rns_transport::InterfaceCapacityError::IfacExceedsWire::ifac_bytes: usize
pub rns_transport::InterfaceCapacityError::IfacExceedsWire::wire_bytes: u32
pub rns_transport::InterfaceCapacityError::InvalidIfac
pub rns_transport::InterfaceCapacityError::LinkCapacityUnavailable
pub rns_transport::InterfaceCapacityError::LinkCapacityUnavailable::clear_mtu: u32
pub rns_transport::InterfaceCapacityError::LinkCapacityUnavailable::interface_id: rns_transport::messages::InterfaceId
pub rns_transport::InterfaceCapacityError::LinkCapacityUnavailable::required: u32
pub struct rns_transport::InterfaceOwner
impl rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::epoch(&self) -> u64
pub fn rns_transport::interface_ownership::InterfaceOwner::id(&self) -> rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwner::is_current(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::is_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::mark_registered(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceOwner::new() -> Self
pub fn rns_transport::interface_ownership::InterfaceOwner::next_revision(&self) -> core::option::Option<Self>
pub fn rns_transport::interface_ownership::InterfaceOwner::revision(&self) -> u64
impl core::cmp::Eq for rns_transport::interface_ownership::InterfaceOwner
impl core::cmp::PartialEq for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::eq(&self, &Self) -> bool
impl core::default::Default for rns_transport::interface_ownership::InterfaceOwner
pub fn rns_transport::interface_ownership::InterfaceOwner::default() -> Self
pub struct rns_transport::InterfaceOwnerId
impl rns_transport::interface_ownership::InterfaceOwnerId
pub fn rns_transport::interface_ownership::InterfaceOwnerId::matches(self, &rns_transport::interface_ownership::InterfaceOwner) -> bool
pub struct rns_transport::InterfacePacketCapacity
pub rns_transport::InterfacePacketCapacity::link_mtu_upgrade: bool
pub rns_transport::InterfacePacketCapacity::max_clear_packet_bytes: u32
pub rns_transport::InterfacePacketCapacity::max_wire_packet_bytes: u32
impl rns_transport::interface_ownership::InterfacePacketCapacity
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::base(u32) -> Self
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::effective_clear_mtu(self, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub fn rns_transport::interface_ownership::InterfacePacketCapacity::link_ceiling(self, rns_transport::messages::InterfaceId, usize) -> core::result::Result<u32, rns_transport::interface_ownership::InterfaceCapacityError>
pub const fn rns_transport::interface_ownership::InterfacePacketCapacity::new(u32, u32, bool) -> Self
pub struct rns_transport::InterfaceTransportSender
impl rns_transport::interface_ownership::InterfaceTransportSender
pub fn rns_transport::interface_ownership::InterfaceTransportSender::actor_sender(&self) -> tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::bind(rns_transport::messages::InterfaceId, rns_transport::interface_ownership::InterfaceOwner, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::capacity(&self) -> usize
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::closed(&self)
pub fn rns_transport::interface_ownership::InterfaceTransportSender::event(&self, rns_transport::messages::TransportMessage) -> rns_transport::messages::TransportMessage
pub fn rns_transport::interface_ownership::InterfaceTransportSender::interface_id(&self) -> rns_transport::messages::InterfaceId
pub fn rns_transport::interface_ownership::InterfaceTransportSender::is_closed(&self) -> bool
pub fn rns_transport::interface_ownership::InterfaceTransportSender::max_capacity(&self) -> usize
pub fn rns_transport::interface_ownership::InterfaceTransportSender::new(rns_transport::messages::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> Self
pub fn rns_transport::interface_ownership::InterfaceTransportSender::owner(&self) -> rns_transport::interface_ownership::InterfaceOwner
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::ready(&self) -> bool
pub async fn rns_transport::interface_ownership::InterfaceTransportSender::send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::SendError<rns_transport::messages::TransportMessage>>
pub fn rns_transport::interface_ownership::InterfaceTransportSender::try_send(&self, rns_transport::messages::TransportMessage) -> core::result::Result<(), tokio::sync::mpsc::error::TrySendError<rns_transport::messages::TransportMessage>>
pub fn rns_transport::now_f64() -> f64
+32
View File
@@ -95,6 +95,38 @@ impl rns_wire::header::PacketHeader
pub fn rns_wire::header::PacketHeader::pack(&self) -> alloc::vec::Vec<u8>
pub fn rns_wire::header::PacketHeader::size(&self) -> usize
pub fn rns_wire::header::PacketHeader::unpack(&[u8]) -> core::result::Result<(Self, usize), rns_wire::header::HeaderError>
pub mod rns_wire::link_signalling
pub enum rns_wire::link_signalling::LinkSignallingError
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::actual: usize
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::legacy: usize
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::modern: usize
pub rns_wire::link_signalling::LinkSignallingError::InvalidMode(u8)
pub rns_wire::link_signalling::LinkSignallingError::InvalidMtu(u32)
pub rns_wire::link_signalling::LinkSignallingError::MduUnavailable
pub struct rns_wire::link_signalling::LinkMtu(_)
impl rns_wire::link_signalling::LinkMtu
pub const rns_wire::link_signalling::LinkMtu::BASE: Self
pub fn rns_wire::link_signalling::LinkMtu::checked_mdu(self) -> core::result::Result<usize, rns_wire::link_signalling::LinkSignallingError>
pub const fn rns_wire::link_signalling::LinkMtu::get(self) -> u32
pub fn rns_wire::link_signalling::LinkMtu::try_from_signal(core::option::Option<u32>) -> core::result::Result<Self, rns_wire::link_signalling::LinkSignallingError>
pub struct rns_wire::link_signalling::LinkSignalling
pub rns_wire::link_signalling::LinkSignalling::mode: u8
pub rns_wire::link_signalling::LinkSignalling::mtu: rns_wire::link_signalling::LinkMtu
pub rns_wire::link_signalling::LinkSignalling::signalling_present: bool
pub struct rns_wire::link_signalling::SignallingData
pub rns_wire::link_signalling::SignallingData::mode: u8
pub rns_wire::link_signalling::SignallingData::mtu: u32
impl rns_wire::link_signalling::SignallingData
pub fn rns_wire::link_signalling::SignallingData::new(u8, u32) -> Self
pub fn rns_wire::link_signalling::SignallingData::pack(&self) -> [u8; 3]
pub fn rns_wire::link_signalling::SignallingData::try_new(u8, u32) -> core::result::Result<Self, rns_wire::link_signalling::LinkSignallingError>
pub fn rns_wire::link_signalling::SignallingData::unpack(&[u8]) -> core::option::Option<Self>
pub const rns_wire::link_signalling::BASE_LINK_MTU: u32
pub const rns_wire::link_signalling::DEFAULT_LINK_MODE: u8
pub const rns_wire::link_signalling::MAX_SIGNALLED_LINK_MTU: u32
pub fn rns_wire::link_signalling::parse_proof_signalling(&[u8]) -> core::result::Result<rns_wire::link_signalling::LinkSignalling, rns_wire::link_signalling::LinkSignallingError>
pub fn rns_wire::link_signalling::parse_request_signalling(&[u8]) -> core::result::Result<rns_wire::link_signalling::LinkSignalling, rns_wire::link_signalling::LinkSignallingError>
pub mod rns_wire::packet
pub enum rns_wire::packet::PacketError
pub rns_wire::packet::PacketError::ExceedsMtu(usize)
+105 -19
View File
@@ -24,8 +24,8 @@
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-crypto.txt",
"itemCount": 91,
"sha256": "4d1e3c0a13e48a84f2510c6586024b3d8f5781b367459bc17d714ca485f1aa63"
"itemCount": 92,
"sha256": "1f4539cfe1dfc1bf78a75e95dc98a3bf14a432cf0292d8d654fc043d5c4d21dc"
},
{
"name": "rns-wire",
@@ -33,8 +33,8 @@
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-wire.txt",
"itemCount": 370,
"sha256": "7ce9011e531c1642912512d9d975b8a7def0bb41f691b6b16177eddecf5bef6d"
"itemCount": 402,
"sha256": "47f17ed4b47f0fc9ccaccc42d00b7635b07083c4eae6782a4f5de7e1452e4688"
},
{
"name": "rns-identity",
@@ -42,8 +42,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-identity.txt",
"itemCount": 374,
"sha256": "f2b692070a3fa1a2cc98edbb40bc75d205daadfa9da9d9994ee194e8436e00c9"
"itemCount": 431,
"sha256": "377cb3b72a97b071e0d590c399d0cc0433b60fe5a6ae37a73657283d3622f037"
},
{
"name": "rns-transport",
@@ -51,8 +51,8 @@
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-transport.txt",
"itemCount": 1702,
"sha256": "30f20b408ac255e1f005e25e79e4999d813ebc6b4f1a501bf573de58db0e25ab"
"itemCount": 1947,
"sha256": "79cd60b1cde9c92e97f58ded693d3754b53311ec16f161ffa5b90775ec3c4a45"
},
{
"name": "rns-link",
@@ -60,8 +60,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-link.txt",
"itemCount": 359,
"sha256": "59d2f211857314e044bf31e5b78e4460483411c9b26c08904f8996295b189984"
"itemCount": 384,
"sha256": "6c7db32623681ef8b2fdce0c54edbb992d307f0fae8b361c65109a6d262d9389"
},
{
"name": "rns-protocol",
@@ -69,8 +69,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-protocol.txt",
"itemCount": 624,
"sha256": "9fd1968c43d3a80b5da65416f43a805e3bfd3420c91acc8ad63a7a3ca58b359c"
"itemCount": 638,
"sha256": "f90d8a7a284b50df43e3c9936f7b3a3a9c4104f4e31cc9ef1c60b833239b7ec6"
},
{
"name": "rns-interface",
@@ -78,8 +78,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-interface.txt",
"itemCount": 1406,
"sha256": "b097f01fc5eac53ed0ce5b6150c47c12f69fb63072ac31789a3995167123af3a"
"itemCount": 1440,
"sha256": "2954226f79c76dd7f3e743d5a36e6895ef5e21dcd16b4fd5544be2932953e7a8"
},
{
"name": "rns-runtime",
@@ -87,8 +87,8 @@
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-runtime.txt",
"itemCount": 2063,
"sha256": "ca162e9ddb542f0daf5817ac26d32be80346d36bdadd70673bf2cdc2535e4e29"
"itemCount": 2145,
"sha256": "a4496892f8c4f6aeb9f840179e1a967b576679056045dd4511d5fe064f32544c"
},
{
"name": "rns-tools",
@@ -110,13 +110,21 @@
}
],
"approvedBreakingChanges": {
"releaseLine": "1.3",
"migrationGuide": "api/migrations/1.3.md",
"releaseLine": "1.4",
"migrationGuide": "api/migrations/1.4.md",
"removed": {
"rns-crypto": [
"pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<[u8; 64], rns_crypto::hkdf::HkdfError>",
"pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::hkdf::HkdfError>"
],
"rns-transport": [
"pub enum rns_transport::discovery::Reason",
"pub enum rns_transport::discovery::receiver::Reason",
"pub fn rns_transport::tunnel::handle_tunnel(&mut rns_transport::tunnel::TunnelTable, [u8; 32], rns_transport::messages::InterfaceId, f64)",
"pub rns_transport::actor::DiscoveryPathRequest::requesting_interface: rns_transport::messages::InterfaceId",
"pub rns_transport::actor::DiscoveryPathRequest::timeout: f64",
"pub rns_transport::actor::TransportActor::discovery_path_requests: std::collections::hash::map::HashMap<[u8; 16], rns_transport::actor::DiscoveryPathRequest>",
"pub rns_transport::actor::TransportActor::pending_tunnel_entries: alloc::vec::Vec<rns_transport::persistence::PersistedTunnelEntry>",
"pub rns_transport::discovery::DiscoveryInterfaceConfig::height: f64",
"pub rns_transport::discovery::DiscoveryInterfaceConfig::latitude: f64",
"pub rns_transport::discovery::DiscoveryInterfaceConfig::longitude: f64",
@@ -125,7 +133,85 @@
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::longitude: f64",
"pub rns_transport::discovery::app_data::DiscoveryInfo::height: f64",
"pub rns_transport::discovery::app_data::DiscoveryInfo::latitude: f64",
"pub rns_transport::discovery::app_data::DiscoveryInfo::longitude: f64"
"pub rns_transport::discovery::app_data::DiscoveryInfo::longitude: f64",
"pub rns_transport::messages::InterfaceEntry::ifac_key: core::option::Option<[u8; 64]>",
"pub rns_transport::tunnel::TunnelEntry::interface_id: rns_transport::messages::InterfaceId"
],
"rns-link": [
"impl rns_link::mtu_discovery::SignallingData",
"pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self",
"pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]",
"pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_link::mtu_discovery::SignallingData) -> alloc::vec::Vec<u8>",
"pub fn rns_link::mtu_discovery::SignallingData::new(u8, u32) -> Self",
"pub fn rns_link::mtu_discovery::SignallingData::pack(&self) -> [u8; 3]",
"pub fn rns_link::mtu_discovery::SignallingData::unpack(&[u8]) -> core::option::Option<Self>",
"pub rns_link::handshake::LinkProofData::signalling: rns_link::mtu_discovery::SignallingData",
"pub rns_link::handshake::LinkRequestData::signalling: rns_link::mtu_discovery::SignallingData",
"pub rns_link::mtu_discovery::SignallingData::mode: u8",
"pub rns_link::mtu_discovery::SignallingData::mtu: u32",
"pub struct rns_link::mtu_discovery::SignallingData"
],
"rns-interface": [
"pub async fn rns_interface::i2p::spawn_i2p_server(rns_interface::i2p::I2PServerConfig, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>",
"pub async fn rns_interface::local::spawn_local_server(rns_interface::local::LocalServerConfig, alloc::sync::Arc<core::sync::atomic::AtomicU64>, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, tokio::sync::mpsc::bounded::Sender<rns_interface::traits::InterfaceHandle>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>",
"pub enum rns_interface::rnode::RNodeStream",
"pub rns_interface::rnode::RNodeStream::Serial(alloc::boxed::Box<dyn serialport::SerialPort>)",
"pub rns_interface::rnode::RNodeStream::Tcp(std::net::tcp::TcpStream)"
],
"rns-runtime": [
"pub fn rns_runtime::interface_factory::InterfacePostInit::from_section(&rns_runtime::config::ConfigSection) -> Self",
"pub fn rns_runtime::link_manager::LinkManager::set_link_packet_channel(&mut self, tokio::sync::mpsc::unbounded::UnboundedSender<(alloc::vec::Vec<u8>, [u8; 16])>)",
"pub mod rns_runtime::remote_management_schema",
"pub rns_runtime::interface_factory::InterfacePostInit::ifac_passphrase: core::option::Option<alloc::string::String>",
"pub rns_runtime::remote_management_schema::InterfaceStats::announce_queue: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::bitrate: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::blocked_ips: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::burst_activated: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::burst_active: bool",
"pub rns_runtime::remote_management_schema::InterfaceStats::clients: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::hash: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::InterfaceStats::held_announces: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::ifac_netname: core::option::Option<alloc::string::String>",
"pub rns_runtime::remote_management_schema::InterfaceStats::ifac_signature: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::InterfaceStats::ifac_size: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::InterfaceStats::incoming_announce_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::incoming_pr_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::mode: u8",
"pub rns_runtime::remote_management_schema::InterfaceStats::name: alloc::string::String",
"pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_announce_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::outgoing_pr_frequency: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_activated: f64",
"pub rns_runtime::remote_management_schema::InterfaceStats::pr_burst_active: bool",
"pub rns_runtime::remote_management_schema::InterfaceStats::rxb: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::rxs: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::short_name: alloc::string::String",
"pub rns_runtime::remote_management_schema::InterfaceStats::status: bool",
"pub rns_runtime::remote_management_schema::InterfaceStats::txb: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::txs: u64",
"pub rns_runtime::remote_management_schema::InterfaceStats::type_: alloc::string::String",
"pub rns_runtime::remote_management_schema::PathEntry::expires: f64",
"pub rns_runtime::remote_management_schema::PathEntry::hash: alloc::vec::Vec<u8>",
"pub rns_runtime::remote_management_schema::PathEntry::hops: u8",
"pub rns_runtime::remote_management_schema::PathEntry::interface: alloc::string::String",
"pub rns_runtime::remote_management_schema::PathEntry::timestamp: f64",
"pub rns_runtime::remote_management_schema::PathEntry::via: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::RateEntry::hash: alloc::vec::Vec<u8>",
"pub rns_runtime::remote_management_schema::RateEntry::rate: f64",
"pub rns_runtime::remote_management_schema::TransportStats::interfaces: alloc::vec::Vec<rns_runtime::remote_management_schema::InterfaceStats>",
"pub rns_runtime::remote_management_schema::TransportStats::network_id: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::TransportStats::probe_responder: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::TransportStats::rss: core::option::Option<u64>",
"pub rns_runtime::remote_management_schema::TransportStats::rxb: u64",
"pub rns_runtime::remote_management_schema::TransportStats::rxs: u64",
"pub rns_runtime::remote_management_schema::TransportStats::transport_id: core::option::Option<alloc::vec::Vec<u8>>",
"pub rns_runtime::remote_management_schema::TransportStats::transport_uptime: core::option::Option<f64>",
"pub rns_runtime::remote_management_schema::TransportStats::txb: u64",
"pub rns_runtime::remote_management_schema::TransportStats::txs: u64",
"pub rns_runtime::rpc::InterfaceStatEntry::ifac_size: usize",
"pub struct rns_runtime::remote_management_schema::InterfaceStats",
"pub struct rns_runtime::remote_management_schema::PathEntry",
"pub struct rns_runtime::remote_management_schema::RateEntry",
"pub struct rns_runtime::remote_management_schema::TransportStats"
]
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
license-file.workspace = true
[features]
default = ["std"]
+20 -5
View File
@@ -1,12 +1,14 @@
//! AES-CBC, no padding (callers use [`crate::pkcs7`]). Key length selects:
//! 16 → AES-128, 32 → AES-256. Wire negotiates AES-256; AES-128 kept for
//! legacy Token material.
//! 16 → AES-128, 32 → AES-256. AES-128 supports legacy Token material.
//! These primitives do not negotiate a cipher or authenticate ciphertext;
//! [`crate::token`] supplies the authenticated Token format.
use aes::{Aes128, Aes256};
use alloc::vec::Vec;
use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
use cbc::{Decryptor, Encryptor};
use thiserror::Error;
use zeroize::Zeroizing;
const AES_BLOCK_SIZE: usize = 16;
@@ -46,7 +48,8 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, AesCb
return Err(AesCbcError::NotBlockAligned);
}
let mut buf = plaintext.to_vec();
// Wiped if an error leaves this plaintext copy unencrypted.
let mut buf = Zeroizing::new(plaintext.to_vec());
match key.len() {
16 => {
let enc = Encryptor::<Aes128>::new_from_slices(key, iv)
@@ -68,10 +71,13 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, AesCb
}
n => return Err(AesCbcError::InvalidKeyLength(n)),
}
Ok(buf)
Ok(core::mem::take(&mut *buf))
}
/// AES-CBC decrypt. Output is still PKCS7-padded; caller strips it.
/// AES-CBC decrypt without checking authentication or removing padding.
/// If the sender applied PKCS7 padding, the caller must validate and strip it.
/// The key must be 16 or 32 bytes, the IV 16 bytes, and the ciphertext a
/// non-zero multiple of 16 bytes.
pub fn decrypt(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, AesCbcError> {
if iv.len() != AES_BLOCK_SIZE {
return Err(AesCbcError::InvalidIvLength(iv.len()));
@@ -174,6 +180,15 @@ mod tests {
assert_eq!(&pt[..], &plaintext[..]);
}
#[test]
fn cipher_state_is_wiped_on_drop() {
fn wiped_on_drop<T: zeroize::ZeroizeOnDrop>() {}
wiped_on_drop::<Encryptor<Aes128>>();
wiped_on_drop::<Encryptor<Aes256>>();
wiped_on_drop::<Decryptor<Aes128>>();
wiped_on_drop::<Decryptor<Aes256>>();
}
/// Different key sizes must produce different ciphertexts for the same input.
#[test]
fn test_aes128_vs_aes256_distinct_ciphertexts() {
+3 -1
View File
@@ -14,7 +14,9 @@ pub enum Ed25519Error {
/// Public key bytes were not a valid Ed25519 point.
#[error("invalid public key bytes")]
InvalidPublicKey,
/// Signature bytes could not be decoded as an Ed25519 signature.
/// Retained signature-decoding error variant. The current `verify` method
/// accepts a fixed 64-byte signature and returns `VerificationFailed` on
/// verification failure.
#[error("invalid signature bytes")]
InvalidSignature,
}
+23 -10
View File
@@ -5,6 +5,7 @@ use alloc::vec::Vec;
use hkdf::Hkdf;
use sha2::Sha256;
use thiserror::Error;
use zeroize::Zeroizing;
/// Per RFC 5869, HKDF-SHA256 can emit at most 255 * HashLen = 8160 bytes.
const MAX_OUTPUT_LENGTH: usize = 255 * 32;
@@ -23,31 +24,36 @@ pub enum HkdfError {
/// HKDF-SHA256 key derivation (RFC 5869).
///
/// `length` is capped at 8160 bytes. `salt = None` uses 32 zero bytes as
/// specified by the RFC; `info = None` uses an empty context string.
/// specified by the RFC; `info = None` uses an empty context string. The
/// output is wiped when it is dropped.
pub fn hkdf_sha256(
length: usize,
ikm: &[u8],
salt: Option<&[u8]>,
info: Option<&[u8]>,
) -> Result<Vec<u8>, HkdfError> {
) -> Result<Zeroizing<Vec<u8>>, HkdfError> {
if length > MAX_OUTPUT_LENGTH {
return Err(HkdfError::OutputTooLong(length));
}
let hk = Hkdf::<Sha256>::new(salt, ikm);
let mut okm = vec![0u8; length];
let mut okm = Zeroizing::new(vec![0u8; length]);
hk.expand(info.unwrap_or(b""), &mut okm)
.map_err(|_| HkdfError::ExpansionFailed)?;
Ok(okm)
}
/// Derive the 64-byte session key used for RNS link encryption:
/// `HKDF-SHA256(length=64, ikm=shared_secret, salt=identity_hash, info=None)`.
pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<[u8; 64], HkdfError> {
let okm = hkdf_sha256(64, shared_secret, Some(salt), None)?;
let mut out = [0u8; 64];
out.copy_from_slice(&okm);
Ok(out)
/// Derive 64 key bytes with the caller-provided salt:
/// `HKDF-SHA256(length=64, ikm=shared_secret, salt=salt, info=None)`.
/// Identity encryption passes the identity hash. Link key derivation instead
/// selects its key length by mode and uses the Link ID as salt.
/// The key is expanded straight into its return buffer, which is wiped on drop.
pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<Zeroizing<[u8; 64]>, HkdfError> {
let mut okm = Zeroizing::new([0u8; 64]);
Hkdf::<Sha256>::new(Some(salt), shared_secret)
.expand(b"", &mut okm[..])
.map_err(|_| HkdfError::ExpansionFailed)?;
Ok(okm)
}
#[cfg(test)]
@@ -84,5 +90,12 @@ mod tests {
fn test_derive_key_64() {
let key = derive_key_64(b"shared_secret", b"salt_value").unwrap();
assert_eq!(key.len(), 64);
let cases: [(&[u8], &[u8]); 2] = [(b"shared_secret", b"salt_value"), (&[7; 32], &[9; 16])];
for (ikm, salt) in cases {
assert_eq!(
&derive_key_64(ikm, salt).unwrap()[..],
&hkdf_sha256(64, ikm, Some(salt), None).unwrap()[..]
);
}
}
}
+12 -3
View File
@@ -1,6 +1,11 @@
//! Cryptographic primitives for Reticulum. Constants, derivation inputs, and
//! wire-visible byte layouts match the Python reference (`RNS/Cryptography/`)
//! exactly — downstream interop depends on it. `no_std + alloc` when `std` is off.
//! Cryptographic primitives used by Reticulum identities, Links and Tokens.
//! This crate exposes low-level ciphers, hashes, key derivation and key types;
//! callers supply the protocol-specific salts, authentication and key lifecycle.
//!
//! Disabling this crate's `std` feature selects `no_std + alloc` for its code.
//! Workspace dependencies retain their own default features, and random/key
//! generation still requires an operating-system entropy source. This setting
//! alone does not make the crate a bare-metal cryptographic backend.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
extern crate alloc;
@@ -16,6 +21,10 @@ pub mod token;
pub mod x25519;
pub use token::TOKEN_OVERHEAD;
/// The wiping types in this crate's API, such as the output of
/// [`hkdf::hkdf_sha256`], for crates that hold secrets without depending on
/// `zeroize` themselves.
pub use zeroize;
use alloc::string::String;
use core::fmt::Write;
+4 -2
View File
@@ -8,7 +8,8 @@ const BLOCK_SIZE: usize = 16;
/// Errors surfaced by [`unpad`].
#[derive(Debug, Error)]
pub enum Pkcs7Error {
/// Trailing byte is zero or greater than the 16-byte block size.
/// Trailing byte is zero, greater than the 16-byte block size, or greater
/// than the input length.
#[error("invalid padding: padding byte value {0} exceeds block size {BLOCK_SIZE}")]
InvalidPaddingValue(u8),
/// The declared padding length doesn't match the trailing bytes.
@@ -33,7 +34,8 @@ pub fn pad(data: &[u8]) -> Vec<u8> {
/// Strip PKCS7 padding for a 16-byte block size.
///
/// All padding bytes are validated; a mismatch returns an error.
/// All padding bytes are validated; a mismatch returns an error. This helper
/// checks the trailing padding only, not the input's total block alignment.
pub fn unpad(data: &[u8]) -> Result<&[u8], Pkcs7Error> {
if data.is_empty() {
return Err(Pkcs7Error::EmptyInput);
+26 -13
View File
@@ -1,4 +1,5 @@
//! RNS encryption token: AES-256-CBC + HMAC-SHA256 over an IV-prefixed ciphertext.
//! RNS encryption token: AES-CBC + HMAC-SHA256 over an IV-prefixed ciphertext.
//! A 64-byte key selects AES-256; a legacy 32-byte key selects AES-128.
use alloc::vec::Vec;
use thiserror::Error;
@@ -15,9 +16,9 @@ pub const TOKEN_OVERHEAD: usize = 48;
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.
/// AES-256 token key size: 32-byte HMAC 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.
/// Legacy AES-128 token key size: 16-byte HMAC 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;
@@ -28,13 +29,15 @@ pub enum TokenError {
/// Key must be 32 or 64 bytes.
#[error("invalid key length: expected 32 or 64, got {0}")]
InvalidKeyLength(usize),
/// Token is shorter than [`TOKEN_OVERHEAD`] so cannot contain IV + HMAC.
/// Retained short-token error variant. The current `decrypt` method maps
/// every token shorter than 64 bytes to `AuthenticationFailed`.
#[error("token too short for decryption")]
TooShort,
/// HMAC tag did not validate.
/// Token length, authentication, block alignment, decryption or padding failed.
#[error("authentication failed")]
AuthenticationFailed,
/// Underlying AES-CBC decrypt returned an error.
/// Retained decryption error variant. The current `decrypt` method maps
/// underlying cipher failures to `AuthenticationFailed`.
#[error("decryption failed")]
DecryptionFailed,
/// Underlying AES-CBC encrypt returned an error.
@@ -63,7 +66,7 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
let (signing_key, encryption_key) = split_key(key)?;
let iv = random_16();
let padded = pkcs7::pad(plaintext);
let padded = Zeroizing::new(pkcs7::pad(plaintext));
let ciphertext =
aes_cbc::encrypt(encryption_key, &iv, &padded).map_err(|_| TokenError::EncryptionFailed)?;
@@ -80,8 +83,13 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
Ok(token)
}
/// Token decrypt. All failure modes collapse to `AuthenticationFailed`
/// (padding-oracle defence). HMAC comparison is constant-time.
/// Authenticate and decrypt a Token. An invalid key length returns
/// `InvalidKeyLength`; malformed-token, authentication, cipher and padding
/// failures return `AuthenticationFailed`. HMAC comparison is constant-time.
///
/// The plaintext is returned in the buffer it was decrypted into, and a failed
/// decryption wipes that buffer. Callers wrap a secret plaintext in
/// [`Zeroizing`] so it is wiped when dropped.
pub fn decrypt(token: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
let (signing_key, encryption_key) = split_key(key)?;
@@ -105,12 +113,17 @@ pub fn decrypt(token: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
return Err(TokenError::AuthenticationFailed);
}
let padded = aes_cbc::decrypt(encryption_key, iv, ciphertext)
.map_err(|_| TokenError::AuthenticationFailed)?;
let mut padded = Zeroizing::new(
aes_cbc::decrypt(encryption_key, iv, ciphertext)
.map_err(|_| TokenError::AuthenticationFailed)?,
);
let plaintext = pkcs7::unpad(&padded).map_err(|_| TokenError::AuthenticationFailed)?;
let len = pkcs7::unpad(&padded)
.map_err(|_| TokenError::AuthenticationFailed)?
.len();
padded.truncate(len);
Ok(plaintext.to_vec())
Ok(core::mem::take(&mut *padded))
}
#[cfg(test)]
+7 -4
View File
@@ -4,7 +4,8 @@ use rand_core::OsRng;
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::Zeroize;
/// X25519 private key (32 bytes, clamped scalar).
/// X25519 private key material (32 bytes). Scalar clamping occurs during
/// public-key derivation and Diffie-Hellman, not when these bytes are stored.
///
/// Key material is zeroized on drop.
pub struct X25519PrivateKey {
@@ -38,14 +39,14 @@ impl X25519PrivateKey {
}
}
/// Construct from a 32-byte scalar.
/// Store 32 bytes of private key material without changing their encoding.
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self {
secret: StaticSecret::from(*bytes),
}
}
/// Return the 32-byte scalar.
/// Return the stored 32-byte private key material.
pub fn to_bytes(&self) -> [u8; 32] {
self.secret.to_bytes()
}
@@ -58,13 +59,15 @@ impl X25519PrivateKey {
}
/// Compute the shared secret with `peer` via X25519 Diffie-Hellman.
/// This primitive does not reject an all-zero result; a protocol requiring
/// a contributory-behavior check must validate the returned secret.
pub fn exchange(&self, peer: &X25519PublicKey) -> [u8; 32] {
self.secret.diffie_hellman(&peer.key).to_bytes()
}
}
impl X25519PublicKey {
/// Parse a 32-byte u-coordinate.
/// Store a 32-byte u-coordinate without rejecting low-order public inputs.
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self {
key: PublicKey::from(*bytes),
+168
View File
@@ -0,0 +1,168 @@
//! Shared by the secret-residue test binaries. A recording allocator copies
//! every block the calling thread frees while a check runs; each check then
//! searches those copies for its secrets.
#![allow(dead_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::{Cell, UnsafeCell};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
const RECORD_CAPACITY: usize = 8 << 20;
struct Recording(UnsafeCell<[u8; RECORD_CAPACITY]>);
// Written only by the armed thread while armed, read only after disarming.
unsafe impl Sync for Recording {}
static RECORDING: Recording = Recording(UnsafeCell::new([0; RECORD_CAPACITY]));
static RECORDED: AtomicUsize = AtomicUsize::new(0);
static OVERFLOWED: AtomicBool = AtomicBool::new(false);
static PEAK: AtomicUsize = AtomicUsize::new(0);
static SERIAL: Mutex<()> = Mutex::new(());
thread_local! {
static ARMED: Cell<bool> = const { Cell::new(false) };
}
struct RecordingAllocator;
fn armed() -> bool {
ARMED.try_with(Cell::get).unwrap_or(false)
}
unsafe impl GlobalAlloc for RecordingAllocator {
// Blocks handed out while armed start zeroed, so a recorded block holds
// only what was written during the check, never a reused block's old bytes.
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
if !armed() {
return unsafe { System.alloc(layout) };
}
PEAK.fetch_max(layout.size(), Ordering::Relaxed);
unsafe { System.alloc_zeroed(layout) }
}
// The default `realloc` frees the old block through `dealloc`, so blocks
// left behind by growth are recorded too.
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
if armed() {
let start = RECORDED.load(Ordering::Relaxed);
let end = start + 4 + layout.size();
if end <= RECORD_CAPACITY {
let base = RECORDING.0.get().cast::<u8>();
unsafe {
base.add(start)
.cast::<[u8; 4]>()
.write_unaligned((layout.size() as u32).to_le_bytes());
std::ptr::copy_nonoverlapping(ptr, base.add(start + 4), layout.size());
}
RECORDED.store(end, Ordering::Relaxed);
} else {
OVERFLOWED.store(true, Ordering::Relaxed);
}
}
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static ALLOCATOR: RecordingAllocator = RecordingAllocator;
pub fn serial() -> MutexGuard<'static, ()> {
SERIAL
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub struct Freed {
pub blocks: Vec<Vec<u8>>,
pub peak_allocation: usize,
}
/// Run `f` and return its result with a copy of every block it freed.
pub fn freed_by<R>(f: impl FnOnce() -> R) -> (R, Freed) {
RECORDED.store(0, Ordering::Relaxed);
OVERFLOWED.store(false, Ordering::Relaxed);
PEAK.store(0, Ordering::Relaxed);
ARMED.with(|armed| armed.set(true));
let result = f();
ARMED.with(|armed| armed.set(false));
assert!(
!OVERFLOWED.load(Ordering::Relaxed),
"freed blocks exceeded the recording buffer"
);
let len = RECORDED.load(Ordering::Relaxed);
let recorded = unsafe { std::slice::from_raw_parts(RECORDING.0.get().cast::<u8>(), len) };
let mut blocks = Vec::new();
let mut at = 0;
while at < len {
let size = u32::from_le_bytes(recorded[at..at + 4].try_into().unwrap()) as usize;
blocks.push(recorded[at + 4..at + 4 + size].to_vec());
at += 4 + size;
}
let freed = Freed {
blocks,
peak_allocation: PEAK.load(Ordering::Relaxed),
};
(result, freed)
}
/// Whether `block` holds 16 consecutive bytes of `secret`.
pub fn holds(block: &[u8], secret: &[u8]) -> bool {
!find(&[block.to_vec()], &[secret]).is_empty()
}
/// For each block holding 16 consecutive bytes of any of `secrets`: its
/// length and the indexes of the secrets it holds.
pub fn find(blocks: &[Vec<u8>], secrets: &[&[u8]]) -> Vec<(usize, Vec<usize>)> {
let mut windows: HashMap<&[u8], Vec<usize>> = HashMap::new();
for (index, secret) in secrets.iter().enumerate() {
assert!(secret.len() >= 16, "secret is too short to search for");
for window in secret.windows(16) {
let owners = windows.entry(window).or_default();
if owners.last() != Some(&index) {
owners.push(index);
}
}
}
let mut found = Vec::new();
for block in blocks {
let mut held: Vec<usize> = block
.windows(16)
.filter_map(|window| windows.get(window))
.flatten()
.copied()
.collect();
held.sort_unstable();
held.dedup();
if !held.is_empty() {
found.push((block.len(), held));
}
}
found
}
/// Fail if any freed block holds part of a secret.
pub fn assert_no_residue(freed: &Freed, secrets: &[(&str, &[u8])]) {
let values: Vec<&[u8]> = secrets.iter().map(|(_, secret)| *secret).collect();
let mut found = Vec::new();
for (len, held) in find(&freed.blocks, &values) {
for index in held {
found.push(format!("{} in a freed {len}-byte block", secrets[index].0));
}
}
assert!(found.is_empty(), "secret residue: {found:?}");
}
pub fn pseudo_random<const N: usize>(seed: u64) -> [u8; N] {
let mut state = seed;
let mut out = [0u8; N];
for byte in &mut out {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
*byte = (state >> 24) as u8;
}
out
}
+137
View File
@@ -0,0 +1,137 @@
//! Plaintext and key material must not survive in freed heap memory.
mod residue;
use residue::{assert_no_residue, freed_by, holds, pseudo_random, serial};
use rns_crypto::{aes_cbc, hkdf, hmac, token};
use std::hint::black_box;
use zeroize::Zeroizing;
#[test]
fn the_harness_finds_unwiped_copies() {
let _serial = serial();
let secret: [u8; 64] = pseudo_random(12);
let ((), dropped) = freed_by(|| drop(black_box(secret.to_vec())));
// A wiped buffer that grew still frees its first block unwiped.
let ((), grown) = freed_by(|| {
let mut copy = Zeroizing::new(Vec::with_capacity(32));
copy.extend_from_slice(&secret[..32]);
copy.extend_from_slice(&secret[32..]);
black_box(&copy);
});
for (case, freed) in [("dropped", dropped), ("grown", grown)] {
assert!(
freed.blocks.iter().any(|block| holds(block, &secret)),
"{case}: copy not found"
);
}
}
#[test]
fn the_harness_ignores_bytes_freed_before_the_check() {
let _serial = serial();
let secret: [u8; 64] = pseudo_random(13);
// Large enough that the allocator hands the same block straight back.
drop(black_box(secret.repeat(1024)));
let ((), freed) = freed_by(|| drop(black_box(Vec::<u8>::with_capacity(64 * 1024))));
assert_no_residue(&freed, &[("secret", &secret)]);
}
#[test]
fn token_encrypt_frees_no_plaintext() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(1);
let plaintext: [u8; 100] = pseudo_random(2);
let (token, freed) = freed_by(|| token::encrypt(&plaintext, &key).unwrap());
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
assert_eq!(
&Zeroizing::new(token::decrypt(&token, &key).unwrap())[..],
&plaintext[..]
);
}
#[test]
fn token_decrypt_frees_no_plaintext() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(3);
let plaintext: [u8; 100] = pseudo_random(4);
let token = token::encrypt(&plaintext, &key).unwrap();
let ((), freed) = freed_by(|| {
let decrypted = Zeroizing::new(token::decrypt(&token, &key).unwrap());
assert_eq!(&decrypted[..], &plaintext[..]);
});
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
}
#[test]
fn token_decrypt_wipes_an_authenticated_plaintext_with_bad_padding() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(5);
let mut plaintext: [u8; 64] = pseudo_random(6);
plaintext[63] = 0;
let iv = [0x24u8; 16];
let mut token = iv.to_vec();
token.extend_from_slice(&aes_cbc::encrypt(&key[32..], &iv, &plaintext).unwrap());
let mac = hmac::hmac_sha256(&key[..32], &token);
token.extend_from_slice(&mac);
let (result, freed) = freed_by(|| token::decrypt(&token, &key));
assert!(matches!(
result,
Err(token::TokenError::AuthenticationFailed)
));
assert_no_residue(&freed, &[("plaintext", &plaintext[..63])]);
}
#[test]
fn aes_cbc_encrypt_with_a_bad_key_frees_no_plaintext() {
let _serial = serial();
let plaintext: [u8; 64] = pseudo_random(7);
let (result, freed) = freed_by(|| aes_cbc::encrypt(&[0x11; 24], &[0x22; 16], &plaintext));
assert!(matches!(
result,
Err(aes_cbc::AesCbcError::InvalidKeyLength(24))
));
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
}
#[test]
fn derive_key_64_frees_no_key() {
let _serial = serial();
let shared: [u8; 32] = pseudo_random(8);
let salt: [u8; 16] = pseudo_random(9);
let expected = hkdf::hkdf_sha256(64, &shared, Some(&salt), None).unwrap();
let ((), freed) = freed_by(|| {
let derived = hkdf::derive_key_64(&shared, &salt).unwrap();
assert_eq!(&derived[..], &expected[..]);
});
assert_no_residue(&freed, &[("derived key", &expected)]);
}
#[test]
fn hkdf_output_is_wiped_when_dropped() {
let _serial = serial();
let ikm: [u8; 32] = pseudo_random(10);
let salt: [u8; 16] = pseudo_random(11);
let expected = hkdf::derive_key_64(&ikm, &salt).unwrap();
let ((), freed) = freed_by(|| {
let okm: Zeroizing<Vec<u8>> = hkdf::hkdf_sha256(64, &ikm, Some(&salt), None).unwrap();
assert_eq!(&okm[..], &expected[..]);
});
assert_no_residue(&freed, &[("HKDF output", &expected[..])]);
}
+5 -1
View File
@@ -5,7 +5,7 @@ publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
license-file.workspace = true
[dependencies]
rns-crypto = { workspace = true, features = ["std"] }
@@ -19,6 +19,10 @@ serde_bytes = { workspace = true }
rand = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
sha2 = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
+13 -7
View File
@@ -35,7 +35,9 @@ pub enum AnnounceError {
InvalidWireTime(u64),
}
/// Parsed announce data.
/// Parsed announce fields; parsing alone does not authenticate them.
/// Call [`Self::validate`] or [`Self::validate_with_known_key`] before learning
/// a destination. Replay, age and ingress policy belong to the caller.
#[derive(Debug, Clone)]
pub struct AnnounceData {
pub public_key: [u8; 64],
@@ -49,8 +51,9 @@ pub struct AnnounceData {
impl AnnounceData {
/// Create and sign an announce for a destination.
///
/// The `random_hash` is `random(5) || timestamp_be(5)` so receivers can
/// detect replays without a shared clock.
/// The `random_hash` is `random(5) || timestamp_be(5)`, using current Unix
/// seconds. This supplies randomness and ordering information; replay
/// rejection requires receiver state and is not performed by this type.
pub fn create(
identity: &Identity,
app_name: &str,
@@ -64,8 +67,9 @@ impl AnnounceData {
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.
/// Create and sign an announce with an explicit 40-bit ordering value.
/// The caller manages persistence before transmission, and manages rotation
/// and expiry clocks separately. No state is persisted by this method.
pub fn create_at(
identity: &Identity,
app_name: &str,
@@ -149,7 +153,8 @@ impl AnnounceData {
/// Parse an announce from packet payload bytes.
///
/// `has_ratchet` must match the packet header's context flag; the ratchet
/// field is not self-delimiting.
/// field is not self-delimiting. This checks minimum length only; use the
/// validation methods before trusting a parsed announce.
pub fn unpack(data: &[u8], has_ratchet: bool) -> Result<Self, AnnounceError> {
let min_size = if has_ratchet {
MIN_ANNOUNCE_SIZE + RATCHET_SIZE
@@ -261,7 +266,8 @@ impl AnnounceData {
}
/// Validate destination-hash binding and first-seen public-key continuity
/// after [`Self::verify_signature`] has succeeded.
/// after [`Self::verify_signature`] has succeeded. Pass the identity
/// returned by that call; this method does not repeat signature validation.
pub fn validate_destination_binding(
&self,
packet_dest_hash: &[u8; 16],
+26 -3
View File
@@ -64,14 +64,15 @@ impl RatchetControlState {
}
}
/// Rotation is due only when a persisted age exists and the wall clock has
/// Rotation is due only when an age anchor 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.
/// Return a cloned candidate recording the supplied rotation time.
/// The caller performs the rotation and persists the candidate.
pub fn with_rotation_at(&self, wall_now: u64) -> Self {
let mut candidate = self.clone();
candidate.last_rotation_wall = Some(wall_now);
@@ -100,6 +101,22 @@ impl RatchetControlState {
/// Persist this state as a signed, bounded MessagePack envelope.
pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
self.save_verified_impl(path, identity, false)
}
/// Persist announce ordering through [`persistence::durable_write`].
/// The caller must wait for success before releasing the corresponding
/// wire bytes and must handle the storage limits documented by that helper.
pub fn save_verified_durable(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
self.save_verified_impl(path, identity, true)
}
fn save_verified_impl(
&self,
path: &Path,
identity: &Identity,
durable: bool,
) -> std::io::Result<()> {
if identity.hash != self.identity_hash {
return Err(invalid_data("control state identity binding mismatch"));
}
@@ -131,7 +148,13 @@ impl RatchetControlState {
if encoded.len() > CONTROL_STATE_MAX_BYTES {
return Err(invalid_data("ratchet control state exceeds size limit"));
}
persistence::atomic_write(path, &encoded)
if durable {
persistence::durable_write(path, &encoded)
.map(|_| ())
.map_err(std::io::Error::other)
} else {
persistence::atomic_write(path, &encoded)
}
}
/// Load and verify state for exactly `identity` and `destination_hash`.
+44 -20
View File
@@ -9,7 +9,9 @@ use zeroize::Zeroizing;
use crate::identity::{DecryptionResult, Identity};
use crate::name_hash::name_hash;
/// Callback invoked on incoming data packets: `fn(plaintext, raw_packet)`.
/// Callback invoked on incoming DATA: `fn(plaintext, raw_packet)`.
/// [`Destination::receive`] supplies only the payload as its second argument;
/// use [`Destination::receive_packet`] when the callback needs the full packet.
pub type PacketCallback = Box<dyn Fn(&[u8], &[u8]) + Send + Sync>;
/// Callback invoked when a new link is established: `fn(link_id)`.
pub type LinkEstablishedCallback = Box<dyn Fn([u8; 16]) + Send + Sync>;
@@ -191,12 +193,13 @@ pub struct Destination {
pub hash: [u8; 16],
pub name_hash: [u8; 10],
pub app_name: String,
/// Human-readable full destination name, including the identity hash.
/// Human-readable full destination name, including an identity hash when applicable.
pub name: String,
/// Identity hash bound into this destination address, when applicable.
pub identity_hash: Option<[u8; 16]>,
pub proof_strategy: ProofStrategy,
/// If set, incoming data is signature-checked but not decrypted.
/// Compatibility flag stored by the setter. The current receive methods
/// do not consult it; setting it does not enable signature-only validation.
pub only_validate_signature: bool,
group_key: Option<Zeroizing<Vec<u8>>>,
@@ -218,12 +221,15 @@ pub struct Destination {
default_app_data: Option<DefaultAppData>,
pub ratchets_enabled: bool,
/// When set, non-ratchet ciphertexts are rejected.
/// For SINGLE decryption, reject ciphertext not authenticated by a supplied
/// retained ratchet key. Does not change Plain or GROUP decryption.
pub ratchets_enforced: bool,
/// OUT: remote peer's most recent ratchet public key, used for forward-secret encryption.
/// Remote ratchet public key selected by [`Self::pack_packet`] unless
/// explicitly overridden. The caller validates its announce and expiry.
pub remote_ratchet_pub: Option<[u8; 32]>,
/// IN: our current ratchet public key, advertised in announces.
/// Local ratchet public key returned by [`Self::get_ratchet_for_announce`].
/// Announce builders use their explicit ratchet argument.
pub local_ratchet_pub: Option<[u8; 32]>,
path_responses: HashMap<Vec<u8>, PathResponseCache>,
@@ -285,7 +291,10 @@ impl Destination {
///
/// For SINGLE/GROUP inbound destinations, a new identity is generated
/// automatically when `identity` is `None`; retrieve it via
/// [`Destination::auto_identity`].
/// [`Destination::auto_identity`]. In that case the generated identity hash
/// is also appended to `app_name` before computing the name hash. Supply
/// an identity explicitly when addressing a fixed application/aspect name.
/// This constructor neither registers with a runtime nor creates a GROUP key.
///
/// See [`Destination::compute_hash`] for the hash derivation.
pub fn new(
@@ -437,7 +446,8 @@ impl Destination {
self.proof_strategy = strategy;
}
/// Set the pre-shared key used for GROUP encryption.
/// Store a pre-shared key without checking its length or destination type.
/// Prefer [`Self::load_group_key`] for validated GROUP key installation.
pub fn set_group_key(&mut self, key: Vec<u8>) {
self.group_key = Some(Zeroizing::new(key));
}
@@ -493,7 +503,8 @@ impl Destination {
/// Produce a proof over `packet_hash` for this (SINGLE) destination.
///
/// `implicit_proof = true` emits the 64-byte signature alone; otherwise
/// the output is `packet_hash || signature`.
/// the output is `packet_hash || signature`. Pass a 32-byte packet hash;
/// its length is not checked here.
pub fn prove(
&self,
packet_hash: &[u8],
@@ -524,8 +535,8 @@ impl Destination {
///
/// Announce and LinkRequest packets are plaintext. Resource payload,
/// Resource proof, keepalive, cache-request, and LRPROOF contexts are also
/// already protected or intentionally plaintext and therefore bypass
/// destination encryption. Other SINGLE/GROUP packets are encrypted here.
/// exempt from destination encryption. The caller must provide any
/// protection those payloads require. Other SINGLE/GROUP packets are encrypted here.
///
/// Ordinary Link packets remain owned by `LinkSession`; LRPROOF is the
/// sole Link context accepted by this stateless builder.
@@ -625,7 +636,9 @@ impl Destination {
/// Encrypt data for this destination.
///
/// For SINGLE destinations a `remote_ratchet_pub` replaces the identity's
/// X25519 key in the ECDH exchange, giving forward secrecy.
/// X25519 key in ECDH. See [`Identity::encrypt`] for its key-compromise
/// boundaries. This method uses only the ratchet argument, not the stored
/// `remote_ratchet_pub` field; [`Self::pack_packet`] selects that fallback.
pub fn encrypt(
&self,
plaintext: &[u8],
@@ -659,7 +672,8 @@ impl Destination {
self.decrypt_with_ratchets(ciphertext, identity, None)
}
/// Decrypt data, trying each ratchet private key before the identity key.
/// Decrypt data. For SINGLE, try supplied ratchet keys only when ratchets
/// are enabled, then the identity key unless ratchets are enforced.
pub fn decrypt_with_ratchets(
&self,
ciphertext: &[u8],
@@ -710,12 +724,14 @@ impl Destination {
}
}
/// Record the remote peer's ratchet public key, learnt from an announce.
/// Record the remote peer's ratchet public key after the caller validates
/// its announce. This setter performs no authentication or expiry check.
pub fn set_remote_ratchet(&mut self, pub_key: [u8; 32]) {
self.remote_ratchet_pub = Some(pub_key);
}
/// Set our outbound ratchet public key from the ratchet ring.
/// Set the local public key that peers can use for ratcheted encryption to us.
/// The caller retains the corresponding private key in its ratchet ring.
pub fn set_local_ratchet(&mut self, pub_key: [u8; 32]) {
self.local_ratchet_pub = Some(pub_key);
}
@@ -737,7 +753,8 @@ impl Destination {
self.link_established_callback = Some(callback);
}
/// Callback invoked under `ProveApp` strategy; returning `true` emits a proof.
/// Callback queried by [`Self::should_prove`] under `ProveApp`. Returning
/// true asks the runtime to emit a proof; the callback does not send one.
pub fn set_proof_requested_callback(&mut self, callback: ProofRequestedCallback) {
self.proof_requested_callback = Some(callback);
}
@@ -807,9 +824,9 @@ impl Destination {
/// Decrypt and dispatch an incoming packet.
///
/// LINKREQUEST (`0x02`) bypasses decryption and is handled by
/// [`Destination::incoming_link_request`]; DATA (`0x00`) packets
/// additionally fire the packet callback.
/// LINKREQUEST (`0x02`) is returned unchanged; the caller must handle Link
/// admission separately. DATA (`0x00`) also invokes the packet callback,
/// passing `data` as its raw-packet argument because no full packet was supplied.
pub fn receive(
&self,
packet_type: u8,
@@ -891,7 +908,9 @@ impl Destination {
self.accept_link_requests
}
/// Enable ratchet forward secrecy. If `enforce`, non-ratchet inbound ciphertext is rejected.
/// Enable use of supplied ratchet keys for SINGLE decryption. If `enforce`,
/// reject ciphertext that no supplied ratchet key can authenticate.
/// This only changes flags; the caller generates, persists and advertises keys.
pub fn enable_ratchets(&mut self, enforce: bool) {
self.ratchets_enabled = true;
self.ratchets_enforced = enforce;
@@ -949,6 +968,11 @@ impl Destination {
}
/// Build announce data with independent wire-ordering and cache clocks.
///
/// Requires an inbound SINGLE destination. The caller must supply its matching
/// signing identity; this builder does not check that binding. A cached tag
/// returns its prior body even if the supplied app data or ratchet changed.
/// Use the explicit ratchet argument; stored ratchet fields are not selected here.
pub fn create_announce_at(
&mut self,
identity: &Identity,
+87 -22
View File
@@ -3,11 +3,11 @@ use rns_crypto::hkdf::derive_key_64;
use rns_crypto::sha::truncated_hash;
use rns_crypto::token;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use thiserror::Error;
use zeroize::{Zeroize, Zeroizing};
use crate::persistence;
use crate::persistence::{self, SecretBytes};
use std::fmt;
use std::path::Path;
use std::sync::Arc;
@@ -24,7 +24,7 @@ pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
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.
/// HKDF-derived token key length: 32-byte HMAC key || 32-byte AES key.
pub const DERIVED_KEY_LENGTH: usize = 64;
/// Per-message overhead of `Identity::encrypt` before PKCS7 padding:
@@ -57,7 +57,8 @@ pub trait LocalKeyBackend: Send + Sync {
/// X25519 ECDH shared secret with `peer_pub`, or `None` if unavailable.
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]>;
/// Drop any cached authentication so the next operation must re-authenticate
/// (e.g. a hardware token re-locks its PIN). No-op for software backends.
/// (e.g. a hardware token re-locks its PIN). The default is a no-op;
/// backends with cached authentication must implement their own reset.
fn lock(&self) {}
}
@@ -67,6 +68,10 @@ pub trait LocalKeyBackend: Send + Sync {
/// - Private (64 B): `X25519_prv(32) || Ed25519_seed(32)`
/// - Public (64 B): `X25519_pub(32) || Ed25519_pub(32)`
/// - Hash (16 B): `SHA-256(public_64)[:16]`
///
/// Public-only identities can verify and encrypt. Hardware-backed identities
/// delegate private operations without exposing a software private key. Keep
/// the public `hash` unchanged: encryption derivation uses it as the HKDF salt.
pub struct Identity {
prv: Option<X25519PrivateKey>,
sig_prv: Option<Ed25519PrivateKey>,
@@ -120,6 +125,7 @@ impl Identity {
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
pub const HASH_LENGTH_BITS: usize = HASH_LENGTH_BITS;
/// Generate a software identity with fresh X25519 and Ed25519 keys.
pub fn new() -> Self {
let prv = X25519PrivateKey::generate();
let sig_prv = Ed25519PrivateKey::generate();
@@ -137,6 +143,8 @@ impl Identity {
}
}
/// Load exactly 64 bytes: an X25519 private key followed by an Ed25519 seed.
/// The caller remains responsible for protecting and wiping its input.
pub fn from_private_key(key: &[u8]) -> Result<Self, IdentityError> {
if key.len() != 64 {
return Err(IdentityError::InvalidPrivateKeyLength(key.len()));
@@ -163,6 +171,8 @@ impl Identity {
}
/// Construct a verify/encrypt-only identity from its 64-byte public key.
/// Checks the length and Ed25519 key encoding; it does not establish who
/// owns the key or reject low-order X25519 input.
pub fn from_public_key(key: &[u8]) -> Result<Self, IdentityError> {
if key.len() != 64 {
return Err(IdentityError::InvalidPublicKeyLength(key.len()));
@@ -188,7 +198,9 @@ impl Identity {
/// Construct an identity whose private operations are served by `backend`
/// (e.g. a hardware token). Public-key-only in memory; `sign` and `decrypt`
/// delegate to the backend. Wire-identical to a software identity.
/// delegate to the backend for base-key operations. The caller must ensure
/// the backend owns the matching private keys and implements the trait
/// contract; construction does not perform a signing or ECDH challenge.
pub fn from_backend(
public_key: &[u8],
backend: Arc<dyn LocalKeyBackend>,
@@ -198,12 +210,16 @@ impl Identity {
Ok(id)
}
/// Load an identity from file, accepting either the current msgpack envelope
/// or a legacy raw 64-byte private key.
/// Load an identity from file, accepting either the raw 64-byte private key
/// that Python and [`Self::to_file`] write, or the older msgpack envelope.
/// A file larger than 1 KiB is refused once 1025 bytes have been read.
pub fn from_file(path: &Path) -> Result<Self, IdentityError> {
let data = std::fs::read(path)?;
let data = persistence::read_secret_file(path, IDENTITY_FILE_MAX_BYTES)?;
if let Ok(persisted) = rmp_serde::from_slice::<IdentityPersisted>(&data) {
// An envelope never fits in 64 bytes, so a raw key is never parsed as one.
if data.len() != 64
&& let Ok(persisted) = rmp_serde::from_slice::<IdentityPersisted>(&data)
{
return Self::from_private_key(&persisted.private_key);
}
@@ -211,7 +227,9 @@ impl Identity {
}
/// Persist the identity as the raw 64-byte private key used by the Python
/// reference implementation, so identity files are interchangeable.
/// reference implementation. This is an unencrypted secret-key file.
/// Fails for public-only and hardware-backed identities because their
/// private key is not extractable here. Uses [`persistence::atomic_write`].
pub fn to_file(&self, path: &Path) -> Result<(), IdentityError> {
let key = self
.get_private_key()
@@ -226,7 +244,8 @@ impl Identity {
Ok(())
}
/// Return the 64-byte private key (`X25519_prv || Ed25519_seed`), zeroised on drop.
/// Return a copy of the software private key (`X25519_prv || Ed25519_seed`),
/// zeroised on drop. Returns `None` for public-only or backend identities.
pub fn get_private_key(&self) -> Option<Zeroizing<[u8; 64]>> {
let prv = self.prv.as_ref()?;
let sig_prv = self.sig_prv.as_ref()?;
@@ -249,6 +268,8 @@ impl Identity {
hex::encode(self.hash)
}
/// Whether both software private keys are present. A hardware-backed
/// identity returns false even when its backend can sign or decrypt.
pub fn has_private_key(&self) -> bool {
self.prv.is_some() && self.sig_prv.is_some()
}
@@ -258,14 +279,16 @@ impl Identity {
self.backend.is_some()
}
/// Re-lock the hardware backend (drop its cached authentication). No-op for
/// software identities. The next private operation will fail until re-auth.
/// Ask the backend to clear cached authentication; a no-op without a backend.
/// Subsequent authentication behavior is defined by [`LocalKeyBackend::lock`].
pub fn lock(&self) {
if let Some(b) = self.backend.as_ref() {
b.lock();
}
}
/// Copy the software signing key; returns `None` for public-only and
/// backend identities. Use [`Self::sign`] to support either private backend.
pub fn get_signing_key(&self) -> Option<Ed25519PrivateKey> {
self.sig_prv
.as_ref()
@@ -281,6 +304,7 @@ impl Identity {
}
}
/// Verify an Ed25519 signature with this identity's public signing key.
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
self.sig_pub.verify(message, signature).is_ok()
}
@@ -290,8 +314,10 @@ impl Identity {
/// Output layout: `ephemeral_X25519_pub(32) || IV(16) || AES-256-CBC(PKCS7(pt)) || HMAC(32)`.
///
/// Passing a `ratchet` public key substitutes it for the identity's X25519
/// public key in the ECDH, giving forward secrecy against later key
/// compromise.
/// public key in ECDH. Later compromise of the base identity key alone
/// does not reveal that ciphertext; compromise of a retained ratchet
/// private key still does. The caller must authenticate the target key.
/// Encryption does not sign the plaintext or identify its sender.
pub fn encrypt(
&self,
plaintext: &[u8],
@@ -311,7 +337,7 @@ impl Identity {
shared.zeroize();
let derived = derived?;
let ciphertext =
token::encrypt(plaintext, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
token::encrypt(plaintext, &derived[..]).map_err(|_| IdentityError::DecryptionFailed)?;
let mut result = Vec::with_capacity(32 + ciphertext.len());
result.extend_from_slice(&ephemeral_pub.to_bytes());
@@ -358,7 +384,7 @@ impl Identity {
let derived_result = derive_key_64(&shared, &self.hash);
shared.zeroize();
if let Ok(derived) = derived_result
&& let Ok(plaintext) = token::decrypt(ct, &derived)
&& let Ok(plaintext) = token::decrypt(ct, &derived[..])
{
return Ok(DecryptionResult {
plaintext,
@@ -387,7 +413,7 @@ impl Identity {
shared.zeroize();
let derived = derived_result?;
let plaintext =
token::decrypt(ct, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
token::decrypt(ct, &derived[..]).map_err(|_| IdentityError::DecryptionFailed)?;
Ok(DecryptionResult {
plaintext,
ratchet_id: None,
@@ -405,7 +431,8 @@ impl Identity {
/// Sign `packet_hash` and return proof bytes.
///
/// `implicit_proof = true` returns the 64-byte signature alone; `false`
/// returns `packet_hash(32) || signature(64)` (96 bytes).
/// returns `packet_hash || signature`. Pass a 32-byte packet hash for the
/// 96-byte wire form; this method accepts other input lengths without validation.
pub fn prove(
&self,
packet_hash: &[u8],
@@ -439,10 +466,15 @@ impl fmt::Display for Identity {
}
}
/// Identity files are a raw key or a small envelope; reading stops one byte
/// past this limit and refuses the file.
const IDENTITY_FILE_MAX_BYTES: usize = 1024;
// Msgpack envelope wrapping the raw 64-byte private key on disk.
#[derive(Serialize, Deserialize)]
struct IdentityPersisted {
private_key: Vec<u8>,
#[derive(Deserialize)]
struct IdentityPersisted<'a> {
#[serde(borrow)]
private_key: SecretBytes<'a, IDENTITY_FILE_MAX_BYTES>,
}
#[cfg(test)]
@@ -592,6 +624,39 @@ mod tests {
let _ = std::fs::remove_dir(&dir);
}
#[test]
fn raw_keys_that_begin_like_an_envelope_load_as_raw_keys() {
let dir = std::env::temp_dir().join(format!(
"reticulum_identity_test_envelope_prefix_{}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
// One-field msgpack arrays holding an empty array, 61 bytes of binary
// that end exactly at byte 64, and three integers.
let prefixes: [&[u8]; 3] = [&[0x91, 0x90], &[0x91, 0xc4, 0x3d], &[0x91, 0x93, 1, 2, 3]];
let mut failures = Vec::new();
for (index, prefix) in prefixes.into_iter().enumerate() {
let mut key = [0u8; 64];
for (offset, byte) in key.iter_mut().enumerate() {
*byte = (offset as u8).wrapping_mul(37).wrapping_add(index as u8);
}
key[..prefix.len()].copy_from_slice(prefix);
let expected = Identity::from_private_key(&key).unwrap();
let path = dir.join(format!("identity-{index}"));
std::fs::write(&path, key).unwrap();
match Identity::from_file(&path) {
Ok(loaded) => {
assert_eq!(loaded.hash, expected.hash, "prefix {prefix:02x?}");
assert_eq!(*loaded.get_private_key().unwrap(), key);
}
Err(e) => failures.push(format!("prefix {prefix:02x?}: {e}")),
}
}
std::fs::remove_dir_all(&dir).unwrap();
assert!(failures.is_empty(), "{failures:?}");
}
#[test]
fn test_file_backward_compat_raw() {
let dir = std::env::temp_dir().join("reticulum_identity_test_compat");
+106 -7
View File
@@ -1,6 +1,9 @@
use std::sync::Arc;
use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use thiserror::Error;
use zeroize::Zeroizing;
/// Fixed IFAC HKDF salt shared with the Python reference.
///
@@ -21,13 +24,24 @@ pub enum IfacError {
///
/// `ifac_origin` concatenates `SHA-256(network_name)` and `SHA-256(passphrase)`
/// for whichever fields are `Some(_)` (a `None` field is omitted, so `None`
/// and `Some("")` differ), then HKDF-SHA256 expands it under the fixed salt.
/// and `Some("")` differ). HKDF-SHA256 expands `SHA-256(ifac_origin)` under
/// the fixed salt.
/// First 32 bytes → X25519 private; second 32 → Ed25519 seed.
pub fn derive_ifac_key(
network_name: Option<&str>,
passphrase: Option<&str>,
) -> Result<[u8; 64], IfacError> {
let mut ifac_origin = Vec::new();
let mut key = [0u8; 64];
derive_into(network_name, passphrase, &mut key)?;
Ok(key)
}
fn derive_into(
network_name: Option<&str>,
passphrase: Option<&str>,
key: &mut [u8; 64],
) -> Result<(), IfacError> {
let mut ifac_origin = Zeroizing::new(Vec::with_capacity(64));
if let Some(name) = network_name {
ifac_origin.extend_from_slice(&sha256(name.as_bytes()));
@@ -36,14 +50,60 @@ pub fn derive_ifac_key(
ifac_origin.extend_from_slice(&sha256(key.as_bytes()));
}
let ifac_origin_hash = sha256(&ifac_origin);
let ifac_origin_hash = Zeroizing::new(sha256(&ifac_origin));
let salt = hex_decode(IFAC_SALT).ok_or(IfacError::InvalidSalt)?;
let derived = hkdf_sha256(64, &ifac_origin_hash, Some(&salt), None)?;
let mut key = [0u8; 64];
let derived = hkdf_sha256(64, &*ifac_origin_hash, Some(&salt), None)?;
key.copy_from_slice(&derived);
Ok(key)
Ok(())
}
/// A derived IFAC key in one heap allocation, wiped when its last clone
/// drops. Clones share the allocation, so tables and queues that move or copy
/// an interface's settings never copy the key.
#[derive(Clone)]
pub struct IfacKey(Arc<Zeroizing<[u8; 64]>>);
impl IfacKey {
/// [`derive_ifac_key`], written straight into the shared allocation.
pub fn derive(network_name: Option<&str>, passphrase: Option<&str>) -> Result<Self, IfacError> {
let mut key = Arc::new(Zeroizing::new([0u8; 64]));
derive_into(
network_name,
passphrase,
Arc::get_mut(&mut key).expect("a new Arc is unique"),
)?;
Ok(Self(key))
}
}
impl From<[u8; 64]> for IfacKey {
fn from(key: [u8; 64]) -> Self {
Self(Arc::new(Zeroizing::new(key)))
}
}
impl std::ops::Deref for IfacKey {
type Target = [u8; 64];
fn deref(&self) -> &[u8; 64] {
&self.0
}
}
impl PartialEq for IfacKey {
fn eq(&self, other: &Self) -> bool {
self.0[..] == other.0[..]
}
}
impl Eq for IfacKey {}
impl std::fmt::Debug for IfacKey {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("IfacKey(<redacted>)")
}
}
/// Build the IFAC identity plus a self-signature over `SHA-256(ifac_key)`.
@@ -64,7 +124,18 @@ pub fn derive_ifac_identity(
Ok((identity, ifac_key, signature))
}
/// Split IFAC key into `(signing_key, masking_key)`, each 32 bytes.
/// The IFAC identity's signature over `SHA-256(ifac_key)`, which Python
/// publishes as an interface's `ifac_signature`.
pub fn ifac_signature(ifac_key: &[u8; 64]) -> Option<[u8; 64]> {
crate::identity::Identity::from_private_key(ifac_key)
.ok()?
.sign(&sha256(ifac_key))
}
/// Split the derived identity material into its first and second 32-byte halves.
/// They are the X25519 private bytes and Ed25519 seed, respectively.
/// IFAC packet masking uses the full 64-byte key as its HKDF salt; the first
/// half is not a separate packet-signing key.
pub fn split_ifac_key(key: &[u8; 64]) -> (&[u8], &[u8]) {
(&key[..32], &key[32..])
}
@@ -83,6 +154,17 @@ fn hex_decode(s: &str) -> Option<Vec<u8>> {
mod tests {
use super::*;
#[test]
fn shared_key_matches_the_derived_bytes() {
let key = IfacKey::derive(Some("testnet"), Some("password")).unwrap();
assert_eq!(
*key,
derive_ifac_key(Some("testnet"), Some("password")).unwrap()
);
assert_eq!(key, IfacKey::from(*key));
assert_eq!(format!("{key:?}"), "IfacKey(<redacted>)");
}
#[test]
fn test_ifac_derivation_deterministic() {
let key1 = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
@@ -139,5 +221,22 @@ mod tests {
let key_hash = sha256(&ifac_key);
assert!(identity.verify(&key_hash, &signature));
assert_eq!(ifac_signature(&ifac_key), Some(signature));
}
/// Upstream `Identity.from_bytes(key).sign(Identity.full_hash(key))` for
/// the `ifac_testnet_password` vector key.
#[test]
fn ifac_signature_matches_upstream() {
let key = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
let expected = hex_decode(
"ce6b8bc4028852077243868e4b5f7faadb715c7a2fb75d1a211d30035f65b0c1\
fc4271ef61e91599e7bcc42723afe97503e3c432b01264185233274e3603e708",
)
.unwrap();
assert_eq!(
ifac_signature(&key).unwrap().as_slice(),
expected.as_slice()
);
}
}
@@ -5,7 +5,8 @@ use std::path::Path;
use crate::persistence;
use rmpv::Value;
/// Record of a destination learnt from a validated announce.
/// Record intended for a destination learned from a validated announce.
/// Construction and file loading do not perform announce authentication.
#[derive(Debug, Clone)]
pub struct KnownDestination {
/// Learn time as a Unix timestamp (seconds).
@@ -33,6 +34,8 @@ impl KnownDestinations {
/// Insert or refresh the entry for `dest_hash`. The `retained` flag is
/// preserved on update so a fresh announce never un-pins an entry.
/// The caller validates the announce, destination binding and key continuity;
/// this method can replace an existing key without checking them.
pub fn remember(
&mut self,
dest_hash: [u8; 16],
@@ -147,7 +150,8 @@ impl KnownDestinations {
/// Drop stale entries past `destination_timeout_secs`. `has_path` is a
/// caller-supplied path-table lookup (this crate doesn't depend on
/// rns-transport). Returns the hashes that were dropped.
/// rns-transport). Pinned entries and entries with a current path are retained.
/// Returns the hashes that were dropped.
pub fn cleanup(
&mut self,
now: f64,
+350 -72
View File
@@ -3,6 +3,17 @@ use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use zeroize::Zeroizing;
mod file_lock;
mod strict;
pub use file_lock::try_lock_exclusive;
pub use strict::{
DurableCleanupOutcome, DurableCommitPhase, DurableDirectoryReceipt, DurableErrorKind,
DurableFileReceipt, DurableWriteError, StorageRisk, durable_create_dir_all, durable_reconcile,
durable_reconcile_directory, durable_reconcile_hash, durable_remove, durable_rename_directory,
durable_write, storage_risk, validate_durable_storage_directory,
};
static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
static ATOMIC_WRITE_LOCK: Mutex<()> = Mutex::new(());
@@ -60,25 +71,132 @@ fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(test), allow(dead_code))]
enum InjectedFailure {
Create,
Write,
Flush,
Sync,
VerifyTemp,
Rename,
VerifyFinal,
/// `Read::read`, retried when a signal interrupts it.
fn read_retrying(reader: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
loop {
match reader.read(buf) {
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
result => return result,
}
}
}
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(())
/// Compare the file at `path` with `data`. The file is read through a stack
/// buffer that is wiped afterwards, so reading back a secret leaves no copy.
fn verify_bytes(path: &Path, data: &[u8]) -> std::io::Result<()> {
let mut file = fs::File::open(path)?;
let mut offset: usize = 0;
let mut chunk = Zeroizing::new([0u8; 8192]);
loop {
let count = read_retrying(&mut file, &mut chunk[..])?;
if count == 0 {
break;
}
let end = offset
.checked_add(count)
.filter(|end| data.get(offset..*end) == Some(&chunk[..count]))
.ok_or_else(|| invalid_data("file readback mismatch"))?;
offset = end;
}
if offset != data.len() {
return Err(invalid_data("file readback length mismatch"));
}
Ok(())
}
/// Read a secret file of at most `max_len` bytes into one buffer that is
/// allocated up front and wiped on drop, so neither growth nor a failed read
/// leaves a copy behind. A longer file is refused with `InvalidData` once
/// `max_len + 1` bytes have been read.
pub fn read_secret_file(path: &Path, max_len: usize) -> std::io::Result<Zeroizing<Vec<u8>>> {
let mut file = fs::File::open(path)?;
let mut data = Zeroizing::new(vec![0u8; max_len.saturating_add(1)]);
let mut filled = 0;
while filled < data.len() {
match read_retrying(&mut file, &mut data[filled..])? {
0 => break,
count => filled += count,
}
}
if filled > max_len {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("file exceeds {max_len}-byte limit"),
));
}
data.truncate(filled);
Ok(data)
}
/// A msgpack byte field read from a secret file. Binary and string values
/// borrow from a slice input; integer arrays fill a buffer reserved once (at
/// most `MAX` bytes) and wiped on drop, so neither growth nor a failed decode
/// leaves a copy behind.
pub(crate) enum SecretBytes<'a, const MAX: usize> {
Borrowed(&'a [u8]),
Owned(Zeroizing<Vec<u8>>),
}
impl<const MAX: usize> std::ops::Deref for SecretBytes<'_, MAX> {
type Target = [u8];
fn deref(&self) -> &[u8] {
match self {
Self::Borrowed(bytes) => bytes,
Self::Owned(bytes) => bytes,
}
}
}
impl<'de: 'a, 'a, const MAX: usize> serde::Deserialize<'de> for SecretBytes<'a, MAX> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_bytes(SecretBytesVisitor::<MAX>)
}
}
struct SecretBytesVisitor<const MAX: usize>;
impl<'de, const MAX: usize> serde::de::Visitor<'de> for SecretBytesVisitor<MAX> {
type Value = SecretBytes<'de, MAX>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a byte array")
}
fn visit_borrowed_bytes<E: serde::de::Error>(self, bytes: &'de [u8]) -> Result<Self::Value, E> {
Ok(SecretBytes::Borrowed(bytes))
}
fn visit_borrowed_str<E: serde::de::Error>(self, text: &'de str) -> Result<Self::Value, E> {
Ok(SecretBytes::Borrowed(text.as_bytes()))
}
fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
Ok(SecretBytes::Owned(Zeroizing::new(bytes.to_vec())))
}
fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Self::Value, E> {
self.visit_bytes(text.as_bytes())
}
fn visit_byte_buf<E: serde::de::Error>(self, bytes: Vec<u8>) -> Result<Self::Value, E> {
Ok(SecretBytes::Owned(Zeroizing::new(bytes)))
}
fn visit_string<E: serde::de::Error>(self, text: String) -> Result<Self::Value, E> {
self.visit_byte_buf(text.into_bytes())
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let capacity = seq.size_hint().unwrap_or(0).min(MAX);
let mut bytes = Zeroizing::new(Vec::with_capacity(capacity));
while let Some(byte) = seq.next_element::<u8>()? {
if bytes.len() == capacity {
return Err(serde::de::Error::invalid_length(capacity + 1, &self));
}
bytes.push(byte);
}
Ok(SecretBytes::Owned(bytes))
}
}
@@ -88,25 +206,17 @@ fn fail_if(stage: InjectedFailure, injected: Option<InjectedFailure>) -> std::io
/// On Unix the temp file is created with mode `0600` so that key material is
/// 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.
/// the rename, parent-directory fsync is best-effort on Unix; its failure does
/// not fail this operation. This is not a guarantee of survival after power
/// loss. Use [`durable_write`] when the caller needs its stricter receipt and
/// recovery-path handling, subject to that helper's filesystem limits.
pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
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;
@@ -122,32 +232,14 @@ fn atomic_write_inner(
.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);
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)?;
verify_bytes(&tmp_path, data)?;
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"));
}
verify_bytes(path, data)?;
#[cfg(unix)]
if let Some(dir) = path.parent()
@@ -203,7 +295,7 @@ mod tests {
use super::*;
use std::path::PathBuf;
fn unique_test_dir(label: &str) -> PathBuf {
pub(super) 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!(
@@ -257,43 +349,146 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
/// Root ignores directory permissions.
#[cfg(unix)]
pub(super) fn is_root() -> bool {
unsafe { libc::geteuid() == 0 }
}
/// Holds the macOS user immutable flag (`chflags uchg`) on a file.
#[cfg(target_os = "macos")]
pub(super) struct Immutable(PathBuf);
#[cfg(target_os = "macos")]
impl Immutable {
pub(super) fn new(path: &Path) -> Self {
Self::set(path, libc::UF_IMMUTABLE);
Self(path.to_path_buf())
}
fn set(path: &Path, flags: libc::c_uint) {
use std::os::unix::ffi::OsStrExt;
let path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
assert_eq!(unsafe { libc::chflags(path.as_ptr(), flags) }, 0);
}
}
#[cfg(target_os = "macos")]
impl Drop for Immutable {
fn drop(&mut self) {
Self::set(&self.0, 0);
}
}
#[test]
fn test_atomic_write_faults_before_rename_preserve_previous_file() {
let dir = unique_test_dir("atomic-faults");
fn atomic_write_into_a_missing_directory_fails_without_creating_it() {
let dir = unique_test_dir("atomic-missing-parent");
let err = atomic_write(&dir.join("state"), b"candidate").unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
assert!(!dir.exists());
}
#[cfg(unix)]
#[test]
fn atomic_write_in_a_read_only_directory_keeps_the_previous_file() {
use std::os::unix::fs::PermissionsExt;
if is_root() {
return;
}
let dir = unique_test_dir("atomic-read-only");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
fs::set_permissions(&dir, fs::Permissions::from_mode(0o500)).unwrap();
for stage in [
InjectedFailure::Create,
InjectedFailure::Write,
InjectedFailure::Flush,
InjectedFailure::Sync,
InjectedFailure::VerifyTemp,
InjectedFailure::Rename,
let result = atomic_write(&path, b"candidate");
fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
assert_eq!(
result.unwrap_err().kind(),
std::io::ErrorKind::PermissionDenied
);
assert_eq!(fs::read(&path).unwrap(), b"previous");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn atomic_write_onto_a_directory_leaves_it_and_no_temporary_file() {
let dir = unique_test_dir("atomic-directory-target");
let target = dir.join("state");
fs::create_dir_all(&target).unwrap();
fs::write(target.join("kept"), b"kept").unwrap();
assert!(atomic_write(&target, b"candidate").is_err());
assert_eq!(fs::read(target.join("kept")).unwrap(), b"kept");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[cfg(target_os = "macos")]
#[test]
fn atomic_write_onto_an_immutable_file_keeps_it() {
let dir = unique_test_dir("atomic-immutable");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
let immutable = Immutable::new(&path);
let result = atomic_write(&path, b"candidate");
drop(immutable);
assert!(result.is_err());
assert_eq!(fs::read(&path).unwrap(), b"previous");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn readback_verification_rejects_changed_short_and_long_files() {
let dir = unique_test_dir("readback");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
let data: Vec<u8> = (0..20_000u32).map(|i| (i % 251) as u8).collect();
fs::write(&path, &data).unwrap();
verify_bytes(&path, &data).unwrap();
let mut changed = data.clone();
changed[12_345] ^= 1;
for (name, contents) in [
("changed", changed),
("short", data[..data.len() - 1].to_vec()),
("long", [&data[..], b"!"].concat()),
("empty", Vec::new()),
] {
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::write(&path, contents).unwrap();
let err = verify_bytes(&path, &data).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData, "{name}");
}
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn test_atomic_write_final_readback_failure_is_reported() {
let dir = unique_test_dir("atomic-readback-fault");
fn secret_reads_are_bounded() {
let dir = unique_test_dir("secret-read");
fs::create_dir_all(&dir).unwrap();
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
let path = dir.join("secret");
let err = atomic_write_inner(&path, b"candidate", Some(InjectedFailure::VerifyFinal))
.unwrap_err();
assert!(err.to_string().contains("injected"));
fs::write(&path, [0xA5; 64]).unwrap();
assert_eq!(&read_secret_file(&path, 64).unwrap()[..], &[0xA5; 64]);
assert_eq!(
fs::read(&path).unwrap(),
b"candidate",
"the caller must not commit live state even if replacement reached disk"
read_secret_file(&path, 63).unwrap_err().kind(),
std::io::ErrorKind::InvalidData
);
fs::write(&path, b"").unwrap();
assert!(read_secret_file(&path, 64).unwrap().is_empty());
assert_eq!(
read_secret_file(&dir.join("missing"), 64)
.unwrap_err()
.kind(),
std::io::ErrorKind::NotFound
);
fs::remove_dir_all(dir).unwrap();
@@ -321,4 +516,87 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
/// Feed `data` to `read` through a FIFO in two halves, signalling the
/// reading thread while it waits for the second. The handler is installed
/// without `SA_RESTART`, so that wait fails with EINTR.
#[cfg(unix)]
pub(super) fn read_through_a_signal<T: Send + 'static>(
label: &str,
data: &[u8],
read: impl FnOnce(&Path) -> std::io::Result<T> + Send + 'static,
) -> std::io::Result<T> {
use std::os::unix::ffi::OsStrExt;
extern "C" fn ignore(_: libc::c_int) {}
let dir = unique_test_dir(label);
fs::create_dir_all(&dir).unwrap();
let path = dir.join("fifo");
let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
unsafe {
assert_eq!(libc::mkfifo(c_path.as_ptr(), 0o600), 0);
let mut action: libc::sigaction = std::mem::zeroed();
action.sa_sigaction = ignore as extern "C" fn(libc::c_int) as libc::sighandler_t;
libc::sigemptyset(&mut action.sa_mask);
assert_eq!(
libc::sigaction(libc::SIGUSR1, &action, std::ptr::null_mut()),
0
);
}
let (thread_tx, thread_rx) = std::sync::mpsc::channel();
let reader_path = path.clone();
let reader = std::thread::spawn(move || {
thread_tx
.send(unsafe { libc::pthread_self() } as usize)
.unwrap();
read(&reader_path)
});
let thread = thread_rx.recv().unwrap() as libc::pthread_t;
let mut fifo = fs::OpenOptions::new().write(true).open(&path).unwrap();
let (first, second) = data.split_at(data.len() / 2);
fifo.write_all(first).unwrap();
for _ in 0..5 {
std::thread::sleep(std::time::Duration::from_millis(20));
unsafe { libc::pthread_kill(thread, libc::SIGUSR1) };
}
// A reader that gave up has closed its end.
let _ = fifo.write_all(second);
drop(fifo);
// Fail instead of hanging if another descriptor still holds the writer.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while !reader.is_finished() {
assert!(
std::time::Instant::now() < deadline,
"reader of {} saw no EOF 30 s after the writer closed",
path.display()
);
std::thread::sleep(std::time::Duration::from_millis(1));
}
let result = reader.join().unwrap();
fs::remove_dir_all(dir).unwrap();
result
}
#[cfg(unix)]
#[test]
fn readback_verification_retries_an_interrupted_read() {
let data = vec![0x5a; 64];
let expected = data.clone();
let result = read_through_a_signal("verify-interrupted", &data, move |path| {
verify_bytes(path, &expected)
});
assert!(result.is_ok(), "{result:?}");
}
#[cfg(unix)]
#[test]
fn secret_file_read_retries_an_interrupted_read() {
let data = vec![0xa5; 64];
let read = read_through_a_signal("secret-read-interrupted", &data, |path| {
read_secret_file(path, 1024)
});
assert_eq!(read.unwrap()[..], data[..]);
}
}
@@ -0,0 +1,72 @@
//! Nonblocking OS file-lock portability. Android's standard-library File lock
//! implementation is unsupported on some supported toolchains; bionic flock
//! provides the same retained-open-file-description ownership on that target.
use std::fs::File;
use std::io;
/// Take an exclusive advisory lock without waiting. Retain the original file
/// for the complete protected operation; do not clone/close handles to transfer
/// ownership since duplication semantics differ by platform. Closing the owning
/// handles (including on process exit) releases the lock. Contention is
/// `WouldBlock`, and unsupported or failed backends are errors, never success.
/// Do not delete/recreate the lock file while an owner may still hold it.
pub fn try_lock_exclusive(file: &File) -> io::Result<()> {
#[cfg(target_os = "android")]
{
use std::os::fd::AsRawFd;
// SAFETY: the borrowed File keeps its descriptor alive for this call;
// flock neither takes ownership nor writes through any Rust pointer.
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(target_os = "android"))]
file.try_lock().map_err(|error| match error {
std::fs::TryLockError::WouldBlock => {
io::Error::new(io::ErrorKind::WouldBlock, "file is locked by another owner")
}
std::fs::TryLockError::Error(error) => error,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn lock_files() -> (std::path::PathBuf, File, File) {
let path = super::super::tests::unique_test_dir("native-lock");
let first = File::create_new(&path).unwrap();
let second = File::options().read(true).write(true).open(&path).unwrap();
(path, first, second)
}
#[test]
fn native_file_lock_contends_and_releases_on_drop() {
let (path, first, second) = lock_files();
try_lock_exclusive(&first).unwrap();
assert_eq!(
try_lock_exclusive(&second).unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
drop(first);
try_lock_exclusive(&second).unwrap();
drop(second);
std::fs::remove_file(path).unwrap();
}
#[cfg(unix)]
#[test]
fn native_file_lock_duplicate_keeps_exclusion_until_last_close() {
let (path, first, second) = lock_files();
try_lock_exclusive(&first).unwrap();
let retained = first.try_clone().unwrap();
drop(first);
assert_eq!(
try_lock_exclusive(&second).unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
drop(retained);
try_lock_exclusive(&second).unwrap();
drop(second);
std::fs::remove_file(path).unwrap();
}
}
File diff suppressed because it is too large. Load diff
+155 -82
View File
@@ -8,7 +8,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use zeroize::{Zeroize, Zeroizing};
use crate::identity::Identity;
use crate::persistence;
use crate::persistence::{self, SecretBytes};
const RATCHET_FILE_MAX_BYTES: usize = 64 * 1024;
const RATCHET_PACKED_MAX_BYTES: usize = 32 * 1024;
@@ -30,25 +30,38 @@ fn pack_ratchet_keys(keys: &[[u8; 32]]) -> std::io::Result<Zeroizing<Vec<u8>>> {
.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()))?,
);
// Sized up front: a growing buffer would free copies of the keys.
let mut packed = Zeroizing::new(Vec::with_capacity(RATCHET_PACKED_MAX_BYTES));
rmp_serde::encode::write(&mut *packed, &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 encode_ring_file(signature: &[u8; 64], packed: &[u8]) -> std::io::Result<Zeroizing<Vec<u8>>> {
let persisted = RatchetRingPersistedWrite {
signature,
ratchets: packed,
};
// Sized up front: a growing buffer would free copies of the keys.
let mut buf = Zeroizing::new(Vec::with_capacity(RATCHET_FILE_MAX_BYTES));
rmp_serde::encode::write_named(&mut *buf, &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"));
}
Ok(buf)
}
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> =
let encoded_keys: Vec<SecretBytes<'_, RATCHET_PACKED_MAX_BYTES>> =
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()
@@ -56,18 +69,13 @@ fn unpack_ratchet_keys(packed: &[u8]) -> std::io::Result<Vec<[u8; 32]>> {
}
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];
keys.resize(encoded_keys.len(), [0u8; 32]);
for (key, encoded) in keys.iter_mut().zip(&encoded_keys) {
key.copy_from_slice(encoded);
keys.push(key);
encoded.as_mut().zeroize();
}
Ok(keys)
}
@@ -83,7 +91,9 @@ pub enum RatchetRingFormat {
LegacyRust,
}
/// A verified ratchet ring plus the format that was read from disk.
/// A loaded ring and its accepted signature format. Inspect the format when
/// requiring authentication of every retained key; legacy signatures cover
/// only the current public key, not the whole historical ring.
pub struct LoadedRatchetRing {
ring: RatchetRing,
format: RatchetRingFormat,
@@ -107,7 +117,9 @@ impl LoadedRatchetRing {
///
/// Index 0 is the most recent key; older keys are retained so decryption can
/// still succeed for in-flight ciphertexts. All key material is zeroised on
/// drop and on truncation.
/// drop and on truncation. Retained private keys still decrypt their historical
/// ciphertext; forward secrecy after device compromise depends on erasing old
/// keys and any copies, including persisted rings and backups.
pub struct RatchetRing {
keys: Vec<[u8; 32]>,
last_rotation: f64,
@@ -158,7 +170,8 @@ impl RatchetRing {
pub_key
}
/// True when at least `rotation_interval` seconds have elapsed since the last rotate.
/// Whether rotation is due at the current wall time. An unknown age is
/// also due; see [`Self::needs_rotation_at`].
pub fn needs_rotation(&self) -> bool {
self.needs_rotation_at(wall_time_secs())
}
@@ -201,7 +214,8 @@ impl RatchetRing {
}
}
/// Replace the live ring with a previously persisted candidate.
/// Replace the live ring with a candidate. The caller must persist it first
/// when durability is required; this method does not verify persistence.
pub fn commit_prepared_rotation(&mut self, prepared: PreparedRatchetRotation) -> [u8; 32] {
let PreparedRatchetRotation {
mut candidate,
@@ -287,24 +301,29 @@ impl RatchetRing {
/// 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 = pack_ratchet_keys(&self.keys)?;
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"));
}
let buf = encode_ring_file(signature, &ratchets_packed)?;
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<()> {
self.save_verified_impl(path, identity, false)
}
/// Sign and persist using [`persistence::durable_write`], with its platform
/// barriers and filesystem limits. An uncertain publication is an error,
/// never a successful checkpoint.
pub fn save_verified_durable(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
self.save_verified_impl(path, identity, true)
}
fn save_verified_impl(
&self,
path: &Path,
identity: &Identity,
durable: bool,
) -> std::io::Result<()> {
let ratchets_packed = pack_ratchet_keys(&self.keys)?;
let signature = identity.sign(&ratchets_packed).ok_or_else(|| {
std::io::Error::new(
@@ -313,22 +332,20 @@ impl RatchetRing {
)
})?;
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"));
let buf = encode_ring_file(&signature, &ratchets_packed)?;
if durable {
persistence::durable_write(path, &buf)
.map(|_| ())
.map_err(std::io::Error::other)
} else {
persistence::atomic_write(path, &buf)
}
persistence::atomic_write(path, &buf)
}
/// Load the ring, retrying with 1s/2s/4s backoff to ride out transient
/// read errors while another process is rewriting the file.
/// read or decode errors. Returns the ring and signature without verifying
/// that signature. Use [`Self::load_verified`] for authenticated loading.
/// This synchronous call can sleep for seven seconds across retries.
pub fn load(path: &Path) -> std::io::Result<(Self, [u8; 64])> {
let mut last_err = None;
let delays_ms = [0, 1000, 2000, 4000];
@@ -338,8 +355,9 @@ impl RatchetRing {
std::thread::sleep(std::time::Duration::from_millis(*delay));
}
match Self::try_load(path) {
Ok(decoded) => return Ok((decoded.ring, decoded.signature)),
let data = persistence::read_secret_file(path, RATCHET_FILE_MAX_BYTES);
match data.and_then(|data| Self::decode(&data).map(|d| (d.ring, d.signature))) {
Ok(loaded) => return Ok(loaded),
Err(e) => {
if attempt < delays_ms.len() - 1 {
tracing::warn!(
@@ -361,9 +379,12 @@ impl RatchetRing {
///
/// 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.
/// valid; that legacy signature does not authenticate the other retained
/// keys. The unsigned rotation timestamp is deliberately ignored. Inspect
/// [`LoadedRatchetRing::format`] if the caller requires canonical coverage.
pub fn load_verified(path: &Path, identity: &Identity) -> std::io::Result<LoadedRatchetRing> {
let decoded = Self::try_load(path)?;
let data = persistence::read_secret_file(path, RATCHET_FILE_MAX_BYTES)?;
let decoded = Self::decode(&data)?;
let format = if identity.verify(&decoded.packed, &decoded.signature) {
RatchetRingFormat::Canonical
@@ -384,14 +405,9 @@ impl RatchetRing {
})
}
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))?,
);
fn decode(data: &[u8]) -> std::io::Result<DecodedRatchetRing<'_>> {
let persisted: RatchetRingPersistedRead =
rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?;
rmp_serde::from_slice(data).map_err(|e| std::io::Error::other(e.to_string()))?;
if persisted.signature.len() != 64 {
return Err(std::io::Error::new(
@@ -403,7 +419,7 @@ impl RatchetRing {
let mut signature = [0u8; 64];
signature.copy_from_slice(&persisted.signature);
let packed = Zeroizing::new(persisted.ratchets);
let packed = persisted.ratchets;
let keys = unpack_ratchet_keys(&packed)?;
let had_legacy_rotation = persisted.last_rotation.is_some();
@@ -424,12 +440,15 @@ impl RatchetRing {
}
}
/// A verified ratchet ring bound to one crash-safe persistence path.
/// A signature-checked ratchet ring bound to one 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.
/// candidate before replacing the live secret state, using
/// [`persistence::atomic_write`] with best-effort parent-directory fsync.
/// Callers needing the strict durable transaction path should manage a
/// [`RatchetRing`] candidate with [`RatchetRing::save_verified_durable`].
pub struct PersistentRatchetRing {
path: PathBuf,
ring: RatchetRing,
@@ -447,6 +466,12 @@ impl std::fmt::Debug for PersistentRatchetRing {
impl PersistentRatchetRing {
/// Load and verify `path`, or initialize it with a signed empty ring.
///
/// Legacy files are accepted even though their signature authenticates
/// only the current public key, and this wrapper discards the format
/// label. If full-ring authentication is required, first call
/// [`RatchetRing::load_verified`] and inspect `LoadedRatchetRing::format`;
/// do not treat every successful `open` as canonical-format verification.
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() {
@@ -494,7 +519,8 @@ impl PersistentRatchetRing {
self.ensure_current_at(identity, wall_time_secs())
}
/// Deterministic form of [`Self::ensure_current`] for runtime/tests.
/// Form of [`Self::ensure_current`] with an explicit clock value. A rotation
/// still generates random key material.
pub fn ensure_current_at(
&mut self,
identity: &Identity,
@@ -509,12 +535,13 @@ impl PersistentRatchetRing {
}
}
/// Force a crash-safe rotation now.
/// Persist a new rotation before replacing the live ring, using the current clock.
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.
/// Persist a new rotation before replacing the live ring, using an explicit clock.
/// Uses the atomic-write semantics described on [`PersistentRatchetRing`].
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(
@@ -528,11 +555,11 @@ impl PersistentRatchetRing {
}
}
struct DecodedRatchetRing {
struct DecodedRatchetRing<'a> {
ring: RatchetRing,
signature: [u8; 64],
had_legacy_rotation: bool,
packed: Zeroizing<Vec<u8>>,
packed: SecretBytes<'a, RATCHET_FILE_MAX_BYTES>,
}
/// A rotation candidate owns a duplicate secret ring and zeroises it on drop
@@ -552,20 +579,20 @@ impl PreparedRatchetRotation {
}
}
#[derive(Serialize, Zeroize)]
struct RatchetRingPersistedWrite {
#[derive(Serialize)]
struct RatchetRingPersistedWrite<'a> {
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
signature: &'a [u8; 64],
#[serde(with = "serde_bytes")]
ratchets: Vec<u8>,
ratchets: &'a [u8],
}
#[derive(Deserialize)]
struct RatchetRingPersistedRead {
#[serde(with = "serde_bytes")]
signature: Vec<u8>,
#[serde(with = "serde_bytes")]
ratchets: Vec<u8>,
struct RatchetRingPersistedRead<'a> {
#[serde(borrow)]
signature: SecretBytes<'a, RATCHET_FILE_MAX_BYTES>,
#[serde(borrow)]
ratchets: SecretBytes<'a, RATCHET_FILE_MAX_BYTES>,
#[serde(default)]
last_rotation: Option<f64>,
}
@@ -636,8 +663,22 @@ impl ReceivedRatchet {
get_ratchet_id(&self.ratchet_pub)
}
/// Persist to `{ratchetdir}/{hex(dest_hash)}` in the shared msgpack format.
/// Persist in the shared MessagePack format at the supplied path, creating
/// missing parents. Stores conventionally use `{ratchetdir}/{hex(dest_hash)}`.
pub fn save(&self, path: &Path) -> std::io::Result<()> {
self.save_impl(path, false)
}
/// Persist a received public ratchet with strict platform barriers.
///
/// The caller must establish the complete parent namespace with the strict
/// directory helpers before publishing or checkpointing cryptographic state.
/// Unlike the legacy cache writer, this method never creates missing parents.
pub fn save_durable(&self, path: &Path) -> std::io::Result<()> {
self.save_impl(path, true)
}
fn save_impl(&self, path: &Path, durable: bool) -> std::io::Result<()> {
let persisted = ReceivedRatchetPersisted {
ratchet: self.ratchet_pub.to_vec(),
received: self.received_at,
@@ -645,11 +686,17 @@ impl ReceivedRatchet {
let buf = rmp_serde::to_vec_named(&persisted)
.map_err(|e| std::io::Error::other(e.to_string()))?;
if let Some(parent) = path.parent() {
if !durable && let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
persistence::atomic_write(path, &buf)
if durable {
persistence::durable_write(path, &buf)
.map(|_| ())
.map_err(std::io::Error::other)
} else {
persistence::atomic_write(path, &buf)
}
}
pub fn load(path: &Path) -> std::io::Result<Self> {
@@ -689,8 +736,9 @@ pub fn ratchet_public_bytes(ratchet_prv: &[u8; 32]) -> [u8; 32] {
prv.public_key().to_bytes()
}
/// Sweep `dir`, deleting expired and unparseable ratchet files. Returns the
/// number of files removed.
/// Sweep `dir`, deleting expired ratchets and files that fail loading for any
/// reason, including read errors. Returns the number successfully removed.
/// Use only a directory dedicated to received-ratchet cache files.
///
/// Only touches disk; pair with [`purge_expired_ratchets_in_memory`] when an
/// in-memory cache is also kept.
@@ -732,6 +780,8 @@ pub fn purge_expired_ratchets_in_memory<K: Eq + std::hash::Hash>(
}
/// Per-destination cache of remote ratchet public keys, with optional disk backing.
/// Callers validate announces before insertion. Disk writes are best-effort;
/// errors are logged while the in-memory entry is still updated.
pub struct ReceivedRatchetStore {
entries: HashMap<[u8; 16], ReceivedRatchet>,
storage_dir: Option<PathBuf>,
@@ -754,14 +804,16 @@ 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.
/// Record `ratchet_pub` for `dest_hash`. Re-inserting the identical key
/// already in memory is a no-op. Other values replace the entry and attempt
/// a disk write when backed; write errors are logged, not returned.
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.
/// same key already in memory remains a no-op and cannot extend its lifetime.
/// This does not load an existing disk entry before comparing keys.
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)
&& existing.ratchet_pub == ratchet_pub
@@ -787,7 +839,8 @@ 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.
/// disk on miss. Yields `None` if the entry is expired, absent, or cannot be
/// loaded. Disk load failures are logged.
pub fn get(&mut self, dest_hash: &[u8; 16]) -> Option<[u8; 32]> {
self.get_at(dest_hash, wall_time_secs())
}
@@ -1122,8 +1175,8 @@ mod tests {
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,
signature: &[0u8; 64],
ratchets: &packed,
};
std::fs::write(&path, rmp_serde::to_vec_named(&envelope).unwrap()).unwrap();
assert_eq!(
@@ -1196,6 +1249,26 @@ mod tests {
assert_eq!(ring.ratchet_interval(), 60);
}
#[test]
fn strict_received_ratchet_refuses_missing_namespace_without_creating_it() {
let dir = std::env::temp_dir().join(format!(
"reticulum-received-strict-{}",
hex::encode(rns_crypto::random::random_32())
));
let path = dir.join("identity/ratchets/received/peer");
let received = ReceivedRatchet::new_at([7; 32], 100.);
assert!(received.save_durable(&path).is_err());
assert!(
!dir.exists(),
"strict writes must not create weak parent entries"
);
// The legacy, non-acknowledged cache API keeps its historical behavior.
received.save(&path).unwrap();
assert_eq!(ReceivedRatchet::load(&path).unwrap().ratchet_pub, [7; 32]);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn test_received_ratchet_msgpack_roundtrip() {
let dir = std::env::temp_dir().join("reticulum_recv_ratchet_test");
@@ -0,0 +1,100 @@
//! Writes beyond the process file-size limit fail with EFBIG and keep the
//! previous file. Each test re-runs itself in a child with a lowered limit.
//! Spawning stays out of the unit-test binary: until a child execs it holds
//! copies of all its parent's descriptors, close-on-exec ones included, so a
//! sibling test's lock or FIFO end would outlive that test's close.
#![cfg(unix)]
use std::fs;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use rns_identity::persistence::{DurableCommitPhase, atomic_write, durable_write};
fn unique_test_dir(label: &str) -> PathBuf {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"reticulum-{label}-{}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos(),
NEXT_ID.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&dir).unwrap();
dir
}
/// Re-run `test` in a child process whose files are limited to `limit`
/// bytes, with SIGXFSZ ignored so a longer write fails with EFBIG. Returns
/// true in the child, which then runs the test body.
fn in_file_size_limited_child(test: &str, limit: u64) -> bool {
const CHILD: &str = "RNS_FILE_SIZE_LIMITED_CHILD";
if std::env::var_os(CHILD).is_some() {
unsafe {
libc::signal(libc::SIGXFSZ, libc::SIG_IGN);
let mut current = std::mem::zeroed::<libc::rlimit>();
assert_eq!(libc::getrlimit(libc::RLIMIT_FSIZE, &mut current), 0);
current.rlim_cur = limit as libc::rlim_t;
assert_eq!(libc::setrlimit(libc::RLIMIT_FSIZE, &current), 0);
}
return true;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([test, "--exact", "--nocapture", "--test-threads=1"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"file-size-limited child failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
false
}
#[test]
fn atomic_write_beyond_the_file_size_limit_keeps_the_previous_file() {
if !in_file_size_limited_child(
"atomic_write_beyond_the_file_size_limit_keeps_the_previous_file",
4096,
) {
return;
}
let dir = unique_test_dir("atomic-file-size");
let path = dir.join("state");
fs::write(&path, b"previous").unwrap();
let err = atomic_write(&path, &[0x5a; 16384]).unwrap_err();
assert_eq!(err.raw_os_error(), Some(libc::EFBIG));
assert_eq!(fs::read(&path).unwrap(), b"previous");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn strict_write_beyond_the_file_size_limit_keeps_the_previous_file() {
if !in_file_size_limited_child(
"strict_write_beyond_the_file_size_limit_keeps_the_previous_file",
4096,
) {
return;
}
let root = unique_test_dir("durable-file-size");
let target = root.join("state");
durable_write(&target, b"old").unwrap();
let failure = durable_write(&target, &[0x5a; 16384]).unwrap_err();
assert_eq!(failure.phase, DurableCommitPhase::NotCommitted);
let source = std::error::Error::source(&failure)
.and_then(|source| source.downcast_ref::<std::io::Error>())
.unwrap();
assert_eq!(source.raw_os_error(), Some(libc::EFBIG));
assert_eq!(fs::read(&target).unwrap(), b"old");
assert_eq!(failure.recovery_paths.len(), 2);
fs::remove_dir_all(root).unwrap();
}
+424
View File
@@ -0,0 +1,424 @@
//! Private keys, derived keys and plaintext must not survive in freed heap
//! memory when identities are stored, loaded and used.
#[path = "../../rns-crypto/tests/residue/mod.rs"]
mod residue;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use residue::{assert_no_residue, freed_by, pseudo_random, serial};
use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use rns_identity::identity::Identity;
use rns_identity::ifac::derive_ifac_key;
use rns_identity::ratchet::{RatchetRing, RatchetRingFormat};
use zeroize::Zeroizing;
struct TempDir(PathBuf);
impl TempDir {
fn new(label: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let path = std::env::temp_dir().join(format!(
"rns-residue-{label}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn derived_key(private: &[u8; 32], ephemeral_public: &[u8], salt: &[u8]) -> Zeroizing<Vec<u8>> {
let private = X25519PrivateKey::from_bytes(private);
let public = X25519PublicKey::from_bytes(ephemeral_public.try_into().unwrap());
let shared = Zeroizing::new(private.exchange(&public));
hkdf_sha256(64, &*shared, Some(salt), None).unwrap()
}
#[test]
fn identity_to_file_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("to-file");
let key: [u8; 64] = pseudo_random(11);
let identity = Identity::from_private_key(&key).unwrap();
let path = dir.0.join("identity");
let ((), freed) = freed_by(|| identity.to_file(&path).unwrap());
assert_no_residue(&freed, &[("private key", &key)]);
assert_eq!(std::fs::read(&path).unwrap(), key);
}
#[test]
fn identity_from_file_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("from-file");
let key: [u8; 64] = pseudo_random(12);
let expected = Identity::from_private_key(&key).unwrap().hash;
let path = dir.0.join("identity");
std::fs::write(&path, key).unwrap();
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
assert_no_residue(&freed, &[("private key", &key)]);
assert_eq!(hash, expected);
}
#[test]
fn identity_from_file_with_a_msgpack_looking_key_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("from-file-msgpack-prefix");
// A one-field array holding a long integer array: a parse of this key as
// an envelope runs out of input partway through.
let mut key = [0u8; 64];
key[..4].copy_from_slice(&[0x91, 0xdc, 0xff, 0xff]);
let tail: [u8; 60] = pseudo_random(13);
for (out, byte) in key[4..].iter_mut().zip(tail) {
*out = byte & 0x7f;
}
let expected = Identity::from_private_key(&key).unwrap().hash;
let path = dir.0.join("identity");
std::fs::write(&path, key).unwrap();
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
assert_no_residue(&freed, &[("private key", &key[4..])]);
assert_eq!(hash, expected);
}
#[test]
fn identity_from_envelope_file_frees_no_key() {
#[derive(serde::Serialize)]
struct Envelope {
private_key: Vec<u8>,
}
let _serial = serial();
let dir = TempDir::new("from-envelope");
let key: [u8; 64] = pseudo_random(14);
let expected = Identity::from_private_key(&key).unwrap().hash;
let envelope = Envelope {
private_key: key.to_vec(),
};
for (name, bytes) in [
("named", rmp_serde::to_vec_named(&envelope).unwrap()),
("compact", rmp_serde::to_vec(&envelope).unwrap()),
] {
let path = dir.0.join(name);
std::fs::write(&path, bytes).unwrap();
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
assert_no_residue(
&freed,
&[
("private key", &key),
("msgpack integers private key", &msgpack_integers(&key)),
],
);
assert_eq!(hash, expected, "{name} envelope");
}
}
#[test]
fn identity_from_file_refuses_an_oversize_file_without_reading_it_whole() {
let _serial = serial();
let dir = TempDir::new("from-file-oversize");
let path = dir.0.join("identity");
std::fs::write(&path, vec![0xc1; 1 << 20]).unwrap();
let (result, freed) = freed_by(|| Identity::from_file(&path));
assert!(result.is_err());
assert!(
freed.peak_allocation < 64 * 1024,
"loading allocated {} bytes",
freed.peak_allocation
);
}
#[test]
fn identity_encrypt_frees_no_plaintext_or_key() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(15);
let identity = Identity::from_private_key(&key).unwrap();
let plaintext: [u8; 100] = pseudo_random(16);
let (ciphertext, freed) = freed_by(|| identity.encrypt(&plaintext, None).unwrap());
let derived = derived_key(
key[..32].try_into().unwrap(),
&ciphertext[..32],
&identity.hash,
);
assert_no_residue(
&freed,
&[("plaintext", &plaintext), ("derived key", &derived)],
);
}
#[test]
fn identity_decrypt_frees_no_plaintext_or_key() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(17);
let identity = Identity::from_private_key(&key).unwrap();
let plaintext: [u8; 100] = pseudo_random(18);
let ciphertext = identity.encrypt(&plaintext, None).unwrap();
let derived = derived_key(
key[..32].try_into().unwrap(),
&ciphertext[..32],
&identity.hash,
);
let ((), freed) = freed_by(|| {
let decrypted = Zeroizing::new(identity.decrypt(&ciphertext, None, false).unwrap());
assert_eq!(&decrypted[..], &plaintext[..]);
});
assert_no_residue(
&freed,
&[("plaintext", &plaintext), ("derived key", &derived)],
);
}
#[test]
fn identity_ratchet_decrypt_frees_no_plaintext_or_key() {
let _serial = serial();
let key: [u8; 64] = pseudo_random(19);
let identity = Identity::from_private_key(&key).unwrap();
let ratchet: [u8; 32] = pseudo_random(20);
let ratchet_public = X25519PrivateKey::from_bytes(&ratchet)
.public_key()
.to_bytes();
let plaintext: [u8; 100] = pseudo_random(21);
let ciphertext = identity.encrypt(&plaintext, Some(&ratchet_public)).unwrap();
let derived = derived_key(&ratchet, &ciphertext[..32], &identity.hash);
let ((), freed) = freed_by(|| {
let ratchets = [&ratchet];
let decrypted = identity
.decrypt_with_ratchet_id(&ciphertext, Some(&ratchets), true)
.unwrap();
let plaintext_copy = Zeroizing::new(decrypted.plaintext);
assert_eq!(&plaintext_copy[..], &plaintext[..]);
});
assert_no_residue(
&freed,
&[
("plaintext", &plaintext),
("derived key", &derived),
("ratchet key", &ratchet),
],
);
}
#[test]
fn ratchet_ring_save_and_load_free_no_ratchet_keys() {
let _serial = serial();
let dir = TempDir::new("ratchets");
let identity = Identity::from_private_key(&pseudo_random::<64>(22)).unwrap();
let mut ring = RatchetRing::new();
for _ in 0..200 {
ring.rotate();
}
let keys = Zeroizing::new(ring.private_keys().to_vec());
let path = dir.0.join("ratchets");
let ((), saved) = freed_by(|| ring.save_verified(&path, &identity).unwrap());
let ((), read) = freed_by(|| {
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
assert_eq!(loaded.ring().private_keys(), &keys[..]);
});
let mut found = Vec::new();
for (stage, freed) in [("save", &saved), ("load", &read)] {
for residue in ratchet_key_residue(freed, &keys) {
found.push(format!("{stage}: {residue}"));
}
}
assert!(found.is_empty(), "secret residue: {found:?}");
}
#[test]
fn ifac_key_derivation_frees_no_key() {
let _serial = serial();
let passphrase = "correct horse battery staple";
let key = derive_ifac_key(Some("residue"), Some(passphrase)).unwrap();
let ((), freed) = freed_by(|| {
let derived = derive_ifac_key(Some("residue"), Some(passphrase)).unwrap();
assert_eq!(derived, key);
});
assert_no_residue(
&freed,
&[
("IFAC key", &key),
("passphrase hash", &sha256(passphrase.as_bytes())),
],
);
}
/// A key as msgpack writes it in an integer array: bytes above 0x7f carry a
/// 0xcc prefix.
fn msgpack_integers(key: &[u8]) -> Vec<u8> {
key.iter()
.flat_map(|&byte| {
if byte < 0x80 {
vec![byte]
} else {
vec![0xcc, byte]
}
})
.collect()
}
/// Ratchet keys found in freed blocks: raw, as packed in an integer array, and
/// as that packing appears again inside the file's integer array.
fn ratchet_key_residue(freed: &residue::Freed, keys: &[[u8; 32]]) -> Vec<String> {
type Encode = fn(&[u8]) -> Vec<u8>;
let forms: [(&str, Encode); 3] = [
("raw", |key| key.to_vec()),
("msgpack integers", msgpack_integers),
("nested msgpack integers", |key| {
msgpack_integers(&msgpack_integers(key))
}),
];
let mut found = Vec::new();
for (form, encode) in forms {
let encoded: Vec<Vec<u8>> = keys.iter().map(|key| encode(key)).collect();
let secrets: Vec<&[u8]> = encoded.iter().map(Vec::as_slice).collect();
let sizes: Vec<usize> = residue::find(&freed.blocks, &secrets)
.into_iter()
.map(|(len, _)| len)
.collect();
if !sizes.is_empty() {
found.push(format!(
"{form} ratchet keys in freed blocks of {sizes:?} bytes"
));
}
}
found
}
/// Releases before the canonical envelope wrote the packed ring and its keys
/// as msgpack integer arrays.
#[derive(serde::Serialize)]
struct LegacyRatchets<T> {
signature: Vec<u8>,
ratchets: Vec<u8>,
last_rotation: T,
}
fn legacy_keys(count: u64, seed: u64) -> Vec<[u8; 32]> {
(0..count).map(|i| pseudo_random(seed + i)).collect()
}
fn legacy_signature(identity: &Identity, keys: &[[u8; 32]]) -> Vec<u8> {
let current_public = X25519PrivateKey::from_bytes(&keys[0])
.public_key()
.to_bytes();
identity.sign(&current_public).unwrap().to_vec()
}
#[test]
fn legacy_ratchet_ring_load_frees_no_ratchet_keys() {
let _serial = serial();
let dir = TempDir::new("legacy-ratchets");
let identity = Identity::from_private_key(&pseudo_random::<64>(23)).unwrap();
let keys = legacy_keys(120, 1000);
let legacy = LegacyRatchets {
signature: legacy_signature(&identity, &keys),
ratchets: rmp_serde::to_vec(&keys).unwrap(),
last_rotation: 0.0,
};
let path = dir.0.join("ratchets");
std::fs::write(&path, rmp_serde::to_vec(&legacy).unwrap()).unwrap();
let ((), freed) = freed_by(|| {
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
assert_eq!(loaded.format(), RatchetRingFormat::LegacyRust);
assert_eq!(loaded.ring().private_keys(), &keys[..]);
});
let found = ratchet_key_residue(&freed, &keys);
assert!(found.is_empty(), "secret residue: {found:?}");
}
#[test]
fn failed_legacy_ratchet_ring_loads_free_no_ratchet_keys() {
let _serial = serial();
let dir = TempDir::new("legacy-ratchets-failed");
let identity = Identity::from_private_key(&pseudo_random::<64>(25)).unwrap();
// Few enough keys that the packed ring is decoded without regrowing.
let keys = legacy_keys(40, 2000);
let signature = legacy_signature(&identity, &keys);
let packed = rmp_serde::to_vec(&keys).unwrap();
assert_eq!(packed[..3], [0xdc, 0x00, 40]);
let mut short_packed = packed.clone();
short_packed[2] += 1;
let file = |signature: &[u8], ratchets: &[u8]| {
rmp_serde::to_vec(&LegacyRatchets {
signature: signature.to_vec(),
ratchets: ratchets.to_vec(),
last_rotation: 0.0,
})
.unwrap()
};
let cases = [
("short signature", file(&signature[..63], &packed)),
(
"malformed rotation",
rmp_serde::to_vec(&LegacyRatchets {
signature: signature.clone(),
ratchets: packed.clone(),
last_rotation: "never",
})
.unwrap(),
),
("missing key", file(&signature, &short_packed)),
];
let mut found = Vec::new();
for (case, bytes) in cases {
let path = dir.0.join(case.replace(' ', "-"));
std::fs::write(&path, bytes).unwrap();
let (result, freed) = freed_by(|| RatchetRing::load_verified(&path, &identity).map(drop));
assert!(result.is_err(), "{case}");
for residue in ratchet_key_residue(&freed, &keys) {
found.push(format!("{case}: {residue}"));
}
}
assert!(found.is_empty(), "secret residue: {found:?}");
}
#[test]
fn identity_from_a_truncated_envelope_frees_no_key() {
let _serial = serial();
let dir = TempDir::new("truncated-envelope");
let mut key: [u8; 64] = pseudo_random(24);
for byte in &mut key {
*byte &= 0x7f;
}
// A one-field envelope declaring 65 key bytes and ending after 64.
let path = dir.0.join("identity");
std::fs::write(&path, [&[0x91, 0xdc, 0x00, 0x41][..], &key].concat()).unwrap();
let (result, freed) = freed_by(|| Identity::from_file(&path));
assert!(result.is_err());
assert_no_residue(&freed, &[("private key", &key)]);
}
+1 -1
View File
@@ -5,7 +5,7 @@ publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
license-file.workspace = true
[features]
default = []
+203 -143
View File
@@ -1,5 +1,10 @@
//! USB serial RNode over Android USB-C OTG via JNI to `UsbManager`. 115200 8N1.
//! RNode over Android USB host access through JNI to `UsbManager`. The
//! driver supports a single CDC-ACM function or CP2102-compatible USB UART
//! (`10c4:ea60`), with bulk IN and OUT endpoints on the same data interface.
//! Setup requires successful 8N1 configuration and matched DTR/RTS assertion,
//! defaulting to 115200 baud; enumeration alone does not establish compatibility.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
@@ -15,7 +20,10 @@ use crate::android_usb_lifecycle::{
UsbReadDrainOutcome, UsbReadResult, UsbReaderBackend, UsbShutdownReport, UsbTransferError,
UsbTxGate, UsbTxPumpExit, UsbWriterBackend, drain_usb_reader_tail, forward_usb_read_chunk,
resolve_usb_device, run_usb_rnode_capability_startup, run_usb_rnode_startup, run_usb_tx_pump,
spawn_owned_usb_io,
spawn_owned_usb_io, usb_bulk_read_size,
};
use crate::android_usb_setup::{
UsbEndpointDescriptor, UsbInterfaceDescriptor, configure_serial_port, select_serial_port,
};
#[cfg(test)]
use crate::kiss;
@@ -42,7 +50,9 @@ const USB_DETACH_ACK_DEADLINE: Duration = Duration::from_millis(500);
const USB_WORKER_JOIN_DEADLINE: Duration = Duration::from_millis(1_250);
const USB_RECONNECT_DELAY: Duration = Duration::from_secs(rnode::RECONNECT_WAIT);
/// USB VIDs of serial chipsets commonly used by RNode hardware.
/// Vendor-ID allowlist used to filter and label enumerated USB devices.
/// This is an enumeration inventory, not a driver compatibility promise.
/// Connection requires CDC-ACM or supported CP210x setup and RNode protocol.
pub const KNOWN_VIDS: &[(u16, &str)] = &[
(0x0403, "FTDI"),
(0x10C4, "Silicon Labs CP210x"),
@@ -156,9 +166,9 @@ pub fn stop_android_usb_rnode_interface(id: InterfaceId) {
let _ = request_android_usb_rnode_stop(id);
}
/// Request stop and wait until the JNI workers have joined and Java ownership
/// is either safely closed or explicitly quarantined. Idempotent; unknown ids
/// have already left the interface registry.
/// Request stop and wait for the owner's shutdown report. A successful result
/// means workers joined and ownership closed; unresolved ownership is
/// quarantined and reported as an error. Unknown IDs return `Ok(())`.
pub async fn stop_android_usb_rnode_interface_and_wait(id: InterfaceId) -> Result<(), String> {
let Some(mut stop_handle) = request_android_usb_rnode_stop(id) else {
return Ok(());
@@ -238,9 +248,11 @@ pub struct AndroidUsbConfig {
pub mode: InterfaceMode,
/// Gate each TX on the radio's CMD_READY. Python default: off.
pub flow_control: bool,
/// Short-term airtime cap, percent (0.0..=100.0). `None` = unlimited.
/// Short-term airtime cap, percent (0.0..=100.0). `None` sends no command
/// and leaves the device's corresponding setting unchanged.
pub st_alock: Option<f32>,
/// Long-term airtime cap, percent (0.0..=100.0). `None` = unlimited.
/// Long-term airtime cap, percent (0.0..=100.0). `None` sends no command
/// and leaves the device's corresponding setting unchanged.
pub lt_alock: Option<f32>,
/// Station-ID beacon: seconds between IDs, sent only after data TX.
pub id_interval: Option<u64>,
@@ -568,10 +580,8 @@ pub async fn resolve_android_usb_device_selector(
}
/// Return whether Android has already granted this app access to `device_name`.
///
/// This is deliberately a probe only. Android permission prompts are owned by
/// the Activity bridge because JNI cannot safely create the required
/// `PendingIntent`/`BroadcastReceiver` interaction here.
/// This is a permission probe and never opens a prompt. The embedding Activity
/// bridge is responsible for requesting access.
pub async fn has_usb_permission(device_name: &str) -> Result<bool, String> {
let dev_name = device_name.to_string();
tokio::task::spawn_blocking(move || {
@@ -643,10 +653,16 @@ fn jni_failure(env: &jni::JNIEnv, context: &str, error: impl std::fmt::Display)
format!("{context}: {error}")
}
fn usb_int_property(env: &jni::JNIEnv, object: JObject<'_>, method: &str) -> Result<i32, String> {
env.call_method(object, method, "()I", &[])
.map_err(|error| jni_failure(env, method, error))?
.i()
.map_err(|error| jni_failure(env, method, error))
}
struct JniUsbConnectionOwner {
connection: Option<GlobalRef>,
data_interface: Option<GlobalRef>,
interface_claimed: bool,
claimed_interfaces: Vec<GlobalRef>,
device_name: String,
lease_phase: JniUsbLeasePhase,
attached: Arc<AtomicBool>,
@@ -663,6 +679,7 @@ struct JniUsbReader {
device_name: String,
attached: Arc<AtomicBool>,
idle_polls: u8,
read_size: i32,
}
struct PendingAndroidUsbOpen {
@@ -757,8 +774,9 @@ fn unregister_android_usb_presence(device_name: &str, attached: &Arc<AtomicBool>
}
}
/// Invalidate the exact active physical generation from Android's USB detach
/// broadcast. Unknown and stale device paths are harmless no-ops.
/// Mark the currently registered connection for `device_name` as detached
/// and wake reconnect loops. Unknown paths are ignored. Selection uses the
/// path alone; callers must supply the current detach notification.
pub fn notify_android_usb_device_detached(device_name: &str) {
if let Some(attached) = android_usb_presence_registry()
.lock()
@@ -838,13 +856,13 @@ fn drop_worker_global_refs_attached(
) {
let connection = connection.take();
let endpoint = endpoint.take();
if let Some(vm) = JAVA_VM.get() {
if let Ok(env) = vm.attach_current_thread() {
drop(endpoint);
drop(connection);
drop(env);
return;
}
if let Some(vm) = JAVA_VM.get()
&& let Ok(env) = vm.attach_current_thread()
{
drop(endpoint);
drop(connection);
drop(env);
return;
}
drop(endpoint);
drop(connection);
@@ -918,8 +936,8 @@ impl UsbReaderBackend for JniUsbReader {
if !self.attached.load(Ordering::Acquire) {
return Err("Android USB device detached".into());
}
let read_size = self.read_size;
with_env(|env| {
const READ_SIZE: i32 = 1_024;
let connection = self
.connection
.as_ref()
@@ -929,7 +947,7 @@ impl UsbReaderBackend for JniUsbReader {
.as_ref()
.ok_or("USB reader endpoint already released")?;
let buffer = env
.new_byte_array(READ_SIZE)
.new_byte_array(read_size)
.map_err(|error| jni_failure(env, "USB read buffer allocation", error))?;
let value = env
.call_method(
@@ -939,7 +957,7 @@ impl UsbReaderBackend for JniUsbReader {
&[
JValue::Object(endpoint.as_obj()),
JValue::Object(buffer.into()),
JValue::Int(READ_SIZE),
JValue::Int(read_size),
JValue::Int(USB_READ_TIMEOUT_MS),
],
)
@@ -991,9 +1009,9 @@ impl UsbReaderBackend for JniUsbReader {
return Ok(UsbReadResult::Idle);
}
self.idle_polls = 0;
if read > READ_SIZE {
if read > read_size {
return Err(format!(
"USB bulk read returned invalid length {read} (capacity {READ_SIZE})"
"USB bulk read returned invalid length {read} (capacity {read_size})"
));
}
let bytes = env
@@ -1033,30 +1051,34 @@ impl UsbConnectionLifecycle for JniUsbConnectionOwner {
close_connection: error,
};
};
let release_interface = if self.interface_claimed {
match self.data_interface.as_ref() {
Some(data_interface) => env
.call_method(
connection.as_obj(),
"releaseInterface",
"(Landroid/hardware/usb/UsbInterface;)Z",
&[JValue::Object(data_interface.as_obj())],
)
.map_err(|error| jni_failure(&env, "releaseInterface", error))
.and_then(|value| {
value
.z()
.map_err(|error| jni_failure(&env, "releaseInterface result", error))
})
.and_then(|released| {
released
.then_some(())
.ok_or_else(|| "Java releaseInterface returned false".into())
}),
None => Err("claimed USB interface reference is missing".into()),
let mut release_errors = Vec::new();
for interface in self.claimed_interfaces.iter().rev() {
let release = env
.call_method(
connection.as_obj(),
"releaseInterface",
"(Landroid/hardware/usb/UsbInterface;)Z",
&[JValue::Object(interface.as_obj())],
)
.map_err(|error| jni_failure(&env, "releaseInterface", error))
.and_then(|value| {
value
.z()
.map_err(|error| jni_failure(&env, "releaseInterface result", error))
})
.and_then(|released| {
released
.then_some(())
.ok_or_else(|| "Java releaseInterface returned false".to_string())
});
if let Err(error) = release {
release_errors.push(error);
}
} else {
}
let release_interface = if release_errors.is_empty() {
Ok(())
} else {
Err(release_errors.join("; "))
};
// close is unconditional, including releaseInterface(false/error).
let close_connection = env
@@ -1097,9 +1119,9 @@ impl UsbConnectionLifecycle for JniUsbConnectionOwner {
// The joined workers have already dropped their temporary refs. Only
// a proven close releases the canonical refs, and does so while this
// cleanup thread is still JNI-attached.
let data_interface = self.data_interface.take();
let interfaces = std::mem::take(&mut self.claimed_interfaces);
let connection = self.connection.take();
drop(data_interface);
drop(interfaces);
drop(connection);
drop(env);
UsbConnectionCleanup::Closed { release_interface }
@@ -1214,24 +1236,18 @@ fn open_usb_serial_attached(
let attached = Arc::new(AtomicBool::new(true));
let mut owner = JniUsbConnectionOwner {
connection: Some(connection_ref),
data_interface: None,
interface_claimed: false,
claimed_interfaces: Vec::new(),
device_name: dev_name.to_string(),
lease_phase: JniUsbLeasePhase::Opening,
attached: attached.clone(),
};
let setup = (|| -> Result<(GlobalRef, GlobalRef), String> {
// CDC-Data (0x0A) or vendor-specific (0xFF), with a matched
// IN/OUT endpoint pair from one interface.
let iface_count = env
.call_method(device, "getInterfaceCount", "()I", &[])
.map_err(|error| jni_failure(env, "getInterfaceCount", error))?
.i()
.map_err(|error| jni_failure(env, "USB interface count", error))?;
let mut data_iface = JObject::null();
let mut ep_in = JObject::null();
let mut ep_out = JObject::null();
let setup = (|| -> Result<(GlobalRef, GlobalRef, i32), String> {
let vendor_id = usb_int_property(env, device, "getVendorId")?;
let product_id = usb_int_property(env, device, "getProductId")?;
let iface_count = usb_int_property(env, device, "getInterfaceCount")?;
let mut interfaces = Vec::new();
let mut descriptors = Vec::new();
for interface_index in 0..iface_count {
let interface = env
.call_method(
@@ -1243,22 +1259,13 @@ fn open_usb_serial_attached(
.map_err(|error| jni_failure(env, "getInterface", error))?
.l()
.map_err(|error| jni_failure(env, "USB interface object", error))?;
let class = env
.call_method(interface, "getInterfaceClass", "()I", &[])
.map_err(|error| jni_failure(env, "getInterfaceClass", error))?
.i()
.map_err(|error| jni_failure(env, "USB interface class", error))?;
if class != 0x0A && class != 0xFF {
continue;
}
let endpoint_count = env
.call_method(interface, "getEndpointCount", "()I", &[])
.map_err(|error| jni_failure(env, "getEndpointCount", error))?
.i()
.map_err(|error| jni_failure(env, "USB endpoint count", error))?;
let mut candidate_in = JObject::null();
let mut candidate_out = JObject::null();
let number = u16::try_from(usb_int_property(env, interface, "getId")?)
.map_err(|_| "Invalid USB interface number".to_string())?;
let alternate_setting = usb_int_property(env, interface, "getAlternateSetting")?;
let class = usb_int_property(env, interface, "getInterfaceClass")?;
let subclass = usb_int_property(env, interface, "getInterfaceSubclass")?;
let endpoint_count = usb_int_property(env, interface, "getEndpointCount")?;
let mut endpoints = Vec::new();
for endpoint_index in 0..endpoint_count {
let endpoint = env
.call_method(
@@ -1270,79 +1277,109 @@ fn open_usb_serial_attached(
.map_err(|error| jni_failure(env, "getEndpoint", error))?
.l()
.map_err(|error| jni_failure(env, "USB endpoint object", error))?;
let direction = env
.call_method(endpoint, "getDirection", "()I", &[])
.map_err(|error| jni_failure(env, "getEndpointDirection", error))?
.i()
.map_err(|error| jni_failure(env, "USB endpoint direction", error))?;
if direction == 0x80 {
candidate_in = endpoint;
} else {
candidate_out = endpoint;
}
}
if !candidate_in.is_null() && !candidate_out.is_null() {
data_iface = interface;
ep_in = candidate_in;
ep_out = candidate_out;
break;
endpoints.push(UsbEndpointDescriptor {
direction: usb_int_property(env, endpoint, "getDirection")?,
transfer_type: usb_int_property(env, endpoint, "getType")?,
});
env.delete_local_ref(endpoint).map_err(|error| {
jni_failure(env, "USB descriptor endpoint release", error)
})?;
}
interfaces.push(interface);
descriptors.push(UsbInterfaceDescriptor {
number,
alternate_setting,
class,
subclass,
endpoints,
});
}
if data_iface.is_null() {
return Err("No CDC-ACM interface found".into());
let port = select_serial_port(vendor_id, product_id, &descriptors)?;
// CDC control and data claims belong to the same cleanup owner.
// A partial claim or setup failure closes this whole connection.
for index in [
Some(port.control_interface),
(port.data_interface != port.control_interface).then_some(port.data_interface),
]
.into_iter()
.flatten()
{
let interface = interfaces[index];
let reference = env
.new_global_ref(interface)
.map_err(|error| jni_failure(env, "USB interface global reference", error))?;
let claimed = env
.call_method(
connection,
"claimInterface",
"(Landroid/hardware/usb/UsbInterface;Z)Z",
&[JValue::Object(interface), JValue::Bool(1)],
)
.map_err(|error| jni_failure(env, "claimInterface", error))?
.z()
.map_err(|error| jni_failure(env, "claimInterface result", error))?;
if !claimed {
return Err("Java claimInterface returned false".into());
}
owner.claimed_interfaces.push(reference);
}
owner.data_interface = Some(
env.new_global_ref(data_iface)
.map_err(|error| jni_failure(env, "USB interface global reference", error))?,
);
let claimed = env
.call_method(
connection,
"claimInterface",
"(Landroid/hardware/usb/UsbInterface;Z)Z",
&[JValue::Object(data_iface), JValue::Bool(1)],
)
.map_err(|error| jni_failure(env, "claimInterface", error))?
.z()
.map_err(|error| jni_failure(env, "claimInterface result", error))?;
if !claimed {
return Err("Java claimInterface returned false".into());
}
owner.interface_claimed = true;
// CDC SET_LINE_CODING remains best-effort for vendor chipsets.
let mut line_coding = [0u8; 7];
line_coding[0..4].copy_from_slice(&baud_rate.to_le_bytes());
line_coding[6] = 8;
if let Ok(line_coding_array) = env.byte_array_from_slice(&line_coding) {
let _ = env.call_method(
configure_serial_port(&port, baud_rate, |request| {
let payload = env
.byte_array_from_slice(request.payload)
.map_err(|error| jni_failure(env, "USB setup payload", error))?;
env.call_method(
connection,
"controlTransfer",
"(IIII[BII)I",
&[
JValue::Int(0x21),
JValue::Int(0x20),
JValue::Int(0),
JValue::Int(0),
JValue::Object(line_coding_array.into()),
JValue::Int(7),
JValue::Int(i32::from(request.request_type)),
JValue::Int(i32::from(request.request)),
JValue::Int(i32::from(request.value)),
JValue::Int(i32::from(request.index)),
JValue::Object(payload.into()),
JValue::Int(request.payload.len() as i32),
JValue::Int(USB_WRITE_TIMEOUT_MS),
],
);
}
clear_pending_jni_exception(env);
)
.map_err(|error| jni_failure(env, "USB serial controlTransfer", error))?
.i()
.map_err(|error| jni_failure(env, "USB serial controlTransfer result", error))
})?;
let endpoint_at = |index: usize| {
env.call_method(
interfaces[port.data_interface],
"getEndpoint",
"(I)Landroid/hardware/usb/UsbEndpoint;",
&[JValue::Int(index as i32)],
)
.map_err(|error| jni_failure(env, "getEndpoint", error))?
.l()
.map_err(|error| jni_failure(env, "USB selected endpoint", error))
};
let ep_in = endpoint_at(port.input_endpoint)?;
let ep_out = endpoint_at(port.output_endpoint)?;
let max_packet_size = env
.call_method(ep_in, "getMaxPacketSize", "()I", &[])
.map_err(|error| jni_failure(env, "getMaxPacketSize", error))?
.i()
.map_err(|error| jni_failure(env, "USB endpoint packet size", error))?;
let input_endpoint = env
.new_global_ref(ep_in)
.map_err(|error| jni_failure(env, "USB input endpoint global reference", error))?;
let output_endpoint = env
.new_global_ref(ep_out)
.map_err(|error| jni_failure(env, "USB output endpoint global reference", error))?;
Ok((input_endpoint, output_endpoint))
Ok((
input_endpoint,
output_endpoint,
usb_bulk_read_size(max_packet_size),
))
})();
let (input_endpoint, output_endpoint) = match setup {
let (input_endpoint, output_endpoint, read_size) = match setup {
Ok(endpoints) => endpoints,
Err(error) => return Err(cleanup_failed_android_usb_open(owner, error)),
};
@@ -1371,6 +1408,7 @@ fn open_usb_serial_attached(
device_name: dev_name.to_string(),
attached,
idle_polls: 0,
read_size,
},
))
});
@@ -1383,8 +1421,8 @@ fn open_usb_serial_attached(
result
}
/// Open the device and claim its CDC data interface. The returned owner is the
/// only component allowed to release the interface and close the connection;
/// Open the device, claim its serial interfaces, and configure its USB UART.
/// The returned owner alone releases those interfaces and closes the connection;
/// its read/write workers hold temporary global references only until joined.
async fn open_usb_serial(
device_name: &str,
@@ -1597,6 +1635,8 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
transport_tx: mpsc::Sender<TransportMessage>,
options: RNodeStartupOptions,
) -> Result<SpawnedRNodeInterface, RNodeSpawnError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
config.validate_device_selector()?;
config.validate().map_err(|error| {
InterfaceError::SendFailed(format!("rnode config {}: {error}", error.field()))
@@ -1750,6 +1790,7 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
let mut stop_requested = false;
let mut drain_reader_tail = false;
let mut terminal_reason = RNodeRuntimeReason::ConnectionLost;
let mut configuration_rejected = None;
loop {
tokio::select! {
@@ -1853,7 +1894,21 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
outcome = forwarding => outcome,
};
match outcome {
UsbInboundOutcome::Complete => {}
UsbInboundOutcome::Complete => {
// Retrying settings the radio cannot use
// only fails again; shutdown detaches it.
if let Some(rejected) = inbound.definitive_rejection() {
tracing::warn!(
name = %read_name,
rejected = ?rejected,
"Android USB RNode rejected the configured settings"
);
configuration_rejected = Some(rejected);
terminal_reason =
RNodeRuntimeReason::ConfigurationRejected;
break;
}
}
UsbInboundOutcome::StopRequested => {
stop_requested = true;
terminal_reason = RNodeRuntimeReason::StopRequested;
@@ -1927,6 +1982,7 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
terminal_reason,
RNodeRuntimeReason::TransportConsumerClosed
| RNodeRuntimeReason::DriverTerminated
| RNodeRuntimeReason::ConfigurationRejected
);
if terminal {
inbound.shutting_down(terminal_reason);
@@ -1956,7 +2012,10 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
online_task.store(false, Ordering::SeqCst);
if terminal {
inbound.stopped(terminal_reason);
match configuration_rejected {
Some(rejected) => inbound.stopped_for_configuration_rejection(rejected),
None => inbound.stopped(terminal_reason),
}
shutdown_status_tx.send_replace(AndroidUsbShutdownStatus::Complete(report));
return;
}
@@ -2003,6 +2062,8 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
);
let interface = InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 508, false),
parent_id: None,
name,
mode: config.mode,
@@ -2024,10 +2085,9 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
Ok(SpawnedRNodeInterface { interface, driver })
}
/// Push an already-KISS-framed control frame through the raw USB writer,
/// bypassing the transport CMD_DATA wrapper. The canonical caller is the
/// BLE→serial handoff, which sends `[FEND, CMD_BT_CTRL, 0x00, FEND]` to turn
/// off the RNode's BT radio before the USB link takes over.
/// Enqueue an already-KISS-framed control message on the supplied raw USB
/// writer channel, bypassing the transport CMD_DATA wrapper. Success confirms
/// queue admission, not device receipt or execution.
pub async fn send_raw_frame(
writer: &mpsc::Sender<Vec<u8>>,
frame: Vec<u8>,
+180 -29
View File
@@ -22,8 +22,10 @@ use crate::rnode_capabilities::RNodeRadioAdmission;
use crate::rnode_capability_preflight::RNodeCapabilityPreflight;
use crate::rnode_protocol::{
RNodeProtocolFrame, RNodeProtocolState, RNodeProtocolTarget, RNodeReadiness,
RNodeReadinessEvidence,
};
use crate::traits::InterfaceId;
#[cfg(test)]
use rns_transport::messages::TransportMessage;
const MIN_TRANSFER_TIMEOUT: Duration = Duration::from_millis(1);
@@ -307,6 +309,18 @@ pub(crate) trait UsbReaderBackend: Send + 'static {
fn read(&mut self) -> Result<UsbReadResult, String>;
}
/// Bulk IN request size: exactly one max-size packet. A longer request stays
/// open when the device's data ends on a packet boundary without a ZLP, times
/// out, and usbdevfs then discards everything it had received.
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
pub(crate) const fn usb_bulk_read_size(max_packet_size: i32) -> i32 {
if max_packet_size > 0 && max_packet_size <= 1_024 {
max_packet_size
} else {
64
}
}
pub(crate) enum UsbConnectionCleanup<O> {
Closed {
release_interface: Result<(), String>,
@@ -878,6 +892,26 @@ impl UsbInboundState {
}
}
/// The setting this generation's radio definitively rejected.
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
pub(crate) fn definitive_rejection(&self) -> Option<RNodeReadinessEvidence> {
self.projection
.as_ref()
.and_then(|projection| projection.protocol.definitive_rejection())
}
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
pub(crate) fn stopped_for_configuration_rejection(&mut self, rejected: RNodeReadinessEvidence) {
if let Some(gate) = &self.tx_gate {
gate.close();
}
if let Some(projection) = self.projection.as_mut() {
projection
.publisher
.stopped_for_configuration_rejection(rejected);
}
}
/// Return the lifecycle publisher after one physical USB generation ends.
///
/// Framing and protocol evidence are intentionally generation-local, but
@@ -906,7 +940,7 @@ pub(crate) async fn forward_usb_read_chunk(
bytes: &[u8],
id: InterfaceId,
received_bytes: &AtomicU64,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
stop_rx: &mut mpsc::Receiver<()>,
) -> UsbInboundOutcome {
forward_usb_read_chunk_inner(
@@ -926,7 +960,7 @@ async fn forward_usb_read_chunk_inner(
bytes: &[u8],
id: InterfaceId,
received_bytes: &AtomicU64,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
stop_rx: &mut mpsc::Receiver<()>,
deadline: Option<tokio::time::Instant>,
) -> UsbInboundOutcome {
@@ -992,7 +1026,7 @@ pub(crate) async fn drain_usb_reader_tail(
state: &mut UsbInboundState,
id: InterfaceId,
received_bytes: &AtomicU64,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
stop_rx: &mut mpsc::Receiver<()>,
deadline: tokio::time::Instant,
) -> UsbReadDrainOutcome {
@@ -1457,7 +1491,7 @@ pub(crate) async fn run_usb_rnode_startup<O: UsbConnectionLifecycle>(
// admission, without making ROM availability a normal-startup requirement.
// Preserve only detect/firmware evidence; queued RF echoes, READY permits,
// DATA and partial framing cannot establish post-init operational readiness.
let mut protocol = RNodeProtocolState::new(target);
let mut protocol = RNodeProtocolState::with_effective_settings(target);
let mut deframer = kiss::RawKissDeframer::new();
let mut observe = |event| -> Result<(), UsbWriteFailure> {
let UsbIoEvent::Read(bytes) = event else {
@@ -2195,6 +2229,15 @@ where
mod tests {
use super::*;
#[test]
fn bulk_reads_request_exactly_one_max_size_packet() {
assert_eq!(usb_bulk_read_size(64), 64);
assert_eq!(usb_bulk_read_size(512), 512);
assert_eq!(usb_bulk_read_size(0), 64);
assert_eq!(usb_bulk_read_size(-1), 64);
assert_eq!(usb_bulk_read_size(4_096), 64);
}
fn usb_candidate(
device_name: &str,
vendor_id: u16,
@@ -2577,7 +2620,7 @@ mod tests {
&framed_protocol_frames(evidence),
1,
&AtomicU64::new(0),
&transport,
&crate::traits::test_registered_sender(1, transport.clone()),
&mut inbound_stop
)
.await,
@@ -2907,12 +2950,14 @@ mod tests {
kiss::frame_with_command_into(rnode::CMD_RESET, &[0xF8], &mut bytes);
kiss::frame_with_command_into(kiss::CMD_DATA, &[1, 2, 3], &mut bytes);
let received = AtomicU64::new(0);
let bound_transport = crate::traits::test_registered_sender(1, transport.clone());
let episode_start = tokio::time::Instant::now();
tokio::time::timeout(USB_PROTOCOL_READINESS_DEADLINE * 2, async {
tokio::select! {
exit = pump => assert_eq!(exit.unwrap(), UsbTxPumpExit::ReadinessTimedOut),
result = forward_usb_read_chunk(
&mut inbound, &bytes, 1, &received, &transport, &mut inbound_stop_rx
&mut inbound, &bytes, 1, &received,
&bound_transport, &mut inbound_stop_rx
) => panic!("full transport queue cannot conclude before pump expiry: {result:?}"),
}
})
@@ -3284,6 +3329,69 @@ mod tests {
.await;
}
/// A cold amplifier board echoes the requested power, then its floor once
/// on: the generation must report a terminal rejection and never open TX.
#[tokio::test]
async fn effective_usb_generation_reports_a_definitive_rejection() {
let target = RNodeProtocolTarget::new(915_000_000, 125_000, 7, 5, 2);
let (mut publisher, driver) =
rnode::new_rnode_driver_observation(rnode::RNodeTransportClass::Usb);
publisher.connection_established();
let mut inbound = UsbInboundState::projected_with_protocol_state(
RNodeProtocolState::with_effective_settings(target),
publisher,
);
let gate = UsbTxGate::new(false, Arc::new(AtomicBool::new(false)));
inbound.attach_tx_gate(gate.clone());
let (_stop_tx, mut stop_rx) = mpsc::channel(1);
let (transport_tx, _transport_rx) = mpsc::channel(1);
let mut floor = post_radio_on_echoes(target);
floor[2] = (rnode::CMD_TXPOWER, vec![13]);
assert_eq!(
forward_usb_read_chunk(
&mut inbound,
&framed_protocol_frames(required_protocol_frames(target)),
0x88,
&AtomicU64::new(0),
&crate::traits::test_registered_sender(0x88, transport_tx.clone()),
&mut stop_rx,
)
.await,
UsbInboundOutcome::Complete
);
assert_eq!(inbound.definitive_rejection(), None);
assert_eq!(
forward_usb_read_chunk(
&mut inbound,
&framed_protocol_frames(floor),
0x88,
&AtomicU64::new(0),
&crate::traits::test_registered_sender(0x88, transport_tx),
&mut stop_rx,
)
.await,
UsbInboundOutcome::Complete
);
assert_eq!(
inbound.definitive_rejection(),
Some(RNodeReadinessEvidence::TransmitPower)
);
assert!(!gate.can_send());
inbound.stopped_for_configuration_rejection(RNodeReadinessEvidence::TransmitPower);
let stopped = driver.snapshot();
assert_eq!(stopped.phase, rnode::RNodeRuntimePhase::Stopped);
assert_eq!(
stopped.reason,
Some(rnode::RNodeRuntimeReason::ConfigurationRejected)
);
assert_eq!(
stopped.configuration_rejection,
Some(RNodeReadinessEvidence::TransmitPower)
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ordinary_usb_startup_discards_preinit_rf_ready_and_partial_frames() {
struct PreinitReader(Option<Vec<u8>>);
@@ -3336,6 +3444,7 @@ mod tests {
for (command, frame) in required_protocol_frames(USB_TEST_TARGET)
.into_iter()
.skip(2)
.chain(post_radio_on_echoes(USB_TEST_TARGET))
{
inbound.project_frame(command, &frame);
}
@@ -3370,6 +3479,22 @@ mod tests {
]
}
/// What RNode firmware echoes for the settings re-asserted after
/// `RADIO_STATE_ON` when the hardware uses them as requested.
fn post_radio_on_echoes(target: RNodeProtocolTarget) -> [(u8, Vec<u8>); 3] {
[
(
rnode::CMD_FREQUENCY,
target.frequency.to_be_bytes().to_vec(),
),
(
rnode::CMD_BANDWIDTH,
target.bandwidth.to_be_bytes().to_vec(),
),
(rnode::CMD_TXPOWER, vec![target.tx_power]),
]
}
fn framed_protocol_frames(frames: impl IntoIterator<Item = (u8, Vec<u8>)>) -> Vec<u8> {
let mut wire = Vec::new();
for (command, payload) in frames {
@@ -3784,7 +3909,7 @@ mod tests {
&[0xBB, kiss::FEND],
0x66,
&received,
&transport_tx,
&crate::traits::test_registered_sender(0x66, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -3796,10 +3921,14 @@ mod tests {
assert_eq!(
forward_usb_read_chunk(
&mut inbound,
&framed_protocol_frames(required_protocol_frames(target)),
&framed_protocol_frames(
required_protocol_frames(target)
.into_iter()
.chain(post_radio_on_echoes(target))
),
0x66,
&received,
&transport_tx,
&crate::traits::test_registered_sender(0x66, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -3919,8 +4048,12 @@ mod tests {
let stale_enqueued = Arc::new(AtomicBool::new(false));
let response = capability_response(0xB8);
let stale_rf = framed_protocol_frames(required_protocol_frames(target).into_iter().skip(2));
let post_init =
framed_protocol_frames(required_protocol_frames(target).into_iter().skip(2));
let post_init = framed_protocol_frames(
required_protocol_frames(target)
.into_iter()
.skip(2)
.chain(post_radio_on_echoes(target)),
);
let reader = SeparateStaleReader {
writer_calls: calls.clone(),
capability_reads: response.chunks(512).map(|chunk| chunk.to_vec()).collect(),
@@ -3995,7 +4128,7 @@ mod tests {
&bytes,
0x77,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(0x77, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4027,7 +4160,7 @@ mod tests {
chunk,
0x55,
&received,
&transport_tx,
&crate::traits::test_registered_sender(0x55, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4042,7 +4175,12 @@ mod tests {
snapshot.configuration,
rnode::RNodeConfigurationState::Verified
);
match transport_rx.recv().await.expect("projected packet") {
match transport_rx
.recv()
.await
.map(crate::traits::test_event_body)
.expect("projected packet")
{
TransportMessage::Inbound(packet) => {
assert_eq!(packet.raw.as_ref(), payload);
assert_eq!(packet.interface_id, 0x55);
@@ -4077,7 +4215,7 @@ mod tests {
&wire,
7,
&received,
&transport_tx,
&crate::traits::test_registered_sender(7, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4104,7 +4242,7 @@ mod tests {
&ready_blocked,
8,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(8, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4146,7 +4284,7 @@ mod tests {
&mut inbound,
9,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(9, transport_tx.clone()),
&mut stop_rx,
tokio::time::Instant::now() + Duration::from_secs(1),
)
@@ -4212,7 +4350,7 @@ mod tests {
&late_detect,
10,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(10, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4656,7 +4794,7 @@ mod tests {
&kiss::frame(&[1, 2, 3]),
1,
&AtomicU64::new(0),
&forward_transport,
&crate::traits::test_registered_sender(1, forward_transport.clone()),
&mut forward_stop_rx,
)
.await
@@ -4836,7 +4974,7 @@ mod tests {
&kiss::frame(&[1, 3, 5]),
2,
&AtomicU64::new(0),
&transport_tx,
&crate::traits::test_registered_sender(2, transport_tx.clone()),
&mut stop_rx,
),
)
@@ -4845,7 +4983,10 @@ mod tests {
UsbInboundOutcome::Complete
);
assert!(matches!(
transport_rx.recv().await,
transport_rx
.recv()
.await
.map(crate::traits::test_event_body),
Some(TransportMessage::Inbound(_))
));
@@ -4890,14 +5031,19 @@ mod tests {
&mut inbound,
77,
&received,
&transport_tx,
&crate::traits::test_registered_sender(77, transport_tx.clone()),
&mut stop_rx,
tokio::time::Instant::now() + Duration::from_secs(1),
)
.await,
UsbReadDrainOutcome::Drained
);
match transport_rx.recv().await.expect("forwarded packet") {
match transport_rx
.recv()
.await
.map(crate::traits::test_event_body)
.expect("forwarded packet")
{
TransportMessage::Inbound(packet) => {
assert_eq!(packet.raw.as_ref(), payload);
assert_eq!(packet.interface_id, 77);
@@ -4914,7 +5060,7 @@ mod tests {
&kiss::frame(&second_payload),
77,
&received,
&transport_tx,
&crate::traits::test_registered_sender(77, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -4962,7 +5108,7 @@ mod tests {
&mut UsbInboundState::new(),
77,
&received,
&transport_tx,
&crate::traits::test_registered_sender(77, transport_tx.clone()),
&mut stop_rx,
deadline,
)
@@ -5124,7 +5270,7 @@ mod tests {
&bytes,
91,
&received,
&transport_tx,
&crate::traits::test_registered_sender(91, transport_tx.clone()),
&mut stop_rx,
)
.await,
@@ -5139,7 +5285,7 @@ mod tests {
&mut inbound,
91,
&received,
&transport_tx,
&crate::traits::test_registered_sender(91, transport_tx.clone()),
&mut stop_rx,
tokio::time::Instant::now() + Duration::from_secs(1),
)
@@ -5155,7 +5301,12 @@ mod tests {
.await
.expect("simultaneous completion did not settle");
match transport_rx.recv().await.expect("forwarded reader tail") {
match transport_rx
.recv()
.await
.map(crate::traits::test_event_body)
.expect("forwarded reader tail")
{
TransportMessage::Inbound(packet) => assert_eq!(packet.raw.as_ref(), [7, 8, 9]),
_ => panic!("unexpected transport message"),
}
@@ -5188,7 +5339,7 @@ mod tests {
&mut UsbInboundState::new(),
9,
&received,
&transport_tx,
&crate::traits::test_registered_sender(9, transport_tx.clone()),
&mut stop_rx,
tokio::time::Instant::now() + Duration::from_secs(1),
)
@@ -0,0 +1,360 @@
//! Production descriptor selection and serial control requests for Android USB.
#[derive(Clone, Debug)]
pub(crate) struct UsbEndpointDescriptor {
pub direction: i32,
pub transfer_type: i32,
}
#[derive(Clone, Debug)]
pub(crate) struct UsbInterfaceDescriptor {
pub number: u16,
pub alternate_setting: i32,
pub class: i32,
pub subclass: i32,
pub endpoints: Vec<UsbEndpointDescriptor>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum UsbSerialKind {
Cp210x,
CdcAcm,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct UsbSerialPort {
pub kind: UsbSerialKind,
/// Positions in UsbDevice's interface array, not bInterfaceNumber.
pub data_interface: usize,
pub control_interface: usize,
/// bInterfaceNumber used as wIndex in control transfers.
pub control_number: u16,
/// Positions in the data interface's endpoint array.
pub input_endpoint: usize,
pub output_endpoint: usize,
}
fn bulk_pair(interface: &UsbInterfaceDescriptor) -> Option<(usize, usize)> {
let mut input = None;
let mut output = None;
for (index, endpoint) in interface.endpoints.iter().enumerate() {
if endpoint.transfer_type != 2 {
continue;
}
match endpoint.direction {
0x80 if input.is_none() => input = Some(index),
0x00 if output.is_none() => output = Some(index),
_ => return None,
}
}
Some((input?, output?))
}
pub(crate) fn select_serial_port(
vendor_id: i32,
product_id: i32,
interfaces: &[UsbInterfaceDescriptor],
) -> Result<UsbSerialPort, String> {
// Heltec V3 uses the standard CP2102/CP2102N VID/PID. Do not apply
// Silicon Labs requests to every vendor-specific interface or VID.
let cp210x = vendor_id == 0x10c4 && product_id == 0xea60;
let mut candidates = interfaces
.iter()
.enumerate()
.filter_map(|(index, interface)| {
if interface.alternate_setting != 0
|| interface.class != if cp210x { 0xff } else { 0x0a }
{
return None;
}
bulk_pair(interface).map(|pair| (index, pair))
});
let (data_interface, (input_endpoint, output_endpoint)) =
candidates.next().ok_or_else(|| {
"No supported USB serial interface with bulk IN and OUT endpoints".to_string()
})?;
if candidates.next().is_some() {
return Err("Multiple USB serial data interfaces are unsupported".into());
}
let control_interface = if cp210x {
data_interface
} else {
// A single CDC-ACM function is unambiguous even when unrelated JTAG
// or other interfaces precede it. Multi-port CDC needs a union/IAD
// association parser; never guess a control interface for it.
let mut controls = interfaces.iter().enumerate().filter(|(_, interface)| {
interface.alternate_setting == 0
&& interface.class == 0x02
&& interface.subclass == 0x02
});
let (index, _) = controls
.next()
.ok_or_else(|| "No CDC-ACM control interface found".to_string())?;
if controls.next().is_some() {
return Err("Multiple CDC-ACM control interfaces are unsupported".into());
}
index
};
Ok(UsbSerialPort {
kind: if cp210x {
UsbSerialKind::Cp210x
} else {
UsbSerialKind::CdcAcm
},
data_interface,
control_interface,
control_number: interfaces[control_interface].number,
input_endpoint,
output_endpoint,
})
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct UsbControlRequest<'a> {
pub request_type: u8,
pub request: u8,
pub value: u16,
pub index: u16,
pub payload: &'a [u8],
}
pub(crate) fn configure_serial_port(
port: &UsbSerialPort,
baud_rate: u32,
mut transfer: impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
) -> Result<(), String> {
if baud_rate == 0 {
return Err("USB serial baud rate must be nonzero".into());
}
let request_type = match port.kind {
UsbSerialKind::Cp210x => 0x41,
UsbSerialKind::CdcAcm => 0x21,
};
let mut send = |request, value, payload: &[u8]| {
let setup = UsbControlRequest {
request_type,
request,
value,
index: port.control_number,
payload,
};
let transferred = transfer(&setup)
.map_err(|error| format!("USB serial setup request 0x{request:02x}: {error}"))?;
if transferred != payload.len() as i32 {
return Err(format!(
"USB serial setup request 0x{request:02x} transferred {transferred} bytes; expected {}",
payload.len()
));
}
Ok(())
};
match port.kind {
UsbSerialKind::Cp210x => {
// Silicon Labs AN571 sections 5.1, 5.5, 5.7, 5.9, 5.11 and
// tables 9-11: https://www.silabs.com/documents/public/application-notes/AN571.pdf
send(0x00, 0x0001, &[])?; // IFC_ENABLE must precede other requests.
send(0x1e, 0, &baud_rate.to_le_bytes())?;
send(0x03, 0x0800, &[])?; // 8 data bits, no parity, 1 stop bit.
// Static DTR/RTS active, no CTS/DSR/DCD or XON/XOFF handshake,
// no NULL stripping or inserted characters. Thresholds unused.
let mut flow = [0u8; 16];
flow[0..4].copy_from_slice(&1u32.to_le_bytes());
flow[4..8].copy_from_slice(&0x40u32.to_le_bytes());
send(0x13, 0, &flow)?;
// Set both lines together, with both write masks. No reset pulse
// or one-line transition to ESP download mode is requested.
// https://docs.espressif.com/projects/esptool/en/latest/esp32s3/advanced-topics/boot-mode-selection.html
send(0x07, 0x0303, &[])?;
}
UsbSerialKind::CdcAcm => {
let mut line_coding = [0u8; 7];
line_coding[..4].copy_from_slice(&baud_rate.to_le_bytes());
line_coding[6] = 8;
send(0x20, 0, &line_coding)?; // SET_LINE_CODING, 8N1.
send(0x22, 3, &[])?; // SET_CONTROL_LINE_STATE, DTR and RTS.
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn interface(
number: u16,
class: i32,
subclass: i32,
endpoints: &[(i32, i32)],
) -> UsbInterfaceDescriptor {
UsbInterfaceDescriptor {
number,
alternate_setting: 0,
class,
subclass,
endpoints: endpoints
.iter()
.map(|&(direction, transfer_type)| UsbEndpointDescriptor {
direction,
transfer_type,
})
.collect(),
}
}
fn cp210x() -> UsbSerialPort {
select_serial_port(
0x10c4,
0xea60,
&[interface(4, 0xff, 0, &[(0x80, 2), (0, 2)])],
)
.unwrap()
}
#[test]
fn cp210x_setup_is_scoped_and_uses_vendor_requests_without_reset() {
let descriptors = [interface(4, 0xff, 0, &[(0x80, 2), (0, 2)])];
for (vid, pid) in [
(0x10c4, 0xea61),
(0x0403, 0x6001),
(0x1a86, 0x7523),
(0x303a, 0x1001),
] {
assert!(select_serial_port(vid, pid, &descriptors).is_err());
}
let mut requests = Vec::new();
configure_serial_port(&cp210x(), 115_200, |request| {
requests.push((
request.request_type,
request.request,
request.value,
request.index,
request.payload.to_vec(),
));
Ok(request.payload.len() as i32)
})
.unwrap();
assert_eq!(
requests,
vec![
(0x41, 0x00, 1, 4, vec![]),
(0x41, 0x1e, 0, 4, vec![0x00, 0xc2, 0x01, 0x00]),
(0x41, 0x03, 0x0800, 4, vec![]),
(
0x41,
0x13,
0,
4,
vec![1, 0, 0, 0, 0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
),
(0x41, 0x07, 0x0303, 4, vec![]),
]
);
}
#[test]
fn cdc_uses_actual_control_number_and_only_bulk_endpoints() {
let port = select_serial_port(
0x303a,
0x1001,
&[
interface(0, 0xff, 0, &[(0x80, 2), (0, 2)]), // JTAG, not CDC.
interface(6, 0x02, 0x02, &[(0x80, 3)]),
interface(7, 0x0a, 0, &[(0x80, 3), (0x80, 2), (0, 2), (0, 3)]),
],
)
.unwrap();
assert_eq!(port.data_interface, 2);
assert_eq!(port.control_interface, 1);
assert_eq!((port.input_endpoint, port.output_endpoint), (1, 2));
let mut requests = Vec::new();
configure_serial_port(&port, 9_600, |request| {
requests.push((
request.request_type,
request.request,
request.value,
request.index,
request.payload.to_vec(),
));
Ok(request.payload.len() as i32)
})
.unwrap();
assert_eq!(
requests,
vec![
(0x21, 0x20, 0, 6, vec![0x80, 0x25, 0, 0, 0, 0, 8]),
(0x21, 0x22, 3, 6, vec![]),
]
);
}
#[test]
fn selection_rejects_incomplete_ambiguous_and_nonbulk_interfaces() {
let control = interface(0, 2, 2, &[(0x80, 3)]);
let data = interface(1, 0x0a, 0, &[(0x80, 2), (0, 2)]);
for descriptors in [
vec![data.clone()],
vec![control.clone(), interface(1, 0x0a, 0, &[(0x80, 3), (0, 3)])],
vec![
control.clone(),
interface(1, 0x0a, 0, &[(0x80, 2)]),
interface(2, 0x0a, 0, &[(0, 2)]),
],
vec![control.clone(), data.clone(), interface(2, 2, 2, &[])],
vec![
control.clone(),
data.clone(),
interface(2, 0x0a, 0, &[(0x80, 2), (0, 2)]),
],
vec![
control.clone(),
interface(1, 0x0a, 0, &[(0x80, 2), (0, 2), (0, 2)]),
],
] {
assert!(select_serial_port(0x303a, 0x1001, &descriptors).is_err());
}
let mut alternate = data.clone();
alternate.alternate_setting = 1;
assert!(select_serial_port(0x303a, 0x1001, &[control, alternate]).is_err());
}
#[test]
fn setup_stops_on_every_failed_short_or_impossible_control_completion() {
let cdc = select_serial_port(
0x303a,
0x1001,
&[
interface(0, 2, 2, &[]),
interface(1, 0x0a, 0, &[(0x80, 2), (0, 2)]),
],
)
.unwrap();
for (port, count) in [(cp210x(), 5), (cdc, 2)] {
for fail_at in 0..count {
for failure in 0..4 {
let mut called = 0;
let result = configure_serial_port(&port, 115_200, |request| {
let index = called;
called += 1;
let length = request.payload.len() as i32;
if index != fail_at {
return Ok(length);
}
match failure {
0 => Err("JNI exception".into()),
1 => Ok(-1),
2 => Ok(length - 1),
_ => Ok(length + 1),
}
});
assert!(result.is_err());
assert_eq!(called, fail_at + 1);
}
}
}
assert!(
configure_serial_port(&cp210x(), 0, |_| panic!("invalid baud must not touch USB"))
.is_err()
);
}
}
+25 -16
View File
@@ -1,8 +1,11 @@
//! Automatic peer discovery over IPv6 link-local multicast.
//! Automatic peer discovery over IPv6 multicast, using link scope by default.
//!
//! Beacons go to a multicast group derived from `SHA-256(group_id)` every
//! ~1.6 s; data flows over unicast UDP. Peers age out after 22 s of silence.
//! Beacons use a group derived from `SHA-256(group_id)`; data uses unicast UDP.
//! The normal beacon interval is 1.6 seconds. With `mobile-throttle`, background
//! beacons use 8 seconds. Periodic maintenance removes peers after at least
//! 22 seconds without a beacon.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -19,7 +22,7 @@ use rns_transport::messages::{InboundPacket, TransportMessage};
pub const DISCOVERY_PORT: u16 = 29716;
pub const DATA_PORT: u16 = 42671;
pub const BEACON_INTERVAL: f64 = 1.6;
/// Background beacon — slow enough to save battery, still inside expiry window.
/// Background beacon interval with feature `mobile-throttle`, in seconds.
pub const BEACON_INTERVAL_BG: f64 = 8.0;
pub const PEER_EXPIRY: f64 = 22.0;
pub const HW_MTU: u32 = 1196;
@@ -157,23 +160,20 @@ impl std::fmt::Display for McastAddrType {
}
}
/// Async events from `spawn_auto_interface`; forwarded to Tauri broadcasts.
/// Async events from AutoInterface instances for embedding applications.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AutoInterfaceEvent {
/// `IPV6_JOIN_GROUP` was rejected by the OS. On Apple this can indicate a
/// missing `com.apple.developer.networking.multicast` entitlement or Local
/// Network authorization that has not been granted yet. On Linux it
/// usually means the interface vanished between enumeration and join.
/// `IPV6_JOIN_GROUP` was rejected by the OS. `reason` contains the reported
/// error; this event alone does not establish a permission or network cause.
JoinFailed {
interface_name: String,
ifname: String,
reason: String,
},
/// Carrier state changed — multicast echoes started or stopped arriving
/// on `ifname` within `MCAST_ECHO_TIMEOUT`. `ok=false` is the trip-wire
/// for Windows Public-profile firewall block, bridged-AP reboot, or
/// general IPv6 multicast suppression. `reason` is human-readable.
/// Carrier state changed as local multicast echoes arrived or timed out on
/// `ifname`. `ok=false` reports missing echoes within `MCAST_ECHO_TIMEOUT`;
/// it does not identify the underlying network or firewall cause.
CarrierState {
interface_name: String,
ifname: String,
@@ -293,7 +293,8 @@ impl MultiIfDedup {
}
}
/// Record the packet and return whether it was already seen within TTL.
/// Return whether this packet hash is still in the bounded TTL cache. New
/// hashes are recorded; a duplicate does not refresh its timestamp.
pub fn is_duplicate(&mut self, data: &[u8]) -> bool {
let hash = rns_crypto::sha::sha256(data);
let now = Instant::now();
@@ -330,7 +331,9 @@ impl Default for MultiIfDedup {
}
}
/// Verify a beacon against `SHA-256(group_id + peer_addr_string)`.
/// Compare the first 32 beacon bytes with `SHA-256(group_id + peer_addr_string)`.
/// Shorter inputs fail; trailing bytes are ignored. This shared-group digest
/// does not authenticate a peer identity.
pub fn verify_beacon(beacon: &[u8], group_id: &str, peer_addr: &Ipv6Addr) -> bool {
if beacon.len() < 32 {
return false;
@@ -507,7 +510,9 @@ pub struct NetworkInterfaceInfo {
pub is_loopback: bool,
}
/// Enumerate all host NICs (including loopback / ignored). Callers filter on top.
/// Enumerate addresses reported by the host and group them by NIC name,
/// including loopback and normally ignored names. Callers apply filters.
/// `is_up` means an address was found; it is not a carrier or reachability test.
pub fn list_network_interfaces() -> Result<Vec<NetworkInterfaceInfo>, String> {
use std::collections::BTreeMap;
@@ -1039,6 +1044,8 @@ pub async fn spawn_auto_interface(
transport_tx: mpsc::Sender<TransportMessage>,
is_foreground: Arc<AtomicBool>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let mcast_group = derive_multicast_address(
&config.group_id,
config.discovery_scope,
@@ -1761,6 +1768,8 @@ pub async fn spawn_auto_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(1196, 1196, true),
parent_id: None,
name,
mode,
+13 -4
View File
@@ -1,5 +1,7 @@
//! AX.25-over-KISS — prepends a UI header (src/dst call+SSID) and strips on RX.
#[cfg(feature = "serial")]
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
#[cfg(feature = "serial")]
use std::sync::Arc;
#[cfg(feature = "serial")]
@@ -98,10 +100,12 @@ impl AX25KISSConfig {
}
}
/// 16-byte AX.25 UI header (AX.25 v2.2 §3.12):
/// Build a 16-byte UI header:
/// `dst_call(6) | dst_ssid(1) | src_call(6) | src_ssid(1) | CTRL | PID`.
/// Callsign bytes left-shifted 1, space-padded to 6. SSID = `0x60 | (ssid<<1)`;
/// src SSID also sets end-of-address bit.
/// At most six input callsign bytes are copied and left-shifted by one; unused
/// positions are filled with literal `0x20`. SSID is `0x60 | (ssid << 1)`;
/// the source SSID also sets the end-of-address bit. This helper does not
/// validate callsigns or SSID ranges.
pub fn build_ax25_header(
dst_call: &[u8],
dst_ssid: u8,
@@ -149,7 +153,8 @@ pub fn frame_ax25_kiss(
kiss::frame(&payload)
}
/// Payload after the 16-byte header, or `None` if too short.
/// Return bytes after the fixed 16-byte header, or `None` for frames of
/// 16 bytes or fewer. Addresses, control, and PID are not validated.
pub fn strip_ax25_header(data: &[u8]) -> Option<&[u8]> {
if data.len() > AX25_HEADER_SIZE {
Some(&data[AX25_HEADER_SIZE..])
@@ -232,6 +237,8 @@ pub async fn spawn_ax25kiss_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
config.validate().map_err(|e| {
crate::traits::InterfaceError::SendFailed(format!("ax25kiss config: {}", e))
})?;
@@ -406,6 +413,8 @@ pub async fn spawn_ax25kiss_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
+90 -15
View File
@@ -1,9 +1,10 @@
//! High-throughput HDLC-over-TCP backbone. Server accepts many peers
//! (each its own [`InterfaceHandle`]); client auto-reconnects.
//! Per-peer tuning: TCP keepalive + TCP_USER_TIMEOUT + NODELAY + large
//! buffers. Inbound deframer is capped (vs Python's unbounded) to avoid
//! malformed-peer memory blow-up.
//! HDLC-over-TCP backbone. The server creates an [`InterfaceHandle`] for each
//! accepted peer; the client reconnects after connection loss.
//! Per-peer socket tuning requests keepalive, NODELAY, and large buffers, with
//! TCP_USER_TIMEOUT where supported. The shared HDLC deframer caps each
//! encoded frame; this is not a bound on total connection memory.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -18,19 +19,23 @@ 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, handoff_accepted_interface,
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection, python_host,
};
use rns_transport::messages::{
InboundPacket, InterfaceInspectionSnapshot, InterfaceInspectionSource, TransportMessage,
};
/// 1 MiB MTU — also the SO_RCVBUF/SNDBUF target (kernel clamps).
/// 1 MiB ceiling for MTU selection and requested socket buffer size.
/// Peer packet capacity is selected separately from the per-peer bitrate and
/// the interface wire budget; the kernel may clamp the socket buffer request.
pub const HW_MTU: u32 = 1_048_576;
/// Listener-side bitrate guess advertised on the parent handle.
pub const BITRATE_GUESS: u64 = 1_000_000_000;
/// Per-peer guess (100 Mbps) — drives [`crate::traits::optimise_mtu`] → 64 KiB MTU.
/// Per-peer bitrate guess (100 Mbps), selecting a 16 KiB MTU through
/// [`crate::traits::optimise_mtu`].
pub const CHILD_BITRATE_GUESS: u64 = 100_000_000;
pub const RECONNECT_WAIT: u64 = 5;
@@ -39,7 +44,7 @@ pub const INITIAL_CONNECT_TIMEOUT: u64 = 5;
pub const TCP_PROBE_AFTER: u32 = 5;
pub const TCP_PROBE_INTERVAL: u32 = 2;
pub const TCP_PROBES: u32 = 12;
/// Linux TCP_USER_TIMEOUT — drops stuck conns when peer goes silent without RST.
/// TCP_USER_TIMEOUT budget in seconds, applied best effort on supported platforms.
pub const TCP_USER_TIMEOUT: u32 = 24;
pub const BLOCK_FAST_FLAPPING: bool = true;
@@ -66,7 +71,9 @@ 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.
/// Reject a tracked IP after more than `fast_flapping_grace` short connections.
/// The process-wide tracking table is bounded; a new IP is not tracked when
/// that table is full.
pub block_fast_flapping: bool,
/// Connections shorter than this duration count as fast flaps.
pub fast_flapping_threshold: Duration,
@@ -102,6 +109,9 @@ pub struct BackboneClientConfig {
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
/// Identity used to request a signed tunnel synthesis for each connection.
/// `None`, or an identity without signing material, sends no synthesis.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl BackboneClientConfig {
@@ -114,8 +124,19 @@ impl BackboneClientConfig {
connect_timeout_secs: INITIAL_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
tunnel_identity: None,
}
}
/// Python `str(BackboneClientInterface)` (BackboneInterface.py:1114-1117).
pub fn python_name(&self) -> String {
format!(
"BackboneInterface[{}/{}:{}]",
self.name,
python_host(&self.target_host),
self.target_port
)
}
}
#[derive(Debug, Clone, Copy)]
@@ -359,7 +380,7 @@ fn child_mtu() -> u32 {
async fn backbone_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
) {
@@ -515,6 +536,8 @@ fn spawn_backbone_server_on_listener(
fast_flap_runtime: FastFlapRuntime,
listener: TcpListener,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "backbone server listening");
@@ -582,8 +605,10 @@ fn spawn_backbone_server_on_listener(
let c_online_r = c_online.clone();
let c_rxb_r = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let dereg_tx = transport_tx.clone();
let transport_tx2 =
InterfaceTransportSender::new(client_id, transport_tx.actor_sender());
let child_owner = transport_tx2.owner();
let dereg_tx = transport_tx2.clone();
let cname = client_name.clone();
let active_client_guard =
ActiveClientGuard::new(Arc::clone(&task_active_clients));
@@ -601,6 +626,12 @@ fn spawn_backbone_server_on_listener(
let handle = InterfaceHandle {
id: client_id,
owner: child_owner,
packet_capacity: InterfacePacketCapacity::new(
child_mtu().min(262144),
262144,
true,
),
parent_id: Some(id),
name: client_name,
mode,
@@ -638,6 +669,8 @@ fn spawn_backbone_server_on_listener(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::base(500),
parent_id: None,
name,
mode,
@@ -663,6 +696,8 @@ pub async fn spawn_backbone_client(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(false));
let online2 = online.clone();
let (tx, rx) = mpsc::channel::<Bytes>(TX_CHANNEL_DEPTH);
@@ -675,11 +710,15 @@ pub async fn spawn_backbone_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let max_tries = config.max_reconnect_tries;
let mut tries: usize = 0;
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
loop {
let after_outage = std::mem::replace(&mut attempted, true);
let target = match tokio::time::timeout(
Duration::from_secs(config.connect_timeout_secs),
resolve_target(&config.target_host, config.target_port, config.prefer_ipv6),
@@ -755,8 +794,14 @@ pub async fn spawn_backbone_client(
};
tune_stream(&stream);
online2.store(true, Ordering::SeqCst);
tries = 0;
// Python synthesizes on every connection (BackboneInterface.py:922,
// :1019).
let synthesis = config
.tunnel_identity
.as_ref()
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(&rx, after_outage, &transport_tx, synthesis, &online2).await;
let c_online = Arc::new(AtomicBool::new(true));
let (reader, writer) = stream.into_split();
@@ -807,6 +852,8 @@ pub async fn spawn_backbone_client(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(child_mtu().min(262144), 262144, true),
parent_id: None,
name,
mode,
@@ -832,6 +879,26 @@ mod tests {
use super::*;
use std::net::{Ipv4Addr, SocketAddr};
#[test]
fn client_python_names_match_python() {
// Python 1.5.5 `str()` output for these interfaces.
for (host, expected) in [
(
"10.0.0.1",
"BackboneInterface[Golden Backbone/10.0.0.1:4243]",
),
(
"fd00::1",
"BackboneInterface[Golden Backbone/[fd00::1]:4243]",
),
] {
assert_eq!(
BackboneClientConfig::new("Golden Backbone", host, 4243).python_name(),
expected
);
}
}
#[derive(Clone)]
struct TestClock {
now: Arc<Mutex<Duration>>,
@@ -1238,6 +1305,7 @@ mod tests {
listener,
)
.unwrap();
parent.owner.mark_registered();
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
let _stream = TcpStream::connect(listen_addr).await.unwrap();
@@ -1245,6 +1313,7 @@ mod tests {
.await
.expect("accepted child handle timed out")
.expect("child handle channel closed");
child.owner.mark_registered();
assert_eq!(inspection_snapshot(&parent).active_clients, Some(1));
clock.advance(Duration::from_millis(1));
child.read_task.abort();
@@ -1286,6 +1355,7 @@ mod tests {
listener,
)
.unwrap();
parent.owner.mark_registered();
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
let mut stream = TcpStream::connect(listen_addr).await.unwrap();
@@ -1313,11 +1383,16 @@ mod tests {
let (tx, mut rx) = mpsc::channel::<TransportMessage>(8);
let handle = spawn_backbone_client(cfg, 99, tx).await.unwrap();
handle.owner.mark_registered();
// Wait for the read_task to finish — guarded by a generous timeout
// to absorb the one RECONNECT_WAIT sleep + connect attempt.
let dereg = tokio::time::timeout(Duration::from_secs(15), async {
loop {
match rx.recv().await {
match rx
.recv()
.await
.map(|event| crate::traits::test_event_for_handle(event, &handle))
{
Some(TransportMessage::DeregisterInterface { id }) => return Some(id),
Some(_) => continue,
None => return None,
+13 -13
View File
@@ -1,9 +1,6 @@
//! Apple CBCentralManager scan driver.
//!
//! Exists to pass `CBCentralManagerScanOptionAllowDuplicatesKey = YES` to
//! `scanForPeripheralsWithServices:options:` — btleplug does not expose
//! that key, and without it CoreBluetooth reports each peripheral at most
//! once per scan session.
//! Apple CBCentralManager scan driver. Requests repeated advertisement
//! callbacks with `CBCentralManagerScanOptionAllowDuplicatesKey = YES` and
//! reuses its native manager between scan cycles.
#![cfg(any(target_os = "ios", target_os = "macos"))]
@@ -77,8 +74,10 @@ fn manager_slot() -> &'static Mutex<SendPtr> {
MANAGER_PTR.get_or_init(|| Mutex::new(SendPtr(std::ptr::null_mut())))
}
/// Start a CBCentralManager scan with `AllowDuplicatesKey = YES`. Empty
/// `services` scans for all advertisements.
/// Request a CBCentralManager scan with `AllowDuplicatesKey = YES`. Empty
/// `services` removes the service filter. On first startup, manager creation
/// and the wait for PoweredOn continue on a worker thread after this function
/// returns; `Ok` is not confirmation that scanning has started.
pub async fn start_scan(
services: Vec<Uuid>,
) -> Result<mpsc::UnboundedReceiver<DiscoveryEvent>, String> {
@@ -228,8 +227,9 @@ pub async fn stop_scan() -> Result<(), String> {
Ok(())
}
/// Full teardown — interface shutdown only. Per-cycle stops use
/// [`stop_scan`] to keep the manager alive (macOS alloc-cycle bug).
/// Detach the delegate, release this module's explicit manager retain, and
/// clear its manager slot during interface shutdown. Per-cycle stops use
/// [`stop_scan`] and retain the manager for reuse.
pub async fn teardown_central() -> Result<(), String> {
let _ = stop_scan().await;
@@ -275,9 +275,9 @@ pub fn current_state() -> CentralState {
lifecycle().current()
}
/// Persistent `CBCentralManager` pointer. Apple central peripheral caches
/// are per-manager, not per-process — `ble_central_apple_connect` must
/// drive `connectPeripheral:` against the same manager that scanned.
/// Borrow the current `CBCentralManager` pointer without retaining it.
/// Connection setup uses the manager that performed discovery. Callers must
/// coordinate teardown; this accessor does not extend the pointer's lifetime.
pub fn central_manager_ptr() -> Option<*mut AnyObject> {
let lock = MANAGER_PTR.get()?;
let g = lock.lock().ok()?;
@@ -1,9 +1,7 @@
//! Apple central-role connect lifecycle. Sister to
//! [`ble_central_apple`](crate::ble_central_apple) (which owns scanning).
//!
//! Apple-specific because btleplug's CoreBluetooth backend allocates its
//! own manager, and two managers in the same process don't share peripheral
//! caches on macOS, so `adapter.peripherals()` returns empty every cycle.
//! Apple central-role connection lifecycle, using the manager and discovered
//! peripherals owned by [`ble_central_apple`](crate::ble_central_apple).
//! Scanning and connection setup share that manager rather than creating a
//! separate btleplug adapter.
#![cfg(any(target_os = "ios", target_os = "macos"))]
@@ -23,13 +21,12 @@ use crate::ble_peer::{
RATSPEAK_SERVICE_UUID, RATSPEAK_TX_UUID,
};
/// `connectPeripheral:` does not self-time-out; iOS RPA rotation leaves
/// ghost identifiers in `Connecting` state forever. 5s recycles ghosts
/// before they block the scan-loop pipeline.
/// Deadline for the connect callback. On timeout, partial connection state
/// is cancelled and released.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Generous safety net for service / characteristic / notify discovery
/// (CoreBluetooth normally responds in ~200 ms).
/// Per-step deadline for service discovery, characteristic discovery, and
/// notification subscription callbacks.
pub const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(10);
const DISCOVERED_TTL: Duration = Duration::from_secs(60);
@@ -65,9 +62,8 @@ static LAST_DISCONNECT_REASON: OnceLock<Mutex<HashMap<String, DisconnectReason>>
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DisconnectReason {
/// `CBErrorPeripheralConnectionTimeout` — almost always an iPhone /
/// Pixel RPA rotating out from under our open link. The peer
/// re-advertises within ~1s.
/// Classification used for `CBErrorPeripheralConnectionTimeout`. The label
/// does not establish address rotation as the cause or guarantee rediscovery.
Rotation,
OtherError,
}
@@ -122,9 +118,9 @@ pub fn take_last_disconnect_reason(address: &str) -> Option<DisconnectReason> {
.and_then(|mut g| g.remove(address))
}
/// Drop frees the retained ObjC objects. Disconnect goes via
/// [`disconnect_peer`] (`cancelPeripheralConnection:`); the delegate
/// callback removes the map entry, dropping the last `Arc`.
/// Owns retained Objective-C connection objects until the final `Arc` is
/// dropped. [`disconnect_peer`] removes the registered peer and requests
/// `cancelPeripheralConnection:`; other owners can outlive that request.
pub struct ConnectedPeer {
pub address: String,
pub protocol: PeerProtocol,
@@ -519,15 +515,19 @@ pub fn disconnect_all() {
}
}
/// Adopt a CBPeripheral handed back via `centralManager:willRestoreState:`.
/// Apple guarantees `peripheral.services` is populated and prior TX-char
/// subscriptions are preserved — only the delegate needs rebinding. On
/// success ownership of the +1 retain passes to `ConnectedPeer::drop`; on
/// Err the retain is released.
/// Adopt a restored peripheral using its cached service and characteristic
/// objects. This function rebinds the delegate; it does not rediscover services
/// or resubscribe to notifications.
///
/// For a nonempty address and non-null pointer, the supplied +1 retain is
/// consumed: success transfers it to the connection owner or releases it if
/// already registered, and service/characteristic failures release it. Invalid
/// arguments return early without releasing the pointer.
///
/// # Safety
/// `peripheral` must be a retained, non-null `CBPeripheral *` whose state
/// is `Connected (= 2)`.
/// `peripheral` must be a valid, retained `CBPeripheral *` in Connected state.
/// The caller must ensure its cached services and notification subscriptions
/// are usable; this function does not establish those conditions.
pub unsafe fn adopt_restored_peer(
address: String,
peripheral: *mut AnyObject,
@@ -633,8 +633,8 @@ pub unsafe fn adopt_restored_peer(
Ok(())
}
/// CB keeps connections alive thanks to `bluetooth-central`
/// UIBackgroundMode + restore-identifier; this just logs inventory.
/// Log connected-peer and pending-write counts when the app resigns active.
/// This hook does not change connection state or guarantee background delivery.
pub fn on_app_will_resign_active() {
let connected = connected_peers().lock().map(|g| g.len()).unwrap_or(0);
let pending = connected_peers()
@@ -654,8 +654,8 @@ pub fn on_app_will_resign_active() {
);
}
/// Prune discovered pointers older than the discovery TTL — after a long
/// background those are RPA-rotated ghosts.
/// Prune discovered pointers older than the discovery TTL and log the
/// remaining discovery and connection counts.
pub fn on_app_did_become_active() {
prune_discovered();
let discovered_remaining = match discovered().lock() {
@@ -1,5 +1,6 @@
//! BLE central (scan) lifecycle. `PlatformUnavailable` rewinds active states
//! to `StartingWaitingPlatform` so scanning resumes after a Bluetooth toggle.
//! BLE central scan lifecycle. `PlatformUnavailable` rewinds starting or
//! scanning states to `StartingWaitingPlatform`. A later `PlatformReady` can
//! resume scanning; stopping states are not rewound.
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Instant;
@@ -12,7 +13,8 @@ pub enum AdvertisedProtocol {
Columba,
}
/// `identifier` is platform-stable (Apple UUIDString, bluer D-Bus path, Android MAC).
/// `identifier` is a platform-provided scan identifier, such as an Apple UUID
/// or Bluetooth address. It is not a persistent authenticated peer identity.
#[derive(Debug, Clone)]
pub struct DiscoveryEvent {
pub identifier: String,
@@ -48,7 +50,7 @@ pub enum CentralState {
StoppingScan,
/// Cleanly torn down. Distinct from `Idle` for telemetry.
Stopped,
/// Bluetooth unsupported / permission denied; requires explicit `Reset`.
/// A fatal platform error was reported; requires explicit `Reset`.
Failed,
}
@@ -75,8 +77,8 @@ pub enum CentralEvent {
StartRequested,
/// Platform ready: adapter calls `scanForPeripheralsWithServices` here.
PlatformReady,
/// Active states rewind to `StartingWaitingPlatform` so recovery
/// resumes scanning.
/// Starting and scanning states rewind to `StartingWaitingPlatform`.
/// Stopping states reject this event.
PlatformUnavailable {
reason: String,
},
+59 -48
View File
@@ -1,18 +1,18 @@
//! BLE Peer-to-Peer mesh interface. Each device acts as both Central
//! (scanner/GATT client) and Peripheral (advertiser/GATT server)
//! simultaneously.
//! BLE peer interface with a central (scanner/GATT client) role and an
//! optional peripheral (advertiser/GATT server) role. Peripheral startup
//! failure leaves the central role running.
//!
//! ## Dual-service GATT
//!
//! ### Ratspeak (primary)
//! - Service: `a1b2c3d4-e5f6-4a5b-8c9d-0e1f2a3b4c5d`
//! - RX: `…4c5e` (WRITE, WRITE_NO_RESPONSE)
//! - TX: `…4c5f` (READ, NOTIFY)
//! - RX: `…4c5e` (peer writes here)
//! - TX: `…4c5f` (peer subscribes to notifications)
//!
//! ### Columba (cross-app compat)
//! - Service: `37145b00-442d-4a94-917f-8f42c5da28e3`
//! - RX: `…28e5` (WRITE, WRITE_NO_RESPONSE)
//! - TX: `…28e4` (READ, NOTIFY, INDICATE)
//! - RX: `…28e5` (peer writes here)
//! - TX: `…28e4` (peer subscribes to notifications)
//!
//! Peer identity binds only from directly-originated, signature-verified LXMF
//! delivery announces. There is no ID characteristic: a statically readable
@@ -26,9 +26,13 @@
//! packets are encoded as a two-frame START/END sequence instead of LONE so
//! older reassemblers can still decode them.
//!
//! Keepalive: 15s interval, 1-byte ping; 3 misses → disconnect. Cap 7
//! simultaneous peers.
//! On the btleplug central backend (Linux/Windows), 15 seconds without a
//! notification triggers a one-byte keepalive write. Three consecutive failed
//! writes end the peer reader loop; a successful write or a nonempty matching
//! notification resets the failure count. Central connections are capped at
//! seven peers.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -56,10 +60,9 @@ pub const COLUMBA_RX_UUID: Uuid = Uuid::from_u128(0x37145b00_442d_4a94_917f_8f42
pub const COLUMBA_ID_UUID: Uuid = Uuid::from_u128(0x37145b00_442d_4a94_917f_8f42c5da28e6);
pub const MAX_PEERS: usize = 7;
/// Upper bound on a fragment set's `total`. A Reticulum packet is <=500 bytes,
/// so even at a pathologically small ATT MTU the count stays well under this;
/// the cap stops an unauthenticated writer from sizing a reassembly buffer off
/// an attacker-controlled 16-bit field (multi-MB allocation per START frame).
/// Maximum accepted fragment count in a received header. This bounds the
/// number of reassembly slots allocated from `total`; it does not independently
/// bound the size of each fragment or total buffered bytes.
pub const MAX_FRAGMENTS: u16 = 64;
pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
pub const KEEPALIVE_MAX_MISSES: u32 = 3;
@@ -68,13 +71,11 @@ pub const MIN_RSSI: i16 = -85;
pub const SCAN_ACTIVE_INTERVAL: Duration = Duration::from_secs(5);
pub const SCAN_IDLE_INTERVAL: Duration = Duration::from_secs(30);
pub const BLE_FRAGMENT_PACING: Duration = Duration::from_millis(8);
/// Upper bound on a single btleplug fragment write; a wedged BlueZ/WinRT stack
/// would otherwise hang the per-peer write loop (and everything queued behind
/// it) forever. Generous — a healthy write completes in milliseconds.
/// Timeout applied while awaiting a single btleplug fragment write. A timeout
/// lets the per-peer writer stop waiting for that operation.
pub const PEER_WRITE_TIMEOUT: Duration = Duration::from_secs(5);
/// Recently-disconnected peers stay "wanted" — scan loop uses the active
/// interval for them until they reconnect or the entry expires.
/// Failure or short-session count that triggers reconnect backoff.
pub const RECONNECT_BACKOFF_FAILURES: u32 = 3;
pub const RECONNECT_BACKOFF_DURATION: Duration = Duration::from_secs(300);
pub const RECONNECT_PRUNE_AFTER: Duration = Duration::from_secs(600);
@@ -106,8 +107,7 @@ pub fn seed_recently_disconnected(map: &RecentlyDisconnected, addresses: Vec<Str
}
}
/// All-zero is the sentinel ("no identity yet") and must never reach
/// advertising.
/// Return whether the input contains exactly 16 bytes and is not all zero.
pub fn is_valid_identity_hash(bytes: &[u8]) -> bool {
bytes.len() == 16 && bytes.iter().any(|b| *b != 0)
}
@@ -116,8 +116,8 @@ pub fn is_valid_identity_hash(bytes: &[u8]) -> bool {
/// that legitimate retransmits eventually reach the original sender.
pub const ANTI_LOOP_TTL: Duration = Duration::from_secs(30);
/// `payload_hash → (sources, first_seen)`. Lets the fan-out skip echoing
/// a packet back to the peers it arrived from.
/// `payload_hash → (sources, last_seen)`. Records allow fan-out to skip peers
/// that recently supplied the same packet.
pub type AntiLoopMap =
Arc<std::sync::Mutex<HashMap<u64, (std::collections::HashSet<String>, Instant)>>>;
@@ -172,7 +172,8 @@ pub fn anti_loop_record(map: &AntiLoopMap, source: String, payload: &[u8]) {
}
}
/// false iff `dest` is one of the peers `payload` arrived from.
/// Return false when an unexpired cache entry for the payload hash includes
/// `dest`. Missing entries and a poisoned cache lock allow sending.
pub fn anti_loop_should_send(map: &AntiLoopMap, dest: &str, payload: &[u8]) -> bool {
let h = payload_hash(payload);
if let Ok(g) = map.lock()
@@ -391,7 +392,7 @@ fn has_wanted_reconnects(map: &RecentlyDisconnected) -> bool {
}
}
/// Already-connected peers stay alive via keepalive.
/// Interval used for background scans with `mobile-throttle`.
pub const SCAN_BACKGROUND_INTERVAL: Duration = Duration::from_secs(60);
const SCAN_SLEEP_SLICE: Duration = Duration::from_secs(2);
@@ -427,7 +428,7 @@ async fn scan_sleep(
}
}
/// BLE 5.0 max.
/// Requested ATT MTU. The platform may negotiate a smaller value.
pub const TARGET_MTU: u16 = 517;
#[repr(u8)]
@@ -453,9 +454,10 @@ impl FragmentType {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BlePeer {
/// 16-byte hex Reticulum identity hash.
/// Legacy identity field, empty in scan results. Live identity resolution is
/// reported by [`BlePeerEvent::IdentityResolved`] as an LXMF delivery address.
pub identity_hash: String,
/// May rotate on Android.
/// Platform scan address or identifier; it may change across rediscovery.
pub ble_address: String,
pub rssi: i16,
pub protocol: PeerProtocol,
@@ -669,9 +671,8 @@ async fn stop_central_connections() {
disconnect_central_peripherals().await;
}
/// Force-disconnect a single central-role mesh peer by BLE address on every
/// platform (previously only Android). The per-peer read loop then runs its
/// own disconnect cleanup / reconnect bookkeeping.
/// Request disconnection of one central-role mesh peer through the platform
/// backend. Subsequent cleanup and reconnect bookkeeping are backend-specific.
pub async fn disconnect_mesh_peer(address: &str) {
#[cfg(target_os = "android")]
{
@@ -989,14 +990,10 @@ fn recent_ratspeak_prune() {
/// Scan for BLE mesh peers advertising Ratspeak or Columba.
///
/// Creates a fresh btleplug adapter, so use this only for scan-only callers.
/// On non-Apple platforms, scan-then-connect flows must use
/// `scan_mesh_peers_shared` with the same adapter they later pass to
/// `connect_mesh_peer`; btleplug adapter instances do not share peripheral
/// registries.
///
/// Safe entry point for one-off scan-only callers and the Apple branch
/// (which uses the native CoreBluetooth path).
/// On non-Apple platforms this creates a btleplug adapter for a one-off scan.
/// Scan-then-connect callers should use `scan_mesh_peers_shared` and pass the
/// same adapter to `connect_mesh_peer`. Apple uses the native CoreBluetooth
/// scan path.
pub async fn scan_mesh_peers(timeout_secs: u64) -> Result<Vec<BlePeer>, String> {
#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))]
{
@@ -5188,7 +5185,7 @@ fn central_writer_key(address: &str) -> String {
))]
struct PeerReadLoopCtx {
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
peer_online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
peer_writers: PeerWriterRegistry,
@@ -5457,13 +5454,12 @@ async fn peer_write_loop(
// Spawn
// ---------------------------------------------------------------------------
/// Spawn a BLE Peer-to-Peer mesh interface.
///
/// Starts both Central (scanning + GATT client) and Peripheral (advertising +
/// GATT server) roles simultaneously. Discovered peers are connected,
/// identities exchanged, and raw Reticulum packets flow bidirectionally
/// through the interface — enabling announces, LXMF messages, and all
/// protocol traffic over BLE. Compatible with Columba (Torlando) BLE mesh.
/// Spawn a BLE peer interface with central scanning and GATT client support.
/// Peripheral advertising and GATT server startup are also attempted; if that
/// role is unavailable, the central role continues. The interface supports
/// Ratspeak and Columba service UUIDs and the fragment format described in
/// this module. Verified direct LXMF delivery announces supply peer identity
/// observations; advertisements alone do not establish identity.
pub async fn spawn_ble_peer_interface(
config: BlePeerConfig,
id: InterfaceId,
@@ -5472,6 +5468,8 @@ pub async fn spawn_ble_peer_interface(
foreground_wake: Arc<tokio::sync::Notify>,
seed_addresses: Vec<String>,
) -> Result<InterfaceHandle, InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let name = config.name.clone();
// Reset the process-wide running flag and advance the session generation
@@ -6843,6 +6841,8 @@ pub async fn spawn_ble_peer_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 500, false),
parent_id: None,
name,
mode: config.mode,
@@ -6869,6 +6869,17 @@ pub async fn spawn_ble_peer_interface(
#[cfg(test)]
mod tests {
/// `Instant::now() - age`, or return from the test when the monotonic clock is
/// younger than `age`: Windows counts from boot, so fresh CI runners can't.
macro_rules! ago_or_skip {
($age:expr) => {
match std::time::Instant::now().checked_sub($age) {
Some(instant) => instant,
None => return,
}
};
}
#[test]
fn remembered_candidates_obey_discovery_expiry_capacity_and_backoff() {
let recent = new_recently_disconnected();
@@ -6896,7 +6907,7 @@ mod tests {
recent.lock().unwrap().insert(
address.into(),
(
Instant::now() - RECONNECT_BACKOFF_DURATION,
ago_or_skip!(RECONNECT_BACKOFF_DURATION),
RECONNECT_BACKOFF_FAILURES,
),
);
@@ -6904,7 +6915,7 @@ mod tests {
recent
.lock()
.unwrap()
.insert(address.into(), (Instant::now() - RECONNECT_PRUNE_AFTER, 0));
.insert(address.into(), (ago_or_skip!(RECONNECT_PRUNE_AFTER), 0));
assert!(remembered_peer_candidate(&[], &connected, &recent).is_none());
}
+13 -27
View File
@@ -1,23 +1,11 @@
//! BLE peripheral lifecycle state machine. Platform adapters (Apple
//! `CBPeripheralManager`, Linux `bluer`, Android `BluetoothGattServer`,
//! Windows `GattServiceProvider`) drive it via [`PeripheralLifecycle::apply`].
//! BLE peripheral lifecycle state machine. Adapters report platform events
//! through [`PeripheralLifecycle::apply`] and perform side effects after the
//! transition returns.
//!
//! Two invariants this encodes that are easy to violate by hand:
//!
//! 1. **Teardown waits for platform confirmation.** iOS has no
//! `peripheralManagerDidStopAdvertising:` callback; the only reliable
//! "stopped" signal is polling `CBPeripheralManager.isAdvertising` until
//! `NO`. Calling `removeAllServices` while still advertising leaves
//! CoreBluetooth in a dirty state that breaks subsequent enables.
//!
//! 2. **Mid-session platform transitions rewind.** A `Resetting` →
//! `PoweredOff` → `PoweredOn` cycle (user toggling Bluetooth, OS stack
//! crash recovery) must drop back to `StartingWaitingPlatform` so the
//! next `PlatformReady` re-registers.
//!
//! Invalid transitions return an error; adapters log and continue rather
//! than panic — BLE backends occasionally deliver out-of-order or redundant
//! callbacks.
//! Teardown waits for advertising to stop before service removal. Starting
//! and advertising states rewind to `StartingWaitingPlatform` after
//! `PlatformUnavailable`; stopping states are not rewound. Invalid transitions
//! return an error rather than changing state.
use std::sync::{Mutex, MutexGuard, PoisonError};
@@ -45,7 +33,8 @@ pub enum PeripheralState {
}
impl PeripheralState {
/// True when the peripheral holds platform resources needing release on teardown.
/// True in starting, advertising, or stopping states. This classifies
/// lifecycle state; it does not inspect platform resource ownership.
pub fn is_active(self) -> bool {
!matches!(self, Self::Idle | Self::Stopped | Self::Failed)
}
@@ -72,19 +61,16 @@ pub enum LifecycleEvent {
StartRequested,
/// Platform ready for service registration + advertising.
PlatformReady,
/// Platform blocked (BT off, permission denied, adapter resetting).
/// Rewinds active states to `StartingWaitingPlatform` to preserve user
/// intent across recovery.
/// The platform became unavailable. Starting and advertising states rewind
/// to `StartingWaitingPlatform`; stopping states reject this event.
PlatformUnavailable {
reason: String,
},
ServicesAdded,
AdvertiseStarted,
StopRequested,
/// `stopAdvertising` completed. On iOS this comes from polling
/// `isAdvertising` since no delegate callback exists. Skipping this and
/// going straight to `removeAllServices` was the root cause of the
/// "disable doesn't fully tear down" bug.
/// `stopAdvertising` completed. The Apple adapter reports this after
/// checking `isAdvertising`; service removal follows this transition.
AdvertiseStopped,
ServicesRemoved,
FatalError {
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -1,5 +1,6 @@
//! HDLC-like framing shared by TCP, Serial, I2P, Local, Pipe, Backbone.
//! Wire: `[FLAG][escaped_payload][FLAG]`. Encode ESC before FLAG; decode FLAG before ESC.
//! HDLC-like framing shared by TCP, Serial, I2P, Local, Pipe, and Backbone.
//! Wire: `[FLAG][escaped_payload][FLAG]`. Payload FLAG and ESC bytes are
//! prefixed with ESC and XORed with [`ESC_MASK`].
/// HDLC frame delimiter.
pub const FLAG: u8 = 0x7E;
@@ -17,7 +18,8 @@ const MAX_FRAME_SIZE: usize = 524288;
/// with headroom; larger frames grow the Vec normally.
const DEFRAME_BUF_CAPACITY: usize = 2048;
/// Append the escape-encoded form of `data` to `out`. No allocation if `out` has capacity.
/// Append the escape-encoded form of `data` to `out`. No allocation is needed
/// when `out` has enough spare capacity for the escaped output.
pub fn escape_into(data: &[u8], out: &mut Vec<u8>) {
let mut i = 0;
while i < data.len() {
+378 -62
View File
@@ -2,17 +2,20 @@
//! Handshake: HELLO → SESSION CREATE → STREAM CONNECT/ACCEPT;
//! stream then carries HDLC-framed packets.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use bytes::Bytes;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use rns_crypto::zeroize::Zeroizing;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
@@ -36,6 +39,12 @@ pub const RECONNECT_WAIT_MAX: u64 = 300;
pub const SAM_VERSION: &str = "3.1";
/// The longest SAM reply line read: the line limit of Python's asyncio SAM
/// client, far past a SESSION STATUS that carries a private key.
const SAM_REPLY_MAX_BYTES: usize = 64 * 1024;
/// An I2P key file holds one base64 SAM private key of a few kilobytes.
const I2P_KEY_FILE_MAX_BYTES: usize = 16 * 1024;
#[derive(Debug, thiserror::Error)]
pub enum SamError {
#[error("SAM I/O error: {0}")]
@@ -78,23 +87,81 @@ pub fn sam_reply_has_token(pairs: &[(String, String)], token: &str) -> bool {
pairs.iter().any(|(k, v)| k == token && v.is_empty())
}
async fn read_sam_reply(
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
) -> Result<String, SamError> {
let mut line = String::new();
let n = reader.read_line(&mut line).await?;
if n == 0 {
return Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"SAM connection closed during handshake",
)));
}
Ok(line.trim_end().to_string())
/// The value of `key` in a reply, borrowed from it.
fn reply_value<'a>(reply: &'a str, key: &str) -> Option<&'a str> {
reply
.split_whitespace()
.find_map(|token| token.strip_prefix(key)?.strip_prefix('='))
}
async fn sam_hello(
/// Whether a reply holds `token` with no value.
fn reply_has_token(reply: &str, token: &str) -> bool {
reply
.split_whitespace()
.any(|word| word == token || word.strip_suffix('=') == Some(token))
}
/// A reply for an error message, with any private key left out.
fn without_destination(reply: &str) -> String {
reply
.split_whitespace()
.map(|token| {
if token.starts_with("DESTINATION=") {
"DESTINATION=<redacted>"
} else {
token
}
})
.collect::<Vec<_>>()
.join(" ")
}
/// Read one reply line into a buffer reserved once and wiped on drop, since a
/// SESSION STATUS reply carries the session's private key. Bytes are read one
/// at a time, so nothing past the line is consumed.
async fn read_sam_reply<R: AsyncRead + Unpin>(
reader: &mut R,
) -> Result<Zeroizing<String>, SamError> {
let mut line = Zeroizing::new(Vec::with_capacity(SAM_REPLY_MAX_BYTES));
loop {
match reader.read_u8().await {
Ok(b'\n') => break,
Ok(_) if line.len() == SAM_REPLY_MAX_BYTES => {
return Err(SamError::UnexpectedReply(format!(
"reply longer than {SAM_REPLY_MAX_BYTES} bytes"
)));
}
Ok(byte) => line.push(byte),
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof && !line.is_empty() => break,
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
return Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"SAM connection closed during handshake",
)));
}
Err(e) => return Err(e.into()),
}
}
let end = line
.iter()
.rposition(|byte| !byte.is_ascii_whitespace())
.map_or(0, |last| last + 1);
line.truncate(end);
match String::from_utf8(std::mem::take(&mut *line)) {
Ok(text) => Ok(Zeroizing::new(text)),
Err(error) => {
drop(Zeroizing::new(error.into_bytes()));
Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"SAM reply is not UTF-8",
)))
}
}
}
async fn sam_hello<R: AsyncRead + Unpin>(
writer: &mut tokio::net::tcp::OwnedWriteHalf,
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
reader: &mut R,
) -> Result<(), SamError> {
let hello_msg = format!("HELLO VERSION MIN={} MAX={}\n", SAM_VERSION, SAM_VERSION);
writer.write_all(hello_msg.as_bytes()).await?;
@@ -106,7 +173,7 @@ async fn sam_hello(
if !sam_reply_has_token(&pairs, "HELLO") || !sam_reply_has_token(&pairs, "REPLY") {
return Err(SamError::HandshakeFailed(format!(
"expected HELLO REPLY, got: {}",
reply
reply.as_str()
)));
}
@@ -118,43 +185,58 @@ async fn sam_hello(
))),
None => Err(SamError::HandshakeFailed(format!(
"no RESULT in HELLO reply: {}",
reply
reply.as_str()
))),
}
}
/// Returns the destination (base64). `private_key=None` = transient.
async fn sam_session_create(
/// Returns the session's private key (base64), wiped on drop.
/// `private_key=None` = transient.
async fn sam_session_create<R: AsyncRead + Unpin>(
writer: &mut tokio::net::tcp::OwnedWriteHalf,
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
reader: &mut R,
session_id: &str,
private_key: Option<&str>,
) -> Result<String, SamError> {
let dest_param = match private_key {
Some(key) => key.to_string(),
None => "TRANSIENT".to_string(),
transient_signature_type: Option<u8>,
) -> Result<Zeroizing<String>, SamError> {
let transient;
let destination = match (private_key, transient_signature_type) {
(Some(key), _) => key,
(None, Some(signature_type)) => {
transient = format!("TRANSIENT SIGNATURE_TYPE={signature_type}");
&transient
}
(None, None) => "TRANSIENT",
};
let create_msg = format!(
"SESSION CREATE STYLE=STREAM ID={} DESTINATION={}\n",
session_id, dest_param
);
// Sized up front: the command carries the private key.
let mut create_msg = Zeroizing::new(String::with_capacity(
64 + session_id.len() + destination.len(),
));
for part in [
"SESSION CREATE STYLE=STREAM ID=",
session_id,
" DESTINATION=",
destination,
"\n",
] {
create_msg.push_str(part);
}
writer.write_all(create_msg.as_bytes()).await?;
writer.flush().await?;
let reply = read_sam_reply(reader).await?;
let pairs = parse_sam_reply(&reply);
if !sam_reply_has_token(&pairs, "SESSION") || !sam_reply_has_token(&pairs, "STATUS") {
if !reply_has_token(&reply, "SESSION") || !reply_has_token(&reply, "STATUS") {
return Err(SamError::SessionFailed(format!(
"expected SESSION STATUS, got: {}",
reply
without_destination(&reply)
)));
}
match sam_reply_get(&pairs, "RESULT") {
match reply_value(&reply, "RESULT") {
Some("OK") => {}
Some(other) => {
let msg_detail = sam_reply_get(&pairs, "MESSAGE").unwrap_or("no details");
let msg_detail = reply_value(&reply, "MESSAGE").unwrap_or("no details");
return Err(SamError::SessionFailed(format!(
"SESSION RESULT={}: {}",
other, msg_detail
@@ -163,13 +245,13 @@ async fn sam_session_create(
None => {
return Err(SamError::SessionFailed(format!(
"no RESULT in SESSION STATUS: {}",
reply
without_destination(&reply)
)));
}
}
match sam_reply_get(&pairs, "DESTINATION") {
Some(dest) => Ok(dest.to_string()),
match reply_value(&reply, "DESTINATION") {
Some(dest) => Ok(Zeroizing::new(dest.to_string())),
None => Err(SamError::SessionFailed(
"SESSION STATUS OK but no DESTINATION returned".to_string(),
)),
@@ -197,7 +279,7 @@ async fn sam_stream_connect(
if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") {
return Err(SamError::StreamFailed(format!(
"expected STREAM STATUS, got: {}",
reply
reply.as_str()
)));
}
@@ -212,7 +294,7 @@ async fn sam_stream_connect(
}
None => Err(SamError::StreamFailed(format!(
"no RESULT in STREAM STATUS: {}",
reply
reply.as_str()
))),
}
}
@@ -234,7 +316,7 @@ async fn sam_stream_accept(
if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") {
return Err(SamError::AcceptFailed(format!(
"expected STREAM STATUS, got: {}",
reply
reply.as_str()
)));
}
@@ -250,7 +332,7 @@ async fn sam_stream_accept(
None => {
return Err(SamError::AcceptFailed(format!(
"no RESULT in STREAM STATUS: {}",
reply
reply.as_str()
)));
}
}
@@ -282,15 +364,40 @@ fn generate_session_id() -> String {
format!("reticulum_{:016x}", id)
}
#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct I2PServerConfig {
pub name: String,
pub sam_host: String,
pub sam_port: u16,
/// Base64 private key for a persistent destination; `None` = transient.
/// Base64 private key for the server's destination, used before `key_path`.
pub keyfile: Option<String>,
/// Optional path for the server destination's private key, used when
/// `keyfile` is absent. A missing or empty file is populated after session
/// creation. Read failures leave the file untouched and use a transient
/// destination; write failures can likewise change the next session's address.
pub key_path: Option<std::path::PathBuf>,
pub reconnect_delay: u64,
pub mode: InterfaceMode,
/// Receives the server's b32 address (Python `I2PInterface.b32`) whenever
/// SAM creates its session.
pub b32: Option<tokio::sync::watch::Sender<Option<String>>>,
}
// The key is the destination's secret; debug output names only its presence.
impl std::fmt::Debug for I2PServerConfig {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("I2PServerConfig")
.field("name", &self.name)
.field("sam_host", &self.sam_host)
.field("sam_port", &self.sam_port)
.field("keyfile", &self.keyfile.as_ref().map(|_| "<redacted>"))
.field("key_path", &self.key_path)
.field("reconnect_delay", &self.reconnect_delay)
.field("mode", &self.mode)
.field("b32", &self.b32)
.finish()
}
}
impl I2PServerConfig {
@@ -300,23 +407,115 @@ impl I2PServerConfig {
sam_host: DEFAULT_SAM_ADDRESS.to_string(),
sam_port: DEFAULT_SAM_PORT,
keyfile: None,
key_path: None,
reconnect_delay: RECONNECT_WAIT,
mode: InterfaceMode::Full,
b32: None,
}
}
}
/// i2plib's signature type for new destinations, EdDSA-SHA512-Ed25519
/// (RNS/vendor/i2plib/sam.py:91-93).
const NEW_DESTINATION_SIGNATURE_TYPE: u8 = 7;
/// The stored key, `None` when there is none yet, read into buffers that are
/// wiped on drop. A file that cannot be read is an error, so it is never
/// replaced.
fn read_private_key(path: &std::path::Path) -> std::io::Result<Option<Zeroizing<String>>> {
let data = match rns_identity::persistence::read_secret_file(path, I2P_KEY_FILE_MAX_BYTES) {
Ok(data) => data,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let key = std::str::from_utf8(&data)
.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidData, "I2P key file is not UTF-8")
})?
.trim();
Ok((!key.is_empty()).then(|| Zeroizing::new(key.to_string())))
}
/// Keep a session's private key readable by its owner only, replaced
/// atomically, as the other private keys are.
fn store_private_key(path: &std::path::Path, key: &str) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
rns_identity::persistence::atomic_write(path, key.as_bytes())
}
/// The b32 address of the destination in a SAM private key: the hash of its
/// first 387 bytes plus its certificate (i2plib `Destination.base32`,
/// RNS/vendor/i2plib/sam.py:113-129).
pub fn destination_b32(private_key: &str) -> Option<String> {
let key = i2p_base64_decode(private_key)?;
let certificate = usize::from(u16::from_be_bytes(key.get(385..387)?.try_into().ok()?));
let hash = rns_crypto::sha::sha256(key.get(..387 + certificate)?);
Some(base32_lowercase(&hash))
}
/// Base64 with I2P's `-~` alphabet (i2plib `i2p_b64decode`), into a buffer
/// sized up front and wiped on drop: the input is usually a private key.
fn i2p_base64_decode(text: &str) -> Option<Zeroizing<Vec<u8>>> {
let mut bytes = Zeroizing::new(Vec::with_capacity(text.len() * 3 / 4));
let (mut buffer, mut bits) = (0u32, 0u32);
for c in text.trim_end_matches('=').bytes() {
let value = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'-' => 62,
b'~' => 63,
_ => return None,
};
buffer = buffer << 6 | u32::from(value);
bits += 6;
if bits >= 8 {
bits -= 8;
bytes.push((buffer >> bits) as u8);
buffer &= (1 << bits) - 1;
}
}
Some(bytes)
}
/// RFC 4648 base32, lowercase and unpadded.
fn base32_lowercase(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
let mut text = String::with_capacity(bytes.len().div_ceil(5) * 8);
let (mut buffer, mut bits) = (0u32, 0u32);
for byte in bytes {
buffer = buffer << 8 | u32::from(*byte);
bits += 8;
while bits >= 5 {
bits -= 5;
text.push(char::from(ALPHABET[(buffer >> bits) as usize & 31]));
}
buffer &= (1 << bits) - 1;
}
if bits > 0 {
text.push(char::from(ALPHABET[(buffer << (5 - bits)) as usize & 31]));
}
text
}
#[derive(Debug, Clone)]
pub struct I2PClientConfig {
pub name: String,
pub sam_host: String,
pub sam_port: u16,
/// Peer I2P destination (base64).
/// Peer destination passed verbatim as SAM STREAM CONNECT's `DESTINATION`
/// value. This library does not perform a separate name lookup.
pub peer_destination: String,
/// Reconnect attempt cap; `None` = unlimited.
/// Consecutive failure cap, including the initial connection attempt. A
/// successful connection resets the count. `None` means unlimited retries.
pub max_reconnect_tries: Option<usize>,
pub reconnect_delay: u64,
pub mode: InterfaceMode,
/// Identity used to request a signed tunnel synthesis for each connection.
/// `None`, or an identity without signing material, sends no synthesis.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl I2PClientConfig {
@@ -329,8 +528,14 @@ impl I2PClientConfig {
max_reconnect_tries: None,
reconnect_delay: RECONNECT_WAIT,
mode: InterfaceMode::Full,
tunnel_identity: None,
}
}
/// Python `str(I2PInterfacePeer)` (I2PInterface.py:714-715).
pub fn python_name(&self) -> String {
format!("I2PInterfacePeer[{}]", self.name)
}
}
/// Connect via SAM streaming session, run HDLC-framed I/O; exponential reconnect.
@@ -339,6 +544,8 @@ pub async fn spawn_i2p_client(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(false));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
@@ -353,10 +560,14 @@ pub async fn spawn_i2p_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let mut pacer = ReconnectPacer::new(config.reconnect_delay, config.max_reconnect_tries);
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
loop {
let after_outage = std::mem::replace(&mut attempted, true);
let session_id = generate_session_id();
let session_stream = match connect_to_sam(&config.sam_host, config.sam_port).await {
@@ -379,10 +590,10 @@ pub async fn spawn_i2p_client(
}
};
let (session_reader, mut session_writer) = session_stream.into_split();
let mut session_buf_reader = BufReader::new(session_reader);
// Read unbuffered: a read buffer would keep SAM's reply, private key included.
let (mut session_reader, mut session_writer) = session_stream.into_split();
if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await {
if let Err(e) = sam_hello(&mut session_writer, &mut session_reader).await {
tracing::warn!(
name = %config.name,
error = %e,
@@ -401,9 +612,10 @@ pub async fn spawn_i2p_client(
let _our_dest = match sam_session_create(
&mut session_writer,
&mut session_buf_reader,
&mut session_reader,
&session_id,
None,
None,
)
.await
{
@@ -505,8 +717,14 @@ pub async fn spawn_i2p_client(
"I2P client: stream connected"
);
online_task.store(true, Ordering::SeqCst);
pacer.reset();
// Python synthesizes on every connection (I2PInterface.py:503,
// :533).
let synthesis = config
.tunnel_identity
.as_ref()
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(&rx, after_outage, &transport_tx, synthesis, &online_task).await;
// BufReader may have prefetched past the handshake; flush its tail first.
let buffered = stream_buf_reader.buffer().to_vec();
@@ -569,6 +787,8 @@ pub async fn spawn_i2p_client(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -589,14 +809,18 @@ pub async fn spawn_i2p_client(
})
}
/// Accept SAM streams; each becomes a sub-interface via `handle_tx`. Session
/// is recreated if the control socket drops.
/// Accept SAM streams; each becomes a sub-interface via `handle_tx`.
/// The session is recreated after an accept-connection or SAM handshake
/// failure. The session control socket is not monitored independently.
pub async fn spawn_i2p_server(
config: I2PServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(false));
let name = config.name.clone();
let mode = config.mode;
@@ -624,21 +848,40 @@ pub async fn spawn_i2p_server(
}
};
let (session_reader, mut session_writer) = session_stream.into_split();
let mut session_buf_reader = BufReader::new(session_reader);
// Read unbuffered: a read buffer would keep SAM's reply, private key included.
let (mut session_reader, mut session_writer) = session_stream.into_split();
if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await {
if let Err(e) = sam_hello(&mut session_writer, &mut session_reader).await {
tracing::warn!(name = %config.name, error = %e, "I2P server: SAM HELLO failed");
tokio::time::sleep(std::time::Duration::from_secs(config.reconnect_delay)).await;
continue;
}
let private_key = config.keyfile.as_deref();
let (private_key, store_key) = match (&config.keyfile, config.key_path.as_deref()) {
(Some(key), _) => (Some(Zeroizing::new(key.clone())), false),
(None, None) => (None, false),
(None, Some(path)) => match read_private_key(path) {
Ok(key) => {
let missing = key.is_none();
(key, missing)
}
Err(error) => {
tracing::warn!(
name = %config.name,
path = %path.display(),
%error,
"I2P server: cannot read its private key; this session's address is transient"
);
(None, false)
}
},
};
let our_dest = match sam_session_create(
&mut session_writer,
&mut session_buf_reader,
&mut session_reader,
&session_id,
private_key,
private_key.as_deref().map(String::as_str),
Some(NEW_DESTINATION_SIGNATURE_TYPE),
)
.await
{
@@ -661,6 +904,20 @@ pub async fn spawn_i2p_server(
dest_len = our_dest.len(),
"I2P server: session created, accepting streams"
);
if store_key
&& let Some(path) = config.key_path.as_deref()
&& let Err(error) = store_private_key(path, &our_dest)
{
tracing::warn!(
name = %config.name,
path = %path.display(),
%error,
"I2P server: failed to store its private key; its address changes with the next session"
);
}
if let Some(b32) = &config.b32 {
b32.send_replace(destination_b32(&our_dest));
}
online_task.store(true, Ordering::SeqCst);
// Each STREAM ACCEPT needs its own SAM TCP connection.
@@ -747,7 +1004,9 @@ pub async fn spawn_i2p_server(
let c_online_r = c_online.clone();
let c_rxb_r = c_rxb.clone();
let transport_tx2 = transport_tx.clone();
let transport_tx2 =
InterfaceTransportSender::new(client_id, transport_tx.actor_sender());
let child_owner = transport_tx2.owner();
let peer_name = client_name.clone();
let c_read_task = tokio::spawn(async move {
i2p_read_loop(
@@ -764,7 +1023,9 @@ pub async fn spawn_i2p_server(
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
owner: child_owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: Some(id),
name: client_name,
mode: config.mode,
direction: InterfaceDirection {
@@ -804,7 +1065,9 @@ pub async fn spawn_i2p_server(
});
Ok(InterfaceHandle {
id: 0,
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -833,7 +1096,7 @@ async fn i2p_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
initial_data: &[u8],
interface_id: InterfaceId,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &InterfaceTransportSender,
online: &AtomicBool,
rxb: &AtomicU64,
) {
@@ -948,6 +1211,16 @@ impl ReconnectPacer {
mod tests {
use super::*;
#[test]
fn peer_python_name_matches_python() {
// Python 1.5.5 `str()` output for this interface.
let peer = "abcdefghijklmnop.b32.i2p";
assert_eq!(
I2PClientConfig::new(&format!("Golden I2P to {peer}"), peer).python_name(),
"I2PInterfacePeer[Golden I2P to abcdefghijklmnop.b32.i2p]"
);
}
#[test]
fn test_i2p_client_config() {
let cfg = I2PClientConfig::new("i2p0", "ABCDEF1234.b32.i2p");
@@ -1056,6 +1329,49 @@ mod tests {
assert!(!sam_reply_has_token(&pairs, "NONEXISTENT"));
}
fn i2p_base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~";
let mut text = String::new();
for chunk in bytes.chunks(3) {
let bits = chunk.iter().enumerate().fold(0u32, |bits, (n, byte)| {
bits | u32::from(*byte) << (16 - 8 * n)
});
for n in 0..=chunk.len() {
text.push(char::from(ALPHABET[(bits >> (18 - 6 * n)) as usize & 63]));
}
text.extend(std::iter::repeat_n('=', 3 - chunk.len()));
}
text
}
fn private_key(certificate: &[u8], secret: u8) -> Vec<u8> {
let mut key: Vec<u8> = (0..384).map(|n| n as u8).collect();
key.extend_from_slice(certificate);
key.extend(std::iter::repeat_n(secret, 288));
key
}
/// Only the destination, keys plus certificate, names the address
/// (i2plib sam.py:113-129); the golden is checked against i2plib in tests.
#[test]
fn the_b32_address_hashes_only_the_destination() {
let ed25519 = [5, 0, 4, 0, 7, 0, 0];
let b32 = destination_b32(&i2p_base64(&private_key(&ed25519, 0x42))).unwrap();
assert_eq!(b32.len(), 52);
assert!(b32.bytes().all(|c| matches!(c, b'a'..=b'z' | b'2'..=b'7')));
assert_eq!(
destination_b32(&i2p_base64(&private_key(&ed25519, 0x24))).as_ref(),
Some(&b32)
);
assert_ne!(
destination_b32(&i2p_base64(&private_key(&[0, 0, 0], 0x42))).as_ref(),
Some(&b32)
);
assert_eq!(destination_b32("not+base64"), None);
assert_eq!(destination_b32(&i2p_base64(&[0; 300])), None);
}
#[test]
fn test_generate_session_id() {
let id1 = generate_session_id();
+29 -9
View File
@@ -1,4 +1,4 @@
//! KISS TNC framing — used by KISS, AX.25-KISS, RNode, RNodeMulti, TCP/I2P.
//! KISS TNC framing for KISS, AX.25-KISS, RNode, RNodeMulti, and optionally TCP.
//! Wire: `[FEND][CMD][escaped_payload][FEND]`.
pub const FEND: u8 = 0xC0;
@@ -164,7 +164,7 @@ impl Default for KissDeframer {
pub struct RawKissDeframer {
buffer: Vec<u8>,
in_frame: bool,
command: u8,
command: Option<u8>,
/// Reusable scratch for unescape output.
unescape_scratch: Vec<u8>,
}
@@ -174,7 +174,7 @@ impl RawKissDeframer {
Self {
buffer: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
in_frame: false,
command: CMD_UNKNOWN,
command: None,
unescape_scratch: Vec::with_capacity(DEFRAME_BUF_CAPACITY),
}
}
@@ -196,12 +196,14 @@ impl RawKissDeframer {
&mut self.unescape_scratch,
Vec::with_capacity(DEFRAME_BUF_CAPACITY),
);
frames.push((self.command, frame_data));
if let Some(command) = self.command {
frames.push((command, frame_data));
}
}
self.buffer.clear();
}
self.in_frame = true;
self.command = CMD_UNKNOWN;
self.command = None;
i = hit + 1;
}
None => {
@@ -221,9 +223,9 @@ impl RawKissDeframer {
/// for the next FEND to resync — matching the previous byte-loop.
fn append_in_frame(&mut self, chunk: &[u8]) {
let mut chunk = chunk;
if self.command == CMD_UNKNOWN {
if self.command.is_none() {
if let Some((&first, rest)) = chunk.split_first() {
self.command = first;
self.command = Some(first);
chunk = rest;
} else {
return;
@@ -232,7 +234,7 @@ impl RawKissDeframer {
if self.buffer.len() + chunk.len() > MAX_FRAME_SIZE {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
self.command = None;
return;
}
self.buffer.extend_from_slice(chunk);
@@ -241,7 +243,7 @@ impl RawKissDeframer {
pub fn reset(&mut self) {
self.buffer.clear();
self.in_frame = false;
self.command = CMD_UNKNOWN;
self.command = None;
}
}
@@ -326,6 +328,24 @@ mod tests {
assert_eq!(frames[0].0, CMD_DATA);
}
#[test]
fn extended_fe_command_survives_every_chunk_boundary() {
let expected = vec![(0xfe, vec![1, FEND, FESC, 2])];
let frame = frame_with_command(0xfe, &expected[0].1);
for split in 0..=frame.len() {
let mut decoder = RawKissDeframer::new();
let mut got = decoder.feed(&frame[..split]);
got.extend(decoder.feed(&frame[split..]));
assert_eq!(got, expected, "split {split}");
}
let mut decoder = RawKissDeframer::new();
let got: Vec<_> = frame
.iter()
.flat_map(|byte| decoder.feed(&[*byte]))
.collect();
assert_eq!(got, expected);
}
#[test]
fn test_raw_deframer_preserves_extended_commands() {
let mut deframer = RawKissDeframer::new();
+15 -3
View File
@@ -1,5 +1,6 @@
//! Serial port + KISS framing; CMD_DATA + CMD_READY flow control.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
@@ -28,8 +29,14 @@ pub struct KissInterfaceConfig {
pub txtail: Option<u8>,
/// Honour CMD_READY from TNC.
pub flow_control: bool,
/// Station-ID beacon: seconds between IDs, counted from the first data
/// TX after the previous beacon (Python `id_interval`/`id_callsign`).
/// Station-ID delay in seconds, armed by data transmission. Both this field
/// and `id_callsign` must be set to enable automatic beacons.
///
/// In this implementation, callsigns shorter than 15 bytes are padded for
/// transmission but compared with the unpadded value when resetting the timer.
/// After becoming due, such a beacon can repeat on each one-second idle poll,
/// subject to flow control and successful writes. Set either option to `None`
/// to disable automatic beaconing.
pub id_interval: Option<u64>,
pub id_callsign: Option<Vec<u8>>,
}
@@ -56,7 +63,7 @@ impl KissInterfaceConfig {
}
/// Beacon frame payload: callsign zero-padded to the 15-byte minimum
/// (Python KISSInterface.py:350-353).
/// (Python `KISSInterface.read_loop`).
pub fn beacon_frame_payload(id_callsign: &[u8]) -> Vec<u8> {
let mut frame = id_callsign.to_vec();
while frame.len() < 15 {
@@ -89,6 +96,8 @@ async fn spawn_kiss_with_port(
transport_tx: mpsc::Sender<TransportMessage>,
port: Box<dyn serialport::SerialPort>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
tracing::info!(
name = %config.name,
port = %config.port,
@@ -283,6 +292,8 @@ async fn spawn_kiss_with_port(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
@@ -371,6 +382,7 @@ mod tests {
let driver = spawn_kiss_with_port(config, 1, inbound, Box::new(slave))
.await
.unwrap();
driver.owner.mark_registered();
let mut revoke = kiss::frame_with_command(kiss::CMD_READY, &[0]);
revoke.extend(kiss::frame(b"read barrier"));
master.write_all(&revoke).unwrap();
+6 -4
View File
@@ -1,12 +1,14 @@
//! Network interface implementations for Reticulum.
//! Each module provides a spawn function returning a Tokio task driving a
//! concrete transport; [`traits::InterfaceHandle`] is the common handle the
//! runtime registers with the transport actor.
//! Network interface implementations and framing helpers for Reticulum.
//! Transport drivers expose [`traits::InterfaceHandle`] for registration with
//! the transport actor; helper modules provide codecs, settings, and lifecycle
//! state. Serial, BLE, and Android USB APIs have feature or platform gates.
#[cfg(target_os = "android")]
pub mod android_usb;
#[cfg(any(target_os = "android", test))]
mod android_usb_lifecycle;
#[cfg(any(target_os = "android", test))]
mod android_usb_setup;
pub mod auto;
pub mod ax25kiss;
pub mod backbone;
+216 -49
View File
@@ -1,6 +1,8 @@
//! Shared-instance IPC. Unix domain sockets where available, TCP on
//! 127.0.0.1 as fallback. HDLC-framed.
//! Shared-instance IPC with HDLC framing. Uses Unix domain sockets on Unix
//! and TCP on non-Unix platforms. TCP defaults to loopback; a `tcp://` value
//! in `socket_path` overrides that endpoint.
use rns_transport::messages::{InterfaceOwner, InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -16,10 +18,12 @@ use rns_transport::messages::{InboundPacket, TransportMessage};
pub const LOCAL_MTU: u32 = 262_144;
/// Default filesystem socket path for non-Linux fallback use.
/// Default filesystem socket path for local IPC.
pub const DEFAULT_SOCKET_PATH: &str = "/tmp/rns_reticulum.sock";
/// On Android `/tmp` isn't writable; falls back to caller's data directory.
/// Return `data_dir/cache/rns_reticulum.sock` on Android when `data_dir` is
/// provided; otherwise return [`DEFAULT_SOCKET_PATH`]. This helper creates no
/// directories and does not check whether the returned path is writable.
pub fn socket_path(data_dir: Option<&std::path::Path>) -> std::path::PathBuf {
if cfg!(target_os = "android")
&& let Some(dir) = data_dir
@@ -33,16 +37,6 @@ 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)
}
@@ -71,7 +65,8 @@ fn display_socket_path(path: &str) -> String {
#[derive(Debug, Clone)]
pub struct LocalServerConfig {
/// Unix socket path (ignored on non-Unix).
/// Unix socket path. On non-Unix platforms, a nonempty `tcp://host:port`
/// value selects the TCP endpoint; other values use the loopback default.
pub socket_path: String,
pub name: String,
}
@@ -103,7 +98,7 @@ impl Default for LocalClientConfig {
async fn local_read_loop<R: AsyncReadExt + Unpin>(
mut reader: R,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
online: Arc<AtomicBool>,
rxb: Arc<AtomicU64>,
) {
@@ -178,7 +173,7 @@ async fn run_local_client_connection<R, W>(
mut writer: W,
rx: &mut mpsc::Receiver<Bytes>,
interface_id: InterfaceId,
transport_tx: &mpsc::Sender<TransportMessage>,
transport_tx: &InterfaceTransportSender,
rxb: &AtomicU64,
txb: &AtomicU64,
) -> LocalClientConnectionEnd
@@ -253,6 +248,8 @@ where
R: AsyncReadExt + Unpin + Send + 'static,
W: AsyncWriteExt + Unpin + Send + 'static,
{
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(true));
let rxb = Arc::new(AtomicU64::new(0));
let txb = Arc::new(AtomicU64::new(0));
@@ -277,6 +274,8 @@ where
InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(262144, 262144, true),
parent_id,
name,
mode: InterfaceMode::Full,
@@ -297,16 +296,20 @@ where
}
}
/// Handle for the listener pseudo-interface (id 0): inbound-only, no
/// per-byte counters of its own.
/// Handle for the listener pseudo-interface: inbound-only, no per-byte
/// counters of its own.
fn server_listener_handle(
id: InterfaceId,
name: String,
online: Arc<AtomicBool>,
tx: mpsc::Sender<Bytes>,
read_task: tokio::task::JoinHandle<()>,
owner: InterfaceOwner,
) -> InterfaceHandle {
InterfaceHandle {
id: 0,
id,
owner,
packet_capacity: InterfacePacketCapacity::new(262144, 262144, true),
parent_id: None,
name,
mode: InterfaceMode::Full,
@@ -397,10 +400,12 @@ mod platform {
pub async fn spawn_local_server_impl(
config: LocalServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let owner = InterfaceOwner::new();
let listener = bind_unix_listener(&config.socket_path)?;
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local server listening");
@@ -421,7 +426,7 @@ mod platform {
let handle = wire_local_stream(
client_id,
client_name,
Some(0),
Some(id),
reader,
writer,
transport_tx.clone(),
@@ -444,7 +449,9 @@ mod platform {
online2.store(false, Ordering::SeqCst);
});
Ok(server_listener_handle(name, online, tx, read_task))
Ok(server_listener_handle(
id, name, online, tx, read_task, owner,
))
}
pub async fn spawn_local_client_impl(
@@ -452,6 +459,8 @@ mod platform {
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
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");
@@ -495,13 +504,16 @@ mod platform {
"local shared-instance connection lost; reconnecting"
);
loop {
tokio::time::sleep(local_reconnect_wait()).await;
tokio::time::sleep(std::time::Duration::from_secs(LOCAL_RECONNECT_WAIT_SECS))
.await;
if transport_tx.is_closed() || rx.is_closed() {
return;
}
match connect_unix_stream(&task_socket_path).await {
Ok(connected) => {
stream = connected;
// Python drops traffic while offline (LocalInterface.py:218).
while rx.try_recv().is_ok() {}
task_online.store(true, Ordering::SeqCst);
tracing::info!(
name = %task_name,
@@ -525,6 +537,8 @@ mod platform {
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(262144, 262144, true),
parent_id: None,
name: config.name,
mode: InterfaceMode::Full,
@@ -564,11 +578,13 @@ mod platform {
pub async fn spawn_local_server_impl(
config: LocalServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let addr = fallback_tcp_addr(&config.socket_path);
let owner = InterfaceOwner::new();
let listener = TcpListener::bind(&addr).await?;
let local_addr = listener.local_addr()?;
tracing::info!(name = %config.name, addr = %local_addr, "local server (TCP fallback) listening");
@@ -590,7 +606,7 @@ mod platform {
let handle = wire_local_stream(
client_id,
client_name,
Some(0),
Some(id),
reader,
writer,
transport_tx.clone(),
@@ -613,7 +629,9 @@ mod platform {
online2.store(false, Ordering::SeqCst);
});
Ok(server_listener_handle(name, online, tx, read_task))
Ok(server_listener_handle(
id, name, online, tx, read_task, owner,
))
}
pub async fn spawn_local_client_impl(
@@ -646,11 +664,12 @@ mod platform {
)]
pub async fn spawn_local_server(
config: LocalServerConfig,
id: InterfaceId,
id_gen: Arc<AtomicU64>,
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
platform::spawn_local_server_impl(config, id_gen, transport_tx, handle_tx).await
platform::spawn_local_server_impl(config, id, id_gen, transport_tx, handle_tx).await
}
#[tracing::instrument(
@@ -695,6 +714,24 @@ mod tests {
}
}
/// The client's real reconnect wait, plus one missed attempt on a loaded host.
#[cfg(unix)]
const RECONNECT_DEADLINE: std::time::Duration =
std::time::Duration::from_secs(2 * LOCAL_RECONNECT_WAIT_SECS);
/// The server hands off an accepted client before that client has
/// necessarily published itself online, so wait for the flag itself.
#[cfg(unix)]
async fn wait_until_online(online: &AtomicBool) {
tokio::time::timeout(std::time::Duration::from_secs(3), async {
while !online.load(Ordering::SeqCst) {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("stable client handle must return online after reconnect");
}
#[test]
fn test_local_mtu() {
assert_eq!(LOCAL_MTU, 262_144);
@@ -733,9 +770,12 @@ mod tests {
name: "test-local-server".to_string(),
};
let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
let server_handle =
spawn_local_server(server_cfg, 499, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
assert_eq!(server_handle.id, 499);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -747,12 +787,21 @@ mod tests {
let client_handle = spawn_local_client(client_cfg, 42, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
accepted.owner.mark_registered();
assert_ne!(accepted.owner, server_handle.owner);
assert_ne!(accepted.owner, client_handle.owner);
assert_eq!(accepted.parent_id, Some(server_handle.id));
assert_eq!(
accepted.packet_capacity,
InterfacePacketCapacity::new(262144, 262144, true)
);
let payload = Bytes::from_static(b"local ipc test");
client_handle.tx.send(payload.clone()).await.unwrap();
@@ -761,7 +810,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &accepted) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, accepted.id);
@@ -777,7 +826,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg2 {
match crate::traits::test_event_for_handle(msg2, &client_handle) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 42);
@@ -804,9 +853,11 @@ mod tests {
socket_path: socket_path.clone(),
name: "dereg-server".to_string(),
};
let server_handle = spawn_local_server(server_cfg, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
let server_handle =
spawn_local_server(server_cfg, 599, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -817,11 +868,13 @@ mod tests {
let client_handle = spawn_local_client(client_cfg, 77, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
accepted.owner.mark_registered();
let server_side_client_id = accepted.id;
// Abort client; server's per-client read_loop sees EOF and exits.
@@ -833,7 +886,9 @@ mod tests {
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv())
.await
{
.map(|message| {
message.map(|event| crate::traits::test_event_for_handle(event, &accepted))
}) {
Ok(Some(TransportMessage::DeregisterInterface { id }))
if id == server_side_client_id =>
{
@@ -869,12 +924,14 @@ mod tests {
};
let server_handle = spawn_local_server(
server_config(),
699,
id_gen.clone(),
transport_tx.clone(),
handle_tx.clone(),
)
.await
.unwrap();
server_handle.owner.mark_registered();
let client_handle = spawn_local_client(
LocalClientConfig {
socket_path: socket_path.clone(),
@@ -885,11 +942,13 @@ mod tests {
)
.await
.unwrap();
client_handle.owner.mark_registered();
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");
first_accepted.owner.mark_registered();
server_handle.read_task.abort();
first_accepted.read_task.abort();
@@ -902,19 +961,22 @@ mod tests {
.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 restarted_server = spawn_local_server(
server_config(),
699,
id_gen,
transport_tx.clone(),
handle_tx,
)
.await
.unwrap();
restarted_server.owner.mark_registered();
let second_accepted = tokio::time::timeout(RECONNECT_DEADLINE, handle_rx.recv())
.await
.expect("client did not reconnect to restarted server")
.expect("handle channel closed");
second_accepted.owner.mark_registered();
wait_until_online(&client_handle.online).await;
let payload = Bytes::from_static(b"after shared restart");
second_accepted.tx.send(payload.clone()).await.unwrap();
@@ -922,7 +984,7 @@ mod tests {
.await
.expect("timeout waiting for post-restart frame")
.expect("transport channel closed");
match inbound {
match crate::traits::test_event_for_handle(inbound, &client_handle) {
TransportMessage::Inbound(packet) => {
assert_eq!(packet.interface_id, 88);
assert_eq!(packet.raw, payload);
@@ -936,4 +998,109 @@ mod tests {
client_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
/// Python's `LocalClientInterface` drops outgoing traffic while offline
/// (LocalInterface.py:218), so nothing queued during an outage reaches
/// the restarted shared instance.
#[cfg(unix)]
#[tokio::test]
async fn test_local_client_drops_traffic_queued_while_disconnected() {
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(950));
let socket_path = unique_test_socket_path("reticulum_offline_queue_test");
let server_config = || LocalServerConfig {
socket_path: socket_path.clone(),
name: "restartable-local-server".to_string(),
};
let server_handle = spawn_local_server(
server_config(),
698,
id_gen.clone(),
transport_tx.clone(),
handle_tx.clone(),
)
.await
.unwrap();
server_handle.owner.mark_registered();
let client_handle = spawn_local_client(
LocalClientConfig {
socket_path: socket_path.clone(),
name: "offline-local-client".to_string(),
},
89,
transport_tx.clone(),
)
.await
.unwrap();
client_handle.owner.mark_registered();
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");
client_handle
.tx
.send(Bytes::from_static(b"queued while offline"))
.await
.unwrap();
let restarted_server = spawn_local_server(
server_config(),
698,
id_gen,
transport_tx.clone(),
handle_tx,
)
.await
.unwrap();
restarted_server.owner.mark_registered();
let second_accepted = tokio::time::timeout(RECONNECT_DEADLINE, handle_rx.recv())
.await
.expect("client did not reconnect to restarted server")
.expect("handle channel closed");
second_accepted.owner.mark_registered();
// Online is published only after the offline queue is dropped.
wait_until_online(&client_handle.online).await;
let after = Bytes::from_static(b"after reconnect");
client_handle.tx.send(after.clone()).await.unwrap();
let first_frame = tokio::time::timeout(std::time::Duration::from_secs(3), async {
loop {
match transport_rx.recv().await.expect("transport channel closed") {
TransportMessage::InterfaceEvent {
interface_id,
message,
..
} if interface_id == second_accepted.id => {
if let TransportMessage::Inbound(packet) = *message {
return packet.raw;
}
}
_ => {}
}
}
})
.await
.expect("the reconnected client's traffic reaches the shared instance");
assert_eq!(
first_frame, after,
"traffic queued while disconnected is dropped"
);
restarted_server.read_task.abort();
second_accepted.read_task.abort();
client_handle.read_task.abort();
let _ = std::fs::remove_file(&socket_path);
}
}
+11 -2
View File
@@ -1,5 +1,9 @@
//! HDLC-framed data over a subprocess's stdin/stdout; respawns on exit.
//! HDLC-framed data over a subprocess's stdin/stdout. The task retries failed
//! spawns and respawns after stdout EOF or a read error. The command is split
//! on whitespace and executed directly: shell quoting, expansion, and
//! pipelines are not interpreted.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -20,7 +24,8 @@ pub const DEFAULT_RESPAWN_DELAY: f64 = 5.0;
pub struct PipeInterfaceConfig {
pub name: String,
pub command: String,
/// Seconds before respawning after subprocess exit.
/// Seconds before respawning. Must be finite, non-negative, and representable
/// as a `Duration`; this field is not validated before the task starts.
pub respawn_delay: f64,
pub mode: InterfaceMode,
}
@@ -41,6 +46,8 @@ pub async fn spawn_pipe_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(true));
let shared_rxb = Arc::new(AtomicU64::new(0));
let shared_txb = Arc::new(AtomicU64::new(0));
@@ -189,6 +196,8 @@ pub async fn spawn_pipe_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -1,4 +1,6 @@
//! Extended-KISS admin codec shared by RNode runtime and `rnodeconf`.
//! Extended-KISS administrative frame codecs and command builders used by
//! `rnodeconf`. These helpers construct or decode bytes; they perform no
//! transport I/O or device authorization.
use std::net::Ipv4Addr;
+18 -20
View File
@@ -1,10 +1,11 @@
//! Privacy-bounded, read-only RNode capability parsing.
//! Read-only RNode capability parsing without retaining device identity bytes.
//!
//! 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.
//! This module checks the EEPROM information lock and MD5 identity-prefix
//! checksum, then returns product/model codes and limits from a static code
//! table. It ignores device signatures: checksum validation is not device
//! authentication. The value retains no source image, identity, signature,
//! configuration, or raw EEPROM fields. Code-table limits are not a hardware
//! measurement or permission to transmit.
use md5::{Digest, Md5};
@@ -203,10 +204,10 @@ pub enum RNodeRadioAdmissionError {
/// 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.
/// `Provisioned` carries capabilities from a locked, checksummed identity
/// prefix. `Unprovisioned` means the info lock at `0x9b` is absent, so product,
/// model, and checksum bytes are not consulted. Neither state authenticates a
/// device signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeEepromImage {
@@ -216,13 +217,11 @@ pub enum RNodeEepromImage {
/// 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.
/// The image must span the information lock at `0x9b`. An unlocked image is
/// [`RNodeEepromImage::Unprovisioned`] without reading product, model, or
/// checksum bytes. A locked image must match the MD5 checksum over stored
/// bytes `0x00..0x0b`; model aliases are not normalised first. Signature bytes
/// are ignored, so this check does not authenticate the device.
pub fn classify_rnode_eeprom_image(
eeprom: &[u8],
) -> Result<RNodeEepromImage, RNodeCapabilityParseError> {
@@ -324,9 +323,8 @@ pub fn admit_rnode_radio_settings(
/// 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.
/// Only generic RNode validation applies. No model-specific profile is
/// inferred, as with unknown and quarantined model codes.
pub fn admit_unprovisioned_rnode_radio_settings(
settings: RNodeRadioSettings,
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
@@ -160,7 +160,7 @@ impl RNodeCapabilityPreflight {
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);
let mut admitted = RNodeProtocolState::with_effective_settings(target);
if evidence.detected {
admitted.apply_frame(crate::rnode::CMD_DETECT, &[crate::rnode::DETECT_RESP]);
}
+43 -6
View File
@@ -3,6 +3,7 @@
//! selected virtual port; one write task prepends `CMD_SEL_INT` so the device
//! picks the right radio.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::collections::HashSet;
use std::io::Write;
use std::sync::Arc;
@@ -205,7 +206,9 @@ impl RNodeMultiConfig {
}
}
/// SEL_INT, push params, then RADIO_STATE=ON last.
/// Select a subinterface, send its radio parameters and configured airtime
/// locks, then turn the radio on. Frequency, bandwidth and transmit power are
/// reasserted after radio-on.
pub fn build_subinterface_init(index: u8, config: &SubInterfaceConfig) -> Vec<u8> {
let mut out = Vec::with_capacity(80);
@@ -236,6 +239,17 @@ pub fn build_subinterface_init(index: u8, config: &SubInterfaceConfig) -> Vec<u8
kiss::frame_with_command_into(rnode::CMD_LT_ALOCK, &[c1, c2], &mut out);
}
kiss::frame_with_command_into(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON], &mut out);
kiss::frame_with_command_into(
rnode::CMD_FREQUENCY,
&config.frequency.to_be_bytes(),
&mut out,
);
kiss::frame_with_command_into(
rnode::CMD_BANDWIDTH,
&config.bandwidth.to_be_bytes(),
&mut out,
);
kiss::frame_with_command_into(rnode::CMD_TXPOWER, &[config.tx_power], &mut out);
out
}
@@ -290,6 +304,9 @@ struct RadioEvidence {
coding_rate: Option<u8>,
tx_power: Option<u8>,
radio_state: Option<u8>,
/// A TX power echo arrived while the radio was on, so the evidence holds
/// the effective values.
effective: bool,
}
impl RadioEvidence {
@@ -300,6 +317,7 @@ impl RadioEvidence {
&& self.coding_rate.is_some()
&& self.tx_power.is_some()
&& self.radio_state.is_some()
&& self.effective
}
fn validate(self, config: &SubInterfaceConfig) -> Result<(), String> {
@@ -440,12 +458,14 @@ impl StartupEvidence {
let value = one_byte(payload, "TX power")?;
if let Some(radio) = self.selected_radio_mut() {
radio.tx_power = Some(value);
radio.effective |= radio.radio_state == Some(rnode::RADIO_STATE_ON);
}
}
rnode::CMD_RADIO_STATE => {
let value = one_byte(payload, "radio state")?;
if let Some(radio) = self.selected_radio_mut() {
radio.radio_state = Some(value);
radio.effective &= value == rnode::RADIO_STATE_ON;
}
}
CMD_ERROR => {
@@ -741,6 +761,10 @@ pub async fn spawn_rnode_multi_interface(
// stays ordered relative to each data frame.
let (write_tx, mut write_rx) = mpsc::channel::<WriteRequest>(256);
let transport_senders: Vec<_> = ids
.iter()
.map(|id| InterfaceTransportSender::new(*id, transport_tx.clone()))
.collect();
let mut background_lanes = Vec::with_capacity(num_subs);
let mut handles = Vec::with_capacity(num_subs);
let mut sub_txb: Vec<Arc<AtomicU64>> = Vec::with_capacity(num_subs);
@@ -819,6 +843,8 @@ pub async fn spawn_rnode_multi_interface(
handles.push(InterfaceHandle {
id: ids[i],
owner: transport_senders[i].owner(),
packet_capacity: InterfacePacketCapacity::new(500, 508, false),
parent_id: None,
name: sub_name,
mode: sub_cfg.mode,
@@ -1046,7 +1072,7 @@ pub async fn spawn_rnode_multi_interface(
snr,
q: None,
});
if transport_tx.send(msg).await.is_err() {
if transport_senders[local_idx].send(msg).await.is_err() {
tracing::warn!(
parent = %parent_name,
"transport channel closed"
@@ -1414,8 +1440,8 @@ mod tests {
let mut deframer = kiss::KissDeframer::new();
let frames = deframer.feed(&seq);
// sel_int + freq + bw + sf + cr + txpower + radio_state
assert_eq!(frames.len(), 7);
// sel_int + freq + bw + sf + cr + txpower + radio_state + freq + bw + txpower
assert_eq!(frames.len(), 10);
}
#[test]
@@ -1427,8 +1453,8 @@ mod tests {
let seq = build_subinterface_init(0, &sub_cfg);
let mut deframer = kiss::KissDeframer::new();
let frames = deframer.feed(&seq);
// 7 base + 2 airtime limits
assert_eq!(frames.len(), 9);
// 10 base + 2 airtime limits
assert_eq!(frames.len(), 12);
}
#[test]
@@ -1772,10 +1798,21 @@ mod tests {
state
.apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON])
.unwrap();
// Pre-RADIO_ON echoes are the request, not what the radio will use.
assert!(!state.radio_complete(0));
state
.apply_frame(rnode::CMD_TXPOWER, &[config.tx_power])
.unwrap();
assert!(state.radio_complete(0));
assert!(state.radios[0].validate(&config).is_ok());
// An amplifier floor reported once on is a mismatch.
state
.apply_frame(rnode::CMD_TXPOWER, &[config.tx_power + 3])
.unwrap();
assert!(state.radios[0].validate(&config).is_err());
let mut mismatch = state.radios[0];
mismatch.coding_rate = Some(config.coding_rate + 1);
assert!(mismatch.validate(&config).is_err());
+199 -13
View File
@@ -1,16 +1,14 @@
//! Deterministic state reduction for the generic, single-radio RNode protocol.
//!
//! This module deliberately does not drive an interface. It gives serial, TCP,
//! USB, and BLE implementations one strict grammar and one order-independent
//! readiness decision to adopt in a later integration step. Callers pass
//! already-deframed extended-KISS command payloads to
//! [`RNodeProtocolState::apply_frame`].
//! Serial, TCP, USB, and BLE drivers pass already-deframed extended-KISS
//! payloads to [`RNodeProtocolState::apply_frame`]. The reducer performs no
//! I/O. Readiness uses the latest accepted evidence in a stable blocker order;
//! effective-setting mode also requires a transmit-power echo after radio-on.
//!
//! The reducer is intentionally limited to generic single-radio readiness and
//! flow-control evidence. It must not be used for `RNodeMultiInterface`: multi
//! virtual-port command bytes overlap generic commands (notably `0x90`). It
//! also does not retain opaque errors, EEPROM contents, hashes, Wi-Fi
//! credentials, signatures, or other administration data.
//! This grammar is not suitable for `RNodeMultiInterface`: its virtual-port
//! command bytes overlap generic commands, notably `0x90`. The reducer retains
//! no opaque errors, EEPROM contents, hashes, Wi-Fi credentials, signatures,
//! or other administration data.
use crate::rnode;
@@ -41,7 +39,8 @@ impl RNodeFirmwareVersion {
}
}
/// Radio settings whose exact echoes establish that configuration completed.
/// Radio settings used to check configuration echoes. Frequency allows
/// [`FREQUENCY_TOLERANCE_HZ`]; the other settings require exact matches.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RNodeProtocolTarget {
pub frequency: u32,
@@ -260,6 +259,21 @@ pub enum RNodeReadinessBlocker {
Mismatch(RNodeReadinessEvidence),
}
impl RNodeReadinessBlocker {
/// The evidence the device definitively rejected, if this blocker is one
/// that retrying the same settings cannot clear. Mirrors upstream Android
/// `RNodeInterface`, which records invalid configuration and firmware as
/// hardware errors and stops reconnecting, but retries a radio
/// initialisation failure.
pub const fn rejected_evidence(self) -> Option<RNodeReadinessEvidence> {
match self {
Self::Mismatch(evidence) => Some(evidence),
Self::UnsupportedFirmware { .. } => Some(RNodeReadinessEvidence::Firmware),
Self::RadioInitialisationFault | Self::Missing(_) => None,
}
}
}
/// Derived readiness of the generic RNode session.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RNodeReadiness {
@@ -296,13 +310,26 @@ pub enum RNodeProtocolEffect {
Rejected(RNodeFrameRejection),
}
/// Pure, order-independent reducer for generic single-radio readiness.
/// Pure reducer for generic single-radio readiness.
///
/// Different evidence categories can arrive in any order; a later value
/// replaces earlier evidence for the same category, and reset clears evidence.
/// [`RNodeProtocolState::with_effective_settings`] additionally requires a
/// transmit-power echo after radio-on.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RNodeProtocolState {
target: RNodeProtocolTarget,
evidence: RNodeProtocolEvidence,
detection_observed: bool,
flow_permission_observed: bool,
effective: Option<EffectiveSettings>,
}
/// Progress toward a transmit-power echo that follows `RADIO_STATE_ON`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct EffectiveSettings {
radio_on: bool,
confirmed: bool,
}
impl RNodeProtocolState {
@@ -323,9 +350,26 @@ impl RNodeProtocolState {
},
detection_observed: false,
flow_permission_observed: false,
effective: None,
}
}
/// Like [`Self::new`], but readiness also waits for a transmit-power echo
/// that follows `RADIO_STATE_ON`.
///
/// `crate::rnode::build_init_sequence` reasserts frequency, bandwidth and
/// transmit power after `RADIO_STATE_ON`. In this mode, readiness requires
/// the later transmit-power echo, and [`Self::definitive_rejection`] returns
/// `None` until it arrives. The reducer checks device-reported values.
pub const fn with_effective_settings(target: RNodeProtocolTarget) -> Self {
let mut state = Self::new(target);
state.effective = Some(EffectiveSettings {
radio_on: false,
confirmed: false,
});
state
}
pub const fn target(&self) -> RNodeProtocolTarget {
self.target
}
@@ -350,11 +394,57 @@ impl RNodeProtocolState {
/// Rejected frames leave state unchanged.
pub fn apply_frame(&mut self, command: u8, payload: &[u8]) -> RNodeProtocolEffect {
match RNodeProtocolFrame::decode(command, payload) {
Ok(frame) => self.apply_decoded_frame(frame),
Ok(frame) => {
let before = self.effective;
let effect = self.apply_decoded_frame(frame);
self.observe_effective_settings(frame);
match (effect, frame) {
(RNodeProtocolEffect::NoChange, RNodeProtocolFrame::RadioState(_))
if self.effective != before =>
{
RNodeProtocolEffect::EvidenceChanged(RNodeReadinessEvidence::RadioState)
}
(RNodeProtocolEffect::NoChange, RNodeProtocolFrame::TransmitPower(_))
if self.effective != before =>
{
RNodeProtocolEffect::EvidenceChanged(RNodeReadinessEvidence::TransmitPower)
}
_ => effect,
}
}
Err(error) => RNodeProtocolEffect::Rejected(error),
}
}
/// The setting the device definitively rejected: a blocker that retrying
/// the same settings cannot clear. With effective settings this waits for
/// the post-`RADIO_STATE_ON` transmit-power echo.
pub fn definitive_rejection(&self) -> Option<RNodeReadinessEvidence> {
if self.effective.is_some_and(|effective| !effective.confirmed) {
return None;
}
match self.readiness() {
RNodeReadiness::Blocked(blocker) => blocker.rejected_evidence(),
RNodeReadiness::Ready => None,
}
}
fn observe_effective_settings(&mut self, frame: RNodeProtocolFrame) {
let Some(effective) = self.effective.as_mut() else {
return;
};
match frame {
RNodeProtocolFrame::RadioState(RNodeRadioState::On) => effective.radio_on = true,
RNodeProtocolFrame::RadioState(RNodeRadioState::Off) | RNodeProtocolFrame::Reset => {
*effective = EffectiveSettings::default();
}
RNodeProtocolFrame::TransmitPower(_) if effective.radio_on => {
effective.confirmed = true;
}
_ => {}
}
}
/// Derive readiness in stable blocker order.
pub fn readiness(&self) -> RNodeReadiness {
use RNodeReadinessBlocker::{Mismatch, Missing};
@@ -411,6 +501,9 @@ impl RNodeProtocolState {
}
Some(_) => {}
}
if self.effective.is_some_and(|effective| !effective.confirmed) {
return RNodeReadiness::Blocked(Missing(TransmitPower));
}
match self.evidence.tx_power {
None => return RNodeReadiness::Blocked(Missing(TransmitPower)),
Some(tx_power) if tx_power != self.target.tx_power => {
@@ -1001,4 +1094,97 @@ mod tests {
RNodeReadiness::Blocked(RNodeReadinessBlocker::RadioInitialisationFault)
);
}
#[test]
fn only_configuration_and_firmware_rejections_are_definitive() {
use RNodeReadinessBlocker::{Mismatch, Missing, RadioInitialisationFault};
use RNodeReadinessEvidence::{Firmware, TransmitPower};
assert_eq!(
Mismatch(TransmitPower).rejected_evidence(),
Some(TransmitPower)
);
let unsupported = RNodeReadinessBlocker::UnsupportedFirmware {
observed: RNodeFirmwareVersion::new(1, 51),
minimum: RNodeFirmwareVersion::MINIMUM_SUPPORTED,
};
assert_eq!(unsupported.rejected_evidence(), Some(Firmware));
assert_eq!(Missing(TransmitPower).rejected_evidence(), None);
assert_eq!(RadioInitialisationFault.rejected_evidence(), None);
let mut state = ready_state();
state.apply_frame(rnode::CMD_TXPOWER, &[TARGET.tx_power - 4]);
let RNodeReadiness::Blocked(blocker) = state.readiness() else {
panic!("a different transmit power echo must block readiness");
};
assert_eq!(blocker.rejected_evidence(), Some(TransmitPower));
}
fn apply_all(state: &mut RNodeProtocolState, frames: &[(u8, Vec<u8>)]) {
for (command, payload) in frames {
state.apply_frame(*command, payload);
}
}
#[test]
fn effective_settings_wait_for_a_transmit_power_echo_after_radio_on() {
let mut state = RNodeProtocolState::with_effective_settings(TARGET);
apply_all(&mut state, &required_frames());
// Pre-RADIO_ON echoes alone satisfy the order-independent reducer only.
assert_eq!(
state.readiness(),
RNodeReadiness::Blocked(RNodeReadinessBlocker::Missing(
RNodeReadinessEvidence::TransmitPower
))
);
assert_eq!(state.definitive_rejection(), None);
// An unchanged value still confirms, and reports the change.
assert_eq!(
state.apply_frame(rnode::CMD_TXPOWER, &[TARGET.tx_power]),
RNodeProtocolEffect::EvidenceChanged(RNodeReadinessEvidence::TransmitPower)
);
assert_eq!(state.readiness(), RNodeReadiness::Ready);
// A radio that turns off needs a fresh confirmation.
state.apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_OFF]);
state.apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON]);
assert_ne!(state.readiness(), RNodeReadiness::Ready);
state.apply_frame(rnode::CMD_TXPOWER, &[TARGET.tx_power]);
assert_eq!(state.readiness(), RNodeReadiness::Ready);
}
#[test]
fn effective_settings_judge_the_amplifier_mapped_echo() {
// A cold amplifier board echoes the request, then its floor once on.
let target = RNodeProtocolTarget::new(915_000_000, 125_000, 7, 5, 2);
let mut state = RNodeProtocolState::with_effective_settings(target);
let mut frames = required_frames().to_vec();
frames[6] = (rnode::CMD_TXPOWER, vec![2]);
apply_all(&mut state, &frames);
assert_eq!(state.definitive_rejection(), None);
state.apply_frame(rnode::CMD_TXPOWER, &[13]);
assert_eq!(
state.definitive_rejection(),
Some(RNodeReadinessEvidence::TransmitPower)
);
// The legacy reducer accepts the same cold echoes.
let mut legacy = RNodeProtocolState::new(target);
apply_all(&mut legacy, &frames);
assert_eq!(legacy.readiness(), RNodeReadiness::Ready);
}
#[test]
fn effective_settings_reset_with_the_device() {
let mut state = RNodeProtocolState::with_effective_settings(TARGET);
apply_all(&mut state, &required_frames());
state.apply_frame(rnode::CMD_TXPOWER, &[TARGET.tx_power]);
assert_eq!(state.readiness(), RNodeReadiness::Ready);
state.apply_frame(rnode::CMD_RESET, &[0xF8]);
apply_all(&mut state, &required_frames());
assert_ne!(state.readiness(), RNodeReadiness::Ready);
}
}
+7 -2
View File
@@ -1,6 +1,7 @@
//! HDLC-framed data over a serial port. Uses `serialport` with
//! `spawn_blocking` because no mature async driver exists yet.
//! HDLC-framed data over a serial port. Requires feature `serial`. Blocking
//! `serialport` reads and writes run through Tokio's `spawn_blocking`.
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
@@ -81,6 +82,8 @@ pub async fn spawn_serial_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let port = serialport::new(&config.port, config.baud_rate)
.data_bits(config.data_bits)
.parity(config.parity)
@@ -192,6 +195,8 @@ pub async fn spawn_serial_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 564, false),
parent_id: None,
name,
mode,
+12 -8
View File
@@ -1,9 +1,10 @@
//! Shared TCP socket tuning for [`crate::tcp`], [`crate::backbone`],
//! [`crate::i2p`], and [`crate::rnode`] (TCP transport).
//! `set_keepalive`: portable SO_KEEPALIVE. `set_keepalive_tuned`: adds Linux
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT. All helpers are generic over
//! the raw-fd/raw-socket borrow, so they accept tokio and std streams alike.
//! `iface_addr_for`: kernel iface name → IpAddr for Backbone `device =` key.
//!
//! The helpers accept Tokio and standard-library streams through their raw
//! socket handles. Keepalive settings are applied where the platform supports
//! them; TCP_USER_TIMEOUT is set on Linux, Android, and Fuchsia. Tuning is
//! best effort. Interface-address helpers resolve local device names.
use std::net::IpAddr;
use std::time::Duration;
@@ -53,7 +54,8 @@ pub fn set_keepalive<S: RawStream>(stream: &S) -> std::io::Result<()> {
with_socket2(stream, |sock| sock.set_keepalive(true))
}
/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort.
/// Request keepalive idle time, interval, and retry count where supported,
/// plus TCP_USER_TIMEOUT on Linux, Android, and Fuchsia. Best effort.
pub fn set_keepalive_tuned<S: RawStream>(
stream: &S,
idle: Duration,
@@ -66,7 +68,8 @@ pub fn set_keepalive_tuned<S: RawStream>(
});
}
/// Raise TCP send/recv buffers; best-effort.
/// Request TCP send and receive buffer sizes. The kernel may adjust them;
/// errors are ignored.
pub fn set_socket_buffers<S: RawStream>(stream: &S, size: usize) {
with_socket2(stream, |sock| {
let _ = sock.set_recv_buffer_size(size);
@@ -124,8 +127,9 @@ pub fn iface_broadcast_for(name: &str) -> Option<std::net::Ipv4Addr> {
})
}
/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back
/// to wildcard bind.
/// Resolve an interface name to `IpAddr`, preferring the requested address
/// family and falling back to the other family. Returns `None` if enumeration
/// fails or no address matches; the caller decides whether to fall back.
pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option<IpAddr> {
let ifaces = match if_addrs::get_if_addrs() {
Ok(v) => v,
+172 -44
View File
@@ -1,3 +1,4 @@
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -9,7 +10,8 @@ use tokio::sync::mpsc;
use crate::hdlc;
use crate::kiss;
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection, python_host,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
@@ -26,15 +28,30 @@ pub const TCP_KEEPIDLE: u32 = 5;
pub const TCP_KEEPINTVL: u32 = 2;
pub const TCP_KEEPCNT: u32 = 12;
/// Tuned keepalive (idle/interval/count + Linux `TCP_USER_TIMEOUT`) for plain
/// TCP client and accepted sockets, matching Python `set_timeouts_linux`.
pub(crate) fn set_tcp_keepalive_tuned(stream: &TcpStream) {
/// Python's ordinary TCP or I2P Linux timeout values through the shared Rust
/// socket tuner. Accepted sockets use ordinary TCP tuning.
pub(crate) fn set_tcp_keepalive_tuned(stream: &TcpStream, i2p_tunneled: bool) {
let (idle, interval, count, user_timeout) = if i2p_tunneled {
(
crate::i2p::I2P_PROBE_AFTER,
crate::i2p::I2P_PROBE_INTERVAL,
crate::i2p::I2P_PROBES as u32,
crate::i2p::I2P_TCP_USER_TIMEOUT,
)
} else {
(
TCP_KEEPIDLE as u64,
TCP_KEEPINTVL as u64,
TCP_KEEPCNT,
DEFAULT_TCP_USER_TIMEOUT,
)
};
crate::socket_tuning::set_keepalive_tuned(
stream,
std::time::Duration::from_secs(TCP_KEEPIDLE as u64),
std::time::Duration::from_secs(TCP_KEEPINTVL as u64),
TCP_KEEPCNT,
std::time::Duration::from_secs(DEFAULT_TCP_USER_TIMEOUT as u64),
std::time::Duration::from_secs(idle),
std::time::Duration::from_secs(interval),
count,
std::time::Duration::from_secs(user_timeout as u64),
);
}
@@ -44,11 +61,17 @@ pub struct TcpClientConfig {
pub target_host: String,
pub target_port: u16,
pub kiss_framing: bool,
/// Use the longer socket timeouts for a TCP connection tunneled over I2P.
pub i2p_tunneled: bool,
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
/// Override HW MTU for link MTU discovery (Python `fixed_mtu`, >= 500).
/// Override the MTU used for link MTU discovery. Accepted values are
/// 500 through 262,144 bytes, inclusive.
pub fixed_mtu: Option<u32>,
/// Identity used to request a signed tunnel synthesis for each non-KISS
/// connection. `None`, or an identity without signing material, sends none.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl TcpClientConfig {
@@ -58,12 +81,24 @@ impl TcpClientConfig {
target_host: host.to_string(),
target_port: port,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
}
}
/// Python `str(TCPClientInterface)` (TCPInterface.py:457-461).
pub fn python_name(&self) -> String {
format!(
"TCPInterface[{}/{}:{}]",
self.name,
python_host(&self.target_host),
self.target_port
)
}
}
#[derive(Debug, Clone)]
@@ -182,7 +217,7 @@ use crate::socket_tuning::set_socket_buffers;
async fn tcp_read_loop(
mut reader: tokio::net::tcp::OwnedReadHalf,
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
transport_tx: InterfaceTransportSender,
state: Arc<TcpInterfaceState>,
kiss_framing: bool,
) {
@@ -294,6 +329,16 @@ pub async fn spawn_tcp_client(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
if config
.fixed_mtu
.is_some_and(|mtu| !(500..=262144).contains(&mtu))
{
return Err(crate::traits::InterfaceError::SendFailed(
"fixed_mtu must be between 500 and 262144 clear packet bytes".into(),
));
}
let online = Arc::new(AtomicBool::new(false));
let online2 = online.clone();
let (tx, rx) = mpsc::channel::<Bytes>(1024);
@@ -310,12 +355,16 @@ pub async fn spawn_tcp_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let max_tries = config.max_reconnect_tries;
let mut tries: usize = 0;
let mut backoff = RECONNECT_WAIT_INITIAL;
// Every attempt after the first follows a failure or an outage.
let mut attempted = false;
loop {
let after_outage = std::mem::replace(&mut attempted, true);
let addr = format!("{}:{}", config.target_host, config.target_port);
let stream = match tokio::time::timeout(
std::time::Duration::from_secs(config.connect_timeout_secs),
@@ -360,7 +409,7 @@ pub async fn spawn_tcp_client(
}
};
set_tcp_keepalive_tuned(&stream);
set_tcp_keepalive_tuned(&stream, config.i2p_tunneled);
// Nagle off for low-latency packets; larger buffers for bulk transfers.
let _ = stream.set_nodelay(true);
@@ -368,9 +417,16 @@ pub async fn spawn_tcp_client(
let state = TcpInterfaceState::with_shared_counters(task_rxb.clone(), task_txb.clone());
state.online.store(true, Ordering::SeqCst);
online2.store(true, Ordering::SeqCst);
tries = 0;
backoff = RECONNECT_WAIT_INITIAL;
// Python synthesizes on every non-KISS connection
// (TCPInterface.py:178-179, :298-299).
let synthesis = config
.tunnel_identity
.as_ref()
.filter(|_| !kiss_framing)
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(&rx, after_outage, &transport_tx, synthesis, &online2).await;
let (reader, writer) = stream.into_split();
@@ -424,6 +480,14 @@ pub async fn spawn_tcp_client(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(
fixed_mtu
.unwrap_or_else(|| crate::traits::optimise_mtu(bitrate).unwrap_or(TCP_HW_MTU))
.min(262144),
262144,
fixed_mtu.is_some() || crate::traits::optimise_mtu(bitrate).is_some(),
),
parent_id: None,
name,
mode,
@@ -461,6 +525,8 @@ async fn spawn_tcp_accepted(
kiss_framing: bool,
mode: InterfaceMode,
) -> InterfaceHandle {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let online = Arc::new(AtomicBool::new(true));
let online2 = online.clone();
let (tx, conn_rx) = mpsc::channel::<Bytes>(1024);
@@ -470,7 +536,7 @@ async fn spawn_tcp_accepted(
let state = TcpInterfaceState::with_shared_counters(shared_rxb.clone(), shared_txb.clone());
state.online.store(true, Ordering::SeqCst);
set_tcp_keepalive_tuned(&stream);
set_tcp_keepalive_tuned(&stream, false);
let _ = stream.set_nodelay(true);
set_socket_buffers(&stream, 131072);
@@ -494,6 +560,14 @@ async fn spawn_tcp_accepted(
let bitrate: u64 = 10_000_000;
InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(
crate::traits::optimise_mtu(bitrate)
.unwrap_or(TCP_HW_MTU)
.min(262144),
262144,
crate::traits::optimise_mtu(bitrate).is_some(),
),
parent_id: Some(parent_id),
name,
mode,
@@ -523,6 +597,8 @@ pub async fn spawn_tcp_server(
transport_tx: mpsc::Sender<TransportMessage>,
handle_tx: mpsc::Sender<InterfaceHandle>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
let addr = match config.device.as_deref() {
Some(device) => {
let ip = address_for_device(device, config.prefer_ipv6).ok_or_else(|| {
@@ -559,7 +635,7 @@ pub async fn spawn_tcp_server(
client_id,
id,
client_name,
transport_tx.clone(),
transport_tx.actor_sender(),
kiss_framing,
mode,
)
@@ -584,6 +660,14 @@ pub async fn spawn_tcp_server(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(
crate::traits::optimise_mtu(bitrate)
.unwrap_or(TCP_HW_MTU)
.min(262144),
262144,
crate::traits::optimise_mtu(bitrate).is_some(),
),
parent_id: None,
name,
mode,
@@ -608,6 +692,24 @@ pub async fn spawn_tcp_server(
mod tests {
use super::*;
#[test]
fn client_python_names_match_python() {
// Python 1.5.5 `str()` output for these interfaces.
for (host, expected) in [
("127.0.0.1", "TCPInterface[Golden Uplink/127.0.0.1:4242]"),
("::1", "TCPInterface[Golden Uplink/[::1]:4242]"),
(
"hub.example.org",
"TCPInterface[Golden Uplink/hub.example.org:4242]",
),
] {
assert_eq!(
TcpClientConfig::new("Golden Uplink", host, 4242).python_name(),
expected
);
}
}
#[test]
fn test_tcp_client_config() {
let config = TcpClientConfig::new("test", "127.0.0.1", 4242);
@@ -623,9 +725,8 @@ mod tests {
assert!(!config.prefer_ipv6);
}
/// T1-2 regression: the client/accept paths must apply the TUNED keepalive
/// (idle 5s + 12 probes × 2s ≈ 29s dead-peer parity with Python), not just
/// SO_KEEPALIVE. Reads the options back via getsockopt.
/// Read back Python's Linux timeout values applied by the shared Rust
/// socket tuner for ordinary TCP and I2P-tunneled connections.
#[cfg(unix)]
#[tokio::test]
async fn tuned_keepalive_applies_python_probe_values() {
@@ -653,33 +754,35 @@ mod tests {
let client = client.unwrap();
let (server, _) = accepted.unwrap();
for stream in [&client, &server] {
set_tcp_keepalive_tuned(stream);
let fd = stream.as_ref().as_raw_fd();
// BSD getsockopt returns the option bit, not 1 — assert enabled.
assert_ne!(get_opt(fd, libc::SOL_SOCKET, libc::SO_KEEPALIVE), 0);
for (i2p_tunneled, _expected) in [(false, [5, 2, 12, 24]), (true, [10, 9, 5, 45])] {
for stream in [&client, &server] {
set_tcp_keepalive_tuned(stream, i2p_tunneled);
let fd = stream.as_ref().as_raw_fd();
// BSD getsockopt returns the option bit, not 1 — assert enabled.
assert_ne!(get_opt(fd, libc::SOL_SOCKET, libc::SO_KEEPALIVE), 0);
#[cfg(target_os = "linux")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE);
#[cfg(target_os = "macos")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE);
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
assert_eq!(idle, TCP_KEEPIDLE as i32);
#[cfg(target_os = "linux")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE);
#[cfg(target_os = "macos")]
let idle = get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE);
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
assert_eq!(idle, _expected[0]);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
_expected[1]
);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
_expected[2]
);
}
#[cfg(target_os = "linux")]
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
TCP_KEEPINTVL as i32
);
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
TCP_KEEPCNT as i32
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT),
_expected[3] * 1000
);
}
#[cfg(target_os = "linux")]
assert_eq!(
get_opt(fd, libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT),
(DEFAULT_TCP_USER_TIMEOUT * 1000) as i32
);
}
}
@@ -700,12 +803,13 @@ mod tests {
config.connect_timeout_secs = 2;
let handle = spawn_tcp_client(config, 77, transport_tx).await.unwrap();
handle.owner.mark_registered();
let msg = tokio::time::timeout(std::time::Duration::from_secs(10), transport_rx.recv())
.await
.expect("expected DeregisterInterface before timeout")
.expect("transport channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &handle) {
TransportMessage::DeregisterInterface { id } => assert_eq!(id, 77),
other => panic!("expected DeregisterInterface, got {other:?}"),
}
@@ -759,6 +863,7 @@ mod tests {
spawn_tcp_server(server_cfg2, 99, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
assert_eq!(server_handle.id, 99);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -768,29 +873,42 @@ mod tests {
target_host: "127.0.0.1".into(),
target_port: port,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
assert_ne!(accepted.owner, server_handle.owner);
assert_ne!(accepted.owner, client_handle.owner);
assert_eq!(accepted.packet_capacity.max_wire_packet_bytes, 262144);
let payload = Bytes::from_static(b"hello from client");
client_handle.tx.send(payload.clone()).await.unwrap();
assert!(
tokio::time::timeout(std::time::Duration::from_millis(20), transport_rx.recv())
.await
.is_err(),
"the first packet waits for accepted-child registration"
);
accepted.owner.mark_registered();
let msg = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
.await
.expect("timeout waiting for transport message")
.expect("transport channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &accepted) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, accepted.id);
@@ -806,7 +924,7 @@ mod tests {
.expect("timeout waiting for reply")
.expect("transport channel closed");
match msg2 {
match crate::traits::test_event_for_handle(msg2, &client_handle) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 1);
@@ -853,13 +971,16 @@ mod tests {
target_host: "127.0.0.1".into(),
target_port: 1,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: 1,
max_reconnect_tries: Some(2),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let handle = spawn_tcp_client(config, 99, transport_tx).await.unwrap();
handle.owner.mark_registered();
// Two failed tries with 5s waits each; 20s headroom.
let result =
@@ -887,6 +1008,7 @@ mod tests {
spawn_tcp_server(server_cfg, 88, id_gen, transport_tx.clone(), handle_tx)
.await
.unwrap();
server_handle.owner.mark_registered();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
@@ -895,19 +1017,23 @@ mod tests {
target_host: "127.0.0.1".into(),
target_port: port,
kiss_framing: false,
i2p_tunneled: false,
connect_timeout_secs: 5,
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone())
.await
.unwrap();
client_handle.owner.mark_registered();
let accepted = tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
.await
.expect("timeout waiting for accepted handle")
.expect("handle channel closed");
accepted.owner.mark_registered();
let server_side_client_id = accepted.id;
// Abort client-side tasks; server's per-client reader sees EOF and exits.
@@ -919,7 +1045,9 @@ mod tests {
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(std::time::Duration::from_millis(500), transport_rx.recv())
.await
{
.map(|message| {
message.map(|event| crate::traits::test_event_for_handle(event, &accepted))
}) {
Ok(Some(TransportMessage::DeregisterInterface { id }))
if id == server_side_client_id =>
{
+111 -6
View File
@@ -6,8 +6,10 @@ use tokio::sync::mpsc;
pub type InterfaceId = u64;
/// Handle returned by every `spawn_*`: write channel, status flag, and read task.
/// Common transport handle: write channel, status flag, and read task.
pub struct InterfaceHandle {
pub owner: rns_transport::messages::InterfaceOwner,
pub packet_capacity: rns_transport::messages::InterfacePacketCapacity,
pub id: InterfaceId,
/// Parent interface for dynamically spawned children such as accepted TCP,
/// Backbone or I2P peers.
@@ -20,9 +22,7 @@ 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.
/// Optional live aggregate inspection source carried into the transport actor.
pub inspection: Option<rns_transport::messages::InterfaceInspectionSource>,
pub tx: mpsc::Sender<Bytes>,
pub read_task: tokio::task::JoinHandle<()>,
@@ -50,7 +50,68 @@ pub(crate) async fn handoff_accepted_interface(
}
}
/// Interface operating mode. Byte values are on-wire constants.
/// The transport identity a client signs its tunnel syntheses with (Python
/// `Transport.identity`). Debug shows only its hash.
#[derive(Clone)]
pub struct TunnelIdentity(pub Arc<rns_identity::identity::Identity>);
impl TunnelIdentity {
/// Build a fresh synthesis using `python_name` as the Python-compatible
/// interface name. Returns `None` when the identity cannot sign.
pub fn synthesis(&self, python_name: &str) -> Option<Bytes> {
rns_transport::tunnel::build_tunnel_synthesis_packet(
&self.0,
rns_transport::tunnel::interface_hash(python_name),
)
.map(Bytes::from)
}
}
impl std::fmt::Debug for TunnelIdentity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("TunnelIdentity")
.field(&hex::encode(self.0.hash))
.finish()
}
}
/// A host as Python's interface `str()` renders it: IPv6 in brackets.
pub(crate) fn python_host(host: &str) -> std::borrow::Cow<'_, str> {
if host.contains(':') {
format!("[{host}]").into()
} else {
host.into()
}
}
/// Start a client connection as Python does: traffic queued during an outage
/// is dropped (TCPInterface.py:314-315), then the connection's synthesis is
/// queued, and only then does the interface report online.
pub(crate) async fn open_client_connection(
outbound: &tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
after_outage: bool,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
synthesis: Option<Bytes>,
online: &AtomicBool,
) {
if after_outage {
let mut queued = outbound.lock().await;
while queued.try_recv().is_ok() {}
}
if let Some(raw_packet) = synthesis {
let _ = transport_tx
.send(
rns_transport::messages::TransportMessage::SynthesizeTunnel {
interface_id: transport_tx.interface_id(),
raw_packet,
},
)
.await;
}
online.store(true, std::sync::atomic::Ordering::SeqCst);
}
/// Interface operating mode. Numeric values match Reticulum interface mode constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
#[derive(Default)]
@@ -106,7 +167,8 @@ pub struct InterfaceDirection {
pub repeat: bool,
}
/// Select an MTU for the given bitrate; `None` below 62.5 kbps minimum.
/// Select an MTU for the given bitrate in bits per second. Returns `None`
/// for rates at or below 62,500 bps.
pub fn optimise_mtu(bitrate: u64) -> Option<u32> {
if bitrate >= 1_000_000_000 {
Some(524_288)
@@ -183,6 +245,45 @@ pub enum InterfaceError {
Io(#[from] std::io::Error),
}
#[cfg(test)]
pub(crate) fn test_registered_sender(
id: rns_transport::messages::InterfaceId,
tx: tokio::sync::mpsc::Sender<rns_transport::messages::TransportMessage>,
) -> rns_transport::messages::InterfaceTransportSender {
let sender = rns_transport::messages::InterfaceTransportSender::new(id, tx);
sender.owner().mark_registered();
sender
}
#[cfg(test)]
pub(crate) fn test_event_body(
message: rns_transport::messages::TransportMessage,
) -> rns_transport::messages::TransportMessage {
match message {
rns_transport::messages::TransportMessage::InterfaceEvent { message, .. } => *message,
message => message,
}
}
#[cfg(test)]
pub(crate) fn test_event_for_handle(
message: rns_transport::messages::TransportMessage,
handle: &InterfaceHandle,
) -> rns_transport::messages::TransportMessage {
match message {
rns_transport::messages::TransportMessage::InterfaceEvent {
interface_id,
owner,
message,
} => {
assert_eq!(interface_id, handle.id);
assert_eq!(owner, handle.owner);
*message
}
other => panic!("expected registration-bound interface event, got {other:?}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -298,6 +399,8 @@ mod tests {
started_rx.await.expect("read task should start");
let handle = InterfaceHandle {
owner: rns_transport::messages::InterfaceOwner::new(),
packet_capacity: rns_transport::messages::InterfacePacketCapacity::base(1),
id: 1,
parent_id: Some(0),
name: "rejected-child".to_string(),
@@ -341,6 +444,8 @@ mod tests {
started_rx.await.expect("read task should start");
let handle = InterfaceHandle {
owner: rns_transport::messages::InterfaceOwner::new(),
packet_capacity: rns_transport::messages::InterfacePacketCapacity::base(1),
id: 2,
parent_id: Some(0),
name: "accepted-child".to_string(),
+11 -2
View File
@@ -1,3 +1,4 @@
use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender};
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -54,6 +55,8 @@ pub async fn spawn_udp_interface(
id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
let transport_tx = InterfaceTransportSender::new(id, transport_tx);
let owner = transport_tx.owner();
// Python UDPInterface `device =`: fill unset listen/forward IPs with the
// NIC's IPv4 broadcast address; a device that can't be resolved is a
// config error, not a silent fallback to wildcard.
@@ -166,6 +169,8 @@ pub async fn spawn_udp_interface(
Ok(InterfaceHandle {
id,
owner,
packet_capacity: InterfacePacketCapacity::new(500, 1064, false),
parent_id: None,
name,
mode,
@@ -236,6 +241,7 @@ mod tests {
let handle = spawn_udp_interface(cfg, 2, transport_tx)
.await
.expect("explicit IPs bypass device resolution");
handle.owner.mark_registered();
handle.read_task.abort();
}
@@ -278,6 +284,7 @@ mod tests {
let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone())
.await
.unwrap();
handle_a.owner.mark_registered();
// Reserve two free ports via bind-drop; handle doesn't expose its addr.
let sock_tmp1 = UdpSocket::bind("127.0.0.1:0").await.unwrap();
@@ -298,9 +305,11 @@ mod tests {
let handle_a = spawn_udp_interface(cfg_a, 10, transport_tx.clone())
.await
.unwrap();
handle_a.owner.mark_registered();
let handle_b = spawn_udp_interface(cfg_b, 20, transport_tx.clone())
.await
.unwrap();
handle_b.owner.mark_registered();
// A → B's listen port; inbound carries B's interface_id (20).
let payload = Bytes::from_static(b"udp test data");
@@ -311,7 +320,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg {
match crate::traits::test_event_for_handle(msg, &handle_b) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, payload);
assert_eq!(pkt.interface_id, 20);
@@ -327,7 +336,7 @@ mod tests {
.expect("timeout")
.expect("channel closed");
match msg2 {
match crate::traits::test_event_for_handle(msg2, &handle_a) {
TransportMessage::Inbound(pkt) => {
assert_eq!(pkt.raw, reply);
assert_eq!(pkt.interface_id, 10);
+5 -4
View File
@@ -1,12 +1,13 @@
//! Weave switching fabric — protocol primitives only.
//! Weave switching-fabric codecs and constants.
//!
//! Wire format (WDCL inside HDLC):
//! ```text
//! [HDLC_FLAG] [escaped WDCL] [HDLC_FLAG]
//! WDCL = [ADDR u32][TYPE u8][PAYLOAD…] ADDR 0xFFFFFFFF = broadcast
//! WDCL = [ADDR:4 bytes][TYPE:1 byte][PAYLOAD...]
//! ADDR 0xFFFFFFFF = broadcast
//! ```
//! Discovery: Ed25519 challenge-response over WDCL_T_DISCOVER / WDCL_T_CONNECT.
//! Runtime spawn (serial I/O, peer mgmt) not yet wired up.
//! This module provides frame and log codecs plus configuration types. It
//! has no serial runtime, discovery handshake, or signature-verification path.
use crate::traits::InterfaceMode;
@@ -0,0 +1,212 @@
//! A SAM session's private key, read from its key file or returned by the SAM
//! bridge, must not survive in freed heap memory.
#[path = "../../rns-crypto/tests/residue/mod.rs"]
mod residue;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use residue::{assert_no_residue, freed_by, pseudo_random, serial};
use rns_interface::i2p::{I2PClientConfig, I2PServerConfig, spawn_i2p_client, spawn_i2p_server};
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~";
/// A SAM private key: a destination of 384 key bytes and an Ed25519 key
/// certificate, then 256 private and 32 signing-key bytes. Returns the key's
/// bytes and its I2P base64 text.
fn sam_private_key(seed: u64) -> (Vec<u8>, String) {
let mut key = pseudo_random::<384>(seed).to_vec();
key.extend_from_slice(&[5, 0, 4, 0, 7, 0, 0]);
key.extend_from_slice(&pseudo_random::<288>(seed + 1));
let mut text = String::new();
for chunk in key.chunks(3) {
let bits = chunk.iter().enumerate().fold(0u32, |bits, (n, byte)| {
bits | u32::from(*byte) << (16 - 8 * n)
});
for n in 0..=chunk.len() {
text.push(char::from(ALPHABET[(bits >> (18 - 6 * n)) as usize & 63]));
}
text.extend(std::iter::repeat_n('=', 3 - chunk.len()));
}
(key, text)
}
/// A SAM bridge on its own threads, so none of its frees are recorded. A
/// session keeps the key it asks for, a transient one gets `transient`, and a
/// STREAM CONNECT succeeds; every socket then stays open.
fn sam_bridge(transient: String) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for socket in listener.incoming() {
let Ok(socket) = socket else { return };
let transient = transient.clone();
std::thread::spawn(move || serve(socket, &transient));
}
});
port
}
fn serve(mut socket: TcpStream, transient: &str) {
let mut reader = BufReader::new(socket.try_clone().unwrap());
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return;
}
let _ = socket.write_all(b"HELLO REPLY RESULT=OK VERSION=3.1\n");
line.clear();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return;
}
if line.starts_with("SESSION CREATE") {
let destination = match line
.split_whitespace()
.find_map(|token| token.strip_prefix("DESTINATION="))
{
Some("TRANSIENT") | None => transient,
Some(key) => key,
};
let _ = socket
.write_all(format!("SESSION STATUS RESULT=OK DESTINATION={destination}\n").as_bytes());
} else if line.starts_with("STREAM CONNECT") {
let _ = socket.write_all(b"STREAM STATUS RESULT=OK\n");
}
let mut rest = Vec::new();
let _ = std::io::Read::read_to_end(&mut reader, &mut rest);
}
/// Run `body` on a current-thread runtime inside the check, then drop the
/// runtime there too, so every task's frees are recorded.
fn checked(body: impl std::future::Future<Output = ()>) -> residue::Freed {
let ((), freed) = freed_by(|| {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(body);
drop(runtime);
});
freed
}
struct TempDir(PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn temp_dir(label: &str) -> TempDir {
let path = std::env::temp_dir().join(format!("rns-i2p-residue-{label}-{}", std::process::id()));
std::fs::create_dir_all(&path).unwrap();
TempDir(path)
}
async fn run_server(sam_port: u16, key_path: PathBuf) {
let (b32_tx, mut b32_rx) = tokio::sync::watch::channel(None);
let mut config = I2PServerConfig::new("residue");
config.sam_host = "127.0.0.1".into();
config.sam_port = sam_port;
config.key_path = Some(key_path);
config.b32 = Some(b32_tx);
let (transport_tx, _transport_rx) = tokio::sync::mpsc::channel(16);
let (handle_tx, _handle_rx) = tokio::sync::mpsc::channel(16);
let _handle = spawn_i2p_server(
config,
1,
Arc::new(AtomicU64::new(2)),
transport_tx,
handle_tx,
)
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(10), b32_rx.wait_for(Option::is_some))
.await
.expect("session created")
.unwrap();
// Let the server reach its STREAM ACCEPT.
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[test]
fn i2p_server_with_a_stored_key_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(10);
let sam_port = sam_bridge(sam_private_key(11).1);
let dir = temp_dir("stored");
let key_path = dir.0.join("i2p.key");
std::fs::write(&key_path, format!("{text}\n")).unwrap();
let freed = checked(run_server(sam_port, key_path));
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_server_storing_a_new_key_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(20);
let sam_port = sam_bridge(text.clone());
let dir = temp_dir("new");
let key_path = dir.0.join("i2p.key");
let freed = checked(run_server(sam_port, key_path.clone()));
assert_eq!(std::fs::read_to_string(&key_path).unwrap(), text);
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_client_session_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(30);
let sam_port = sam_bridge(text.clone());
let peer = sam_private_key(40).1;
let freed = checked(async move {
let mut config = I2PClientConfig::new("residue", &peer[..516]);
config.sam_host = "127.0.0.1".into();
config.sam_port = sam_port;
let (transport_tx, mut transport_rx) = tokio::sync::mpsc::channel(16);
let handle = spawn_i2p_client(config, 1, transport_tx).await.unwrap();
tokio::time::timeout(Duration::from_secs(10), async {
while !handle.online.load(Ordering::SeqCst) {
tokio::select! {
_ = transport_rx.recv() => {}
_ = tokio::time::sleep(Duration::from_millis(10)) => {}
}
}
})
.await
.expect("client online");
});
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_server_debug_output_hides_its_key() {
let (_, text) = sam_private_key(50);
let mut config = I2PServerConfig::new("residue");
config.keyfile = Some(text.clone());
let shown = format!("{config:?}");
assert!(!shown.contains(&text[..32]), "{shown}");
assert!(shown.contains("residue"), "{shown}");
}
+7 -1
View File
@@ -5,7 +5,7 @@ publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
license-file.workspace = true
[features]
default = ["std"]
@@ -22,5 +22,11 @@ rand = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_System_Performance"] }
[dev-dependencies]
proptest = { workspace = true }
+323
View File
@@ -0,0 +1,323 @@
//! A monotonic clock for deadlines that account for system suspension.
//!
//! Uses `CLOCK_BOOTTIME` on Linux and Android, `CLOCK_MONOTONIC_RAW` on Apple
//! platforms, and the performance counter on Windows. Other targets fall back
//! to `std::time::Instant` from the first reading, inheriting that platform
//! clock's suspend behavior.
//!
//! This type does not schedule a wakeup or change the clock used by an async
//! timer. Check deadlines against [`ContinuousInstant::now`] on a regular
//! tick and after resuming. Link and request timing elsewhere in this crate
//! still uses `std::time::Instant`.
use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::time::Duration;
/// A reading of this module's clock, in signed nanoseconds from the
/// platform's origin, usually boot.
///
/// Readings are process-local: never persist one or send it to another
/// process, which is what wall time is for. They do not convert to or from
/// `std::time::Instant`, so the two clocks never mix.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ContinuousInstant(i64);
impl ContinuousInstant {
/// The current reading.
///
/// # Panics
///
/// If the platform clock fails, as `std::time::Instant::now` does.
pub fn now() -> Self {
Self(backend::now_nanos())
}
/// The time from `earlier` to `self`, or zero if `earlier` is later.
pub fn duration_since(self, earlier: Self) -> Duration {
self.saturating_duration_since(earlier)
}
/// The time from `earlier` to `self`, or zero if `earlier` is later.
pub fn saturating_duration_since(self, earlier: Self) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default()
}
/// The time from `earlier` to `self`, or `None` if `earlier` is later.
pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
let nanos = i128::from(self.0) - i128::from(earlier.0);
u64::try_from(nanos).ok().map(Duration::from_nanos)
}
/// The time since this reading, with the suspend behavior of the selected
/// backend described at module level.
pub fn elapsed(self) -> Duration {
Self::now().duration_since(self)
}
/// `self + duration`, or `None` beyond the clock's range, about 292 years
/// either side of its origin.
pub fn checked_add(self, duration: Duration) -> Option<Self> {
Self::from_nanos(i128::from(self.0) + nanos(duration)?)
}
/// `self - duration`, or `None` beyond the clock's range, about 292 years
/// either side of its origin.
pub fn checked_sub(self, duration: Duration) -> Option<Self> {
Self::from_nanos(i128::from(self.0) - nanos(duration)?)
}
fn from_nanos(nanos: i128) -> Option<Self> {
i64::try_from(nanos).ok().map(Self)
}
}
fn nanos(duration: Duration) -> Option<i128> {
i128::try_from(duration.as_nanos()).ok()
}
/// # Panics
///
/// Beyond the clock's range, as `std::time::Instant` does.
impl Add<Duration> for ContinuousInstant {
type Output = Self;
fn add(self, duration: Duration) -> Self {
self.checked_add(duration)
.expect("overflow when adding duration to instant")
}
}
impl AddAssign<Duration> for ContinuousInstant {
fn add_assign(&mut self, duration: Duration) {
*self = *self + duration;
}
}
/// # Panics
///
/// Beyond the clock's range, as `std::time::Instant` does.
impl Sub<Duration> for ContinuousInstant {
type Output = Self;
fn sub(self, duration: Duration) -> Self {
self.checked_sub(duration)
.expect("overflow when subtracting duration from instant")
}
}
impl SubAssign<Duration> for ContinuousInstant {
fn sub_assign(&mut self, duration: Duration) {
*self = *self - duration;
}
}
/// The time from `earlier` to `self`, or zero if `earlier` is later.
impl Sub for ContinuousInstant {
type Output = Duration;
fn sub(self, earlier: Self) -> Duration {
self.duration_since(earlier)
}
}
#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
mod backend {
#[cfg(any(target_os = "linux", target_os = "android"))]
const CLOCK: libc::clockid_t = libc::CLOCK_BOOTTIME;
#[cfg(target_vendor = "apple")]
const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC_RAW;
// `time_t` and `c_long` are 32 bits wide on some of these targets.
#[allow(clippy::useless_conversion)]
pub(super) fn now_nanos() -> i64 {
let mut now = std::mem::MaybeUninit::<libc::timespec>::uninit();
// SAFETY: `now` is valid for writes of a timespec for the whole call.
let result = unsafe { libc::clock_gettime(CLOCK, now.as_mut_ptr()) };
assert_eq!(
result,
0,
"clock_gettime failed: {}",
std::io::Error::last_os_error()
);
// SAFETY: a successful `clock_gettime` filled in `now`.
let now = unsafe { now.assume_init() };
i64::from(now.tv_sec) * 1_000_000_000 + i64::from(now.tv_nsec)
}
}
#[cfg(windows)]
mod backend {
use std::sync::OnceLock;
use windows_sys::Win32::System::Performance::{
QueryPerformanceCounter, QueryPerformanceFrequency,
};
fn frequency() -> i64 {
static FREQUENCY: OnceLock<i64> = OnceLock::new();
*FREQUENCY.get_or_init(|| {
let mut frequency = 0;
// SAFETY: `frequency` is a valid, writable i64 for the whole call.
let succeeded = unsafe { QueryPerformanceFrequency(&mut frequency) } != 0;
assert!(
succeeded && frequency > 0,
"QueryPerformanceFrequency failed"
);
frequency
})
}
pub(super) fn now_nanos() -> i64 {
let mut counter = 0;
// SAFETY: `counter` is a valid, writable i64 for the whole call.
let succeeded = unsafe { QueryPerformanceCounter(&mut counter) } != 0;
assert!(succeeded, "QueryPerformanceCounter failed");
let nanos = i128::from(counter) * 1_000_000_000 / i128::from(frequency());
i64::try_from(nanos).expect("performance counter beyond the clock's range")
}
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
windows
)))]
mod backend {
use std::sync::OnceLock;
use std::time::Instant;
pub(super) fn now_nanos() -> i64 {
static ORIGIN: OnceLock<Instant> = OnceLock::new();
let origin = *ORIGIN.get_or_init(Instant::now);
i64::try_from(origin.elapsed().as_nanos()).expect("clock beyond its range")
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn readings_never_go_backwards() {
let mut last = ContinuousInstant::now();
for _ in 0..10_000 {
let now = ContinuousInstant::now();
assert!(now >= last, "{now:?} after {last:?}");
last = now;
}
}
/// While the system is awake the clock keeps `Instant`'s rate, which
/// catches a backend's unit or scaling mistake. Each reading is bracketed
/// by two `Instant` readings, so a preemption widens the bounds instead of
/// failing the check.
#[test]
fn it_runs_at_instants_rate_while_awake() {
let bracketed = || {
let before = std::time::Instant::now();
let reading = ContinuousInstant::now();
(before, reading, std::time::Instant::now())
};
let (start_before, start, start_after) = bracketed();
std::thread::sleep(Duration::from_millis(200));
let (end_before, end, end_after) = bracketed();
let advance = (end - start).as_secs_f64();
let shortest = end_before.duration_since(start_after).as_secs_f64();
let longest = end_after.duration_since(start_before).as_secs_f64();
assert!(
(shortest * 0.95..=longest * 1.05).contains(&advance),
"advanced {advance}s while Instant advanced {shortest}s to {longest}s"
);
}
#[test]
fn backdating_never_underflows() {
let now = ContinuousInstant::now();
let century = Duration::from_secs(100 * 365 * 24 * 3600);
let past = now - century;
assert!(past < now);
assert_eq!(now.duration_since(past), century);
let later = ContinuousInstant::now();
assert_eq!(later - past - (later - now), century);
}
#[test]
fn a_later_earlier_reading_saturates() {
let (earlier, later) = (ContinuousInstant(-5), ContinuousInstant(7));
assert_eq!(later - earlier, Duration::from_nanos(12));
assert_eq!(earlier - later, Duration::ZERO);
assert_eq!(earlier.duration_since(later), Duration::ZERO);
assert_eq!(earlier.saturating_duration_since(later), Duration::ZERO);
assert_eq!(earlier.checked_duration_since(later), None);
assert_eq!(later.checked_duration_since(later), Some(Duration::ZERO));
}
#[test]
fn arithmetic_beyond_the_range_is_none() {
let (min, max) = (ContinuousInstant(i64::MIN), ContinuousInstant(i64::MAX));
assert_eq!(max.checked_add(Duration::from_nanos(1)), None);
assert_eq!(min.checked_sub(Duration::from_nanos(1)), None);
assert_eq!(ContinuousInstant(0).checked_add(Duration::MAX), None);
assert_eq!(ContinuousInstant(0).checked_sub(Duration::MAX), None);
assert_eq!(
max.checked_duration_since(min),
Some(Duration::from_nanos(u64::MAX))
);
}
#[test]
#[should_panic(expected = "overflow when adding duration to instant")]
fn adding_beyond_the_range_panics() {
let _ = ContinuousInstant(i64::MAX) + Duration::from_nanos(1);
}
#[test]
#[should_panic(expected = "overflow when subtracting duration from instant")]
fn subtracting_beyond_the_range_panics() {
let _ = ContinuousInstant(i64::MIN) - Duration::from_nanos(1);
}
#[test]
fn assigning_operators_match_the_plain_ones() {
let start = ContinuousInstant(1_000);
let mut moved = start;
moved += Duration::from_nanos(250);
assert_eq!(moved, start + Duration::from_nanos(250));
moved -= Duration::from_nanos(500);
assert_eq!(moved, start - Duration::from_nanos(250));
}
proptest! {
#[test]
fn a_duration_added_is_the_duration_measured(origin in any::<i64>(), nanos in any::<u64>()) {
let start = ContinuousInstant(origin);
let duration = Duration::from_nanos(nanos);
match start.checked_add(duration) {
Some(end) => {
prop_assert_eq!(end - start, duration);
prop_assert_eq!(end.checked_sub(duration), Some(start));
prop_assert_eq!(start.saturating_duration_since(end), Duration::ZERO);
prop_assert_eq!(
start.checked_duration_since(end),
(nanos == 0).then_some(Duration::ZERO)
);
}
None => prop_assert!(i128::from(origin) + i128::from(nanos) > i128::from(i64::MAX)),
}
}
#[test]
fn a_duration_subtracted_is_the_duration_measured(origin in any::<i64>(), nanos in any::<u64>()) {
let end = ContinuousInstant(origin);
let duration = Duration::from_nanos(nanos);
match end.checked_sub(duration) {
Some(start) => {
prop_assert_eq!(end.duration_since(start), duration);
prop_assert_eq!(start.checked_add(duration), Some(end));
}
None => prop_assert!(i128::from(origin) - i128::from(nanos) < i128::from(i64::MIN)),
}
}
}
}
+7 -5
View File
@@ -42,7 +42,7 @@ pub const TRAFFIC_TIMEOUT_FLOOR_MS: u64 = 5;
pub const MODE_AES128_CBC: u8 = 0x00;
/// Default: AES-256-CBC.
pub const MODE_AES256_CBC: u8 = 0x01;
/// Reserved for future AES-256-GCM support.
/// Reserved AES-256-GCM identifier; not accepted by current Link endpoints.
pub const MODE_AES256_GCM: u8 = 0x02;
pub const MODE_OTP_RESERVED: u8 = 0x03;
pub const MODE_PQ_RESERVED_1: u8 = 0x04;
@@ -50,7 +50,8 @@ pub const MODE_PQ_RESERVED_2: u8 = 0x05;
pub const MODE_PQ_RESERVED_3: u8 = 0x06;
pub const MODE_PQ_RESERVED_4: u8 = 0x07;
/// Encryption modes accepted by this implementation; others are advertised-but-refused.
/// Encryption modes accepted by [`crate::link::Link`] endpoints. Other mode
/// identifiers are representable on the wire but rejected by those endpoints.
pub const ENABLED_MODES: &[u8] = &[MODE_AES256_CBC];
pub const DEFAULT_MODE: u8 = MODE_AES256_CBC;
@@ -67,13 +68,14 @@ pub const ACCEPT_ALL: u8 = 0x02;
/// Low 21 bits of the 24-bit MTU signalling value carry the MTU.
pub const MTU_BYTEMASK: u32 = 0x001F_FFFF;
/// Bits 21-23 of the MTU signalling value carry the encryption mode.
/// Mask for mode bits 5–7 of the first signalling byte. In the full 24-bit
/// big-endian signalling value, those are bits 21–23 (mask `0xE00000`).
pub const MODE_BYTEMASK: u32 = 0x00E0;
/// Derived key length for AES-256-CBC: 32 bytes cipher key || 32 bytes HMAC key.
/// Derived key length for AES-256-CBC: 32-byte HMAC key || 32-byte cipher key.
pub const AES256_DERIVED_KEY_LENGTH: usize = 64;
/// Derived key length for AES-128-CBC: 16 bytes cipher key || 16 bytes HMAC key.
/// Derived key length for AES-128-CBC: 16-byte HMAC key || 16-byte cipher key.
pub const AES128_DERIVED_KEY_LENGTH: usize = 32;
/// Seconds of slack granted to a response beyond its nominal transfer time.
+3 -2
View File
@@ -18,8 +18,9 @@ pub fn link_encrypt(keys: &LinkKeys, plaintext: &[u8]) -> Result<Vec<u8>, LinkCr
/// Decrypt a ciphertext frame with the link's session keys.
///
/// Errors are deliberately opaque — padding and HMAC failures are indistinguishable
/// to callers so timing side channels cannot leak which check failed.
/// All token errors map to `DecryptionFailed`, so the error value does not
/// distinguish padding, HMAC, or key-length failure. This error mapping alone
/// is not a guarantee of identical execution time for every invalid input.
pub fn link_decrypt(keys: &LinkKeys, ciphertext: &[u8]) -> Result<Vec<u8>, LinkCryptoError> {
let mut combined_key = Zeroizing::new(Vec::with_capacity(
keys.signing_key.len() + keys.encryption_key.len(),
+47 -9
View File
@@ -49,7 +49,8 @@ impl EphemeralKeys {
/// Link request payload (Message 1: initiator -> destination).
///
/// Wire format: `X25519_pub(32) || Ed25519_pub(32) || signalling(3)` — 67 bytes.
/// Modern wire format: `X25519_pub(32) || Ed25519_pub(32) || signalling(3)`
/// (67 bytes). Parsing also accepts the 64-byte legacy form without signalling.
#[derive(Debug, Clone)]
pub struct LinkRequestData {
pub peer_x25519_pub: [u8; 32],
@@ -69,8 +70,9 @@ impl LinkRequestData {
/// Parse a link request payload.
///
/// Python accepts exactly the legacy 64-byte key payload or the modern
/// 67-byte key payload with signalling. Other lengths are dropped.
/// Accepts exactly the legacy 64-byte key payload or modern 67-byte
/// payload, and validates the signalled MTU domain. It does not authenticate
/// the keys or enforce the endpoint's enabled cipher modes.
pub fn unpack(data: &[u8]) -> Result<Self, HandshakeError> {
if data.len() < ECPUBSIZE {
return Err(HandshakeError::TooShort);
@@ -79,6 +81,7 @@ impl LinkRequestData {
return Err(HandshakeError::InvalidLength(data.len()));
}
rns_wire::link_signalling::parse_request_signalling(data)?;
let mut x25519_pub = [0u8; 32];
x25519_pub.copy_from_slice(&data[0..32]);
@@ -105,7 +108,9 @@ impl LinkRequestData {
///
/// The hashable body is `flags_low_nibble || dest_hash || context || data[..ECPUBSIZE]`
/// — the signalling trailer is intentionally excluded so both sides agree on the same
/// link ID regardless of MTU/mode negotiation.
/// link ID regardless of MTU/mode signalling. The flags are fixed to a SINGLE
/// LINKREQUEST with context NONE. Short payloads are hashed as supplied;
/// validate request shape separately with [`LinkRequestData::unpack`].
pub fn compute_link_id(destination_hash: &[u8; 16], request_data: &[u8]) -> [u8; 16] {
// LinkRequest(0x02) | DestinationType::Single(0x00); context is PacketContext::None.
let flags_low_nibble = 0x02u8;
@@ -122,6 +127,11 @@ pub fn compute_link_id(destination_hash: &[u8; 16], request_data: &[u8]) -> [u8;
}
/// Compute the link ID from a full raw packet (for transport relay paths).
/// The caller supplies a validated packet and its matching header type.
///
/// # Panics
///
/// Panics if `raw` is empty; see [`rns_wire::hash::link_id_from_raw`].
pub fn compute_link_id_from_raw(raw: &[u8], header_type: rns_wire::flags::HeaderType) -> [u8; 16] {
rns_wire::hash::link_id_from_raw(raw, header_type)
}
@@ -131,6 +141,11 @@ pub fn compute_link_id_from_raw(raw: &[u8], header_type: rns_wire::flags::Header
/// Wire format: `signature(64) || X25519_pub(32) || signalling(3)` — 99 bytes.
/// The signature covers `link_id || responder_x25519_pub || identity_ed25519_pub || signalling`
/// under the destination's long-term identity Ed25519 key.
///
/// Parsing also accepts a 96-byte legacy body, but this representation does
/// not preserve trailer absence. Its `pack` and `validate` methods use the
/// modern three-byte trailer. Use [`crate::link::Link::validate_proof`] with
/// the original bytes to validate legacy or modern incoming proofs.
#[derive(Debug, Clone)]
pub struct LinkProofData {
pub signature: [u8; 64],
@@ -208,7 +223,9 @@ impl LinkProofData {
}
/// Parse a proof payload, accepting exactly 96-byte legacy frames or
/// 99-byte frames with signalling.
/// 99-byte frames with signalling. Validates the MTU domain but not the
/// signature or endpoint mode policy. A legacy body receives default
/// signalling in this representation; see [`LinkProofData`].
pub fn unpack(data: &[u8]) -> Result<Self, HandshakeError> {
if data.len() < 96 {
return Err(HandshakeError::TooShort);
@@ -217,6 +234,7 @@ impl LinkProofData {
return Err(HandshakeError::InvalidLength(data.len()));
}
rns_wire::link_signalling::parse_proof_signalling(data)?;
let mut signature = [0u8; 64];
signature.copy_from_slice(&data[0..64]);
@@ -239,7 +257,10 @@ impl LinkProofData {
})
}
/// Verify the proof signature against the destination's identity public key.
/// Verify a modern proof signature, including this representation's trailer.
/// `peer_ed25519_pub` must be the destination identity bytes corresponding
/// to `identity_verify_key`. For an incoming legacy proof, use
/// [`crate::link::Link::validate_proof`] with the original packet payload.
pub fn validate(
&self,
identity_verify_key: &Ed25519PublicKey,
@@ -259,7 +280,9 @@ impl LinkProofData {
}
}
/// Perform the ECDH handshake and derive session keys.
/// Perform ECDH and derive session keys. This primitive does not authenticate
/// a handshake proof or enforce the current endpoint admission policy; see
/// [`LinkKeys::derive`] for its supported modes and input responsibilities.
pub fn perform_handshake(
my_x25519_prv: &X25519PrivateKey,
peer_x25519_pub_bytes: &[u8; 32],
@@ -272,6 +295,8 @@ pub fn perform_handshake(
#[derive(Debug, thiserror::Error)]
pub enum HandshakeError {
#[error(transparent)]
Signalling(#[from] rns_wire::link_signalling::LinkSignallingError),
#[error("handshake data too short")]
TooShort,
#[error("invalid handshake data length: {0}")]
@@ -527,7 +552,7 @@ mod tests {
x25519_pub: [u8; 32],
ed25519_pub: [u8; 32],
mode in 0u8..=7,
mtu in 0u32..=crate::constants::MTU_BYTEMASK,
mtu in prop_oneof![Just(0u32), 500u32..=crate::constants::MTU_BYTEMASK],
) {
let signalling = SignallingData::new(mode, mtu);
// EphemeralKeys is the higher-level wrapper; we pack the
@@ -553,7 +578,7 @@ mod tests {
signature: [u8; 64],
responder_x25519_pub: [u8; 32],
mode in 0u8..=7,
mtu in 0u32..=crate::constants::MTU_BYTEMASK,
mtu in prop_oneof![Just(0u32), 500u32..=crate::constants::MTU_BYTEMASK],
) {
let signalling = SignallingData::new(mode, mtu);
let proof = LinkProofData {
@@ -570,5 +595,18 @@ mod tests {
prop_assert_eq!(unpacked.signalling, signalling);
prop_assert_eq!(unpacked.pack(), packed);
}
/// The representation packer remains permissive, but both handshake
/// parsers reject every nonzero offer below the supported Link floor.
#[test]
fn proptest_handshake_rejects_sub_base_mtu(mode in 0u8..=7, mtu in 1u32..500) {
let signalling = SignallingData::new(mode, mtu).pack();
let mut request = vec![0u8; ECPUBSIZE];
request.extend_from_slice(&signalling);
prop_assert!(LinkRequestData::unpack(&request).is_err());
let mut proof = vec![0u8; 96];
proof.extend_from_slice(&signalling);
prop_assert!(LinkProofData::unpack(&proof).is_err());
}
}
}
+5 -2
View File
@@ -4,7 +4,9 @@ use crate::constants::*;
/// Keepalive timing state for a single link.
///
/// Only the initiator side schedules keepalives; the responder simply echoes them.
/// Only the initiator schedules requests. The responder can suppress a reply
/// when it has sent other traffic within the keepalive interval. The owner
/// records activity and sends any required frames.
#[derive(Debug, Clone)]
pub struct KeepaliveState {
pub keepalive_interval: Duration,
@@ -46,7 +48,8 @@ impl KeepaliveState {
/// Rescale the keepalive interval after a new RTT measurement.
///
/// Interval scales linearly with RTT up to `KEEPALIVE_MAX_RTT`, then saturates.
/// Interval scales linearly with RTT, clamped to `KEEPALIVE_MIN` through
/// `KEEPALIVE_MAX`; it reaches the upper limit at `KEEPALIVE_MAX_RTT`.
/// Jitter is re-rolled so the ±10% spread is relative to the new interval.
pub fn update_from_rtt(&mut self, rtt: Duration) {
let rtt_secs = rtt.as_secs_f64();
+9 -4
View File
@@ -1,14 +1,15 @@
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use zeroize::{Zeroize, Zeroizing};
use zeroize::Zeroize;
use crate::constants::{
AES128_DERIVED_KEY_LENGTH, AES256_DERIVED_KEY_LENGTH, MODE_AES128_CBC, MODE_AES256_CBC,
};
/// Derived session keys for a link.
/// Symmetric session keys shared by both directions of a Link. Cloning copies
/// the key material; each owned copy is zeroised when dropped.
#[derive(Clone)]
pub struct LinkKeys {
/// HMAC-SHA256 signing key.
/// HMAC-SHA256 authentication key, distinct from an Ed25519 signing key.
pub signing_key: Vec<u8>,
/// AES encryption key.
pub encryption_key: Vec<u8>,
@@ -20,6 +21,10 @@ impl LinkKeys {
/// Runs `HKDF-SHA256(ECDH(my_prv, peer_pub), salt = link_id)` and splits the
/// output into `signing_key || encryption_key`. Intermediate shared secrets
/// are zeroized as soon as HKDF consumes them.
///
/// This primitive accepts AES-128-CBC and AES-256-CBC; endpoint admission
/// is narrower (see [`crate::constants::ENABLED_MODES`]). It does not
/// authenticate the peer or reject an all-zero X25519 shared secret.
pub fn derive(
my_prv: &X25519PrivateKey,
peer_pub: &X25519PublicKey,
@@ -38,7 +43,7 @@ impl LinkKeys {
rns_crypto::hkdf::hkdf_sha256(derived_key_length, &shared_key, Some(link_id), None)
.map_err(|_| LinkKeyError::HkdfFailed);
shared_key.zeroize();
let derived = Zeroizing::new(derived_result?);
let derived = derived_result?;
let half = derived_key_length / 2;
let signing_key = derived[..half].to_vec();
+5 -2
View File
@@ -1,7 +1,10 @@
//! Encrypted point-to-point Links between two Reticulum destinations.
//! LR/LRPROOF handshake → AES-256 + HMAC-SHA256 session, MTU discovery,
//! keepalives, request/response. Python reference: `RNS/Link.py`.
//! LR/LRPROOF handshake, AES-256-CBC + HMAC-SHA256 sessions, checked MTU
//! signalling, keepalives, and request/response. Current [`link::Link`] endpoints
//! use the 500-byte base MTU; representable signalling offers are a wider domain.
//! The owning runtime sends packets, drives ticks, and dispatches Link callbacks.
pub mod clock;
pub mod constants;
pub mod encryption;
pub mod handshake;
+314 -138
View File
@@ -11,7 +11,7 @@ use crate::handshake::{
};
use crate::keepalive::KeepaliveState;
use crate::key_derivation::LinkKeys;
use crate::mtu_discovery::SignallingData;
use crate::mtu_discovery::{LinkMtu, SignallingData};
use crate::request::RequestReceipt;
/// Link lifecycle states.
@@ -25,11 +25,12 @@ pub enum LinkState {
Active = 0x02,
/// No inbound traffic for `stale_time`.
Stale = 0x03,
/// Link torn down and keys purged.
/// Link torn down and its owned keys purged. External key copies remain
/// the responsibility of their owners.
Closed = 0x04,
}
/// The local endpoint's immutable role in a Link session.
/// The local endpoint's role, fixed by construction for a valid Link session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkRole {
Initiator,
@@ -55,6 +56,11 @@ pub enum PacketProofError {
InvalidSignature,
}
/// Local timeout input cannot be represented without overflow.
#[derive(Debug, thiserror::Error, Clone, Copy, PartialEq, Eq)]
#[error("timeout must be finite, nonnegative and representable by this platform")]
pub struct TimeoutError;
/// Reason for link closure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CloseReason {
@@ -102,7 +108,8 @@ pub enum OutboundResourceState {
Failed,
}
/// The result of a `request()` call indicating how the request should be sent.
/// Size classification returned by [`Link::classify_request`].
/// The contained bytes remain plaintext and have not been sent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RequestSendMode {
/// Request fits in a single packet (data size <= MDU).
@@ -150,7 +157,10 @@ fn peer_reported_rtt(secs: f64) -> Option<Duration> {
/// An encrypted bidirectional tunnel between two peers.
///
/// The state machine is driven by `tick()` calls from the owning actor/runtime;
/// there is no internal watchdog thread.
/// there is no internal watchdog thread. It uses `std::time::Instant` for
/// state deadlines. The owner handles transport, peer-key trust, callback
/// dispatch and packet-size admission. Keep public role, ID, mode and budget
/// fields consistent with construction; changing them does not renegotiate a Link.
pub struct Link {
/// Truncated SHA-256 of the request's hashable part.
pub link_id: [u8; 16],
@@ -160,6 +170,8 @@ pub struct Link {
pub teardown_reason: Option<CloseReason>,
pub is_initiator: bool,
pub mode: u8,
offered_mode: u8,
offered_mtu: LinkMtu,
ephemeral_keys: Option<EphemeralKeys>,
peer_x25519_pub: Option<[u8; 32]>,
@@ -217,24 +229,29 @@ pub struct Link {
pub rssi: Option<f64>,
/// Signal-to-noise ratio in dB.
pub snr: Option<f64>,
/// Link quality indicator in `[0.0, 1.0]`.
/// Caller/interface-supplied quality value. Stored without normalization
/// or clamping; its scale depends on the source interface.
pub q: Option<f64>,
track_phy_stats: bool,
pub has_channel: bool,
pub packet_callback: Option<PacketCallback>,
/// Called when a resource transfer begins; returns `true` to accept.
/// Stored acceptance callback for an owner that dispatches it. Link itself
/// does not invoke this callback; [`Self::should_accept_resource`] returns
/// the configured strategy without calling it.
pub resource_callback: Option<ResourceCallback>,
pub remote_identified_callback: Option<RemoteIdentifiedCallback>,
/// Fires when the link transitions to `Active`.
/// Stored activation callback. The owner dispatches it; state transitions
/// in this type do not invoke Link lifecycle callbacks themselves.
pub link_established_callback: Option<LinkCallback>,
pub link_closed_callback: Option<LinkCallback>,
}
/// Callback for decrypted link-packet payloads.
pub type PacketCallback = Box<dyn Fn(&[u8]) + Send + Sync>;
/// Callback for accepting or rejecting an incoming resource transfer.
/// Owner-dispatched Resource acceptance callback. Its boolean input is supplied
/// by that owner; `true` as the return value means acceptance.
pub type ResourceCallback = Box<dyn Fn(bool) -> bool + Send + Sync>;
/// Callback fired after the remote peer identifies on the link.
pub type RemoteIdentifiedCallback = Box<dyn Fn(&Link, &[u8; 64]) + Send + Sync>;
@@ -274,6 +291,8 @@ impl Link {
teardown_reason: None,
is_initiator: true,
mode: DEFAULT_MODE,
offered_mode: DEFAULT_MODE,
offered_mtu: LinkMtu::BASE,
ephemeral_keys: Some(ephemeral_keys),
peer_x25519_pub: None,
peer_packet_proof_key: None,
@@ -320,14 +339,32 @@ impl Link {
}
/// Extend the establishment timeout, typically by the transport's first-hop RTT.
#[deprecated(note = "use try_extend_establishment_timeout to report invalid input")]
pub fn extend_establishment_timeout(&mut self, additional_secs: f64) {
self.establishment_timeout += Duration::from_secs_f64(additional_secs);
let _ = self.try_extend_establishment_timeout(additional_secs);
}
pub fn try_extend_establishment_timeout(
&mut self,
additional_secs: f64,
) -> Result<(), TimeoutError> {
let additional = Duration::try_from_secs_f64(additional_secs).map_err(|_| TimeoutError)?;
let timeout = self
.establishment_timeout
.checked_add(additional)
.ok_or(TimeoutError)?;
self.request_time.checked_add(timeout).ok_or(TimeoutError)?;
self.establishment_timeout = timeout;
Ok(())
}
/// Handle a received link proof (initiator side, Message 2).
///
/// Verifies the signature, runs ECDH, derives session keys, and returns the
/// encrypted RTT measurement (Message 3) to hand back to the responder.
/// The caller must supply the authenticated destination identity key and
/// its matching Ed25519 public bytes. Success activates the local initiator;
/// it does not transmit the RTT payload or dispatch lifecycle callbacks.
pub fn validate_proof(
&mut self,
proof_data: &[u8],
@@ -338,90 +375,68 @@ impl Link {
return Err(HandshakeError::InvalidSignature);
}
// LRPROOF is unauthenticated until its signature validates. Reject a
// mismatched mode without mutating the pending Link, otherwise any
// party that learns the link id could cancel establishment before the
// legitimate proof arrives.
if proof_data.len() > 96 {
let proof_mode = (proof_data[96] & MODE_BYTEMASK as u8) >> 5;
if proof_mode != self.mode {
return Err(HandshakeError::InvalidSignature);
}
let checked = rns_wire::link_signalling::parse_proof_signalling(proof_data)?;
if checked.mode != self.offered_mode {
return Err(HandshakeError::InvalidSignature);
}
if !ENABLED_MODES.contains(&checked.mode) {
return Err(HandshakeError::UnsupportedMode(checked.mode));
}
if checked.mtu > self.offered_mtu {
return Err(rns_wire::link_signalling::LinkSignallingError::InvalidMtu(
checked.mtu.get(),
)
.into());
}
let mdu = checked.mtu.checked_mdu()?;
let proof = LinkProofData::unpack(proof_data)?;
if proof.signalling.mode != self.mode {
// Authenticate the original trailer, including zero or exact absence.
// Normalizing metadata must never change bytes covered by the signature.
let mut signed = Vec::with_capacity(83);
signed.extend_from_slice(&self.link_id);
signed.extend_from_slice(&proof.responder_x25519_pub);
signed.extend_from_slice(identity_ed25519_pub_bytes);
signed.extend_from_slice(&proof_data[96..]);
if identity_verify_key
.verify(&signed, &proof.signature)
.is_err()
{
return Err(HandshakeError::InvalidSignature);
}
// Verify the signature before deriving session keys so we never hold keys
// tied to an unvalidated proof, even transiently. Invalid proofs leave
// the initiator Pending so another interface can still deliver the
// authentic proof before the establishment timeout.
if !proof.validate(
identity_verify_key,
&self.link_id,
identity_ed25519_pub_bytes,
) {
return Err(HandshakeError::InvalidSignature);
}
self.establishment_cost += proof_data.len();
self.peer_x25519_pub = Some(proof.responder_x25519_pub);
self.peer_packet_proof_key = Some(*identity_ed25519_pub_bytes);
let ephemeral = self
.ephemeral_keys
.as_ref()
.ok_or(HandshakeError::InvalidSignature)?;
let keys = perform_handshake(
&ephemeral.x25519_prv,
&proof.responder_x25519_pub,
&self.link_id,
self.mode,
checked.mode,
)?;
self.session_keys = Some(keys);
self.state = LinkState::Handshake;
tracing::debug!(link_id = ?self.link_id, "link state -> Handshake (initiator)");
let rtt = self.request_time.elapsed();
let mut rtt_bytes = Vec::new();
rmpv::encode::write_value(&mut rtt_bytes, &rmpv::Value::F64(rtt.as_secs_f64()))
.map_err(|_| HandshakeError::InvalidSignature)?;
let encrypted_rtt =
link_encrypt(&keys, &rtt_bytes).map_err(|_| HandshakeError::InvalidSignature)?;
// All fallible validation/crypto work completes before pending state,
// key ownership, timing or accounting is changed.
self.establishment_cost = self.establishment_cost.saturating_add(proof_data.len());
self.peer_x25519_pub = Some(proof.responder_x25519_pub);
self.peer_packet_proof_key = Some(*identity_ed25519_pub_bytes);
self.session_keys = Some(keys);
self.mode = checked.mode;
self.mtu = checked.mtu.get();
self.mdu = mdu;
self.rtt = Some(rtt);
self.state = LinkState::Active;
self.activated_at = Some(Instant::now());
tracing::debug!(
link_id = ?self.link_id,
rtt_ms = rtt.as_millis() as u64,
"link state -> Active (initiator)"
);
// Seed the keepalive baseline so stale detection starts from activation.
self.keepalive.mark_activated();
let rtt_secs_val = rtt.as_secs_f64();
if rtt_secs_val > 0.0 && self.establishment_cost > 0 {
self.establishment_rate = Some(self.establishment_cost as f64 / rtt_secs_val);
}
self.keepalive.update_from_rtt(rtt);
if proof.signalling.mtu > 0 {
self.mtu = self.mtu.min(proof.signalling.mtu);
if rtt.as_secs_f64() > 0.0 {
self.establishment_rate = Some(self.establishment_cost as f64 / rtt.as_secs_f64());
}
self.update_mdu();
// RTT is carried as a msgpack f64 so both ends see the same encoding.
let rtt_secs = rtt.as_secs_f64();
let mut rtt_bytes = Vec::new();
rmpv::encode::write_value(&mut rtt_bytes, &rmpv::Value::F64(rtt_secs))
.map_err(|_| HandshakeError::InvalidSignature)?;
let encrypted_rtt = self
.encrypt(&rtt_bytes)
.map_err(|_| HandshakeError::InvalidSignature)?;
tracing::debug!(link_id = ?self.link_id, rtt_ms = rtt.as_millis() as u64, "link state -> Active (initiator)");
Ok(encrypted_rtt)
}
@@ -491,10 +506,14 @@ impl Link {
let request = LinkRequestData::unpack(request_data)?;
let link_id = compute_link_id(&destination_hash, request_data);
if request.signalling.mode != MODE_AES128_CBC && request.signalling.mode != MODE_AES256_CBC
{
if !ENABLED_MODES.contains(&request.signalling.mode) {
return Err(HandshakeError::UnsupportedMode(request.signalling.mode));
}
// Current host endpoints are deliberately base-only; transit upgrade
// support does not imply high-MTU Resource support at an endpoint.
let offered = LinkMtu::try_from_signal(Some(request.signalling.mtu))?;
let accepted_mtu = offered.min(LinkMtu::BASE);
let accepted_mdu = accepted_mtu.checked_mdu()?;
let responder_keys = EphemeralKeys::generate();
@@ -507,8 +526,7 @@ impl Link {
// The proof binds the link to the responder's long-term identity key, not
// its ephemeral one — that's what lets the initiator authenticate us.
let signalling =
SignallingData::new(request.signalling.mode, rns_wire::constants::MTU as u32);
let signalling = SignallingData::try_new(request.signalling.mode, accepted_mtu.get())?;
let responder_x25519_pub = responder_keys.x25519_pub.to_bytes();
let sig_bytes = signalling.pack();
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3);
@@ -535,6 +553,8 @@ impl Link {
teardown_reason: None,
is_initiator: false,
mode: request.signalling.mode,
offered_mode: request.signalling.mode,
offered_mtu: accepted_mtu,
ephemeral_keys: Some(responder_keys),
peer_x25519_pub: Some(request.peer_x25519_pub),
peer_packet_proof_key: Some(request.peer_ed25519_pub),
@@ -547,8 +567,8 @@ impl Link {
activated_at: None,
stale_since: None,
keepalive: KeepaliveState::new(false),
mtu: request.signalling.mtu.min(rns_wire::constants::MTU as u32),
mdu: rns_wire::constants::LINK_MDU,
mtu: accepted_mtu.get(),
mdu: accepted_mdu,
resource_strategy: ResourceStrategy::default(),
pending_requests: Vec::new(),
incoming_resources: Vec::new(),
@@ -588,6 +608,7 @@ impl Link {
return Err(HandshakeError::InvalidSignature);
}
let mdu = LinkMtu::try_from_signal(Some(self.mtu))?.checked_mdu()?;
self.establishment_cost += encrypted_data.len();
let plaintext = self
@@ -607,7 +628,7 @@ impl Link {
self.state = LinkState::Active;
self.activated_at = Some(Instant::now());
self.keepalive.mark_activated();
self.update_mdu();
self.mdu = mdu;
tracing::debug!(link_id = ?self.link_id, "link state -> Active (responder)");
if let Some(rtt) = self.rtt {
@@ -620,7 +641,9 @@ impl Link {
Ok(())
}
/// AES-CBC encrypt with the initiator-to-responder session key.
/// AES-CBC encrypt with the shared bidirectional session keys.
/// Requires keys, but does not check active state, enforce the MDU, send a
/// packet, or update traffic counters.
pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, LinkCryptoError> {
let keys = self
.session_keys
@@ -640,7 +663,7 @@ impl Link {
/// Build a LINKIDENTIFY payload that reveals the initiator's identity.
///
/// Wire format (after encryption): `public_key(64) || signature(64)`, where
/// Plaintext before encryption: `public_key(64) || signature(64)`, where
/// the signature covers `link_id(16) || public_key(64)`. Send with context
/// LINKIDENTIFY (0xFB).
pub fn identify(
@@ -694,11 +717,22 @@ impl Link {
}
/// Verify a received LINKIDENTIFY and record the remote identity key.
///
/// As in Python's `Link.receive`, only a responder accepts it, from the
/// handshake on: the initiator turns Active on the proof and may identify
/// before its RTT packet arrives. The first valid identity is retained;
/// subsequent valid identifications return the existing key. The owner
/// handles callbacks and any application admission policy.
pub fn handle_identification(
&mut self,
encrypted_data: &[u8],
) -> Result<[u8; 64], LinkCryptoError> {
if self.state != LinkState::Active {
if self.role() != LinkRole::Responder
|| !matches!(
self.state,
LinkState::Handshake | LinkState::Active | LinkState::Stale
)
{
return Err(LinkCryptoError::DecryptionFailed);
}
@@ -751,8 +785,10 @@ impl Link {
/// Build a REQUEST payload and return `(encrypted, request_id)`.
///
/// Plaintext is msgpack `[timestamp_f64, sha256_trunc(path), data]`. Send with
/// context REQUEST (0x09); the returned `request_id` matches what the remote
/// side will compute.
/// context REQUEST (0x09). The initial ID hashes the plaintext body. For an
/// inline packet, the owner must replace it with that packet's truncated
/// hash via [`Self::update_pending_request_id`]. Resource requests retain
/// the body hash. This method does not enforce the MDU or send data.
pub fn request(
&mut self,
path: &str,
@@ -773,6 +809,10 @@ impl Link {
///
/// Packet-sized callers encrypt the returned body directly. Bodies larger
/// than the Link MDU are passed to Resource with the returned request ID.
/// A complete MessagePack value in `data` is embedded as that value; other
/// bytes become a binary field. `None` becomes nil. Inline packet callers
/// replace the initial body-hash ID after packing the packet, as described
/// on [`Self::request`].
pub fn prepare_request(
&mut self,
path: &str,
@@ -909,7 +949,9 @@ impl Link {
}
}
/// Decrypt and parse a REQUEST packet into `(request_id, path_hash, timestamp, data)`.
/// Decrypt and parse a REQUEST body into `(request_id, path_hash, timestamp, data)`.
/// The returned ID hashes the plaintext body; an inline-packet dispatcher
/// uses the received packet's truncated hash as the actual request ID.
pub fn handle_request(
&self,
encrypted_data: &[u8],
@@ -922,7 +964,10 @@ impl Link {
///
/// 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.
/// so they use this parser directly. This parser checks the first three
/// array fields but accepts additional fields and trailing bytes; it does
/// not authorize a handler or validate timestamp freshness. Binary/string
/// payloads become raw bytes; other MessagePack values are re-encoded.
pub fn parse_request(plaintext: &[u8]) -> Result<ParsedRequestData, LinkCryptoError> {
// request_id = SHA-256(packed_request)[:16]
let request_id = truncated_hash(plaintext);
@@ -965,7 +1010,8 @@ impl Link {
}
/// Build plaintext msgpack `[request_id, response_data]` for a Link
/// response packet or response resource.
/// response packet or response resource. A complete MessagePack value in
/// `response_data` is embedded as that value; other bytes become binary.
pub fn pack_response(
request_id: &[u8; 16],
response_data: &[u8],
@@ -982,7 +1028,9 @@ impl Link {
}
/// Decrypt a RESPONSE payload, deliver it to the matching receipt, and return
/// `(request_id, response_data)`.
/// `(request_id, response_data)`. A well-formed response is returned even
/// when no pending receipt matches; successful parsing is not proof that a
/// request was completed.
pub fn handle_response(
&mut self,
encrypted_data: &[u8],
@@ -1006,7 +1054,9 @@ impl Link {
}
/// Parse plaintext MsgPack `[request_id, response_data]` without mutating
/// pending request state.
/// pending request state. Checks the first two array fields, accepts extra
/// fields and trailing bytes, and applies the same payload-byte conversion
/// as [`Self::parse_request`].
pub fn parse_response_plaintext(
plaintext: &[u8],
) -> Result<([u8; 16], Vec<u8>), LinkCryptoError> {
@@ -1085,7 +1135,8 @@ impl Link {
self.encrypt(&rtt_bytes)
}
/// Return this endpoint's immutable Link role.
/// Return the role selected by `is_initiator`. The owner must not change
/// that field during a session.
pub fn role(&self) -> LinkRole {
if self.is_initiator {
LinkRole::Initiator
@@ -1348,7 +1399,8 @@ impl Link {
}
}
/// Current PHY measurements as `(rssi, snr, q)`.
/// Current PHY measurements as `(rssi, snr, q)`. Returns three `None` values
/// when tracking is disabled, even if forced measurements were stored.
pub fn phy_stats(&self) -> (Option<f64>, Option<f64>, Option<f64>) {
let stats = self.phy_stats_snapshot();
(stats.rssi, stats.snr, stats.q)
@@ -1378,7 +1430,8 @@ impl Link {
self.track_phy_stats.then_some(self.q).flatten()
}
/// Clone of the session keys, for handing to a Channel or Resource.
/// Clone the session keys for a Channel or Resource. Closing this Link
/// drops its own keys, not copies already returned to callers.
pub fn session_keys(&self) -> Option<LinkKeys> {
self.session_keys.clone()
}
@@ -1568,7 +1621,8 @@ impl Link {
self.packet_callback = Some(Box::new(cb));
}
/// Install a callback invoked for each inbound resource; return `true` to accept.
/// Store a Resource acceptance callback for the owner to dispatch. This
/// setter does not connect it to a runtime or invoke it automatically.
pub fn set_resource_callback(&mut self, cb: impl Fn(bool) -> bool + Send + Sync + 'static) {
self.resource_callback = Some(Box::new(cb));
}
@@ -1588,21 +1642,6 @@ impl Link {
self.link_closed_callback = Some(Box::new(cb));
}
/// Recompute MDU from the current MTU.
///
/// MDU = `floor((mtu - header - token) / AES block) * AES block - 1`; the
/// trailing `-1` reserves room for PKCS7 padding worst case.
fn update_mdu(&mut self) {
let mtu = self.mtu as usize;
let overhead =
1 + rns_wire::constants::HEADER_MINSIZE + rns_wire::constants::TOKEN_OVERHEAD;
if mtu > overhead {
self.mdu = ((mtu - overhead) / rns_wire::constants::AES128_BLOCKSIZE)
* rns_wire::constants::AES128_BLOCKSIZE
- 1;
}
}
pub fn is_active(&self) -> bool {
self.state == LinkState::Active
}
@@ -1733,7 +1772,8 @@ impl Link {
}
}
/// Whether the link can accept a new outbound resource.
/// Whether the tracked outbound Resource states allow another transfer.
/// The owner must separately check Link state and admission limits.
///
/// Allows new transfers not just when the queue is empty but also when all
/// existing transfers have finished sending data and are only waiting on the
@@ -1763,6 +1803,7 @@ impl Link {
}
/// Default request timeout: `rtt * TRAFFIC_TIMEOUT_FACTOR + 1.125 * RESPONSE_MAX_GRACE_TIME`.
/// Uses a one-second RTT when none has been measured.
pub fn default_request_timeout(&self) -> Duration {
self.rtt
.unwrap_or(Duration::from_secs(1))
@@ -1950,39 +1991,116 @@ mod tests {
}
#[test]
fn test_responder_accepts_python_inbound_modes() {
let dest_hash = [0xA2; 16];
let identity_key = Ed25519PrivateKey::generate();
let (mut request_link, request_data) = Link::new_initiator(dest_hash, 1);
let mut aes128_request = request_data.clone();
aes128_request[64] = MODE_AES128_CBC << 5;
let (responder, proof) =
Link::new_responder(&aes128_request, &identity_key, dest_hash, 1).unwrap();
assert_eq!(responder.mode, MODE_AES128_CBC);
fn responder_mtu_boundary_matrix_is_base_only_and_never_wraps() {
let identity = Ed25519PrivateKey::generate();
let (_, request) = Link::new_initiator([5; 16], 1);
for mtu in 1..500 {
let mut candidate = request.clone();
candidate[64..].copy_from_slice(&SignallingData::new(DEFAULT_MODE, mtu).pack());
assert!(
Link::new_responder(&candidate, &identity, [5; 16], 1).is_err(),
"mtu {mtu}"
);
}
for mtu in [0, 500, 501, MTU_BYTEMASK] {
let mut candidate = request.clone();
candidate[64..].copy_from_slice(&SignallingData::new(DEFAULT_MODE, mtu).pack());
let (responder, proof) =
Link::new_responder(&candidate, &identity, [5; 16], 1).unwrap();
assert_eq!(responder.mtu, 500);
assert_eq!(responder.mdu, rns_wire::constants::LINK_MDU);
assert_eq!(LinkProofData::unpack(&proof).unwrap().signalling.mtu, 500);
}
assert_eq!(
LinkProofData::unpack(&proof).unwrap().signalling.mode,
MODE_AES128_CBC
Link::new_responder(&request[..64], &identity, [5; 16], 1)
.unwrap()
.0
.mtu,
500
);
}
let identity_pub = identity_key.public_key();
#[test]
fn initiator_bad_mtu_proof_never_mutates_pending_owner() {
let identity = Ed25519PrivateKey::generate();
let public = identity.public_key();
let (mut initiator, request) = Link::new_initiator([6; 16], 1);
let (_responder, good) = Link::new_responder(&request, &identity, [6; 16], 1).unwrap();
let parsed = LinkProofData::unpack(&good).unwrap();
let cost = initiator.establishment_cost;
for mtu in (1..500).chain([501, MTU_BYTEMASK]) {
let invalid = LinkProofData::create(
&identity,
&parsed.responder_x25519_pub,
&public.to_bytes(),
&initiator.link_id,
SignallingData::new(DEFAULT_MODE, mtu),
)
.pack();
assert!(
initiator
.validate_proof(&invalid, &public, &public.to_bytes())
.is_err(),
"mtu {mtu}"
);
assert_eq!(initiator.state, LinkState::Pending);
assert!(!initiator.has_keys());
assert_eq!(initiator.establishment_cost, cost);
assert_eq!(initiator.mtu, 500);
assert_eq!(initiator.mdu, rns_wire::constants::LINK_MDU);
}
assert!(
request_link
.validate_proof(&proof, &identity_pub, &identity_pub.to_bytes())
.is_err(),
"initiator requested AES256 and must reject an AES128 proof"
initiator
.validate_proof(&good, &public, &public.to_bytes())
.is_ok()
);
assert_eq!(request_link.state, LinkState::Pending);
}
let mut unsupported_request = request_data;
unsupported_request[64] = MODE_AES256_GCM << 5;
assert!(
matches!(
Link::new_responder(&unsupported_request, &identity_key, dest_hash, 1),
Err(HandshakeError::UnsupportedMode(mode)) if mode == MODE_AES256_GCM
),
"Python raises for unsupported inbound mode 2"
);
#[test]
fn legacy_and_zero_proofs_authenticate_original_bytes_then_normalize() {
let identity = Ed25519PrivateKey::generate();
let public = identity.public_key();
for legacy in [false, true] {
let (mut initiator, request) = Link::new_initiator([7; 16], 1);
let (_, proof) = Link::new_responder(&request, &identity, [7; 16], 1).unwrap();
let parsed = LinkProofData::unpack(&proof).unwrap();
let mut signed = Vec::new();
signed.extend_from_slice(&initiator.link_id);
signed.extend_from_slice(&parsed.responder_x25519_pub);
signed.extend_from_slice(&public.to_bytes());
let signalling = SignallingData::new(DEFAULT_MODE, 0).pack();
if !legacy {
signed.extend_from_slice(&signalling);
}
let mut wire = identity.sign(&signed).to_vec();
wire.extend_from_slice(&parsed.responder_x25519_pub);
if !legacy {
wire.extend_from_slice(&signalling);
}
initiator
.validate_proof(&wire, &public, &public.to_bytes())
.unwrap();
assert_eq!(initiator.mtu, 500);
assert_eq!(initiator.mdu, rns_wire::constants::LINK_MDU);
}
}
#[test]
fn responder_rejects_disabled_modes() {
let identity = Ed25519PrivateKey::generate();
let (_, request) = Link::new_initiator([0xA2; 16], 1);
for mode in 0..=7 {
let mut candidate = request.clone();
candidate[64..].copy_from_slice(&SignallingData::new(mode, 500).pack());
let result = Link::new_responder(&candidate, &identity, [0xA2; 16], 1);
if ENABLED_MODES.contains(&mode) {
assert!(result.is_ok());
} else {
assert!(
matches!(result,Err(HandshakeError::UnsupportedMode(value)) if value==mode)
);
}
}
}
#[test]
@@ -2000,6 +2118,19 @@ mod tests {
assert_eq!(initiator.state, LinkState::Pending);
}
#[test]
fn establishment_extension_rejects_invalid_without_mutation() {
let (mut link, _) = Link::new_initiator([3; 16], 1);
let initial = link.establishment_timeout;
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, f64::MAX] {
assert!(link.try_extend_establishment_timeout(bad).is_err());
assert_eq!(link.establishment_timeout, initial);
}
link.try_extend_establishment_timeout(0.0).unwrap();
link.try_extend_establishment_timeout(2.0).unwrap();
assert_eq!(link.establishment_timeout, initial + Duration::from_secs(2));
}
#[test]
fn test_establishment_timeout() {
let dest_hash = [0xAA; 16];
@@ -2479,6 +2610,51 @@ mod tests {
assert_eq!(responder.remote_identity().unwrap(), &first_pub);
}
#[test]
fn test_identify_before_rtt_is_accepted() {
// Python's initiator turns Active on the proof, so its LINKIDENTIFY can
// reach a responder still waiting for the RTT packet.
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 (mut 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);
let client = Ed25519PrivateKey::generate();
let mut client_pub = [0u8; 64];
client_pub[..32].copy_from_slice(&[0x11; 32]);
client_pub[32..].copy_from_slice(&client.public_key().to_bytes());
let identify_data = initiator.identify(&client_pub, &client).unwrap();
assert_eq!(
responder.handle_identification(&identify_data).unwrap(),
client_pub
);
responder.receive_rtt_packet(&rtt_data).unwrap();
assert_eq!(responder.state, LinkState::Active);
assert_eq!(responder.remote_identity(), Some(&client_pub));
}
#[test]
fn test_initiator_rejects_identification() {
// Only the responder learns a remote identity from LINKIDENTIFY.
let (mut initiator, _responder, _) = make_active_link();
let before = initiator.remote_identity().copied();
let peer = Ed25519PrivateKey::generate();
let mut peer_pub = [0u8; 64];
peer_pub[32..].copy_from_slice(&peer.public_key().to_bytes());
let identify_data = initiator.identify(&peer_pub, &peer).unwrap();
assert!(initiator.handle_identification(&identify_data).is_err());
assert!(!initiator.identified);
assert_eq!(initiator.remote_identity().copied(), before);
}
#[test]
fn test_identify_non_initiator_fails() {
let (_initiator, responder, _identity) = make_active_link();
+6 -39
View File
@@ -1,46 +1,13 @@
use crate::constants::{MODE_BYTEMASK, MTU_BYTEMASK};
/// MTU and encryption-mode signalling packed into 3 bytes (big-endian).
///
/// Wire layout: `[23:21] mode (0..=7)`, `[20:0] mtu (0..=2_097_151)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SignallingData {
pub mode: u8,
pub mtu: u32,
}
impl SignallingData {
pub fn new(mode: u8, mtu: u32) -> Self {
Self {
mode: mode & 0x07,
mtu: mtu & MTU_BYTEMASK,
}
}
/// Pack into 3 big-endian bytes.
pub fn pack(&self) -> [u8; 3] {
let value = (self.mtu & MTU_BYTEMASK) | ((((self.mode as u32) << 5) & MODE_BYTEMASK) << 16);
let bytes = value.to_be_bytes();
// Value fits in 24 bits; drop the high byte of the u32.
[bytes[1], bytes[2], bytes[3]]
}
/// Parse 3 big-endian bytes. Returns `None` if the input is shorter.
pub fn unpack(bytes: &[u8]) -> Option<Self> {
if bytes.len() < 3 {
return None;
}
let value = ((bytes[0] as u32) << 16) | ((bytes[1] as u32) << 8) | (bytes[2] as u32);
let mtu = value & MTU_BYTEMASK;
let mode = ((value >> 21) & 0x07) as u8;
Some(Self { mode, mtu })
}
}
//! Shared dependency-neutral Link signalling representation and checked budget.
pub use rns_wire::link_signalling::{
LinkMtu, LinkSignalling, LinkSignallingError, SignallingData, parse_proof_signalling,
parse_request_signalling,
};
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::{DEFAULT_MODE, MODE_AES256_CBC};
use crate::constants::{DEFAULT_MODE, MODE_AES256_CBC, MTU_BYTEMASK};
#[test]
fn test_pack_unpack_roundtrip() {
+12 -7
View File
@@ -13,8 +13,9 @@ pub enum RequestState {
Receiving,
Delivered,
Failed,
/// Response payload has arrived; kept distinct from [`Delivered`] so callers
/// can distinguish "ack with data" from "ack only".
/// Response payload arrived through [`RequestReceipt::receive_response`].
/// [`Delivered`] can represent either an ack-only transition or a response
/// recorded through [`RequestReceipt::deliver`].
///
/// [`Delivered`]: RequestState::Delivered
ResponseReceived,
@@ -28,12 +29,13 @@ pub struct RequestCallbacks {
pub progress: Option<ProgressCallback>,
}
/// Callback invoked once when a request receives a response or terminal failure.
/// Callback consumed at most once per registration on a response or failure.
pub type RequestCallback = Box<dyn FnOnce(&RequestReceipt) + Send>;
/// Progress callback for resource-backed request responses.
pub type ProgressCallback = Box<dyn Fn(f32) + Send + Sync>;
/// Tracks the lifecycle of an outbound request over a link.
/// Tracks an outbound request. The owner drives timeout and delivery methods;
/// this type does not start a timer or observe a Resource transfer itself.
pub struct RequestReceipt {
pub request_id: [u8; 32],
pub link_id: [u8; 16],
@@ -42,7 +44,8 @@ pub struct RequestReceipt {
pub timeout: Duration,
pub response: Option<Vec<u8>>,
pub rtt: Option<Duration>,
/// Transfer progress in [0.0, 1.0]; only meaningful for resource responses.
/// Caller-supplied transfer progress, conventionally in `[0.0, 1.0]` for
/// Resource responses. Neither this public field nor its setter clamps values.
pub progress: f32,
pub callbacks: RequestCallbacks,
}
@@ -125,7 +128,8 @@ impl RequestReceipt {
}
}
/// Transition to `Delivered` without a response payload (ack-only).
/// Transition from `Sent` to `Delivered` without a response payload (ack-only).
/// Other states are unchanged; this does not invoke a response callback.
pub fn mark_delivered(&mut self) {
if self.state == RequestState::Sent {
self.state = RequestState::Delivered;
@@ -158,7 +162,8 @@ impl RequestReceipt {
}
}
/// True once the request has reached a terminal state (delivered, failed, or response received).
/// Whether the request is no longer pending for timeout processing.
/// A `Delivered` receipt can still transition through [`Self::receive_response`].
pub fn concluded(&self) -> bool {
matches!(
self.state,
+2 -1
View File
@@ -5,7 +5,7 @@ publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
license-file.workspace = true
[dependencies]
rns-crypto = { workspace = true, features = ["std"] }
@@ -17,6 +17,7 @@ tracing = { workspace = true }
bzip2 = { workspace = true }
rmpv = { workspace = true }
rmp-serde = { workspace = true }
serde = { workspace = true }
hex = { workspace = true }
[dev-dependencies]
+22 -16
View File
@@ -6,12 +6,13 @@ use crate::stream_data::{STREAM_ID_MAX, StreamDataMessage};
/// Upper bound on a single chunk before the writer splits (16 KiB).
pub const MAX_CHUNK_LEN: usize = 16384;
/// Number of progressively smaller segments the writer will try when
/// compressing a chunk before giving up and sending it uncompressed.
/// Exclusive upper bound for compression-prefix trials. The writer tries
/// chunk/1, chunk/2 and chunk/3 before falling back to raw bytes.
pub const COMPRESSION_TRIES: usize = 4;
/// Accumulates inbound [`StreamDataMessage`] payloads into a byte queue and
/// tracks explicit EOF.
/// Accumulates decoded [`StreamDataMessage`] payloads and tracks explicit EOF.
/// The owner must provide ordered messages, bound queued data, and stop feeding
/// after EOF; this queue has no size limit and accepts later data.
pub struct StreamReader {
stream_id: u16,
buffer: VecDeque<u8>,
@@ -27,8 +28,8 @@ impl StreamReader {
}
}
/// Append `msg` to the buffer. Returns `false` (and ignores the payload)
/// if the message belongs to a different stream.
/// Append an already-decoded `msg`; this method does not decompress its data.
/// Returns `false` and ignores the payload for a different stream ID.
pub fn feed(&mut self, msg: &StreamDataMessage) -> bool {
if msg.stream_id != self.stream_id {
return false;
@@ -47,9 +48,9 @@ impl StreamReader {
/// Pop up to `size` bytes off the front of the buffer.
///
/// Returns `None` when the buffer is empty and EOF has not yet arrived,
/// and `Some(Vec::new())` once it has — letting callers distinguish "wait"
/// from "end of stream".
/// For a positive `size`, `None` means the empty stream is still open, and
/// `Some(Vec::new())` means EOF with no buffered data. A zero-size read can
/// also return an empty vector while data remains; it is not an EOF test.
pub fn read(&mut self, size: usize) -> Option<Vec<u8>> {
if self.buffer.is_empty() {
if self.eof {
@@ -89,8 +90,10 @@ impl StreamReader {
}
}
/// Chunks outbound bytes into [`StreamDataMessage`]s sized for the underlying
/// channel, opportunistically compressing each chunk with bzip2.
/// Chunks outbound bytes into [`StreamDataMessage`]s with optional bzip2
/// compression. `max_data_len` must be positive and excludes the two-byte
/// stream header and six-byte Channel envelope. Zero is not checked and makes
/// a nonempty write fail to advance. Stream IDs are masked to 14 bits.
pub struct StreamWriter {
stream_id: u16,
max_data_len: usize,
@@ -106,9 +109,10 @@ impl StreamWriter {
}
}
/// Slice `data` into channel-sized frames. Each frame is sent compressed
/// if bzip2 would fit a larger source segment into `max_data_len` than the
/// uncompressed alternative; otherwise the chunk is sent raw.
/// Slice `data` into frames within the configured payload budget. A prefix
/// is compressed when bzip2 makes it smaller and its encoded size is
/// strictly below `max_data_len`; otherwise the writer takes raw bytes.
/// Returned frames still need packing, Channel admission and transmission.
pub fn write(&mut self, data: &[u8]) -> Result<Vec<StreamDataMessage>, BufferError> {
if self.closed {
return Err(BufferError::WriterClosed);
@@ -200,8 +204,10 @@ pub enum BufferError {
WriterClosed,
}
/// Bidirectional convenience wrapper that pairs a [`StreamWriter`] and
/// [`StreamReader`] on the same stream ID.
/// Pairs a [`StreamWriter`] and [`StreamReader`] on the same stream.
/// `max_data_len` must satisfy the writer's positive-budget requirement.
/// Use an ID in `0..=STREAM_ID_MAX`: the reader/writer mask higher bits,
/// while this wrapper's `stream_id()` returns the original argument.
pub struct ChannelBuffer {
writer: StreamWriter,
reader: StreamReader,
+123 -43
View File
@@ -17,7 +17,7 @@ pub const WINDOW_MAX_MEDIUM: usize = 12;
pub const WINDOW_MAX_FAST: usize = 48;
/// Upper ceiling on `window_max` across all tiers; also sizes pre-allocated guard regions.
pub const WINDOW_MAX: usize = WINDOW_MAX_FAST;
/// Consecutive rounds at a tier's RTT before `window_max` is promoted to that tier.
/// RTT sample threshold used to promote the window ceiling; see [`ChannelWindow::grow`].
pub const FAST_RATE_THRESHOLD: usize = 10;
/// RTT at or below which a link is considered "fast" (seconds).
pub const RTT_FAST: f64 = 0.18;
@@ -25,7 +25,8 @@ pub const RTT_FAST: f64 = 0.18;
pub const RTT_MEDIUM: f64 = 0.75;
/// RTT above which a fresh window starts at a single slot.
pub const RTT_SLOW: f64 = 1.45;
/// Minimum gap `shrink()` will leave between `window_max` and `window_min`.
/// Gap threshold below which `shrink()` stops lowering the window ceiling.
/// This does not establish a minimum gap for freshly constructed windows.
pub const WINDOW_FLEXIBILITY: usize = 4;
pub const SEQ_MAX: u16 = 0xFFFF;
@@ -34,15 +35,27 @@ pub const SEQ_MODULUS: u32 = 0x10000;
/// Envelope header: `msgtype(2) || sequence(2) || length(2)`.
pub const ENVELOPE_HEADER_SIZE: usize = 6;
/// Retransmissions an envelope may absorb before the channel is torn down.
/// Maximum send attempts per envelope, including its initial transmission.
/// The next timeout tears down the channel after this limit is reached.
pub const MAX_TRIES: usize = 5;
/// Floor for the `rtt * 2.5` term used as the base of the retransmit backoff.
pub const MIN_TIMEOUT_BASE: f64 = 0.025;
/// Retained RTT ceiling, matching the Link peer-RTT policy.
pub const RTT_MAX: f64 = 720.0;
fn initial_rtt(rtt: f64) -> f64 {
if rtt.is_finite() && rtt >= 0.0 {
rtt.min(RTT_MAX)
} else {
1.0
}
}
/// One outgoing or incoming channel frame.
/// One outgoing or incoming Channel frame.
///
/// Wire format: `msgtype(2 BE) || sequence(2 BE) || length(2 BE) || data`.
/// Packing does not validate the payload length before casting it to `u16`;
/// callers must enforce both the 65,535-byte field limit and their Link budget.
#[derive(Debug, Clone)]
pub struct Envelope {
pub msg_type: u16,
@@ -125,10 +138,10 @@ pub struct ChannelWindow {
}
impl ChannelWindow {
/// Build a window sized to the initial `rtt`. Links slower than
/// `RTT_SLOW` start pinned at a single slot with zero flexibility so we
/// don't spray bursts onto a marginal path.
/// Build a window sized to the initial `rtt`. Links slower than `RTT_SLOW`
/// start with `window`, `window_min` and `window_max` all set to one.
pub fn new(rtt: f64) -> Self {
let rtt = initial_rtt(rtt);
if rtt > RTT_SLOW {
Self {
window: 1,
@@ -150,13 +163,18 @@ impl ChannelWindow {
}
}
/// Record a successful delivery at `rtt` and open the window one notch.
/// Record a successful delivery and open the window one slot if possible.
///
/// Only after `FAST_RATE_THRESHOLD` *consecutive* rounds at the same tier
/// does the ceiling (`window_max`) get promoted — a single fast RTT can't
/// unlock the fast tier. Any measurement that falls out of a tier resets
/// that tier's counter.
/// Fast samples advance the fast counter without resetting the medium
/// counter. Medium samples advance the medium counter and reset the fast
/// counter; slower samples reset both. Promotion uses `FAST_RATE_THRESHOLD`.
/// A zero RTT can grow the window but does not update these counters.
pub fn grow(&mut self, rtt: f64) {
self.clamp_window();
if !rtt.is_finite() || rtt < 0.0 {
return;
}
let rtt = rtt.min(RTT_MAX);
if self.window < self.window_max {
self.window += 1;
}
@@ -171,7 +189,7 @@ impl ChannelWindow {
if rtt > RTT_MEDIUM {
self.medium_rate_rounds = 0;
} else {
self.medium_rate_rounds += 1;
self.medium_rate_rounds = self.medium_rate_rounds.saturating_add(1);
if self.window_max < WINDOW_MAX_MEDIUM
&& self.medium_rate_rounds == FAST_RATE_THRESHOLD
{
@@ -180,7 +198,7 @@ impl ChannelWindow {
}
}
} else {
self.fast_rate_rounds += 1;
self.fast_rate_rounds = self.fast_rate_rounds.saturating_add(1);
if self.window_max < WINDOW_MAX_FAST && self.fast_rate_rounds == FAST_RATE_THRESHOLD {
self.window_max = WINDOW_MAX_FAST;
self.window_min = WINDOW_MIN_LIMIT_FAST;
@@ -188,10 +206,18 @@ impl ChannelWindow {
}
}
/// Pull the window in on retransmit. Also walks `window_max` downwards so
/// long-term packet loss actually demotes the link tier, stopping at the
/// configured `window_flexibility` gap above `window_min`.
/// Cap the public window fields at `WINDOW_MAX` before growth or shrinkage.
fn clamp_window(&mut self) {
self.window = self.window.min(WINDOW_MAX);
self.window_min = self.window_min.min(WINDOW_MAX);
self.window_max = self.window_max.min(WINDOW_MAX);
self.window_flexibility = self.window_flexibility.min(WINDOW_MAX);
}
/// Reduce the window by one when above its minimum. In that case also
/// reduce the ceiling if it exceeds `window_min + window_flexibility`.
pub fn shrink(&mut self) {
self.clamp_window();
if self.window > self.window_min {
self.window -= 1;
@@ -202,22 +228,23 @@ impl ChannelWindow {
}
}
/// Handler for inbound messages on a channel.
/// Handler for inbound messages on a Channel.
///
/// Invoked with `(msg_type, payload)`. Return `true` to consume the message
/// (subsequent handlers are skipped) or `false` to fall through.
/// Receives `(msg_type, payload)`. Returning `true` skips later handlers;
/// `false` continues the chain. The message still appears in the tuples
/// returned by [`Channel::receive`], regardless of this return value.
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.
/// Sequenced message state machine for a Reticulum Link.
///
/// The channel is passive: the owning runtime calls `send`/`receive`/
/// `timeout`/`delivered` to step the state machine. When one or more message
/// types are registered, inbound envelopes carrying an unregistered type are
/// rejected rather than silently dropped.
/// The owner drives `send`, `receive`, `timeout` and `delivered`, supplies
/// authenticated delivery proofs, and sends the returned bytes. Register
/// every inbound message type before receiving it; an empty registry accepts
/// no types. The Channel itself provides neither encryption nor a scheduler.
pub struct Channel {
next_tx_sequence: u16,
next_rx_sequence: u16,
@@ -226,7 +253,7 @@ pub struct Channel {
pub window: ChannelWindow,
pub active: bool,
current_rtt: f64,
/// When non-empty, only these types are accepted on `receive`.
/// Only registered types are accepted on `receive`; an empty list accepts none.
registered_types: Vec<u16>,
/// Called in registration order on each delivered message; the first
/// handler that returns `true` stops the chain.
@@ -236,6 +263,7 @@ pub struct Channel {
impl Channel {
pub fn new(rtt: f64) -> Self {
let rtt = initial_rtt(rtt);
Self {
next_tx_sequence: 0,
next_rx_sequence: 0,
@@ -264,7 +292,9 @@ impl Channel {
Ok(())
}
/// Register a reserved system type (`>= 0xF000`) for reception.
/// Register a reserved system type (`>= 0xF000`) for reception. This low-level
/// method does not enforce the reserved range; use `register_message_type`
/// for application-defined IDs.
pub fn register_system_type(&mut self, msg_type: u16) {
if !self.registered_types.contains(&msg_type) {
self.registered_types.push(msg_type);
@@ -328,17 +358,22 @@ impl Channel {
.iter()
.filter(|e| e.state != MessageState::Delivered)
.count();
outstanding < self.window.window
outstanding < self.window.window.min(WINDOW_MAX)
}
/// True when every outbound envelope has been acknowledged and removed.
/// True when the TX ring is empty. During normal operation this follows
/// acknowledgement of every queued envelope; `shutdown` also empties the
/// ring by discarding it, so this alone is not a delivery guarantee.
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.
/// Pack `msg`, enqueue it, and return the raw envelope to send. Fails when
/// closed or the window is saturated. This entry point does not enforce a
/// Link MDU or the `u16` payload limit. [`LinkChannel::prepare_send`] checks
/// its configured MDU, but an explicit budget above 65,541 bytes does not
/// protect the length field. Keep the serialized payload at most 65,535
/// bytes and within the transport budget before enqueueing.
pub fn send(&mut self, msg: &dyn MessageBase) -> Result<Vec<u8>, ChannelError> {
self.send_tracked(msg).map(|(_, raw)| raw)
}
@@ -380,8 +415,10 @@ impl Channel {
Ok((seq, raw))
}
/// Mark a TX envelope as acknowledged and drain any in-order delivered
/// frames off the front of the ring, then open the window.
/// Mark a TX envelope acknowledged, drain delivered envelopes from the
/// front, and grow the window. The owner must authenticate the packet proof
/// and map it to the correct sequence. Even an unknown sequence grows the
/// window, so do not call this for unrelated or repeated proofs.
pub fn delivered(&mut self, sequence: u16, rtt: f64) {
if let Some(env) = self.tx_ring.iter_mut().find(|e| e.sequence == sequence) {
env.state = MessageState::Delivered;
@@ -401,7 +438,7 @@ impl Channel {
/// is marked inactive at that point).
pub fn timeout(&mut self, sequence: u16) -> Result<Option<Vec<u8>>, ChannelError> {
if let Some(env) = self.tx_ring.iter_mut().find(|e| e.sequence == sequence) {
env.tries += 1;
env.tries = env.tries.saturating_add(1);
if env.tries > MAX_TRIES {
self.active = false;
return Err(ChannelError::MaxRetriesExceeded);
@@ -532,20 +569,21 @@ impl Channel {
/// based on the latest Link RTT supplied by the owning runtime.
pub fn compute_timeout(&self, tries: usize) -> f64 {
let rtt = self.current_rtt;
let backoff = 1.5_f64.powi(tries.saturating_sub(1) as i32);
let backoff = 1.5_f64.powi((tries.clamp(1, MAX_TRIES) - 1) as i32);
let base = (rtt * 2.5).max(MIN_TIMEOUT_BASE);
let outstanding = self.outstanding_count() as f64 + 1.5;
let outstanding = self.outstanding_count().min(WINDOW_MAX) as f64 + 1.5;
backoff * base * outstanding
}
fn timeout_duration(&self, tries: usize) -> Duration {
Duration::from_secs_f64(self.compute_timeout(tries).max(MIN_TIMEOUT_BASE))
Duration::try_from_secs_f64(self.compute_timeout(tries).max(MIN_TIMEOUT_BASE))
.unwrap_or(Duration::from_secs(1))
}
/// 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;
self.current_rtt = rtt.min(RTT_MAX);
}
}
@@ -602,12 +640,13 @@ pub struct PreparedChannelData {
}
impl LinkChannel {
/// Plain-text channel (no transport-side encryption).
/// Channel without encryption in this wrapper. The owner supplies the
/// transport and is responsible for any required Link 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.
/// Channel without wrapper encryption, using an explicit Link MDU.
pub fn new_with_mdu(link_id: [u8; 16], rtt: f64, link_mdu: usize) -> Self {
Self {
channel: Channel::new(rtt),
@@ -644,8 +683,13 @@ impl LinkChannel {
}
}
/// Pack `msg`, encrypt with the session keys if present, and return the
/// wire bytes.
/// Enforce the Link payload budget, enqueue `msg`, and encrypt its Channel
/// envelope if keys are present. Returns a packet body, not a complete
/// Reticulum packet. The caller must frame and send it, then route delivery
/// proofs back to the assigned sequence. With an explicit Link MDU above
/// 65,541 bytes, separately check that the serialized payload is at most
/// 65,535 bytes: this method does not validate the `u16` length field.
/// An encryption error occurs after enqueueing and does not roll back the envelope.
pub fn prepare_send(&mut self, msg: &dyn MessageBase) -> Result<Vec<u8>, ChannelError> {
self.prepare_send_tracked(msg).map(|prepared| prepared.data)
}
@@ -1041,6 +1085,42 @@ mod tests {
assert_eq!(w.window_max, w.window_min + w.window_flexibility);
}
#[test]
fn channel_hostile_rtt_and_public_window_remain_bounded() {
for rtt in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0] {
let mut channel = Channel::new(rtt);
assert_eq!(channel.current_rtt, 1.0);
let before = channel.window.window;
channel.window.grow(rtt);
assert_eq!(channel.window.window, before);
channel.update_rtt(rtt);
assert_eq!(channel.current_rtt, 1.0);
assert!(
channel
.timeout_duration(usize::MAX)
.as_secs_f64()
.is_finite()
);
}
let mut channel = Channel::new(f64::MAX);
assert_eq!(channel.current_rtt, RTT_MAX);
channel.window.window = usize::MAX;
channel.window.window_max = usize::MAX;
channel.window.window_min = usize::MAX;
channel.window.window_flexibility = usize::MAX;
channel.window.grow(0.1);
channel.window.shrink();
assert!(channel.window.window <= WINDOW_MAX);
for _ in 0..WINDOW_MAX {
channel.send(&TestMessage::new(b"bounded")).unwrap();
}
assert!(!channel.is_ready_to_send());
assert_eq!(
channel.compute_timeout(usize::MAX),
channel.compute_timeout(MAX_TRIES)
);
}
#[test]
fn test_window_slow_rtt_init() {
// RTT past RTT_SLOW must start pinned at a single slot with no flex.
+4 -3
View File
@@ -14,10 +14,11 @@ pub fn bz2_compress(data: &[u8]) -> Result<Vec<u8>, CompressionError> {
.map_err(|_| CompressionError::CompressFailed)
}
/// Decompress bzip2 `data`, failing once the output would exceed `max_size`.
/// Decompress bzip2 `data`, checking `max_size` after each 8192-byte read.
///
/// Decoding in chunks lets us stop early on a decompression bomb rather than
/// allocating the full expanded buffer.
/// Decoding stops when accumulated output exceeds the limit, at most one read
/// chunk beyond it. This is an output-length check, not a strict bound on peak
/// allocation or decoder working memory.
pub fn bz2_decompress(data: &[u8], max_size: usize) -> Result<Vec<u8>, CompressionError> {
let mut decoder = bzip2::read::BzDecoder::new(data);
let mut output = Vec::new();
+13 -3
View File
@@ -1,6 +1,13 @@
//! Higher-level protocol layers over Links: resource transfer, channels,
//! buffers, and stream I/O. Python reference: `RNS/Resource.py`,
//! `RNS/Channel.py`, `RNS/Buffer.py`.
//! Resource transfer, Channels and byte streams over Reticulum Links.
//!
//! The state machines are passive: their owner supplies packet I/O, Link keys,
//! proof routing and timeout polling. Use [`resource::OutboundTransfer`] and
//! [`resource::InboundTransfer`] for request-driven Resource transfer,
//! [`channel::LinkChannel`] for sequenced messages, and [`buffer::ChannelBuffer`]
//! for byte-stream framing on a Channel. Codec helpers do not establish Links
//! or authorize application actions.
//!
//! Python reference formats: `RNS/Resource.py`, `RNS/Channel.py`, `RNS/Buffer.py`.
pub mod buffer;
pub mod channel;
@@ -10,3 +17,6 @@ pub mod resource;
pub mod resource_adv;
pub mod rnsh;
pub mod stream_data;
/// Exact Resource control-packet admission using the production encoders.
pub mod resource_control;
+250 -196
View File
@@ -5,8 +5,8 @@ use rns_crypto::sha::full_hash;
use crate::compression;
/// Lifecycle state of a resource transfer. `Rejected` is tagged 0x09 — not
/// 0x00 — so it is wire-distinguishable from `None`.
/// Lifecycle state of a Resource transfer. `Rejected` has discriminant
/// `0x09`, distinct from `None` (`0x00`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ResourceState {
@@ -36,13 +36,15 @@ pub const RATE_FAST: usize = 6250;
pub const RATE_VERY_SLOW: usize = 250;
pub const WINDOW_FLEXIBILITY: usize = 4;
pub const MAPHASH_LEN: usize = 4;
/// Only the low 4 bytes of the resource's random tag ship on the wire (in the
/// advertisement's `r` field) and feed the map-hash calculation.
/// Size of the random tag generated by this implementation and included in
/// its advertisement and part/resource hash inputs.
pub const RANDOM_HASH_SIZE: usize = 4;
pub const SDU: usize = rns_wire::constants::MDU;
/// Largest payload that fits a single-segment resource (1 MiB - 1).
/// Maximum uncompressed content per segment (1 MiB - 1), including any
/// three-byte metadata prefix and metadata bytes.
pub const MAX_EFFICIENT_SIZE: usize = 1_048_575;
/// Largest metadata block that a 3-byte length prefix can encode.
/// Metadata length representable by the three-byte prefix. Constructors also
/// require metadata and its prefix to fit the first segment's smaller budget.
pub const METADATA_MAX_SIZE: usize = 16_777_215;
pub const MAX_RETRIES: usize = 16;
pub const MAX_ADV_RETRIES: usize = 4;
@@ -146,8 +148,9 @@ pub fn compute_expected_proof(data: &[u8], resource_hash: &[u8; 32]) -> [u8; 32]
full_hash(&input)
}
/// Decode a sender-to-receiver hashmap update:
/// `resource_hash(32) || msgpack([segment_index, hashmap_bytes])`.
/// Decode `resource_hash(32) || msgpack([segment_index, hashmap_bytes])`.
/// This parser does not reject trailing bytes or validate the resource binding,
/// segment range or four-byte entry alignment; the transfer owner must do so.
pub fn parse_hashmap_update(data: &[u8]) -> Result<([u8; 32], usize, Vec<u8>), ResourceError> {
if data.len() < 32 {
return Err(ResourceError::Corrupt);
@@ -188,13 +191,9 @@ impl WindowState {
}
}
/// Grow the window once a whole batch has arrived. Must be called before
/// the next request batch is dispatched so the new slots are visible to
/// the batch-size calculation.
///
/// Also slides `window_min` up when the window has outgrown its
/// flexibility band, and promotes the ceiling for sustained fast or
/// very-slow links.
/// Grow the window after a received batch, before calculating the next
/// request size. The minimum follows a growing window; sustained fast rounds
/// promote its ceiling, while sustained very-slow rounds lower and clamp it.
pub fn grow(&mut self, rate: usize) {
if self.window < self.window_max {
self.window += 1;
@@ -228,9 +227,9 @@ impl WindowState {
}
}
/// Shrink the window after a timeout. Both the instantaneous `window`
/// and the ceiling `window_max` contract, and the flexibility band
/// between them is kept within `WINDOW_FLEXIBILITY - 1`.
/// Shrink the window and ceiling toward their minimum after a timeout.
/// If the ceiling remains more than `WINDOW_FLEXIBILITY - 1` above the
/// window, lower it once more; one call need not close a larger gap.
pub fn shrink(&mut self) {
if self.window > self.window_min {
self.window -= 1;
@@ -273,17 +272,18 @@ pub struct OutboundResource {
pub window: WindowState,
pub retries: usize,
pub sdu: usize,
/// Optional payload metadata. When set it is prepended to the resource
/// data as `length(3 BE) || metadata` before compression.
/// Framed metadata: `length(3 BE) || metadata`, already including the prefix.
/// Prepended to the payload before compression by the constructors.
pub metadata: Option<Vec<u8>>,
/// Size of the packed metadata block (length prefix included).
pub metadata_size: usize,
}
impl OutboundResource {
/// Build a single-segment outbound resource. Payloads above
/// `MAX_EFFICIENT_SIZE` must use `MultiSegmentOutbound`. `encrypt_fn` is
/// applied to the assembled blob after compression, before chunking.
/// Build a single segment. Data plus framed metadata must fit
/// `MAX_EFFICIENT_SIZE`; use [`MultiSegmentOutbound`] or
/// [`LazyMultiSegmentOutbound`] for larger payloads. `encrypt_fn`, when
/// supplied, runs on the whole compressed blob before part slicing.
pub fn new(
data: Vec<u8>,
auto_compress: bool,
@@ -296,13 +296,13 @@ impl OutboundResource {
// `with_options_inner` for the retry loop.
const MAX_COLLISION_RETRIES: usize = 5;
/// Extended constructor with optional metadata and a custom SDU.
/// Construct with optional metadata and a custom part SDU.
///
/// `metadata` is framed as `length(3 BE) || bytes` and prepended to the
/// data before compression/encryption, matching the Python layout.
///
/// `link_sdu` lets callers override the default SDU when the link has
/// negotiated a non-standard MTU.
/// Metadata is prepended as `length(3 BE) || bytes` before compression and
/// counts toward the segment content limit. `link_sdu` must be nonzero and
/// changes part slicing only; control-packet admission still uses the base
/// Reticulum MTU. Supplying an encryption hook sets the encrypted flag, so
/// the hook must return encrypted bytes rather than silently falling back.
pub fn with_options(
data: Vec<u8>,
auto_compress: bool,
@@ -323,6 +323,20 @@ impl OutboundResource {
encrypt_fn: Option<&ResourceEncryptor<'_>>,
collision_retries: usize,
) -> Result<Self, ResourceError> {
let sdu = link_sdu.unwrap_or(SDU);
if sdu == 0 {
return Err(ResourceError::InvalidAdvertisement);
}
// Part slicing is independent from the complete Link control budget.
crate::resource_control::preflight_outbound_with_sdu(
data.len(),
metadata.as_ref().map(Vec::len),
None,
false,
encrypt_fn.is_some(),
sdu,
rns_wire::constants::MTU,
)?;
let (packed_metadata, metadata_size, has_metadata) = if let Some(ref meta) = metadata {
if meta.len() > METADATA_MAX_SIZE {
return Err(ResourceError::MetadataTooLarge);
@@ -404,6 +418,15 @@ impl OutboundResource {
}
if has_collision && collision_retries < Self::MAX_COLLISION_RETRIES {
// Release attempt-local copies before retrying. Holding these until
// recursive return multiplies peak memory by the retry count.
drop(packed_metadata);
drop(full_data);
drop(processed_data);
drop(blob);
drop(parts);
drop(map_hashes);
drop(collision_guard);
return Self::with_options_inner(
data,
auto_compress,
@@ -447,8 +470,10 @@ impl OutboundResource {
})
}
/// Check a received delivery proof. Proofs ship as
/// `dest_hash(32) || proof_hash(32)`; only the last 32 bytes are compared.
/// Compare bytes 32..64 of a proof with the expected proof hash and mark
/// complete on a match. The first 32 bytes are a resource hash, but this
/// method does not check them or reject trailing bytes. Prefer
/// [`OutboundTransfer::handle_proof`] for length and resource binding checks.
pub fn validate_proof(&mut self, proof_data: &[u8]) -> bool {
if proof_data.len() < 64 {
return false;
@@ -470,9 +495,11 @@ impl OutboundResource {
self.parts.len()
}
/// Respond to an HMU / resource-request from the receiver. Returns the
/// part indices to (re)send; an exhausted HMU transitions the sender
/// into `AwaitingProof` and returns an empty vector.
/// Handle this low-level helper's compact feedback format: a flag followed
/// by the last received part hash. An exhausted flag sets `AwaitingProof`;
/// otherwise return the following window of part indices. This is not the
/// standard RESOURCE_REQ or sender-to-receiver RESOURCE_HMU parser; use
/// [`OutboundTransfer::handle_request_packet`] for normal part requests.
pub fn handle_hmu(&mut self, plaintext: &[u8]) -> Vec<usize> {
if plaintext.is_empty() {
return Vec::new();
@@ -549,8 +576,10 @@ impl InboundResource {
)
}
/// Extended constructor that lets callers supply a non-default SDU when
/// the underlying link has negotiated a custom MTU.
/// Construct with an optional part SDU. Checks the transfer-size and
/// part-count allocation bounds, but does not establish full advertisement
/// consistency or authenticate it. The owner must validate data/segment
/// limits, the SDU, map hashes and the owning Link before construction.
// Mirrors Resource ADV fields after decoding; these values are validated
// together because they describe one advertised transfer.
#[allow(clippy::too_many_arguments)]
@@ -658,13 +687,14 @@ impl InboundResource {
self.consecutive_completed == self.total_parts
}
/// Reassemble the received parts into the original payload.
/// Concatenate parts, apply `decrypt_fn` if supplied, strip the random-tag
/// prefix, optionally decompress, verify the resource hash, and extract
/// metadata. Returns payload bytes only; metadata is stored in `self.metadata`.
///
/// Steps: concatenate parts → optional decrypt → strip random hash →
/// decompress (bounded by `MAX_EFFICIENT_SIZE` to stop decompression
/// bombs) → verify hash → split off metadata if `flags.has_metadata`.
/// The extracted metadata is stashed in `self.metadata` and the return
/// value is the payload only.
/// The compressed-output check uses `MAX_EFFICIENT_SIZE`; it is not a
/// strict peak-memory bound. Decryption follows the supplied hook, not
/// `flags.encrypted`, so the owner must provide the correct hook and enforce
/// advertised length/part bounds before calling this method.
pub fn assemble(
&mut self,
decrypt_fn: Option<&ResourceDecryptor<'_>>,
@@ -733,7 +763,10 @@ impl InboundResource {
Ok(payload)
}
/// Build the 64-byte delivery proof (`resource_hash(32) || expected_proof(32)`).
/// Build `resource_hash(32) || expected_proof(32)`. `data` must be the full
/// uncompressed content, including framed metadata, rather than just the
/// payload returned by `assemble`. [`InboundTransfer::complete`] handles
/// that reconstruction. This method itself does not check transfer state.
pub fn generate_proof(&self, data: &[u8]) -> Vec<u8> {
let proof = compute_expected_proof(data, &self.resource_hash);
let mut proof_data = Vec::with_capacity(64);
@@ -778,6 +811,12 @@ pub enum ResourceError {
DecompressionFailed,
#[error("invalid metadata prefix: declared {declared} bytes, available {available} bytes")]
InvalidMetadata { declared: usize, available: usize },
#[error("resource control {context:?} requires {encoded_len} packet bytes, MTU is {mtu}")]
ControlFrameTooLarge {
context: rns_wire::context::PacketContext,
encoded_len: usize,
mtu: usize,
},
#[error("invalid advertisement")]
InvalidAdvertisement,
#[error("map hash collision persists after retries")]
@@ -791,7 +830,8 @@ pub enum ResourceError {
DuplicateSegment,
}
/// Upper bound on the combined size of all segments (128 MiB - 1).
/// Upper bound on input payload size across all segments (128 MiB - 1).
/// The segment-count limit and first-segment metadata budget also apply.
pub const MAX_RESOURCE_SIZE: usize = 134_217_727;
/// Max segments per split resource. Caps the ADV's `l` field so a peer
@@ -850,8 +890,9 @@ impl MultiSegmentOutbound {
Self::with_encrypt(data, auto_compress, None)
}
/// Variant of [`Self::new`] that applies `encrypt_fn` per segment so
/// part payloads are protected while ADVs remain addressable.
/// Apply `encrypt_fn` separately to each assembled segment before part
/// slicing. Advertisement/control packet encryption remains the owner's
/// responsibility.
pub fn with_encrypt(
data: Vec<u8>,
auto_compress: bool,
@@ -860,9 +901,10 @@ impl MultiSegmentOutbound {
Self::with_options(data, auto_compress, None, None, false, encrypt_fn)
}
/// Split a resource while preserving per-resource metadata and request
/// flags. Metadata rides on the first segment and reduces that segment's
/// payload budget so no segment exceeds `MAX_EFFICIENT_SIZE`.
/// Split a resource while preserving its request ID and response flag.
/// Metadata belongs to the first segment and reduces that segment's payload
/// budget. The caller must set any additional request semantics it needs;
/// this constructor does not set `flags.is_request`.
pub fn with_options(
data: Vec<u8>,
auto_compress: bool,
@@ -913,10 +955,9 @@ impl MultiSegmentOutbound {
.all(|s| s.state == ResourceState::Complete)
}
/// Mark every still-active segment as `Failed` and report how many were
/// newly transitioned. Emitting per-segment cancel packets is left to
/// the engine, which observes `Failed` on its next tick. Already-failed
/// or already-complete segments are skipped.
/// Mark each segment that is neither `Failed` nor `Complete` as failed and
/// return the number changed. This only mutates local state; the owner must
/// emit any required cancel packets itself.
pub fn cancel_all(&mut self) -> usize {
let mut cancelled = 0;
for segment in &mut self.segments {
@@ -939,9 +980,9 @@ impl LazyMultiSegmentOutbound {
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.
/// Create a sequential split-Resource plan with a request ID, response
/// flag and optional first-segment metadata. Metadata counts against the
/// first segment's content budget; `flags.is_request` is not set here.
pub fn with_options(
data: Vec<u8>,
auto_compress: bool,
@@ -963,6 +1004,15 @@ impl LazyMultiSegmentOutbound {
return Err(ResourceError::TooLarge);
}
crate::resource_control::preflight_outbound(
data_size,
metadata.as_ref().map(Vec::len),
request_id.as_deref(),
is_response,
true,
rns_wire::constants::MTU,
)?;
// `original_hash` covers the uncompressed concatenated payload so the
// receiver can verify reassembly across all segments.
let random_hash: [u8; RANDOM_HASH_SIZE] =
@@ -992,9 +1042,10 @@ impl LazyMultiSegmentOutbound {
.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.
/// Build the next segment. Request another only after the returned segment
/// has completed or been terminally discarded to bound live allocations.
/// If first-segment construction fails, its metadata has already been taken
/// from the plan; discard the failed plan instead of retrying this method.
pub fn next_segment(
&mut self,
encrypt_fn: Option<&ResourceEncryptor<'_>>,
@@ -1046,25 +1097,27 @@ impl LazyMultiSegmentOutbound {
}
}
/// 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
/// `set_segment_data` (runtime, where `InboundTransfer` owns the segment).
/// Collect independently verified Resource segments in order. Use
/// `set_segment` with `assemble_segment`, or pass already verified payloads to
/// `set_segment_data`. `reassemble` concatenates those payloads; it does not
/// recompute or verify `original_hash` or impose a total byte limit.
pub struct MultiSegmentInbound {
pub original_hash: [u8; 32],
pub total_segments: usize,
pub segments: Vec<Option<InboundResource>>,
pub assembled_segments: Vec<Option<Vec<u8>>>,
pub data_size: usize,
/// First non-None metadata observed across the segment stream. Rust's
/// `MultiSegmentOutbound` attaches no per-segment metadata, but Python
/// peers may.
/// First metadata supplied through `set_metadata`. Outbound constructors
/// can attach metadata to the first segment; the owner must carry it here
/// after assembling that segment.
pub metadata: Option<Vec<u8>>,
}
impl MultiSegmentInbound {
/// Allocate slots for `total_segments` segments; seed with the
/// `original_hash` advertised by the sender for the full payload.
/// Allocate slots and retain the sender's `original_hash`. Before calling,
/// validate a nonzero count no greater than `MAX_SEGMENTS` and the transfer
/// limits. This constructor does not check them and allocates directly from
/// `total_segments`.
pub fn new(total_segments: usize, original_hash: [u8; 32]) -> Self {
Self {
original_hash,
@@ -1163,8 +1216,13 @@ impl MultiSegmentInbound {
}
}
/// Either side of a single-segment resource transfer, tagged with the owning
/// link's ID and optionally its session keys for transparent encryption.
/// Low-level Resource wrapper with optional session keys.
///
/// With keys, `next_part`/`receive_part` add/remove per-part encryption. The
/// encrypted constructor also encrypts the whole blob, so this adds a layer
/// not used by normal Resource packets. Use [`OutboundTransfer`] and
/// [`InboundTransfer`] for normal Resource transfer, with whole-blob
/// encryption and caller-owned control packets.
pub struct LinkResource {
pub link_id: [u8; 16],
pub outbound: Option<OutboundResource>,
@@ -1173,7 +1231,8 @@ pub struct LinkResource {
}
impl LinkResource {
/// Build an outbound resource for sending over a plaintext link.
/// Build an outbound Resource without blob encryption. The wrapper
/// does not establish a Link or add transport authentication.
pub fn new_outbound(
link_id: [u8; 16],
data: Vec<u8>,
@@ -1188,8 +1247,11 @@ impl LinkResource {
})
}
/// Build an outbound resource whose reassembled blob is encrypted with
/// the supplied link session keys before chunking.
/// Encrypt the complete blob before slicing it, retaining the supplied
/// keys for the wrapper's additional per-part layer. Keys must be valid
/// negotiated Link keys: this constructor silently uses plaintext if
/// `link_encrypt` fails. For normal Resource transmission, use the transfer
/// engine rather than this wrapper's `next_part` method.
pub fn new_outbound_encrypted(
link_id: [u8; 16],
data: Vec<u8>,
@@ -1240,9 +1302,10 @@ impl LinkResource {
})
}
/// Per-part transport encryption for outbound transfers. Returns the
/// ciphertext when the link carries session keys, otherwise the
/// untouched plaintext.
/// Return one stored part, adding encryption if `session_keys` is set.
/// For an encrypted outbound Resource, that part is already a slice of an
/// encrypted blob. The additional layer is not part of the normal raw
/// RESOURCE packet body.
pub fn next_part(&self, index: usize) -> Option<Vec<u8>> {
let part = self.outbound.as_ref()?.get_part(index)?;
if let Some(ref keys) = self.session_keys {
@@ -1252,8 +1315,10 @@ impl LinkResource {
}
}
/// Inbound counterpart of `next_part`. Decryption failures silently
/// drop the part (returning false) so the caller can simply retry.
/// Remove the wrapper's per-part encryption, if configured, before storing
/// the part. Returns `false` for decryption failure or an unaccepted part.
/// Normal Resource parts are slices of a whole encrypted blob and must not
/// be individually decrypted with this method.
pub fn receive_part(&mut self, data: Vec<u8>) -> bool {
let plaintext = if let Some(ref keys) = self.session_keys {
match rns_link::encryption::link_decrypt(keys, &data) {
@@ -1274,8 +1339,9 @@ impl LinkResource {
self.inbound.as_ref().is_some_and(|i| i.is_complete())
}
/// Reassemble the inbound resource, applying session-key decryption when
/// keys were provided at construction.
/// Reassemble the inbound Resource, decrypting the entire blob when
/// `session_keys` is set. `new_inbound` leaves those keys unset; callers
/// using the wrapper's encryption must assign matching keys themselves.
pub fn assemble(&mut self) -> Result<Vec<u8>, ResourceError> {
let decrypt_fn: Option<Box<ResourceDecryptor<'_>>> =
if let Some(ref keys) = self.session_keys {
@@ -1330,7 +1396,8 @@ pub enum TransferAction {
/// `(part_index, part_data)`.
SendPart(usize, Vec<u8>),
SendProof(Vec<u8>),
/// Hashmap update frame from receiver to sender.
/// Sender-to-receiver hashmap update: resource hash followed by
/// MessagePack `[segment_index, hashmap_bytes]`.
SendHmu(Vec<u8>),
/// Receiver-to-sender request for specific parts. Payload layout:
/// `exhausted_flag || optional last_map_hash || resource_hash || requested_part_hashes...`.
@@ -1383,9 +1450,13 @@ impl OutboundTransfer {
Ok(Self::from_resource(resource, rtt))
}
/// Pre-encrypt the blob with link session keys before chunking. Parts
/// emitted from this transfer are already ciphertext and must be sent
/// raw (context=Resource, no additional link-layer encryption).
/// Encrypt the blob before chunking. Send emitted parts as raw Resource
/// packet bodies, without another Link encryption layer.
///
/// Pass valid negotiated session keys. This convenience constructor
/// silently falls back to plaintext if `link_encrypt` fails; it does not
/// return that encryption error. Callers needing explicit failure handling
/// should build and validate their Resource before `from_prebuilt`.
pub fn new_encrypted(
data: Vec<u8>,
auto_compress: bool,
@@ -1444,10 +1515,17 @@ impl OutboundTransfer {
}
if !self.advertised {
let advertisement = match self.create_advertisement() {
Ok(bytes) => bytes,
Err(error) => {
self.resource.state = ResourceState::Failed;
return TransferAction::Failed(error.to_string());
}
};
self.advertised = true;
self.started_at = Instant::now();
self.resource.state = ResourceState::Advertised;
return TransferAction::SendAdvertisement(self.create_advertisement());
return TransferAction::SendAdvertisement(advertisement);
}
self.check_timeout()
@@ -1504,7 +1582,13 @@ impl OutboundTransfer {
if self.retries < MAX_ADV_RETRIES {
self.retries += 1;
self.started_at = Instant::now();
TransferAction::SendAdvertisement(self.create_advertisement())
match self.create_advertisement() {
Ok(bytes) => TransferAction::SendAdvertisement(bytes),
Err(error) => {
self.resource.state = ResourceState::Failed;
TransferAction::Failed(error.to_string())
}
}
} else {
self.resource.state = ResourceState::Failed;
TransferAction::Failed("resource advertisement timed out".to_string())
@@ -1542,16 +1626,20 @@ impl OutboundTransfer {
}
}
/// Consume a hashmap-update frame from the receiver.
/// Consume the receiver-feedback format paired with
/// [`InboundTransfer::create_hmu`]. It is distinct from the normal
/// sender-to-receiver RESOURCE_HMU map update.
///
/// Wire layout:
/// exhausted_flag(1) = 0xFF (complete) or 0x00 (incomplete)
/// [last_map_hash(4)] — only when exhausted
/// resource_hash(32)
/// requested_hashes(N * MAPHASH_LEN) — hashes the receiver still needs
/// ```text
/// flag(1): 0xFF = complete, 0x00 = incomplete
/// [last_map_hash(4)]: present only when complete
/// resource_hash(32)
/// requested_hashes(N * MAPHASH_LEN)
/// ```
///
/// When not exhausted, parts in the sent window whose hash is *not* in
/// the requested set are marked confirmed.
/// With an incomplete flag, mark sent-window parts absent from the requested
/// set as confirmed. With a complete flag, mark all parts confirmed and wait
/// for proof. Use `handle_request_packet` for standard RESOURCE_REQ traffic.
pub fn handle_hmu(&mut self, hmu_data: &[u8]) {
if hmu_data.is_empty()
|| matches!(
@@ -1648,17 +1736,19 @@ impl OutboundTransfer {
}
}
/// Sender-side handler for a RESOURCE_REQ built by the receiver's
/// `request_next()`.
/// Handle a standard RESOURCE_REQ from `InboundTransfer::request_next`,
/// deduplicating it by packet hash before processing.
///
/// Wire layout:
/// exhausted_flag(1) = 0xFF (needs more hashmap) / 0x00 (normal)
/// [last_map_hash(MAPHASH_LEN)] — only when exhausted
/// resource_hash(32)
/// requested_hashes(N * MAPHASH_LEN)
/// ```text
/// flag(1): 0xFF = needs more hashmap, 0x00 = normal
/// [last_map_hash(MAPHASH_LEN)]: present only when exhausted
/// resource_hash(32)
/// requested_hashes(N * MAPHASH_LEN)
/// ```
///
/// Returns the parts to retransmit and — when the receiver's hashmap is
/// exhausted — an HMU carrying the next hashmap segment.
/// Return requested parts and, when needed, a sender-to-receiver hashmap
/// update. The caller must supply the actual received packet hash and send
/// each returned action with its appropriate context and encryption.
pub fn handle_request_packet(
&mut self,
packet_hash: [u8; 32],
@@ -1801,18 +1891,11 @@ impl OutboundTransfer {
}
// HMU wire layout: resource_hash(32) || msgpack([segment, hashmap]).
let hmu_payload = {
use rmpv::Value;
let arr = Value::Array(vec![
Value::Integer((segment as u64).into()),
Value::Binary(hashmap_bytes),
]);
let mut buf = Vec::new();
buf.extend_from_slice(&self.resource.resource_hash);
rmpv::encode::write_value(&mut buf, &arr)
.expect("msgpack encode should succeed");
buf
};
let hmu_payload = crate::resource_control::encode_hashmap_update(
&self.resource.resource_hash,
segment,
&hashmap_bytes,
);
actions.push(TransferAction::SendHmu(hmu_payload));
}
@@ -1883,9 +1966,17 @@ impl OutboundTransfer {
}
/// Build the msgpack-encoded advertisement that precedes the transfer.
fn create_advertisement(&self) -> Vec<u8> {
use rmpv::Value;
fn create_advertisement(&self) -> Result<Vec<u8>, ResourceError> {
let mtu = rns_wire::constants::MTU;
if let Some(id) = self.resource.request_id.as_deref() {
crate::resource_control::check_control_frame(
rns_wire::context::PacketContext::ResourceAdv,
id.len(),
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
}
let mut adv = crate::resource_adv::ResourceAdvertisement::new(
self.resource.total_size,
self.resource.advertisement_data_size,
@@ -1911,59 +2002,8 @@ impl OutboundTransfer {
}
adv.request_id = self.resource.request_id.clone();
let q_val = match &adv.request_id {
Some(id) => Value::Binary(id.clone()),
None => Value::Nil,
};
let pairs: Vec<(Value, Value)> = vec![
(
Value::String("t".into()),
Value::Integer(adv.transfer_size.into()),
),
(
Value::String("d".into()),
Value::Integer(adv.data_size.into()),
),
(
Value::String("n".into()),
Value::Integer(adv.num_parts.into()),
),
(
Value::String("h".into()),
Value::Binary(adv.resource_hash.to_vec()),
),
(
Value::String("r".into()),
Value::Binary(adv.random_hash.to_vec()),
),
(
Value::String("o".into()),
Value::Binary(adv.original_hash.to_vec()),
),
(
Value::String("i".into()),
Value::Integer(adv.segment_index.into()),
),
(
Value::String("l".into()),
Value::Integer(adv.total_segments.into()),
),
(Value::String("q".into()), q_val),
(
Value::String("f".into()),
Value::Integer(adv.flags.to_byte().into()),
),
(
Value::String("m".into()),
Value::Binary(adv.hashmap.clone()),
),
];
let value = Value::Map(pairs);
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &value).expect("msgpack encode failed");
buf
crate::resource_control::check_advertisement(&adv, mtu)?;
Ok(adv.pack())
}
/// Fraction of unique parts transmitted, in `0.0..=1.0`.
@@ -1979,8 +2019,10 @@ impl OutboundTransfer {
}
}
/// Receiver-side resource transfer state machine. Accepts parts, emits HMUs
/// and RESOURCE_REQs, and produces the delivery proof once every part is in.
/// Receiver-side Resource state machine. Requests missing parts and hashmap
/// segments. A `Complete` action means all parts arrived; the owner must
/// then call [`Self::complete`] to decrypt/verify the content and generate
/// proof before reporting successful delivery.
pub struct InboundTransfer {
pub resource: InboundResource,
pub parts_since_hmu: usize,
@@ -2323,11 +2365,10 @@ impl InboundTransfer {
TransferAction::None
}
/// Merge a hashmap-update segment from the sender into our local
/// map_hashes and immediately request the parts it unlocks.
///
/// Wire layout:
/// resource_hash(32) || msgpack([segment_index, hashmap_bytes])
/// Merge a solicited sender hashmap segment and request newly available
/// parts. This method takes the decoded segment and hash bytes; the owner
/// must first authenticate/decrypt the control packet and verify its
/// resource hash after [`parse_hashmap_update`].
pub fn hashmap_update(&mut self, segment: usize, hashmap_data: &[u8]) -> TransferAction {
if self.resource.state != ResourceState::Transferring {
return TransferAction::None;
@@ -2404,8 +2445,10 @@ impl InboundTransfer {
self.request_next()
}
/// Encode the receiver-side HMU frame. See `handle_hmu` on the sender for
/// the wire layout.
/// Encode the receiver-feedback format consumed by
/// [`OutboundTransfer::handle_hmu`]. This is not the standard
/// sender-to-receiver RESOURCE_HMU map update. Normal receive flow uses
/// [`Self::request_next`] to request parts or additional map hashes.
pub fn create_hmu(&self) -> Vec<u8> {
let is_complete = self.resource.is_complete();
let exhausted = if is_complete {
@@ -2446,9 +2489,9 @@ impl InboundTransfer {
/// An optional `decrypt_fn` is passed through to `InboundResource::assemble()`.
///
/// The proof is computed over the full decompressed blob (metadata
/// header + payload) to match Python Resource.py:744, where
/// `self.data` still holds the metadata-inclusive bytes when
/// `prove()` runs. `assemble()` strips metadata from the value it
/// header + payload), matching Python `Resource.assemble` and
/// `Resource.prove`: `self.data` retains the metadata-inclusive bytes
/// until proof generation. `assemble()` strips metadata from the value it
/// returns to callers, so we reconstruct the pre-strip bytes here
/// before hashing.
pub fn complete(
@@ -2495,6 +2538,17 @@ impl InboundTransfer {
#[cfg(test)]
mod tests {
/// `Instant::now() - age`, or return from the test when the monotonic clock is
/// younger than `age`: Windows counts from boot, so fresh CI runners can't.
macro_rules! ago_or_skip {
($age:expr) => {
match std::time::Instant::now().checked_sub($age) {
Some(instant) => instant,
None => return,
}
};
}
use super::*;
#[test]
@@ -3007,7 +3061,7 @@ mod tests {
TransferAction::SendAdvertisement(_)
));
transfer.started_at = Instant::now() - Duration::from_secs(60);
transfer.started_at = ago_or_skip!(Duration::from_secs(60));
assert!(matches!(
transfer.check_timeout(),
TransferAction::SendAdvertisement(_)
@@ -3026,7 +3080,7 @@ mod tests {
.unwrap();
transfer.tick();
transfer.retries = MAX_ADV_RETRIES;
transfer.started_at = Instant::now() - Duration::from_secs(60);
transfer.started_at = ago_or_skip!(Duration::from_secs(60));
assert!(matches!(
transfer.check_timeout(),
@@ -3410,7 +3464,7 @@ mod tests {
let (data, mut sender, mut receiver) = loss_test_pair(8192, Duration::from_secs(2));
// Lose the first advertisement, then the first receiver request. The
// sender remains Advertised through arbitrary local polling.
sender.started_at = Instant::now() - Duration::from_secs(60);
sender.started_at = ago_or_skip!(Duration::from_secs(60));
assert!(matches!(
sender.tick(),
TransferAction::SendAdvertisement(_)
@@ -3423,7 +3477,7 @@ mod tests {
assert_eq!(sender.tick(), TransferAction::None);
}
assert_eq!(sender.resource.state, ResourceState::Advertised);
receiver.last_activity = Instant::now() - Duration::from_secs(60);
receiver.last_activity = ago_or_skip!(Duration::from_secs(60));
assert!(matches!(
receiver.check_timeout(),
TransferAction::SendRequest(_)
@@ -3448,7 +3502,7 @@ mod tests {
let mut lost_hmu = false;
for _ in 0..1000 {
if matches!(pending, TransferAction::None) {
receiver.last_activity = Instant::now() - Duration::from_secs(600);
receiver.last_activity = ago_or_skip!(Duration::from_secs(600));
pending = receiver.check_timeout();
}
let TransferAction::SendRequest(request) = pending else {
@@ -3506,7 +3560,7 @@ mod tests {
sender.handle_request(&request);
}
assert_eq!(sender.last_progress, progress_at);
sender.last_progress = Instant::now() - sender.progress_timeout() - Duration::from_secs(1);
sender.last_progress = ago_or_skip!(sender.progress_timeout() + Duration::from_secs(1));
assert_eq!(
sender.tick(),
TransferAction::Failed("resource part requests timed out".to_string())
@@ -3514,13 +3568,13 @@ mod tests {
assert!(sender.handle_request(&request).is_empty());
for _ in 0..MAX_RETRIES {
receiver.last_activity = Instant::now() - Duration::from_secs(600);
receiver.last_activity = ago_or_skip!(Duration::from_secs(600));
assert!(matches!(
receiver.check_timeout(),
TransferAction::SendRequest(_)
));
}
receiver.last_activity = Instant::now() - Duration::from_secs(600);
receiver.last_activity = ago_or_skip!(Duration::from_secs(600));
assert!(matches!(
receiver.check_timeout(),
TransferAction::Failed(_)
@@ -3540,7 +3594,7 @@ mod tests {
assert_eq!(sender.resource.state, ResourceState::AwaitingProof);
// Receiver has delivered, but its proof is lost. Sender must release
// ownership as failed, never infer success from all parts being sent.
sender.last_progress = Instant::now() - sender.progress_timeout() - Duration::from_secs(1);
sender.last_progress = ago_or_skip!(sender.progress_timeout() + Duration::from_secs(1));
assert_eq!(
sender.tick(),
TransferAction::Failed("resource proof timed out".to_string())
@@ -3566,14 +3620,14 @@ mod tests {
"do not replace the slow RTT with local scheduling time"
);
assert!(sender.progress_timeout() > Duration::from_secs(180));
sender.last_progress = Instant::now() - Duration::from_secs(180);
sender.last_progress = ago_or_skip!(Duration::from_secs(180));
assert_eq!(sender.check_timeout(), TransferAction::None);
// No absolute transfer deadline: requesting new parts restarts the
// bounded no-progress owner even after a long healthy transfer.
let mut next = vec![HASHMAP_IS_NOT_EXHAUSTED];
next.extend_from_slice(&sender.resource.resource_hash);
next.extend_from_slice(&sender.resource.map_hashes[4]);
sender.started_at = Instant::now() - Duration::from_secs(3600);
sender.started_at = ago_or_skip!(Duration::from_secs(3600));
sender.handle_request(&next);
assert!(sender.last_progress.elapsed() < Duration::from_secs(1));
assert_eq!(sender.check_timeout(), TransferAction::None);
@@ -4753,7 +4807,7 @@ mod tests {
inbound.outstanding_parts = 2;
// Set last_activity far enough in the past to trigger timeout
inbound.last_activity = Instant::now() - Duration::from_secs(60);
inbound.last_activity = ago_or_skip!(Duration::from_secs(60));
let initial_retries = inbound.retries_left;
let action = inbound.check_timeout();
@@ -4789,7 +4843,7 @@ mod tests {
inbound.outstanding_parts = 2;
inbound.retries_left = 0;
inbound.last_activity = Instant::now() - Duration::from_secs(60);
inbound.last_activity = ago_or_skip!(Duration::from_secs(60));
let action = inbound.check_timeout();
assert!(matches!(action, TransferAction::Failed(_)));
+91 -65
View File
@@ -1,9 +1,13 @@
use crate::resource::{MAPHASH_LEN, ResourceFlags};
/// Advertisement overhead in bytes (non-hashmap data).
/// Nominal non-hashmap overhead used by the hashmap-capacity estimator.
/// Actual MessagePack size depends on field values; use exact control admission
/// before transmission.
pub const OVERHEAD: usize = 134;
/// Maximum map-hash entries that fit alongside the advertisement overhead in one MDU.
/// Estimate map-hash capacity as `(mdu - OVERHEAD) / MAPHASH_LEN`. This does
/// not check the actual advertisement encoding or encrypted packet length; use
/// [`crate::resource_control::check_advertisement`] for admission.
pub fn hashmap_max_len(mdu: usize) -> usize {
if mdu > OVERHEAD {
(mdu - OVERHEAD) / MAPHASH_LEN
@@ -48,8 +52,9 @@ pub struct ResourceAdvertisement {
}
impl ResourceAdvertisement {
/// Build an advertisement with no metadata prefix. Equivalent to
/// [`Self::with_metadata_size`] with `metadata_size = 0`.
/// Build an advertisement with a local metadata-size annotation of zero.
/// Equivalent to [`Self::with_metadata_size`] with `metadata_size = 0`; it
/// does not clear the caller-supplied `has_metadata` flag.
// Mirrors the Resource ADV wire fields; grouping these into a builder
// would hide the packet layout this constructor exists to preserve.
#[allow(clippy::too_many_arguments)]
@@ -76,9 +81,10 @@ impl ResourceAdvertisement {
)
}
/// Build an advertisement, truncating `map_hashes` to what actually fits in
/// the MDU. Callers are expected to send the remaining hashes in a
/// subsequent hashmap-update packet.
/// Build an advertisement, truncating `map_hashes` using the nominal MDU
/// estimate. Send remaining hashes in subsequent hashmap updates. Before
/// sending, call [`crate::resource_control::check_advertisement`] to verify
/// the actual encoded packet size.
// Same Resource ADV field set as `new`, plus the local metadata prefix
// size needed to split payload from metadata after receive.
#[allow(clippy::too_many_arguments)]
@@ -117,11 +123,25 @@ impl ResourceAdvertisement {
}
}
/// Decode an advertisement produced by [`Self::pack`] or by the Python
/// reference implementation.
/// Decode an advertisement body after checking that its length fits an
/// encrypted Link control packet with a minimum header and base MTU.
///
/// This is field decoding, not complete transfer admission. It accepts
/// trailing bytes, chooses the first matching map key, and truncates `h`
/// and `o` to 32 bytes. The random tag must contain at least four bytes.
/// Callers must validate segment counts, lengths, flags and hash-map shape
/// before allocating a receiver; see [`crate::resource::InboundResource`].
pub fn unpack(data: &[u8]) -> Result<Self, String> {
use rmpv::Value;
crate::resource_control::check_control_frame(
rns_wire::context::PacketContext::ResourceAdv,
data.len(),
true,
rns_wire::constants::HEADER_MINSIZE,
rns_wire::constants::MTU,
)
.map_err(|error| error.to_string())?;
let value =
rmpv::decode::read_value(&mut &data[..]).map_err(|e| format!("msgpack decode: {e}"))?;
@@ -205,64 +225,29 @@ impl ResourceAdvertisement {
/// Encode as the msgpack map described on the struct docs.
pub fn pack(&self) -> Vec<u8> {
use rmpv::Value;
let q_val = match &self.request_id {
Some(id) => Value::Binary(id.clone()),
None => Value::Nil,
};
let pairs: Vec<(Value, Value)> = vec![
(
Value::String("t".into()),
Value::Integer(self.transfer_size.into()),
),
(
Value::String("d".into()),
Value::Integer(self.data_size.into()),
),
(
Value::String("n".into()),
Value::Integer(self.num_parts.into()),
),
(
Value::String("h".into()),
Value::Binary(self.resource_hash.to_vec()),
),
(
Value::String("r".into()),
Value::Binary(self.random_hash.to_vec()),
),
(
Value::String("o".into()),
Value::Binary(self.original_hash.to_vec()),
),
(
Value::String("i".into()),
Value::Integer(self.segment_index.into()),
),
(
Value::String("l".into()),
Value::Integer(self.total_segments.into()),
),
(Value::String("q".into()), q_val),
(
Value::String("f".into()),
Value::Integer(self.flags.to_byte().into()),
),
(
Value::String("m".into()),
Value::Binary(self.hashmap.clone()),
),
];
let value = Value::Map(pairs);
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &value).expect("msgpack encode should succeed");
buf
let mut output = Vec::new();
self.pack_into(&mut output).expect("Vec messagepack write");
output
}
/// Split the packed `hashmap` field into fixed-length map-hash entries.
/// Write the same wire encoding to either a real buffer or bounded counter.
/// Borrowing fields avoids allocating a duplicate hashmap/request-ID tree.
pub fn pack_into<W: std::io::Write>(&self, writer: W) -> Result<(), rmp_serde::encode::Error> {
serde::Serialize::serialize(
&AdvertisementRef(self),
&mut rmp_serde::Serializer::new(writer),
)
}
pub fn encoded_len(&self) -> Result<usize, crate::resource::ResourceError> {
let mut counter = EncodedLength(0);
self.pack_into(&mut counter)
.map_err(|_| crate::resource::ResourceError::TooLarge)?;
Ok(counter.0)
}
/// Split `hashmap` into four-byte entries, dropping any incomplete trailing
/// entry. Validate divisibility first when rejecting malformed input.
pub fn get_map_hashes(&self) -> Vec<[u8; MAPHASH_LEN]> {
self.hashmap
.as_chunks::<MAPHASH_LEN>()
@@ -277,6 +262,47 @@ impl ResourceAdvertisement {
}
}
struct AdvertisementRef<'a>(&'a ResourceAdvertisement);
struct BinaryRef<'a>(&'a [u8]);
impl serde::Serialize for BinaryRef<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_bytes(self.0)
}
}
impl serde::Serialize for AdvertisementRef<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
let a = self.0;
let mut map = serializer.serialize_map(Some(11))?;
map.serialize_entry("t", &a.transfer_size)?;
map.serialize_entry("d", &a.data_size)?;
map.serialize_entry("n", &a.num_parts)?;
map.serialize_entry("h", &BinaryRef(&a.resource_hash))?;
map.serialize_entry("r", &BinaryRef(&a.random_hash))?;
map.serialize_entry("o", &BinaryRef(&a.original_hash))?;
map.serialize_entry("i", &a.segment_index)?;
map.serialize_entry("l", &a.total_segments)?;
map.serialize_entry("q", &a.request_id.as_deref().map(BinaryRef))?;
map.serialize_entry("f", &a.flags.to_byte())?;
map.serialize_entry("m", &BinaryRef(&a.hashmap))?;
map.end()
}
}
/// Counting sink uses the actual serializer, with no transfer-sized scratch.
struct EncodedLength(usize);
impl std::io::Write for EncodedLength {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0 = self
.0
.checked_add(bytes.len())
.ok_or_else(|| std::io::Error::other("length overflow"))?;
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
+354
View File
@@ -0,0 +1,354 @@
//! Checked admission for fixed-stride Resource control frames.
//! A decoder profile is not a promise that the transport can carry a control.
use crate::resource::{
MAPHASH_LEN, MAX_EFFICIENT_SIZE, MAX_RESOURCE_SIZE, MAX_SEGMENTS, RANDOM_HASH_SIZE,
ResourceError, ResourceFlags, SDU, WINDOW_MAX,
};
use crate::resource_adv::ResourceAdvertisement;
use rns_wire::context::PacketContext;
/// Pinned Python Resource hashmap stride. Never derive it from a small custom MTU.
pub const HASHMAP_STRIDE: usize = 74;
/// CBC token framing used by Link encryption, with checked arithmetic.
pub fn encrypted_len(plaintext_len: usize) -> Result<usize, ResourceError> {
plaintext_len
.checked_div(16)
.and_then(|n| n.checked_add(1))
.and_then(|n| n.checked_mul(16))
.and_then(|n| n.checked_add(48))
.ok_or(ResourceError::TooLarge)
}
/// Check `header_len + body_len` against `mtu`, including CBC token overhead
/// when `encrypted` is true. `header_len` is caller-supplied; any additional
/// interface framing is outside this calculation. `context` labels errors,
/// not a check that the payload matches that context.
pub fn check_control_frame(
context: PacketContext,
payload_len: usize,
encrypted: bool,
header_len: usize,
mtu: usize,
) -> Result<(), ResourceError> {
let body = if encrypted {
encrypted_len(payload_len)?
} else {
payload_len
};
let encoded_len = header_len
.checked_add(body)
.ok_or(ResourceError::TooLarge)?;
if encoded_len > mtu {
return Err(ResourceError::ControlFrameTooLarge {
context,
encoded_len,
mtu,
});
}
Ok(())
}
/// Check one already-described advertisement without allocating its encoded body.
pub fn check_advertisement(
advertisement: &ResourceAdvertisement,
mtu: usize,
) -> Result<(), ResourceError> {
check_control_frame(
PacketContext::ResourceAdv,
advertisement.encoded_len()?,
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)
}
/// Preflight the largest control shapes across all segments, before copying the
/// source, allocating parts/hashmaps, reserving a transfer, or invoking encryption.
/// Compression only shrinks the admitted upper bound. The 74-hash stride stays
/// fixed. Request identifiers are borrowed here, including their real length.
pub fn preflight_outbound(
data_len: usize,
metadata_len: Option<usize>,
request_id: Option<&[u8]>,
is_response: bool,
encrypted: bool,
mtu: usize,
) -> Result<(), ResourceError> {
preflight_outbound_with_sdu(
data_len,
metadata_len,
request_id,
is_response,
encrypted,
SDU,
mtu,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn preflight_outbound_with_sdu(
data_len: usize,
metadata_len: Option<usize>,
request_id: Option<&[u8]>,
is_response: bool,
encrypted: bool,
part_sdu: usize,
mtu: usize,
) -> Result<(), ResourceError> {
if part_sdu == 0 {
return Err(ResourceError::InvalidAdvertisement);
}
if data_len > MAX_RESOURCE_SIZE {
return Err(ResourceError::TooLarge);
}
let metadata_wire = metadata_len
.map(|n| n.checked_add(3).ok_or(ResourceError::MetadataTooLarge))
.transpose()?
.unwrap_or(0);
if metadata_wire > MAX_EFFICIENT_SIZE {
return Err(ResourceError::MetadataTooLarge);
}
let total_data = data_len
.checked_add(metadata_wire)
.ok_or(ResourceError::TooLarge)?;
let first = data_len.min(MAX_EFFICIENT_SIZE - metadata_wire);
let total_segments = 1usize
.checked_add(data_len.saturating_sub(first).div_ceil(MAX_EFFICIENT_SIZE))
.ok_or(ResourceError::TooLarge)?;
if total_segments > MAX_SEGMENTS {
return Err(ResourceError::TooLarge);
}
// Request ID storage is bounded by the packet before copying into the small
// temporary advertisement. No attacker-sized allocation precedes admission.
if let Some(id) = request_id {
check_control_frame(
PacketContext::ResourceAdv,
id.len(),
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
}
let segment_len = total_data.min(MAX_EFFICIENT_SIZE);
let blob = segment_len
.checked_add(RANDOM_HASH_SIZE)
.ok_or(ResourceError::TooLarge)?;
let transfer_size = if encrypted {
encrypted_len(blob)?
} else {
blob
};
let parts = transfer_size.div_ceil(part_sdu);
let hashes = [[0u8; MAPHASH_LEN]; HASHMAP_STRIDE];
let mut advertisement = ResourceAdvertisement::new(
transfer_size,
total_data,
parts,
[0; 32],
vec![0; RANDOM_HASH_SIZE],
ResourceFlags {
encrypted,
compressed: false,
split: total_segments > 1,
is_request: request_id.is_some() && !is_response,
is_response,
has_metadata: metadata_len.is_some(),
},
&hashes[..parts.min(HASHMAP_STRIDE)],
rns_wire::constants::LINK_MDU,
);
advertisement.segment_index = total_segments;
advertisement.total_segments = total_segments;
advertisement.request_id = request_id.map(<[u8]>::to_vec);
check_advertisement(&advertisement, mtu)?;
// HMU uses the production MessagePack encoder and largest possible segment
// index for this admitted source. At most 296 hashmap octets are materialized.
let max_map_segment = parts.saturating_sub(1) / HASHMAP_STRIDE;
let hmu = encode_hashmap_update(
&[0; 32],
max_map_segment,
&[0; HASHMAP_STRIDE * MAPHASH_LEN],
);
check_control_frame(
PacketContext::ResourceHmu,
hmu.len(),
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
// Exhaustion marker + last map hash + resource hash + maximum request window.
check_control_frame(
PacketContext::ResourceReq,
1 + MAPHASH_LEN + 32 + WINDOW_MAX * MAPHASH_LEN,
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
check_control_frame(
PacketContext::ResourcePrf,
64,
false,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)?;
check_control_frame(
PacketContext::ResourceIcl,
32,
true,
rns_wire::constants::HEADER_MINSIZE,
mtu,
)
}
/// Shared HMU encoder used by size admission and real transmission.
pub fn encode_hashmap_update(resource_hash: &[u8; 32], segment: usize, hashes: &[u8]) -> Vec<u8> {
use rmpv::Value;
let value = Value::Array(vec![
Value::Integer((segment as u64).into()),
Value::Binary(hashes.to_vec()),
]);
let mut output = resource_hash.to_vec();
rmpv::encode::write_value(&mut output, &value).expect("Vec MessagePack write");
output
}
#[cfg(test)]
mod tests {
use super::*;
fn advertisement(request_id: Option<Vec<u8>>) -> ResourceAdvertisement {
let mut adv = ResourceAdvertisement::new(
1_048_640,
1_048_575,
2260,
[1; 32],
vec![2; 4],
ResourceFlags {
encrypted: true,
compressed: false,
split: false,
is_request: request_id.is_some(),
is_response: false,
has_metadata: false,
},
&[[3; 4]; 74],
rns_wire::constants::LINK_MDU,
);
adv.request_id = request_id;
adv
}
#[test]
fn control_preflight_shared_advertisement_encoder_matches_retained_wire() {
use rmpv::Value;
for id in [None, Some(vec![7; 16])] {
let a = advertisement(id);
let pairs = vec![
("t", Value::from(a.transfer_size as u64)),
("d", Value::from(a.data_size as u64)),
("n", Value::from(a.num_parts as u64)),
("h", Value::Binary(a.resource_hash.to_vec())),
("r", Value::Binary(a.random_hash.clone())),
("o", Value::Binary(a.original_hash.to_vec())),
("i", Value::from(a.segment_index as u64)),
("l", Value::from(a.total_segments as u64)),
(
"q",
a.request_id
.clone()
.map(Value::Binary)
.unwrap_or(Value::Nil),
),
("f", Value::from(a.flags.to_byte())),
("m", Value::Binary(a.hashmap.clone())),
];
let old = Value::Map(
pairs
.into_iter()
.map(|(k, v)| (Value::from(k), v))
.collect(),
);
let mut expected = Vec::new();
rmpv::encode::write_value(&mut expected, &old).unwrap();
assert_eq!(a.pack(), expected);
assert_eq!(a.encoded_len().unwrap(), expected.len());
assert!(check_advertisement(&a, 500).is_ok());
}
let a = advertisement(Some(vec![7; 16]));
let exact = 19 + encrypted_len(a.encoded_len().unwrap()).unwrap();
assert_eq!(exact, 499);
assert!(check_advertisement(&a, 499).is_ok());
assert!(matches!(
check_advertisement(&a, 498),
Err(ResourceError::ControlFrameTooLarge {
encoded_len: 499,
..
})
));
}
#[test]
fn control_preflight_extreme_metadata_shape_uses_no_large_source() {
let mut a = advertisement(Some(vec![7; 16]));
a.data_size = 1 << 30;
a.segment_index = 1024;
a.total_segments = 1025;
a.flags.split = true;
assert!(matches!(
check_advertisement(&a, 500),
Err(ResourceError::ControlFrameTooLarge { .. })
));
assert!(matches!(
preflight_outbound(0, None, Some(&[7; 500]), false, true, 500),
Err(ResourceError::ControlFrameTooLarge { .. })
));
assert!(matches!(
encrypted_len(usize::MAX),
Err(ResourceError::TooLarge)
));
}
#[test]
fn control_preflight_preserves_stride_and_refuses_before_encrypt_or_parts() {
assert_eq!(
HASHMAP_STRIDE,
crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU)
);
preflight_outbound(75 * SDU, None, None, false, true, 500).unwrap();
preflight_outbound(MAX_EFFICIENT_SIZE, None, Some(&[0; 16]), false, true, 500).unwrap();
let called = std::cell::Cell::new(false);
let encrypt = |_: &[u8]| {
called.set(true);
Vec::new()
};
let result = crate::resource::OutboundResource::with_options(
vec![0; 32],
false,
None,
Some(0),
Some(&encrypt),
);
assert!(matches!(result, Err(ResourceError::InvalidAdvertisement)));
assert!(!called.get());
}
#[test]
fn control_preflight_late_metadata_mutation_cannot_enter_advertised() {
let mut transfer = crate::resource::OutboundTransfer::new(
vec![0; 16],
false,
std::time::Duration::from_millis(10),
)
.unwrap();
transfer.resource.request_id = Some(vec![0; 500]);
assert!(matches!(
transfer.tick(),
crate::resource::TransferAction::Failed(_)
));
assert_eq!(
transfer.resource.state,
crate::resource::ResourceState::Failed
);
assert!(matches!(
transfer.tick(),
crate::resource::TransferAction::Failed(_)
));
assert!(ResourceAdvertisement::unpack(&vec![0; 500]).is_err());
}
}
+8 -2
View File
@@ -1,6 +1,12 @@
//! rnsh channel message codecs.
//! rnsh Channel message codecs.
//!
//! Python reference: `RNS/Utilities/rnsh/protocol.py`.
//! Use `MessageBase` to pack/unpack a message or `RnshMessage::decode` to
//! dispatch by type, and register `MESSAGE_TYPES` with the Channel. These
//! codecs do not execute commands or authorize a remote shell.
//!
//! Stream messages use IDs 0/1/2 for stdin/stdout/stderr and the Buffer
//! compression format. Decoding expands compressed data while retaining its
//! flag; clear the flag or recompress before repacking that message.
use std::io::Cursor;
+8 -4
View File
@@ -10,10 +10,14 @@ pub const OVERHEAD: usize = 8;
/// Stream frame for the Buffer protocol.
///
/// Wire layout (2-byte big-endian header followed by payload):
/// - bit 15: EOF flag
/// - bit 14: compressed flag (payload is bz2)
/// - bits 13..0: stream ID (0..=16_383)
/// Wire layout (two-byte big-endian header followed by payload):
/// - bit 15: EOF
/// - bit 14: bzip2-compressed payload
/// - bits 13..0: stream ID (`0..=16_383`)
///
/// `MessageBase::unpack` decompresses into `data` but retains the received
/// `compressed` flag. `pack` only serializes the fields; before repacking a
/// decoded compressed frame, clear the flag or recompress its data.
#[derive(Debug, Clone)]
pub struct StreamDataMessage {
pub stream_id: u16,
+1 -1
View File
@@ -4,7 +4,7 @@ description = "Hardware-backed identity (YubiKey/Nitrokey PIV) for Reticulum"
publish = false
version.workspace = true
edition.workspace = true
license.workspace = true
license-file.workspace = true
rust-version.workspace = true
[dependencies]
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff. Show more