From dc50ce539032651ae066ccfd2596f863b9fc8aa0 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:13:50 -0700 Subject: [PATCH] docs: refresh guides and reference help --- CHANGELOG.md | 7 +- README.md | 95 +++-- api/README.md | 6 +- api/migrations/1.4.md | 12 +- api/migrations/capacity-and-receipts.md | 15 +- crates/rns-crypto/src/aes_cbc.rs | 10 +- crates/rns-crypto/src/ed25519.rs | 4 +- crates/rns-crypto/src/hkdf.rs | 6 +- crates/rns-crypto/src/lib.rs | 11 +- crates/rns-crypto/src/pkcs7.rs | 6 +- crates/rns-crypto/src/token.rs | 20 +- crates/rns-crypto/src/x25519.rs | 11 +- crates/rns-identity/src/announce.rs | 20 +- crates/rns-identity/src/announce_state.rs | 9 +- crates/rns-identity/src/destination.rs | 64 ++- crates/rns-identity/src/identity.rs | 43 +- crates/rns-identity/src/ifac.rs | 8 +- crates/rns-identity/src/known_destinations.rs | 8 +- crates/rns-identity/src/persistence.rs | 6 +- crates/rns-identity/src/persistence/strict.rs | 8 +- crates/rns-identity/src/ratchet.rs | 69 ++- crates/rns-interface/src/android_usb.rs | 40 +- crates/rns-interface/src/auto.rs | 36 +- crates/rns-interface/src/ax25kiss.rs | 11 +- crates/rns-interface/src/backbone.rs | 26 +- crates/rns-interface/src/ble_central_apple.rs | 26 +- .../src/ble_central_apple_connect.rs | 56 +-- .../src/ble_central_lifecycle.rs | 14 +- crates/rns-interface/src/ble_peer.rs | 85 ++-- .../rns-interface/src/ble_peer_lifecycle.rs | 40 +- crates/rns-interface/src/ble_rnode.rs | 101 ++--- crates/rns-interface/src/hdlc.rs | 8 +- crates/rns-interface/src/i2p.rs | 21 +- crates/rns-interface/src/kiss.rs | 2 +- crates/rns-interface/src/kiss_iface.rs | 12 +- crates/rns-interface/src/lib.rs | 8 +- crates/rns-interface/src/local.rs | 14 +- crates/rns-interface/src/pipe.rs | 8 +- crates/rns-interface/src/rnode.rs | 61 +-- crates/rns-interface/src/rnode_admin.rs | 4 +- .../rns-interface/src/rnode_capabilities.rs | 38 +- crates/rns-interface/src/rnode_multi.rs | 6 +- crates/rns-interface/src/rnode_protocol.rs | 36 +- crates/rns-interface/src/serial.rs | 4 +- crates/rns-interface/src/socket_tuning.rs | 20 +- crates/rns-interface/src/tcp.rs | 7 +- crates/rns-interface/src/traits.rs | 15 +- crates/rns-interface/src/weave.rs | 9 +- crates/rns-link/src/clock.rs | 24 +- crates/rns-link/src/constants.rs | 12 +- crates/rns-link/src/encryption.rs | 5 +- crates/rns-link/src/handshake.rs | 35 +- crates/rns-link/src/keepalive.rs | 7 +- crates/rns-link/src/key_derivation.rs | 9 +- crates/rns-link/src/lib.rs | 6 +- crates/rns-link/src/link.rs | 85 +++- crates/rns-link/src/request.rs | 19 +- crates/rns-protocol/src/buffer.rs | 38 +- crates/rns-protocol/src/channel.rs | 89 ++-- crates/rns-protocol/src/compression.rs | 7 +- crates/rns-protocol/src/lib.rs | 13 +- crates/rns-protocol/src/resource.rs | 268 +++++++----- crates/rns-protocol/src/resource_adv.rs | 33 +- crates/rns-protocol/src/resource_control.rs | 5 +- crates/rns-protocol/src/rnsh.rs | 10 +- crates/rns-protocol/src/stream_data.rs | 12 +- crates/rns-ratkey/src/apdu.rs | 48 ++- crates/rns-ratkey/src/attestation.rs | 70 ++-- crates/rns-ratkey/src/backend.rs | 29 +- crates/rns-ratkey/src/detect.rs | 10 +- crates/rns-ratkey/src/error.rs | 12 +- crates/rns-ratkey/src/hardware.rs | 33 +- crates/rns-ratkey/src/hwid.rs | 27 +- crates/rns-ratkey/src/lib.rs | 21 +- crates/rns-ratkey/src/mock.rs | 10 +- crates/rns-ratkey/src/pin.rs | 9 +- crates/rns-ratkey/src/provision.rs | 39 +- crates/rns-ratkey/src/seed.rs | 20 +- crates/rns-ratkey/src/session.rs | 65 ++- crates/rns-ratkey/src/transport.rs | 14 +- crates/rns-runtime/examples/README.md | 87 +++- crates/rns-runtime/examples/echo.rs | 2 +- crates/rns-runtime/src/buffer_stream.rs | 11 +- crates/rns-runtime/src/config.rs | 13 +- crates/rns-runtime/src/config/ifac.rs | 12 +- crates/rns-runtime/src/deferred_request.rs | 7 +- .../rns-runtime/src/destination_resolver.rs | 26 +- crates/rns-runtime/src/destination_runtime.rs | 46 +- crates/rns-runtime/src/inbound_link_packet.rs | 12 +- crates/rns-runtime/src/interface_factory.rs | 115 +++-- crates/rns-runtime/src/jobs.rs | 6 +- crates/rns-runtime/src/lifecycle.rs | 21 +- crates/rns-runtime/src/link_client.rs | 17 +- crates/rns-runtime/src/link_manager.rs | 325 +++++++++----- crates/rns-runtime/src/link_session.rs | 121 +++++- crates/rns-runtime/src/platform.rs | 12 +- crates/rns-runtime/src/probe.rs | 30 +- crates/rns-runtime/src/remote_management.rs | 24 +- crates/rns-runtime/src/resource_source.rs | 10 +- crates/rns-runtime/src/reticulum.rs | 394 ++++++++++------- crates/rns-runtime/src/rncp.rs | 76 +++- crates/rns-runtime/src/rnsh.rs | 45 +- crates/rns-runtime/src/rpc.rs | 49 ++- crates/rns-runtime/src/rpc_server.rs | 17 +- crates/rns-runtime/src/shared_instance.rs | 24 +- .../rns-tools/src/commands/ifac_migration.rs | 3 +- crates/rns-tools/src/commands/rncp.rs | 28 +- .../src/commands/rnid/hw_commands.rs | 36 +- crates/rns-tools/src/commands/rnid/main.rs | 60 ++- crates/rns-tools/src/commands/rnodeconf.rs | 60 ++- crates/rns-tools/src/commands/rnpath.rs | 20 +- crates/rns-tools/src/commands/rnprobe.rs | 10 +- crates/rns-tools/src/commands/rnsd.rs | 10 +- crates/rns-tools/src/commands/rnsh.rs | 18 + crates/rns-tools/src/commands/rnstatus.rs | 10 +- crates/rns-tools/src/format.rs | 9 +- crates/rns-tools/src/hash.rs | 4 +- crates/rns-tools/src/lib.rs | 17 +- .../src/actor/announce_admission.rs | 3 +- crates/rns-transport/src/actor/mod.rs | 216 ++++++---- .../rns-transport/src/actor/path_recovery.rs | 3 +- crates/rns-transport/src/announce.rs | 18 +- crates/rns-transport/src/announce_dispatch.rs | 34 +- crates/rns-transport/src/await_path.rs | 29 +- crates/rns-transport/src/background_egress.rs | 42 +- crates/rns-transport/src/blackhole.rs | 40 +- crates/rns-transport/src/constants.rs | 154 ++++--- .../rns-transport/src/discovery/announcer.rs | 116 +++-- .../rns-transport/src/discovery/app_data.rs | 83 ++-- .../src/discovery/autoconnect.rs | 17 +- .../src/discovery/blackhole_manifest.rs | 82 ++-- .../src/discovery/blackhole_subscriber.rs | 67 ++- .../rns-transport/src/discovery/constants.rs | 68 +-- crates/rns-transport/src/discovery/mod.rs | 24 +- .../rns-transport/src/discovery/receiver.rs | 116 +++-- crates/rns-transport/src/discovery/stamper.rs | 44 +- crates/rns-transport/src/discovery/storage.rs | 75 +++- crates/rns-transport/src/hashlist.rs | 35 +- crates/rns-transport/src/ifac.rs | 46 +- crates/rns-transport/src/ingress.rs | 83 ++-- .../rns-transport/src/interface_ownership.rs | 57 ++- crates/rns-transport/src/lib.rs | 16 +- .../src/link_endpoint_dispatch.rs | 56 ++- crates/rns-transport/src/link_messages.rs | 41 +- crates/rns-transport/src/link_table.rs | 29 +- crates/rns-transport/src/link_transit.rs | 11 +- crates/rns-transport/src/messages.rs | 395 +++++++++++------- crates/rns-transport/src/path_discovery.rs | 7 +- crates/rns-transport/src/path_recovery.rs | 20 +- crates/rns-transport/src/path_table.rs | 72 ++-- crates/rns-transport/src/persistence.rs | 225 +++++++--- crates/rns-transport/src/rate_limit.rs | 39 +- crates/rns-transport/src/reverse_table.rs | 18 +- crates/rns-transport/src/traffic.rs | 14 +- crates/rns-transport/src/tunnel.rs | 59 ++- crates/rns-wire/src/constants.rs | 5 +- crates/rns-wire/src/context.rs | 7 +- crates/rns-wire/src/flags.rs | 32 +- crates/rns-wire/src/hash.rs | 40 +- crates/rns-wire/src/header.rs | 9 +- crates/rns-wire/src/lib.rs | 8 +- crates/rns-wire/src/packet.rs | 23 +- crates/rns-wire/src/proof.rs | 5 +- crates/rns-wire/src/receipt.rs | 37 +- crates/rns-wire/src/types.rs | 12 +- scripts/ci/check_release_archives.py | 11 +- scripts/ci/check_source_release_contract.py | 6 +- tools/check-api-baseline.py | 11 +- tools/check-api-manifest.py | 6 +- 169 files changed, 4288 insertions(+), 2395 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index feb3ce5..01aa154 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,7 +32,7 @@ - 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 no longer leave copies of keys or plaintext in freed memory, and identity files larger than 1 KiB are refused. +- 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. @@ -46,12 +46,15 @@ ## 1.4.0 - 2026-10-12 +This section records the source-version transition. It is not a standalone +1.4.0 binary release; the published standalone release remains 1.3.0. + - 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. This source-breaking release uses the `~1.4.0` compatibility line. +- 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 diff --git a/README.md b/README.md index 1dedfee..e432425 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ [![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-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) | @@ -39,6 +39,18 @@ rsReticulum can live beside other Reticulum tools on `PATH` without worry. ## Build It +This guide describes the 1.4.0 source line at `5b38cae702a5b3984adf12a435f6d3012fcf90e1`, also used by Ratspeak 1.0.37. The published standalone tool download is [v1.3.0](https://github.com/ratspeak/rsReticulum/releases/tag/v1.3.0); use [its README](https://github.com/ratspeak/rsReticulum/blob/v1.3.0/README.md) and bundled `--help` for that build. A Cargo version in the current source is not a separate binary release. + +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 +62,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 +88,9 @@ Arch: sudo pacman -S --needed base-devel pkgconf ``` -##### Build the tools: +Build the tools: ```bash -cd rsReticulum cargo build --release --locked ``` @@ -92,7 +102,6 @@ Build Tools, install the "Desktop development with C++" workload. Build from PowerShell: ```powershell -cd rsReticulum cargo build --release --locked ``` @@ -111,10 +120,10 @@ 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] @@ -132,9 +141,9 @@ rncp-rs rncp-rs -l [-b SECONDS] [-s DEST_DIR] [-a ]... rncp-rs -l -F [-j ] [-a |-n]... rncp-rs -f [-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] [-- CMD...] ``` @@ -142,14 +151,21 @@ rnsh-rs [-i FILE] [-s NAME] [-N] [-m] [-w SECONDS] [-- 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 ` or an `allowed_identities` file. -`rncp-rs -F` can serve fetch requests to authenticated clients; use -`-j ` to bound file access unless unrestricted fetch paths are -intentional. +`rncp-rs` has a listener authorization limitation in both the current source +and standalone 1.3.0: `-a ` 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 ` to constrain fetched paths to a directory under trusted local +control; it is not an operating-system sandbox. + +`rnodeconf-rs` in both the current source and standalone 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 +173,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 +189,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 -w peer.pub -rnid-rs -M -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 -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 +216,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 +237,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] @@ -244,13 +261,13 @@ 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. | @@ -273,8 +290,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 @@ -283,15 +300,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 standalone 1.3.0 release baseline 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 @@ -308,7 +327,7 @@ Known gaps and intentional limits: 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. diff --git a/api/README.md b/api/README.md index 2bb500e..7d865a6 100644 --- a/api/README.md +++ b/api/README.md @@ -1,5 +1,9 @@ # Rust API +This guide describes the 1.4.0 source API. For published standalone 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,7 +73,7 @@ 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 in-development [capacity, IFAC and receipt migration guide](migrations/capacity-and-receipts.md) describes the next coordinated source boundary. It does not select a release version. +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 diff --git a/api/migrations/1.4.md b/api/migrations/1.4.md index 22814d2..93806c3 100644 --- a/api/migrations/1.4.md +++ b/api/migrations/1.4.md @@ -1,4 +1,8 @@ -# 1.4 source migration (unreleased) +# Migrating to the 1.4 source API + +The 1.4 source line is used by Ratspeak 1.0.37. The published standalone +command-line download remains 1.3.0; these APIs and migration commands require +a matching 1.4 source build. The 1.4 source line introduces explicit interface-capacity ownership and durable application admission. Existing published releases are unchanged. Migrate @@ -110,9 +114,9 @@ match needs a wildcard arm. 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, and check that -deadline on a regular tick: tokio's timers and the operating system's waits -count awake time only, so a timer armed for it fires late by the whole sleep. +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. diff --git a/api/migrations/capacity-and-receipts.md b/api/migrations/capacity-and-receipts.md index 9ae6cbc..4726ecb 100644 --- a/api/migrations/capacity-and-receipts.md +++ b/api/migrations/capacity-and-receipts.md @@ -1,7 +1,8 @@ # Capacity, IFAC configuration, and application packet receipts -These changes are part of the unreleased1.4.0 source line. They do not change -the existing published1.3.0 release or establish a new release date. +These changes are part of the 1.4.0 source line used by Ratspeak 1.0.37. They +are not included in the published standalone 1.3.0 tools. The migration +command below requires a matching 1.4 source build. ## Interface ownership and packet capacity @@ -50,10 +51,12 @@ verification or the exact interface owner retained from the request/proof path. ## Explicit IFAC units -An explicit `ifac_size` is interpreted as bits only when accompanied by -`ifac_size_unit = bits`. The byte escape hatch is `ifac_size_bytes`; it cannot -coexist with the bits fields. Supported effective sizes are 1–64 bytes. A bare -old `ifac_size` requires migration; its historical meaning is not guessed. +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. diff --git a/crates/rns-crypto/src/aes_cbc.rs b/crates/rns-crypto/src/aes_cbc.rs index f31b0d3..7ca9d2f 100644 --- a/crates/rns-crypto/src/aes_cbc.rs +++ b/crates/rns-crypto/src/aes_cbc.rs @@ -1,6 +1,7 @@ //! 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; @@ -73,7 +74,10 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result, AesCb 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, AesCbcError> { if iv.len() != AES_BLOCK_SIZE { return Err(AesCbcError::InvalidIvLength(iv.len())); diff --git a/crates/rns-crypto/src/ed25519.rs b/crates/rns-crypto/src/ed25519.rs index 8b8e4e8..0729a82 100644 --- a/crates/rns-crypto/src/ed25519.rs +++ b/crates/rns-crypto/src/ed25519.rs @@ -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, } diff --git a/crates/rns-crypto/src/hkdf.rs b/crates/rns-crypto/src/hkdf.rs index 730646c..a4e9621 100644 --- a/crates/rns-crypto/src/hkdf.rs +++ b/crates/rns-crypto/src/hkdf.rs @@ -43,8 +43,10 @@ pub fn hkdf_sha256( 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)`. +/// 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, HkdfError> { let mut okm = Zeroizing::new([0u8; 64]); diff --git a/crates/rns-crypto/src/lib.rs b/crates/rns-crypto/src/lib.rs index c4511c5..24c16fc 100644 --- a/crates/rns-crypto/src/lib.rs +++ b/crates/rns-crypto/src/lib.rs @@ -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; diff --git a/crates/rns-crypto/src/pkcs7.rs b/crates/rns-crypto/src/pkcs7.rs index 4ca0998..f00e16c 100644 --- a/crates/rns-crypto/src/pkcs7.rs +++ b/crates/rns-crypto/src/pkcs7.rs @@ -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 { /// 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); diff --git a/crates/rns-crypto/src/token.rs b/crates/rns-crypto/src/token.rs index a9f1aa5..dd9040c 100644 --- a/crates/rns-crypto/src/token.rs +++ b/crates/rns-crypto/src/token.rs @@ -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. @@ -80,8 +83,9 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result, 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 diff --git a/crates/rns-crypto/src/x25519.rs b/crates/rns-crypto/src/x25519.rs index 0d91d9d..6c88c62 100644 --- a/crates/rns-crypto/src/x25519.rs +++ b/crates/rns-crypto/src/x25519.rs @@ -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), diff --git a/crates/rns-identity/src/announce.rs b/crates/rns-identity/src/announce.rs index 7da4748..150ca77 100644 --- a/crates/rns-identity/src/announce.rs +++ b/crates/rns-identity/src/announce.rs @@ -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 { 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], diff --git a/crates/rns-identity/src/announce_state.rs b/crates/rns-identity/src/announce_state.rs index 5fd2885..f5be2db 100644 --- a/crates/rns-identity/src/announce_state.rs +++ b/crates/rns-identity/src/announce_state.rs @@ -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); @@ -103,7 +104,9 @@ impl RatchetControlState { self.save_verified_impl(path, identity, false) } - /// Persist announce ordering before releasing the corresponding wire bytes. + /// 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) } diff --git a/crates/rns-identity/src/destination.rs b/crates/rns-identity/src/destination.rs index aa4c9e2..c7e446c 100644 --- a/crates/rns-identity/src/destination.rs +++ b/crates/rns-identity/src/destination.rs @@ -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; /// Callback invoked when a new link is established: `fn(link_id)`. pub type LinkEstablishedCallback = Box; @@ -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>>, @@ -218,12 +221,15 @@ pub struct Destination { default_app_data: Option, 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, 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) { 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, diff --git a/crates/rns-identity/src/identity.rs b/crates/rns-identity/src/identity.rs index f63c1f5..e9827c5 100644 --- a/crates/rns-identity/src/identity.rs +++ b/crates/rns-identity/src/identity.rs @@ -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, sig_prv: Option, @@ -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 { 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 { 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, @@ -215,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() @@ -230,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> { let prv = self.prv.as_ref()?; let sig_prv = self.sig_prv.as_ref()?; @@ -253,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() } @@ -262,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 { self.sig_prv .as_ref() @@ -285,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() } @@ -294,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], @@ -409,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], diff --git a/crates/rns-identity/src/ifac.rs b/crates/rns-identity/src/ifac.rs index b07a968..b1e398a 100644 --- a/crates/rns-identity/src/ifac.rs +++ b/crates/rns-identity/src/ifac.rs @@ -24,7 +24,8 @@ 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>, @@ -131,7 +132,10 @@ pub fn ifac_signature(ifac_key: &[u8; 64]) -> Option<[u8; 64]> { .sign(&sha256(ifac_key)) } -/// Split IFAC key into `(signing_key, masking_key)`, each 32 bytes. +/// 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..]) } diff --git a/crates/rns-identity/src/known_destinations.rs b/crates/rns-identity/src/known_destinations.rs index eaec538..1a18972 100644 --- a/crates/rns-identity/src/known_destinations.rs +++ b/crates/rns-identity/src/known_destinations.rs @@ -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, diff --git a/crates/rns-identity/src/persistence.rs b/crates/rns-identity/src/persistence.rs index d48faa5..97ca734 100644 --- a/crates/rns-identity/src/persistence.rs +++ b/crates/rns-identity/src/persistence.rs @@ -206,8 +206,10 @@ impl<'de, const MAX: usize> serde::de::Visitor<'de> for SecretBytesVisitor /// 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<()> { let _write_guard = ATOMIC_WRITE_LOCK .lock() diff --git a/crates/rns-identity/src/persistence/strict.rs b/crates/rns-identity/src/persistence/strict.rs index 33b4e4c..1413baf 100644 --- a/crates/rns-identity/src/persistence/strict.rs +++ b/crates/rns-identity/src/persistence/strict.rs @@ -139,7 +139,7 @@ fn target_path(path: &Path) -> io::Result { pub enum StorageRisk { /// Network or user-space filesystem; flushes may not reach stable storage. Remote, - /// RAM-backed filesystem; contents do not survive a restart. + /// RAM-backed filesystem; contents do not survive a system restart. Volatile, } @@ -152,7 +152,9 @@ impl std::fmt::Display for StorageRisk { } } -/// Classify the filesystem holding `path`; `None` is ordinary local storage. +/// Classify known filesystem risks for an existing path. `None` means no risk +/// was identified by this platform's checks, not proof of durable local storage. +/// Platforms without a classifier return `None`. pub fn storage_risk(path: &Path) -> io::Result> { filesystem_risk(&fs::canonicalize(path)?) } @@ -526,6 +528,8 @@ fn directory_chain_barrier(path: &Path, witness: &DurableFileReceipt) -> io::Res /// Re-establish an existing journal-owned directory transition after restart. /// The caller must first verify the journal's expected paths, entries and hashes; /// this receipt acknowledges only the renewed native directory/witness barriers. +/// On Windows this returns `DurabilityUnsupported`; recovery must use a +/// journaled fresh sibling directory transition instead. pub fn durable_reconcile_directory( path: &Path, witness: &DurableFileReceipt, diff --git a/crates/rns-identity/src/ratchet.rs b/crates/rns-identity/src/ratchet.rs index 3621fc1..b150fbb 100644 --- a/crates/rns-identity/src/ratchet.rs +++ b/crates/rns-identity/src/ratchet.rs @@ -91,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, @@ -115,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, @@ -166,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()) } @@ -209,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, @@ -305,8 +311,9 @@ impl RatchetRing { self.save_verified_impl(path, identity, false) } - /// Acknowledge only the platform's strict file and namespace barriers. - /// An uncertain publication is an error, never a successful checkpoint. + /// 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) } @@ -336,7 +343,9 @@ impl RatchetRing { } /// 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]; @@ -370,7 +379,9 @@ 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 { let data = persistence::read_secret_file(path, RATCHET_FILE_MAX_BYTES)?; let decoded = Self::decode(&data)?; @@ -429,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, @@ -452,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, identity: &Identity) -> std::io::Result { let path = path.as_ref().to_path_buf(); let ring = if path.is_file() { @@ -499,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, @@ -514,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( @@ -641,7 +663,8 @@ 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) } @@ -713,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. @@ -756,6 +780,8 @@ pub fn purge_expired_ratchets_in_memory( } /// 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, @@ -778,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 @@ -811,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()) } diff --git a/crates/rns-interface/src/android_usb.rs b/crates/rns-interface/src/android_usb.rs index 559ab57..6b65d77 100644 --- a/crates/rns-interface/src/android_usb.rs +++ b/crates/rns-interface/src/android_usb.rs @@ -1,4 +1,8 @@ -//! 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 selects a CDC data (`0x0A`) or vendor-specific (`0xFF`) interface +//! with IN and OUT endpoints on that same interface. It requests 8N1 line +//! coding, defaulting to 115200 baud. That control request is best effort; +//! enumeration alone does not establish chipset compatibility. use rns_transport::messages::{InterfacePacketCapacity, InterfaceTransportSender}; use std::collections::HashMap; @@ -43,7 +47,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. +/// Connection still requires a suitable CDC-data or vendor-specific interface +/// and a device compatible with this driver's line control and RNode protocol. pub const KNOWN_VIDS: &[(u16, &str)] = &[ (0x0403, "FTDI"), (0x10C4, "Silicon Labs CP210x"), @@ -157,9 +163,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(()); @@ -239,9 +245,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, - /// 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, /// Station-ID beacon: seconds between IDs, sent only after data TX. pub id_interval: Option, @@ -569,10 +577,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 { let dev_name = device_name.to_string(); tokio::task::spawn_blocking(move || { @@ -759,8 +765,9 @@ fn unregister_android_usb_presence(device_name: &str, attached: &Arc } } -/// 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() @@ -2059,10 +2066,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>, frame: Vec, diff --git a/crates/rns-interface/src/auto.rs b/crates/rns-interface/src/auto.rs index beb283f..1de31f5 100644 --- a/crates/rns-interface/src/auto.rs +++ b/crates/rns-interface/src/auto.rs @@ -1,7 +1,9 @@ -//! 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}; @@ -20,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; @@ -158,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, @@ -294,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(); @@ -331,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; @@ -508,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, String> { use std::collections::BTreeMap; diff --git a/crates/rns-interface/src/ax25kiss.rs b/crates/rns-interface/src/ax25kiss.rs index e6d6112..ffb7dd4 100644 --- a/crates/rns-interface/src/ax25kiss.rs +++ b/crates/rns-interface/src/ax25kiss.rs @@ -100,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, @@ -151,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..]) diff --git a/crates/rns-interface/src/backbone.rs b/crates/rns-interface/src/backbone.rs index e7d8c42..bb8dc81 100644 --- a/crates/rns-interface/src/backbone.rs +++ b/crates/rns-interface/src/backbone.rs @@ -1,8 +1,8 @@ -//! 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; @@ -26,13 +26,16 @@ 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; @@ -41,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; @@ -68,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, - /// 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, @@ -104,7 +109,8 @@ pub struct BackboneClientConfig { pub connect_timeout_secs: u64, pub max_reconnect_tries: Option, pub mode: InterfaceMode, - /// Signs a tunnel synthesis for every connection; `None` sends none. + /// 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, } diff --git a/crates/rns-interface/src/ble_central_apple.rs b/crates/rns-interface/src/ble_central_apple.rs index 399e570..0d28f8b 100644 --- a/crates/rns-interface/src/ble_central_apple.rs +++ b/crates/rns-interface/src/ble_central_apple.rs @@ -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 { 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, ) -> Result, 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()?; diff --git a/crates/rns-interface/src/ble_central_apple_connect.rs b/crates/rns-interface/src/ble_central_apple_connect.rs index 9e531e6..1af0305 100644 --- a/crates/rns-interface/src/ble_central_apple_connect.rs +++ b/crates/rns-interface/src/ble_central_apple_connect.rs @@ -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> #[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 { .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() { diff --git a/crates/rns-interface/src/ble_central_lifecycle.rs b/crates/rns-interface/src/ble_central_lifecycle.rs index 925f88b..9e3c68a 100644 --- a/crates/rns-interface/src/ble_central_lifecycle.rs +++ b/crates/rns-interface/src/ble_central_lifecycle.rs @@ -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, }, diff --git a/crates/rns-interface/src/ble_peer.rs b/crates/rns-interface/src/ble_peer.rs index e8c075f..742d24a 100644 --- a/crates/rns-interface/src/ble_peer.rs +++ b/crates/rns-interface/src/ble_peer.rs @@ -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,8 +26,11 @@ //! 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; @@ -57,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; @@ -69,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); @@ -107,8 +107,7 @@ pub fn seed_recently_disconnected(map: &RecentlyDisconnected, addresses: Vec bool { bytes.len() == 16 && bytes.iter().any(|b| *b != 0) } @@ -117,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, Instant)>>>; @@ -173,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() @@ -392,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); @@ -428,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)] @@ -454,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, @@ -670,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")] { @@ -990,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, String> { #[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))] { @@ -5458,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, diff --git a/crates/rns-interface/src/ble_peer_lifecycle.rs b/crates/rns-interface/src/ble_peer_lifecycle.rs index 4696041..949c82e 100644 --- a/crates/rns-interface/src/ble_peer_lifecycle.rs +++ b/crates/rns-interface/src/ble_peer_lifecycle.rs @@ -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 { diff --git a/crates/rns-interface/src/ble_rnode.rs b/crates/rns-interface/src/ble_rnode.rs index 0879272..d1dea3a 100644 --- a/crates/rns-interface/src/ble_rnode.rs +++ b/crates/rns-interface/src/ble_rnode.rs @@ -39,8 +39,9 @@ type BleCentralEventStream = std::pin::Pin bool { false } -/// Tear down the in-flight pair attempt: -/// 1. Flip `aborted` so any subsequent `request_passkey` rejects without -/// broadcasting a fresh prompt. -/// 2. Drop the oneshot so the current `request_passkey` (if any) resolves -/// with `Canceled`. -/// 3. Notify the task running `linux_trigger_pairing` to drop its -/// `device.pair()` future — bluer translates that drop into a BlueZ -/// `CancelPairing` D-Bus call so the daemon stops retrying SMP. -/// 4. Drain any prompts queued in the broadcast channel so a relay that -/// hasn't run since cancel can't surface a stale prompt. +/// Cancel the in-flight Linux pairing attempt. Marks it aborted, drops the +/// waiting passkey sender, and notifies the pairing task to cancel its pending +/// operation. Already broadcast prompts are not removed; consumers must use +/// attempt IDs and completion events to discard stale prompts. #[cfg(target_os = "linux")] pub fn linux_cancel_pairing() { let cancel_notify = if let Ok(mut guard) = LINUX_PAIRING_STATE.lock() { @@ -1235,7 +1231,8 @@ pub fn linux_cancel_pairing() { #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "lowercase")] pub enum BleDeviceType { - /// Advertises the Nordic UART Service. + /// Classified as an RNode candidate by the scan filter; not authenticated + /// as RNode firmware. RNode, Unknown, } @@ -1246,15 +1243,10 @@ pub struct BleDevice { pub address: String, pub rssi: Option, pub device_type: BleDeviceType, - /// True if the OS already has a bond with this device. - /// - /// Reliability by platform: - /// - Android: ground truth (Kotlin reads `BluetoothDevice.bondState`). - /// - Linux: ground truth (bluer's `device.is_paired()` queried in - /// `scan_ble_devices`). - /// - Apple (iOS / macOS) and Windows: always `false` — neither - /// CoreBluetooth nor btleplug's WinRT backend exposes bond state. - /// Embedding UIs should hide bonded-state badges on these platforms. + /// Paired-state observation. This module queries BlueZ on Linux, returning + /// false if the query fails; its other scan backends report false. Android + /// embedding code may populate this field from a native bond-state query. + /// False therefore does not always mean that the device is unpaired. pub bonded: bool, } @@ -1391,25 +1383,15 @@ pub async fn ble_adapter_present() -> Result { } } -/// Tags anything advertising the Nordic UART Service as `RNode`, the rest -/// as `Unknown`. +/// Scan for named RNode candidates. A result must have a name beginning with +/// `RNode` and either advertise Nordic UART Service or report no service UUIDs. +/// Unnamed and other devices are omitted. This is a discovery filter, not +/// firmware or identity authentication. /// -/// `bonded` semantics by platform: -/// - **Linux**: queried directly from BlueZ via bluer's `device.is_paired()`. -/// Ground truth. -/// - **Android**: not used here — the Android frontend bypasses this -/// function entirely and reads `BluetoothDevice.bondState` natively in -/// Kotlin. -/// - **Apple (iOS / macOS) and Windows**: always `false`. CoreBluetooth -/// (by design, for privacy) and btleplug's WinRT backend don't expose -/// bond state to apps. Embedding UIs should hide bonded-state badges on -/// these platforms. -/// -/// Apple bonded-state detection would require an objc2 bridge to -/// `CBCentralManager.retrievePeripheralsWithIdentifiers(_:)` or a local cache. -/// -/// Windows bonded-state detection would require a WinRT -/// `BluetoothLEDevice.DeviceInformation.Pairing.IsPaired` binding. +/// On Linux, `bonded` uses BlueZ's paired flag and is false when the query +/// fails. This function reports false on other platforms; Android embedding +/// code can obtain bond state separately through its native bridge. A false +/// result outside Linux does not establish that no bond exists. pub async fn scan_ble_devices(timeout_secs: u64) -> Result, String> { let adapter = get_adapter().await.map_err(|e| format!("{e}"))?; @@ -2720,8 +2702,9 @@ fn project_ble_rnode_startup_bytes( projection } -/// Auto-reconnect across drops; resolve_ble_target re-runs every retry so -/// iOS RPA rotation heals automatically. +/// Reconnect after connection loss, resolving the configured BLE target on +/// each retry. Rediscovery depends on the target remaining identifiable; +/// address changes do not guarantee a successful reconnect. pub async fn spawn_ble_rnode_interface( config: BleRNodeConfig, id: InterfaceId, @@ -2734,11 +2717,10 @@ pub async fn spawn_ble_rnode_interface( ) } -/// Spawn a desktop BLE RNode interface with privacy-safe local observation. +/// Spawn a btleplug-based BLE RNode interface with local driver observation. /// -/// This retains btleplug ownership and the compatibility facade above. The -/// native Android TCP bridge has its own lifecycle and is intentionally not -/// projected here. +/// This owns the btleplug connection. The native Android TCP bridge uses the +/// separate `spawn_ble_rnode_interface_native_with_driver` entry point. pub async fn spawn_ble_rnode_interface_with_driver( config: BleRNodeConfig, id: InterfaceId, @@ -2754,14 +2736,13 @@ pub async fn spawn_ble_rnode_interface_with_driver( .map_err(RNodeSpawnError::into_legacy_interface_error) } -/// Spawn a desktop BLE RNode interface with an explicit startup policy. +/// Spawn a btleplug-based BLE RNode interface with an explicit startup policy. /// -/// BLE connection work remains asynchronous, so capability results arrive on -/// the returned driver observation rather than as a late function error. A -/// deterministic capability rejection on any connection generation publishes -/// terminal [`RNodeRuntimeReason::CapabilityAdmissionRejected`]. A response -/// timeout or transport loss retains the established BLE reconnect policy. -/// [`RNodeStartupOptions::default`] preserves the historical wire sequence. +/// Connection work is asynchronous, so capability outcomes arrive through the +/// returned driver observation. Deterministic rejection on any generation +/// publishes terminal [`RNodeRuntimeReason::CapabilityAdmissionRejected`]. +/// A response timeout or transport loss retains the reconnect policy. +/// [`RNodeStartupOptions::default`] does not request EEPROM capability data. pub async fn spawn_ble_rnode_interface_with_driver_and_options( config: BleRNodeConfig, id: InterfaceId, @@ -3750,13 +3731,13 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options( Ok(SpawnedRNodeInterface { interface, driver }) } -/// Android-only TCP-bridge variant. btleplug's deprecated JNI breaks on -/// Android 14+, so Kotlin (`RatspeakBleGatt.kt`) owns the GATT lifecycle -/// and forwards NUS bytes over `tcp_port`. +/// TCP-bridge entry point used by the Android native BLE integration. Kotlin +/// (`RatspeakBleGatt.kt`) owns GATT and forwards NUS bytes over `tcp_port`; +/// this Rust function itself is available with feature `ble` on other targets. /// -/// The bridge admits the local connection before its GATT link exists, so -/// each TCP generation sends nothing until the bridge writes its first byte; -/// Kotlin marks attachment with a zero-count acknowledgement. +/// Each TCP generation sends no startup bytes until the bridge produces its +/// first byte. The Android bridge marks attachment with a zero-count +/// acknowledgement. pub async fn spawn_ble_rnode_interface_native( config: BleRNodeConfig, id: InterfaceId, diff --git a/crates/rns-interface/src/hdlc.rs b/crates/rns-interface/src/hdlc.rs index 1340a7d..73dd1d7 100644 --- a/crates/rns-interface/src/hdlc.rs +++ b/crates/rns-interface/src/hdlc.rs @@ -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) { let mut i = 0; while i < data.len() { diff --git a/crates/rns-interface/src/i2p.rs b/crates/rns-interface/src/i2p.rs index c5980d5..2291730 100644 --- a/crates/rns-interface/src/i2p.rs +++ b/crates/rns-interface/src/i2p.rs @@ -371,9 +371,10 @@ pub struct I2PServerConfig { pub sam_port: u16, /// Base64 private key for the server's destination, used before `key_path`. pub keyfile: Option, - /// File holding the server's private key, as Python keeps it under - /// `storage/i2p` (I2PInterface.py:225-255): every session uses it, and - /// the first session's key is written to it when it is missing. + /// 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, pub reconnect_delay: u64, pub mode: InterfaceMode, @@ -504,13 +505,16 @@ 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, pub reconnect_delay: u64, pub mode: InterfaceMode, - /// Signs a tunnel synthesis for every connection; `None` sends none. + /// 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, } @@ -805,8 +809,9 @@ 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, diff --git a/crates/rns-interface/src/kiss.rs b/crates/rns-interface/src/kiss.rs index 96c9f1e..d8690e8 100644 --- a/crates/rns-interface/src/kiss.rs +++ b/crates/rns-interface/src/kiss.rs @@ -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; diff --git a/crates/rns-interface/src/kiss_iface.rs b/crates/rns-interface/src/kiss_iface.rs index ecfb77f..015d6f4 100644 --- a/crates/rns-interface/src/kiss_iface.rs +++ b/crates/rns-interface/src/kiss_iface.rs @@ -29,8 +29,14 @@ pub struct KissInterfaceConfig { pub txtail: Option, /// 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, pub id_callsign: Option>, } @@ -57,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 { let mut frame = id_callsign.to_vec(); while frame.len() < 15 { diff --git a/crates/rns-interface/src/lib.rs b/crates/rns-interface/src/lib.rs index 1f630d1..c4e2b7f 100644 --- a/crates/rns-interface/src/lib.rs +++ b/crates/rns-interface/src/lib.rs @@ -1,7 +1,7 @@ -//! 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; diff --git a/crates/rns-interface/src/local.rs b/crates/rns-interface/src/local.rs index 82a65fe..d0e22e9 100644 --- a/crates/rns-interface/src/local.rs +++ b/crates/rns-interface/src/local.rs @@ -1,5 +1,6 @@ -//! 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; @@ -17,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 @@ -62,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, } diff --git a/crates/rns-interface/src/pipe.rs b/crates/rns-interface/src/pipe.rs index 6ddf503..229721f 100644 --- a/crates/rns-interface/src/pipe.rs +++ b/crates/rns-interface/src/pipe.rs @@ -1,4 +1,7 @@ -//! 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; @@ -21,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, } diff --git a/crates/rns-interface/src/rnode.rs b/crates/rns-interface/src/rnode.rs index ccab491..c2c4829 100644 --- a/crates/rns-interface/src/rnode.rs +++ b/crates/rns-interface/src/rnode.rs @@ -1,12 +1,13 @@ //! LoRa radio control via RNode firmware's extended-KISS protocol. -//! Shared constants + transport-agnostic response handler. Serial: -//! [`spawn_rnode_interface`] (feature `serial`); BLE: the optional -//! `ble_rnode` module (feature `ble`). +//! Shared constants and response codecs are available without a transport +//! feature. `spawn_rnode_interface` supports serial ports with feature +//! `serial`, and TCP with either `serial` or `rnode-tcp`. BLE drivers are in +//! the optional `ble_rnode` module (feature `ble`). //! -//! Transport selection is driven by the `port` string in [`RNodeConfig`]: -//! - `/dev/ttyUSB0`, `COM3`, etc. -> serial (feature `serial` required) -//! - `tcp://192.168.1.1` -> TCP, default port 7633 -//! - `tcp://192.168.1.1:9000` -> TCP, explicit port +//! Transport selection uses the `port` string in [`RNodeConfig`]: +//! - `/dev/ttyUSB0`, `COM3`, etc.: serial (`serial` required). +//! - `tcp://192.168.1.1`: TCP, default port 7633. +//! - `tcp://192.168.1.1:9000`: TCP, explicit port. use bytes::Bytes; #[cfg(any(feature = "serial", feature = "rnode-tcp"))] @@ -163,12 +164,14 @@ enum RNodeCapabilityPolicy { } impl RNodeStartupOptions { - /// Require a validated EEPROM capability image before radio settings are - /// sent to each connection generation. + /// Require EEPROM capability classification before radio settings are sent + /// to each connection generation. /// - /// Known models enforce their reviewed frequency and TX-power limits. - /// A validated but unknown or quarantined model is admitted explicitly as - /// unverified; no model alias or capability profile is inferred. + /// Locked images must pass the identity-prefix checksum. Known models enforce + /// their code-table frequency and TX-power limits. Unknown or quarantined + /// models are admitted as unverified; unlocked images are admitted as + /// unprovisioned. Neither case infers model-specific limits. This check does + /// not authenticate a device signature. /// /// Each options-aware transport documents how its first connection reports /// admission failure. Synchronously prepared transports can return @@ -502,7 +505,8 @@ pub enum RNodePortFailureClass { NotFound, /// The OS denied this process access to the port. AccessDenied, - /// Another process holds the port. + /// Port-open failure classified as in use. On Unix this includes the + /// serial library's `NoDevice` error; it does not identify a locking process. InUse, /// Any other failure, including an unreachable TCP endpoint. Unavailable, @@ -2363,10 +2367,10 @@ impl RNodeStream { Ok(Self::Tcp(stream)) } - /// Shallow-clone the stream for the write half. + /// Clone an I/O handle for the write half. /// - /// - Serial: uses `SerialPort::try_clone`. - /// - TCP: uses `TcpStream::try_clone` (both halves share the same fd). + /// - Serial uses `SerialPort::try_clone`. + /// - TCP uses `TcpStream::try_clone`; the handles refer to the same socket. pub fn try_clone(&self) -> std::io::Result { match self { #[cfg(feature = "serial")] @@ -2891,9 +2895,11 @@ pub struct RNodeConfig { pub tx_power: u8, pub mode: InterfaceMode, 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, - /// 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, /// Station-ID beacon: seconds between IDs, armed by data TX /// (Python `id_interval`/`id_callsign`, callsign max 32 bytes). @@ -2980,8 +2986,8 @@ impl RNodeConfig { } } - /// Validate all generic RNode RF and airtime settings without touching the - /// configured endpoint. These bounds match upstream RNodeInterface 1.4. + /// Validate generic RF and airtime bounds without touching the configured + /// endpoint. Model-specific capability admission is a separate check. pub fn validate(&self) -> Result<(), RNodeConfigValidationError> { RNodeRadioSettings::from(self).validate()?; validate_airtime(RNodeConfigField::ShortTermAirtime, self.st_alock)?; @@ -3043,7 +3049,9 @@ fn validate_airtime( Ok(()) } -/// LoRa on-air bps via `SF * (4/CR) / (2^SF / BW_kHz) * 1000`. 0 on invalid. +/// Estimate LoRa bit rate as `SF * (4/CR) / (2^SF / BW_kHz) * 1000`, truncated +/// to whole bits per second. Returns zero for zero inputs or a non-positive or +/// non-finite result; this helper does not validate the radio's supported ranges. pub fn calculate_bitrate(sf: u8, cr: u8, bandwidth_hz: u32) -> u64 { if sf == 0 || cr == 0 || bandwidth_hz == 0 { return 0; @@ -3132,12 +3140,11 @@ fn build_radio_configuration_sequence_before_on( out } -/// KISS init sequence. Order matters: turn the radio off first so persisted -/// TNC startup profiles cannot keep old parameters active, and airtime locks -/// precede RADIO_STATE=ON. Frequency, bandwidth and transmit power then follow -/// RADIO_STATE=ON again: RNode firmware maps them to what the hardware will -/// use only while the radio is on, so these last echoes report the effective -/// settings that [`RNodeProtocolState::with_effective_settings`] judges. +/// KISS initialization sequence: radio off, radio parameters and configured +/// airtime locks, then radio on. Frequency, bandwidth and transmit power are +/// reasserted after radio-on. [`RNodeProtocolState::with_effective_settings`] +/// requires that later transmit-power echo before declaring readiness or a +/// definitive settings rejection. pub fn build_init_sequence(config: &RNodeConfig) -> Vec { let settings = RNodeRadioSettings::from(config); let airtime = build_airtime_sequence(config); diff --git a/crates/rns-interface/src/rnode_admin.rs b/crates/rns-interface/src/rnode_admin.rs index ffc96c3..1e6e429 100644 --- a/crates/rns-interface/src/rnode_admin.rs +++ b/crates/rns-interface/src/rnode_admin.rs @@ -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; diff --git a/crates/rns-interface/src/rnode_capabilities.rs b/crates/rns-interface/src/rnode_capabilities.rs index 0461feb..c892124 100644 --- a/crates/rns-interface/src/rnode_capabilities.rs +++ b/crates/rns-interface/src/rnode_capabilities.rs @@ -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 { @@ -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 { diff --git a/crates/rns-interface/src/rnode_multi.rs b/crates/rns-interface/src/rnode_multi.rs index 5eb9223..38b8e1d 100644 --- a/crates/rns-interface/src/rnode_multi.rs +++ b/crates/rns-interface/src/rnode_multi.rs @@ -206,9 +206,9 @@ impl RNodeMultiConfig { } } -/// SEL_INT, push params, RADIO_STATE=ON, then frequency, bandwidth and TX -/// power again: firmware maps them to what the hardware will use only while -/// the radio is on, so these last echoes report the effective settings. +/// 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 { let mut out = Vec::with_capacity(80); diff --git a/crates/rns-interface/src/rnode_protocol.rs b/crates/rns-interface/src/rnode_protocol.rs index 75b3c4b..5556b27 100644 --- a/crates/rns-interface/src/rnode_protocol.rs +++ b/crates/rns-interface/src/rnode_protocol.rs @@ -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, @@ -313,8 +312,10 @@ pub enum RNodeProtocolEffect { /// Pure reducer for generic single-radio readiness. /// -/// Order-independent unless created with -/// [`RNodeProtocolState::with_effective_settings`]. +/// 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, @@ -356,11 +357,10 @@ impl RNodeProtocolState { /// Like [`Self::new`], but readiness also waits for a transmit-power echo /// that follows `RADIO_STATE_ON`. /// - /// RNode firmware maps frequency, bandwidth and amplifier-backed transmit - /// power to what the hardware will use only while the radio is on; a cold - /// radio echoes the request. Callers re-assert those settings after - /// `RADIO_STATE_ON` (as `rnode::build_init_sequence` does), so readiness - /// and [`Self::definitive_rejection`] judge the effective values. + /// `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 { diff --git a/crates/rns-interface/src/serial.rs b/crates/rns-interface/src/serial.rs index fb9fb0e..bf76b61 100644 --- a/crates/rns-interface/src/serial.rs +++ b/crates/rns-interface/src/serial.rs @@ -1,5 +1,5 @@ -//! 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; diff --git a/crates/rns-interface/src/socket_tuning.rs b/crates/rns-interface/src/socket_tuning.rs index b28189e..d26e425 100644 --- a/crates/rns-interface/src/socket_tuning.rs +++ b/crates/rns-interface/src/socket_tuning.rs @@ -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(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( stream: &S, idle: Duration, @@ -66,7 +68,8 @@ pub fn set_keepalive_tuned( }); } -/// 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(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 { }) } -/// 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 { let ifaces = match if_addrs::get_if_addrs() { Ok(v) => v, diff --git a/crates/rns-interface/src/tcp.rs b/crates/rns-interface/src/tcp.rs index f8f50f4..c669946 100644 --- a/crates/rns-interface/src/tcp.rs +++ b/crates/rns-interface/src/tcp.rs @@ -66,10 +66,11 @@ pub struct TcpClientConfig { pub connect_timeout_secs: u64, pub max_reconnect_tries: Option, 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, - /// Signs a tunnel synthesis for every connection unless KISS-framed; - /// `None` sends none. + /// 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, } diff --git a/crates/rns-interface/src/traits.rs b/crates/rns-interface/src/traits.rs index f5bb64a..6ce1a62 100644 --- a/crates/rns-interface/src/traits.rs +++ b/crates/rns-interface/src/traits.rs @@ -6,7 +6,7 @@ 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, @@ -22,9 +22,7 @@ pub struct InterfaceHandle { pub online: Arc, pub rxb: Option>, pub txb: Option>, - /// 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, pub tx: mpsc::Sender, pub read_task: tokio::task::JoinHandle<()>, @@ -58,8 +56,8 @@ pub(crate) async fn handoff_accepted_interface( pub struct TunnelIdentity(pub Arc); impl TunnelIdentity { - /// A fresh synthesis for the interface whose Python `str()` is - /// `python_name` (Transport.py:2764-2785). + /// 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 { rns_transport::tunnel::build_tunnel_synthesis_packet( &self.0, @@ -113,7 +111,7 @@ pub(crate) async fn open_client_connection( online.store(true, std::sync::atomic::Ordering::SeqCst); } -/// Interface operating mode. Byte values are on-wire constants. +/// Interface operating mode. Numeric values match Reticulum interface mode constants. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] #[derive(Default)] @@ -169,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 { if bitrate >= 1_000_000_000 { Some(524_288) diff --git a/crates/rns-interface/src/weave.rs b/crates/rns-interface/src/weave.rs index 851e1ac..66bf58a 100644 --- a/crates/rns-interface/src/weave.rs +++ b/crates/rns-interface/src/weave.rs @@ -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; diff --git a/crates/rns-link/src/clock.rs b/crates/rns-link/src/clock.rs index 6a4db6b..9a9c301 100644 --- a/crates/rns-link/src/clock.rs +++ b/crates/rns-link/src/clock.rs @@ -1,20 +1,19 @@ -//! A monotonic clock that keeps counting while the system is suspended. +//! A monotonic clock for deadlines that account for system suspension. //! -//! `std::time::Instant` stops while Apple, Linux and Android systems sleep, -//! so a deadline measured on it ends late by the whole sleep. This clock -//! counts that time: `CLOCK_BOOTTIME` on Linux and Android, -//! `CLOCK_MONOTONIC_RAW` (`mach_continuous_time`) on Apple platforms, and the -//! performance counter on Windows. On other targets it is best effort, -//! `std::time::Instant` from the first reading in the process. +//! 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. //! -//! Timers do not run on this clock: tokio and the operating system's waits -//! count awake time only. Check a deadline against [`ContinuousInstant::now`] -//! on a regular tick instead of arming a timer for it. +//! 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 the suspend-counting clock, in signed nanoseconds from the +/// 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 @@ -49,7 +48,8 @@ impl ContinuousInstant { u64::try_from(nanos).ok().map(Duration::from_nanos) } - /// The time since this reading, including time the system was suspended. + /// 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) } diff --git a/crates/rns-link/src/constants.rs b/crates/rns-link/src/constants.rs index 9d23ec3..4be1e90 100644 --- a/crates/rns-link/src/constants.rs +++ b/crates/rns-link/src/constants.rs @@ -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. diff --git a/crates/rns-link/src/encryption.rs b/crates/rns-link/src/encryption.rs index f9cd12e..0c04f54 100644 --- a/crates/rns-link/src/encryption.rs +++ b/crates/rns-link/src/encryption.rs @@ -18,8 +18,9 @@ pub fn link_encrypt(keys: &LinkKeys, plaintext: &[u8]) -> Result, 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, LinkCryptoError> { let mut combined_key = Zeroizing::new(Vec::with_capacity( keys.signing_key.len() + keys.encryption_key.len(), diff --git a/crates/rns-link/src/handshake.rs b/crates/rns-link/src/handshake.rs index f817206..5a8a50f 100644 --- a/crates/rns-link/src/handshake.rs +++ b/crates/rns-link/src/handshake.rs @@ -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 { if data.len() < ECPUBSIZE { return Err(HandshakeError::TooShort); @@ -106,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; @@ -123,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) } @@ -132,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], @@ -209,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 { if data.len() < 96 { return Err(HandshakeError::TooShort); @@ -241,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, @@ -261,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], diff --git a/crates/rns-link/src/keepalive.rs b/crates/rns-link/src/keepalive.rs index 890b3fc..767118f 100644 --- a/crates/rns-link/src/keepalive.rs +++ b/crates/rns-link/src/keepalive.rs @@ -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(); diff --git a/crates/rns-link/src/key_derivation.rs b/crates/rns-link/src/key_derivation.rs index b564992..f673a8a 100644 --- a/crates/rns-link/src/key_derivation.rs +++ b/crates/rns-link/src/key_derivation.rs @@ -5,10 +5,11 @@ 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, /// AES encryption key. pub encryption_key: Vec, @@ -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, diff --git a/crates/rns-link/src/lib.rs b/crates/rns-link/src/lib.rs index efc4aed..8527c78 100644 --- a/crates/rns-link/src/lib.rs +++ b/crates/rns-link/src/lib.rs @@ -1,6 +1,8 @@ //! 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; diff --git a/crates/rns-link/src/link.rs b/crates/rns-link/src/link.rs index 8e75a94..b807f98 100644 --- a/crates/rns-link/src/link.rs +++ b/crates/rns-link/src/link.rs @@ -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, @@ -107,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). @@ -155,7 +157,10 @@ fn peer_reported_rtt(secs: f64) -> Option { /// 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], @@ -224,24 +229,29 @@ pub struct Link { pub rssi: Option, /// Signal-to-noise ratio in dB. pub snr: Option, - /// 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, track_phy_stats: bool, pub has_channel: bool, pub packet_callback: Option, - /// 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, pub remote_identified_callback: Option, - /// 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, pub link_closed_callback: Option, } /// Callback for decrypted link-packet payloads. pub type PacketCallback = Box; -/// 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 bool + Send + Sync>; /// Callback fired after the remote peer identifies on the link. pub type RemoteIdentifiedCallback = Box; @@ -352,6 +362,9 @@ impl Link { /// /// 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], @@ -628,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, LinkCryptoError> { let keys = self .session_keys @@ -648,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( @@ -705,7 +720,9 @@ impl Link { /// /// 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. + /// 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], @@ -768,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, @@ -790,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, @@ -926,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], @@ -939,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 { // request_id = SHA-256(packed_request)[:16] let request_id = truncated_hash(plaintext); @@ -982,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], @@ -999,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], @@ -1023,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), LinkCryptoError> { @@ -1102,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 @@ -1365,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, Option, Option) { let stats = self.phy_stats_snapshot(); (stats.rssi, stats.snr, stats.q) @@ -1395,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 { self.session_keys.clone() } @@ -1585,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)); } @@ -1735,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 @@ -1765,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)) diff --git a/crates/rns-link/src/request.rs b/crates/rns-link/src/request.rs index f145062..b57ebce 100644 --- a/crates/rns-link/src/request.rs +++ b/crates/rns-link/src/request.rs @@ -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, } -/// 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; /// Progress callback for resource-backed request responses. pub type ProgressCallback = Box; -/// 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>, pub rtt: Option, - /// 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, diff --git a/crates/rns-protocol/src/buffer.rs b/crates/rns-protocol/src/buffer.rs index 15252c1..5115008 100644 --- a/crates/rns-protocol/src/buffer.rs +++ b/crates/rns-protocol/src/buffer.rs @@ -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, @@ -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> { 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, 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, diff --git a/crates/rns-protocol/src/channel.rs b/crates/rns-protocol/src/channel.rs index a160a2d..6d6f1a6 100644 --- a/crates/rns-protocol/src/channel.rs +++ b/crates/rns-protocol/src/channel.rs @@ -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,7 +35,8 @@ 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. @@ -49,9 +51,11 @@ fn initial_rtt(rtt: f64) -> f64 { } } -/// 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, @@ -134,9 +138,8 @@ 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 { @@ -160,12 +163,12 @@ 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 { @@ -203,9 +206,7 @@ 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); @@ -213,6 +214,8 @@ impl ChannelWindow { 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 { @@ -225,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 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, @@ -249,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, /// Called in registration order on each delivered message; the first /// handler that returns `true` stops the chain. @@ -288,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); @@ -355,14 +361,19 @@ impl Channel { 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, ChannelError> { self.send_tracked(msg).map(|(_, raw)| raw) } @@ -404,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; @@ -627,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), @@ -669,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, ChannelError> { self.prepare_send_tracked(msg).map(|prepared| prepared.data) } diff --git a/crates/rns-protocol/src/compression.rs b/crates/rns-protocol/src/compression.rs index 7866297..dac2124 100644 --- a/crates/rns-protocol/src/compression.rs +++ b/crates/rns-protocol/src/compression.rs @@ -14,10 +14,11 @@ pub fn bz2_compress(data: &[u8]) -> Result, 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, CompressionError> { let mut decoder = bzip2::read::BzDecoder::new(data); let mut output = Vec::new(); diff --git a/crates/rns-protocol/src/lib.rs b/crates/rns-protocol/src/lib.rs index 9cd81c4..9c14522 100644 --- a/crates/rns-protocol/src/lib.rs +++ b/crates/rns-protocol/src/lib.rs @@ -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; diff --git a/crates/rns-protocol/src/resource.rs b/crates/rns-protocol/src/resource.rs index d230c0b..0ddd16b 100644 --- a/crates/rns-protocol/src/resource.rs +++ b/crates/rns-protocol/src/resource.rs @@ -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), 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>, /// 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, 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, auto_compress: bool, @@ -470,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; @@ -493,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 { if plaintext.is_empty() { return Vec::new(); @@ -572,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)] @@ -681,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<'_>>, @@ -756,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 { let proof = compute_expected_proof(data, &self.resource_hash); let mut proof_data = Vec::with_capacity(64); @@ -820,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 @@ -879,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, auto_compress: bool, @@ -889,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, auto_compress: bool, @@ -942,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 { @@ -968,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, auto_compress: bool, @@ -1030,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<'_>>, @@ -1084,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>, pub assembled_segments: Vec>>, 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>, } 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, @@ -1201,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, @@ -1211,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, @@ -1226,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, @@ -1278,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> { let part = self.outbound.as_ref()?.get_part(index)?; if let Some(ref keys) = self.session_keys { @@ -1290,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) -> bool { let plaintext = if let Some(ref keys) = self.session_keys { match rns_link::encryption::link_decrypt(keys, &data) { @@ -1312,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, ResourceError> { let decrypt_fn: Option>> = if let Some(ref keys) = self.session_keys { @@ -1368,7 +1396,8 @@ pub enum TransferAction { /// `(part_index, part_data)`. SendPart(usize, Vec), SendProof(Vec), - /// Hashmap update frame from receiver to sender. + /// Sender-to-receiver hashmap update: resource hash followed by + /// MessagePack `[segment_index, hashmap_bytes]`. SendHmu(Vec), /// Receiver-to-sender request for specific parts. Payload layout: /// `exhausted_flag || optional last_map_hash || resource_hash || requested_part_hashes...`. @@ -1421,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, auto_compress: bool, @@ -1593,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!( @@ -1699,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], @@ -1980,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, @@ -2324,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; @@ -2405,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 { let is_complete = self.resource.is_complete(); let exhausted = if is_complete { @@ -2447,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( diff --git a/crates/rns-protocol/src/resource_adv.rs b/crates/rns-protocol/src/resource_adv.rs index 0ae08c2..0e9f35d 100644 --- a/crates/rns-protocol/src/resource_adv.rs +++ b/crates/rns-protocol/src/resource_adv.rs @@ -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,8 +123,14 @@ 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 { use rmpv::Value; @@ -234,7 +246,8 @@ impl ResourceAdvertisement { Ok(counter.0) } - /// Split the packed `hashmap` field into fixed-length map-hash entries. + /// 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::() diff --git a/crates/rns-protocol/src/resource_control.rs b/crates/rns-protocol/src/resource_control.rs index ae2331a..b89725a 100644 --- a/crates/rns-protocol/src/resource_control.rs +++ b/crates/rns-protocol/src/resource_control.rs @@ -20,7 +20,10 @@ pub fn encrypted_len(plaintext_len: usize) -> Result { .ok_or(ResourceError::TooLarge) } -/// Check the actual Reticulum packet length before encryption or state admission. +/// 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, diff --git a/crates/rns-protocol/src/rnsh.rs b/crates/rns-protocol/src/rnsh.rs index 9d13728..a7bbb58 100644 --- a/crates/rns-protocol/src/rnsh.rs +++ b/crates/rns-protocol/src/rnsh.rs @@ -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; diff --git a/crates/rns-protocol/src/stream_data.rs b/crates/rns-protocol/src/stream_data.rs index 266a7ee..ea3bb9c 100644 --- a/crates/rns-protocol/src/stream_data.rs +++ b/crates/rns-protocol/src/stream_data.rs @@ -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, diff --git a/crates/rns-ratkey/src/apdu.rs b/crates/rns-ratkey/src/apdu.rs index 435b801..c51630e 100644 --- a/crates/rns-ratkey/src/apdu.rs +++ b/crates/rns-ratkey/src/apdu.rs @@ -1,6 +1,14 @@ -//! PIV APDU build/parse. Specs: ISO 7816-4 (APDU), NIST SP 800-73-4 (PIV), -//! Yubico Ed25519 (0xE0) / X25519 (0xE1) extensions. -//! Ref: +//! Build and parse PIV APDUs using ISO 7816-4, NIST SP 800-73-4 and the +//! Yubico Ed25519 (`0xE0`)/X25519 (`0xE1`) extensions. Builders return command +//! bytes; they do not transmit, authenticate, or validate every input. +//! +//! Call [`check_response`] on a full response before passing its body to a +//! parser. PIN/PUK fields truncate to eight bytes and pad with `0xFF`; callers +//! must validate their permitted length and character set. Returned command +//! buffers can contain secrets and are ordinary `Vec` values: wipe them +//! after use. Large-message builders do not enforce card/APDU length limits. +//! +//! Reference: use crate::error::RatkeyError; @@ -171,7 +179,9 @@ pub fn select_piv() -> Vec { build_apdu(INS_SELECT, 0x04, 0x00, PIV_AID) } -/// PIN is ASCII, 0xFF-padded to 8 bytes (NIST SP 800-73-4 §2.4.3). +/// Build VERIFY with at most eight input bytes, padded with `0xFF`. +/// The caller must validate ASCII and the card's PIN-length policy first; +/// this builder neither rejects oversized input nor sends the command. pub fn verify_pin(pin: &str) -> Vec { use zeroize::Zeroize; let mut pin_data = [0xFFu8; 8]; @@ -198,7 +208,9 @@ pub fn change_pin(old_pin: &str, new_pin: &str) -> Vec { cmd } -/// RESET RETRY COUNTER: unblock a locked PIN with the PUK and set a new PIN. +/// Build RESET RETRY COUNTER to set a new PIN using the PUK, whether or not +/// the PIN is already blocked. Validate both inputs before building; each +/// field is truncated to eight bytes. pub fn reset_retry(puk: &str, new_pin: &str) -> Vec { use zeroize::Zeroize; let mut data = [0xFFu8; 16]; @@ -213,9 +225,11 @@ pub fn reset_retry(puk: &str, new_pin: &str) -> Vec { cmd } -/// RESET PIV: erase all PIV data and restore factory PIV secrets. -/// -/// YubiKey only accepts this command after both the PIN and PUK are blocked. +/// Build the destructive Yubico PIV reset command. It clears user keys, +/// certificates and PIV data and restores PIV PIN/PUK/management-key defaults; +/// slot F9 attestation material and other YubiKey applications are unaffected. +/// Both PIN and PUK must already be blocked; this builder does not block them. +/// YubiKey Bio MPE requires a different, device-wide reset workflow. pub fn reset_piv() -> Vec { build_apdu(INS_RESET_PIV, 0x00, 0x00, &[]) } @@ -295,7 +309,9 @@ fn import_key( build_apdu(INS_IMPORT_KEY, alg, slot, &data) } -/// GENERAL AUTHENTICATE Ed25519 sign. Send raw message — device does SHA-512 internally; no pre-hash. +/// Build an Ed25519 signing command for the raw message, not a caller-created +/// prehash. The device performs Ed25519's hashing. The builder does not bound +/// message length to the card's command capacity. pub fn sign_ed25519(slot: u8, message: &[u8]) -> Vec { let challenge = tlv(TAG_AUTH_CHALLENGE, message); // Empty response tag = request sig output. @@ -328,12 +344,14 @@ pub fn get_metadata(slot: u8) -> Vec { build_apdu(INS_GET_METADATA, 0x00, slot, &[]) } -/// Yubico proprietary; unsupported on Nitrokey 3. +/// Build the Yubico firmware-version command. Device detection uses this +/// only for readers classified as YubiKey; support is not probed here. pub fn get_version() -> Vec { build_apdu(INS_GET_VERSION, 0x00, 0x00, &[]) } -/// Yubico proprietary; unsupported on Nitrokey 3. +/// Build the Yubico serial-number command. Device detection uses this +/// only for readers classified as YubiKey; support is not probed here. pub fn get_serial() -> Vec { build_apdu(INS_GET_SERIAL, 0x00, 0x00, &[]) } @@ -499,10 +517,10 @@ pub fn parse_ecdh_response(data: &[u8]) -> Result<[u8; 32], RatkeyError> { Ok(out) } -/// GET METADATA public key: field tag 0x04, then EC point tag 0x86 → 32 bytes. -/// `find_tlv_value` recurses into a `7F49` wrapper if present, so both the -/// bare (`86 20 ..`) and wrapped (`7F49 .. 86 20 ..`) encodings resolve. -/// Yubico 5.3+ extension; Nitrokey 3 does not implement GET METADATA. +/// Read a 32-byte public key from Yubico GET METADATA field `0x04`, then +/// point tag `0x86`. Both bare and `7F49`-wrapped points are accepted. +/// This parser does not probe device/firmware support or validate the key +/// algorithm; the caller must establish those separately. pub fn parse_metadata_public_key(metadata: &[u8]) -> Result<[u8; 32], RatkeyError> { let pubkey_field = find_tlv_value(metadata, TAG_METADATA_PUBLIC_KEY).ok_or(RatkeyError::Apdu { diff --git a/crates/rns-ratkey/src/attestation.rs b/crates/rns-ratkey/src/attestation.rs index 6c0a926..eafaded 100644 --- a/crates/rns-ratkey/src/attestation.rs +++ b/crates/rns-ratkey/src/attestation.rs @@ -1,37 +1,24 @@ -//! YubiKey PIV attestation verification. Bundled root CAs — never fetched at runtime. +//! Verify Yubico PIV attestation paths using bundled roots and intermediates; +//! no certificates are fetched at runtime. The pool contains the legacy PIV +//! root and the newer Attestation Root 1 with A/B/B2 PIV branches. It does +//! not cover every preview, replacement or future attestation chain. //! -//! Legacy chain (firmware < 5.7.4): -//! per-key attestation cert → device intermediate (slot F9) -//! → `Yubico PIV Root CA Serial 263751` (bundled root). +//! A successful `chain_verified` means each child signature on the selected +//! path verifies with RSA PKCS#1 v1.5 (SHA-256 or SHA-512), its terminal root +//! matches a pinned DER SHA-256 fingerprint, and all selected certificates +//! are within their validity windows. The pinned root's self-signature is not +//! checked. Issuer names are compared as DER, not by full RFC 5280 name rules. //! -//! New chain (firmware >= 5.7.4): -//! per-key attestation cert → device intermediate (slot F9) -//! → `Yubico PIV Attestation {A,B,B2} 1` (bundled intermediate) -//! → `Yubico Attestation Intermediate {A,B} 1` (bundled intermediate) -//! → `Yubico Attestation Root 1` (bundled root). -//! The two tiers of intermediate CAs are not present on the device; they are -//! bundled here from Yubico's published attestation PKI (yubico-intermediate.pem). -//! Both A and B branches plus the 2025 B2 PIV intermediate are bundled, so any -//! firmware-5.7.4+ YubiKey PIV attestation chains to the bundled root. +//! This is not full PKIX validation: revocation, constraints, key usage and +//! path-length enforcement are not checked. It also does not compare the leaf +//! public key or serial with an expected token/identity. The caller must bind +//! the certificate to the key it intends to trust. Metadata extraction alone +//! is not verification; metadata and firmware-derived labels are returned +//! even when the chain fails. `supports_attestation` is only a device-label +//! filter, not a live capability probe. //! -//! Nitrokey 3 does not support PIV attestation (firmware 1.8) — verification skipped. -//! -//! ## What `chain_verified == true` means here -//! -//! Every link from the per-key attestation cert up to (and including) a bundled -//! trust anchor has a valid RSA PKCS#1 v1.5 signature (issuer public key over the -//! child's TBS bytes), the terminal issuer's DER SHA-256 matches a pinned -//! fingerprint constant, and every certificate in the walked path is inside its -//! notBefore/notAfter validity window at verification time. -//! -//! ## Explicit non-goals (NOT checked) -//! -//! Revocation (CRL/OCSP), name constraints, basicConstraints/keyUsage/pathlen -//! enforcement, and the remainder of RFC 5280 path validation are intentionally -//! out of scope. The root's own self-signature is not verified — the root is -//! trusted by pinned fingerprint plus validity window. All required chain links -//! are sha256WithRSAEncryption; the per-cert signature OID is still inspected so -//! a sha512WithRSA link would be honored rather than silently mis-verified. +//! See [Yubico PIV attestation](https://developers.yubico.com/PIV/Introduction/PIV_attestation.html) +//! for the device-generation requirement and published certificate chains. use crate::error::RatkeyError; @@ -114,22 +101,25 @@ pub struct AttestationVerification { /// True only when the attestation certificate chain has been /// cryptographically verified to a bundled trusted root. pub verified: bool, - /// True when Yubico attestation metadata could be extracted from the cert. + /// True when a firmware-version value was found by the metadata scanner. + /// It does not mean every metadata field is present or authenticated. pub metadata_extracted: bool, /// Explicit chain-verification label for UI/CLI surfaces. pub chain_verified: bool, pub info: AttestationInfo, - /// "legacy" or "new". + /// Firmware-derived label: "legacy", "new", or "unknown". This is not the + /// identity of the trust anchor actually selected by chain verification. pub root_ca: String, pub description: String, } -/// Verify chain: attestation cert (from ATTEST F9) + device intermediate (slot F9). +/// Check a per-key attestation statement (ATTEST command `F9` targeting its +/// key slot) and the device certificate read from slot F9 against the bundled +/// chain pool. `Ok(result)` can contain `verified == false`; inspect that field. /// -/// Sets `verified`/`chain_verified == true` only when every signature from the -/// per-key cert up to a bundled, fingerprint-pinned Yubico root validates and -/// all walked certs are inside their validity window. See module docs for the -/// precise meaning and the explicit non-goals. +/// This verifies the selected certificate signatures and validity windows, +/// not binding to an expected public key or device serial. See the module +/// documentation for the precise trust checks and remaining caller duties. pub fn verify_attestation( attestation_cert_der: &[u8], device_cert_der: &[u8], @@ -194,7 +184,9 @@ fn build_description( } } -/// YubiKey 5 (firmware >= 4.3.0) only. Nitrokey 3 has no PIV attestation. +/// Return true only for the exact device label `"yubikey5"`. This function +/// does not inspect firmware, key origin, certificate availability or a card; +/// all other labels, including `"nitrokey3"`, return false. pub fn supports_attestation(device_type: &str) -> bool { device_type == "yubikey5" } diff --git a/crates/rns-ratkey/src/backend.rs b/crates/rns-ratkey/src/backend.rs index 8eab9c8..105fe1c 100644 --- a/crates/rns-ratkey/src/backend.rs +++ b/crates/rns-ratkey/src/backend.rs @@ -1,7 +1,11 @@ -//! Bridges a PIV token to an `rns_identity::Identity` via the `LocalKeyBackend` -//! seam. The PIV session runs on a dedicated thread — pcsc handles want serial -//! APDU access and are not `Sync` — so the backend handle holds only channel -//! senders and is therefore `Send + Sync`, usable directly from the async runtime. +//! Bridge a PC/SC PIV session to `rns_identity::Identity` through +//! `LocalKeyBackend`. A dedicated worker serializes card access; the shared +//! backend handle is `Send + Sync`, but its methods block waiting for replies. +//! Async callers should use an appropriate blocking execution context. +//! +//! `lock` waits for an attempted applet reselect but does not return its result. +//! An acknowledgement is not proof the card was relocked; callers needing +//! that result must use the fallible session API. use std::sync::mpsc::{self, Sender}; use std::sync::{Arc, Mutex}; @@ -29,8 +33,9 @@ enum Cmd { Lock { reply: Sender<()> }, } -/// `LocalKeyBackend` over a PIV token. Each call round-trips a request to the -/// card-service thread and blocks for the device's reply (PIV ops are ~10-50ms). +/// `LocalKeyBackend` over a PIV token. Each call blocks for the card-service +/// thread's reply; touch prompts or transport delays can make this much longer +/// than a normal cryptographic operation. No per-call timeout is imposed here. pub struct HardwareBackend { cmd_tx: Mutex>, } @@ -72,10 +77,14 @@ impl LocalKeyBackend for HardwareBackend { } } -/// Connect to the token described by `hwid`, verify the on-device keys match it -/// (fail-closed), unlock with `pin`, and return an `Identity` whose private -/// operations run on the device. The PIV session lives on a worker thread that -/// exits when the returned identity (and its backend) is dropped. +/// Connect to the first detected PC/SC token, compare its fixed 9A/9D public +/// keys with `hwid`, verify `pin`, and return a device-backed `Identity`. +/// The file's serial, slot overrides and cache-timeout policy do not select or +/// configure this session. A different first token yields an error even if a +/// matching token is attached elsewhere. +/// +/// The worker exits after all backend/identity clones are dropped. This +/// function blocks during connection and PIN verification. pub fn load_hardware_identity(hwid: &HwidConfig, pin: &str) -> Result { let ed_pub = hwid.ed25519_pub_bytes()?; let x_pub = hwid.x25519_pub_bytes()?; diff --git a/crates/rns-ratkey/src/detect.rs b/crates/rns-ratkey/src/detect.rs index f49d689..6dddcab 100644 --- a/crates/rns-ratkey/src/detect.rs +++ b/crates/rns-ratkey/src/detect.rs @@ -7,9 +7,11 @@ pub struct DeviceInfo { pub reader_name: String, pub serial: Option, pub firmware: Option, - /// Slot 9A occupied. + /// Whether GET METADATA succeeded for slot 9A. An error also produces false; + /// this is not a verified Ed25519-key or empty-slot diagnosis. pub has_signing_key: bool, - /// Slot 9D occupied. + /// Whether GET METADATA succeeded for slot 9D. An error also produces false; + /// this is not a verified X25519-key or empty-slot diagnosis. pub has_encryption_key: bool, } @@ -30,7 +32,9 @@ impl DeviceType { } } -/// YubiKey readers contain "Yubico" / "YubiKey"; Nitrokey 3 contains "Nitrokey". +/// Classify a reader name by case-insensitive substrings: `yubico`/`yubikey` +/// or `nitrokey`. This does not verify a model, firmware, algorithm support +/// or authenticity; unmatched names yield `Unknown`. pub fn detect_device_type(reader_name: &str) -> DeviceType { let lower = reader_name.to_lowercase(); if lower.contains("yubico") || lower.contains("yubikey") { diff --git a/crates/rns-ratkey/src/error.rs b/crates/rns-ratkey/src/error.rs index 575b6e9..22e81a2 100644 --- a/crates/rns-ratkey/src/error.rs +++ b/crates/rns-ratkey/src/error.rs @@ -11,15 +11,19 @@ pub enum RatkeyError { #[error("PIN verification failed ({remaining} attempts remaining)")] PinFailed { remaining: u8 }, - /// PIN locked (retry counter exhausted); PIV reset or recovery-code unlock required. - #[error("PIN locked — reset the PIV application to recover")] + /// PIN retries are exhausted. A valid PUK can set a new PIN without + /// erasing keys; destructive PIV reset is the fallback when recovery is + /// unavailable. + #[error("PIN locked; a valid PUK can set a new PIN without erasing keys")] PinLocked, #[error("PIV recovery code failed ({remaining} attempts remaining)")] PukFailed { remaining: u8 }, - /// Recovery counter exhausted; PIV reset is required. - #[error("PIV recovery counter locked — reset the PIV application to recover")] + /// PUK retries are exhausted. It can no longer recover the PIN; restoring + /// PIV recovery requires a destructive reset. An otherwise valid PIN may + /// still work until its own retry counter is exhausted. + #[error("PIV recovery counter locked; a working PIN may still be usable. Resetting PIV erases user keys")] PukLocked, #[error("PIV reset requires both retry counters to be blocked")] diff --git a/crates/rns-ratkey/src/hardware.rs b/crates/rns-ratkey/src/hardware.rs index b775d49..06f5699 100644 --- a/crates/rns-ratkey/src/hardware.rs +++ b/crates/rns-ratkey/src/hardware.rs @@ -1,6 +1,8 @@ -//! `HardwareIdentity`: a public-key-only `Identity` whose private ops are served -//! by an `IdentityBackend` (real PIV session or mock). Wire-compatible with -//! software identities. +//! Wrapper pairing a public-only `Identity` with private operations supplied +//! by an `IdentityBackend`. Call this wrapper's `sign`/`decrypt` methods for +//! backend operations; its contained `Identity` and `as_identity()` remain +//! public-only. The separate PC/SC `load_hardware_identity` adapter attaches a +//! backend directly to an `Identity`. use std::path::Path; @@ -25,7 +27,8 @@ pub trait IdentityBackend { fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>; fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>; fn is_connected(&self) -> bool; - /// Re-lock the session (require PIN again on the next op). + /// Ask the backend to clear its authorization state. Handle errors; the + /// required next authentication depends on the backend and slot policy. fn lock(&mut self) -> Result<(), RatkeyError>; } @@ -82,8 +85,10 @@ pub struct HardwareIdentity { } impl HardwareIdentity { - /// Build from a `.hwid` config + a backend. Fail-closed: the device's slot - /// public keys must match the published identity. + /// Compare the backend's fixed slot-9A/9D public keys with `.hwid` and build + /// the wrapper. This does not validate the file's declared identity hash, + /// serial, attestation status or policy fields; the runtime identity hash + /// is derived from the matched public keys. Slot overrides are not used. pub fn from_hwid( config: HwidConfig, mut backend: Box, @@ -180,6 +185,8 @@ impl HardwareIdentity { &self.x25519_pub } + /// Borrow the public-only identity for hashing, encryption and verification. + /// This reference does not route signing or decryption through the backend. pub fn as_identity(&self) -> &Identity { &self.identity } @@ -192,8 +199,13 @@ impl HardwareIdentity { self.backend.ecdh_x25519(SLOT_9D, peer_pub_bytes) } - /// Ciphertext = ephemeral_pub(32) || AES-256-CBC token. Mirrors `Identity::decrypt` - /// but does the ECDH on-device. + /// Decrypt `ephemeral_pub(32) || AES-256-CBC token` with on-device identity + /// ECDH and host-side HKDF/token decryption. Returned plaintext is caller-owned. + /// + /// Unlike `Identity::decrypt`, this wrapper does not try the + /// supplied ratchet keys. With `Some(ratchets)` and `enforce_ratchets`, it + /// fails; with `None`, the enforcement flag is ignored and identity ECDH + /// is attempted. Do not use this helper as a ratchet-only admission check. pub fn decrypt( &mut self, ciphertext: &[u8], @@ -240,8 +252,9 @@ impl HardwareIdentity { self.backend.is_connected() } - /// Re-lock the session; the next sign/ECDH will require the PIN again. - /// The app calls this on its session timeout and on quit. + /// Delegate locking to the backend and return its result. The owner must + /// call this for its timeout/quit policy and handle a failed lock; this + /// wrapper has no automatic session timer. pub fn lock(&mut self) -> Result<(), RatkeyError> { self.backend.lock() } diff --git a/crates/rns-ratkey/src/hwid.rs b/crates/rns-ratkey/src/hwid.rs index 1f8b366..3577ca4 100644 --- a/crates/rns-ratkey/src/hwid.rs +++ b/crates/rns-ratkey/src/hwid.rs @@ -1,5 +1,11 @@ -//! `.hwid` TOML: public metadata for a hardware identity. No private key material ever. -//! Location: `/identities/{hash_hex}/identity.hwid`. +//! TOML metadata for a hardware identity. The defined fields contain public +//! keys, device/policy annotations and optional certificates, not a private-key +//! backup. Provisioning writes `//identity.hwid`; +//! the caller chooses that directory. +//! +//! Parsing checks the TOML shape, not key/hash binding, device authenticity, +//! attestation validity or policy enforcement. Strings and status fields are +//! caller-controlled; loaders must perform the checks they rely on. use std::path::Path; use std::str::FromStr; @@ -34,7 +40,8 @@ pub struct HwidIdentity { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HwidDevice { - /// "yubikey5" or "nitrokey3". + /// Device label, for example "yubikey5", "nitrokey3" or "unknown". + /// The label alone does not establish firmware or algorithm compatibility. #[serde(rename = "type")] pub device_type: String, pub serial: u32, @@ -59,7 +66,9 @@ pub struct HwidSlots { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HwidPolicy { - /// Seconds; 0 = never cache. + /// Requested PIN-cache duration in seconds; zero conventionally disables + /// cache reuse. The current PivSession/PCSC identity loader does not apply + /// this field and uses its own five-minute cache. #[serde(default = "default_pin_cache_timeout")] pub pin_cache_timeout: u64, /// "always" | "cached" | "never". @@ -87,8 +96,9 @@ pub struct HwidAttestation { pub ed25519_cert: String, #[serde(default)] pub x25519_cert: String, - /// Cryptographic attestation-chain verification status. Metadata - /// extraction alone must not set this true. + /// Stored attestation-chain verification claim. Metadata extraction alone + /// must not set it true; reading the TOML does not reverify the claim or + /// bind these certificates to the configured public keys. #[serde(default)] pub verified: bool, } @@ -102,7 +112,8 @@ pub struct HwidApp { #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct HwidBackup { - /// 0=none, 1=device-clone, 2=encrypted-offline. + /// Backup annotation: 0=none, 1=device-clone, 2=encrypted-offline. + /// This field does not create, restore or verify a backup. #[serde(default)] pub tier: u8, /// Tier 1 only. @@ -131,7 +142,7 @@ impl HwidConfig { pub fn to_string(&self) -> Result { let header = "# RATKEY Hardware Identity \u{2014} DO NOT EDIT MANUALLY\n\ - # Private keys exist ONLY on the hardware device.\n\n"; + # This file contains public metadata, not private keys.\n\n"; let body = toml::to_string_pretty(self).map_err(|e| RatkeyError::InvalidHwid(e.to_string()))?; Ok(format!("{header}{body}")) diff --git a/crates/rns-ratkey/src/lib.rs b/crates/rns-ratkey/src/lib.rs index 4e08ba5..860ded4 100644 --- a/crates/rns-ratkey/src/lib.rs +++ b/crates/rns-ratkey/src/lib.rs @@ -1,11 +1,18 @@ -//! Hardware-backed identity (YubiKey 5, Nitrokey 3) via PIV. Ed25519 sign + X25519 -//! ECDH keys live on-device; only public keys and results leave the token. -//! Wire-compatible with software identities. +//! PIV-backed Reticulum identities using Ed25519 signing and X25519 ECDH. +//! The token performs private-key operations; ECDH results and derived token +//! keys are processed on the host. Recoverable provisioning also derives +//! private keys on the host before importing them; on-device generation does +//! not provide a seed backup. Both produce ordinary Reticulum identities. //! -//! The PIV protocol logic (`PivSession`, `apdu`) is transport-agnostic; the -//! `PivTransport` seam isolates platform access. The `hardware` feature adds the -//! PC/SC transport (`PcscTransport`) and its `connect()` entry points. Mobile -//! NFC/USB transports implement `PivTransport` from the application layer. +//! A device needs both algorithms and the PIV extensions used by the selected +//! workflow. Standard non-FIPS YubiKey 5 firmware 5.7+ provides these algorithms. +//! Recognizing a Nitrokey reader name does not establish workflow compatibility. +//! See [Yubico PIV algorithms](https://developers.yubico.com/PIV/Introduction/YubiKey_and_PIV.html) +//! and [Nitrokey algorithm support](https://docs.nitrokey.com/nitrokeys/nitrokey3/faq). +//! +//! [`PivSession`] uses a caller-supplied [`PivTransport`]. The `hardware` feature +//! adds desktop PC/SC and its connection helpers; applications can supply other +//! transports. The default build includes codecs and mocks, not a PC/SC driver. pub mod apdu; pub mod attestation; diff --git a/crates/rns-ratkey/src/mock.rs b/crates/rns-ratkey/src/mock.rs index c7cfecc..71e14c9 100644 --- a/crates/rns-ratkey/src/mock.rs +++ b/crates/rns-ratkey/src/mock.rs @@ -1,6 +1,7 @@ -//! In-memory PIV mock with real Ed25519/X25519 crypto; signatures/ECDH are bit-identical -//! to software results for test vector reuse. Simulates PIN retry/lockout, touch policy, -//! disconnect, slot state. Primary dev/validation env until hardware lands. +//! In-memory test double using the software Ed25519/X25519 implementations. +//! It models PIN retries, connection state, slots and an explicit touch flag; +//! it does not reproduce card transport, management authentication, firmware +//! behavior or every touch policy. Private keys remain in host memory. use std::collections::HashMap; @@ -19,7 +20,8 @@ pub const SLOT_9D: u8 = 0x9D; pub enum TouchPolicy { Never, Always, - /// YubiKey ~15s cache. + /// Yubico policy value for a roughly 15-second touch cache. The mock does + /// not simulate that timer; only `Always` checks its touch-required flag. Cached, } diff --git a/crates/rns-ratkey/src/pin.rs b/crates/rns-ratkey/src/pin.rs index 203a187..a407cd0 100644 --- a/crates/rns-ratkey/src/pin.rs +++ b/crates/rns-ratkey/src/pin.rs @@ -1,4 +1,7 @@ -//! PIN cache: `Zeroizing` wiped on drop or expiry. +//! Host-side PIN cache backed by `Zeroizing`. Replacing, clearing or +//! dropping the stored value wipes it. Expiry only makes `get` return `None`; +//! it does not clear the allocation or relock a card. The owner must call +//! `clear` and perform any required card-session lock. use std::time::{Duration, Instant}; use zeroize::Zeroizing; @@ -10,7 +13,9 @@ pub struct PinCache { } impl PinCache { - /// `Duration::ZERO` disables caching (PIN required every op). + /// `Duration::ZERO` disables cache reuse. `cache` still stores the PIN until + /// clear/replacement/drop; this setting does not force an already-authorized + /// card to require a PIN for each operation. pub fn new(timeout: Duration) -> Self { Self { pin: None, diff --git a/crates/rns-ratkey/src/provision.rs b/crates/rns-ratkey/src/provision.rs index fbe074f..2d2ef3c 100644 --- a/crates/rns-ratkey/src/provision.rs +++ b/crates/rns-ratkey/src/provision.rs @@ -1,4 +1,13 @@ -//! Generate keys on-device, derive identity hash, write `.hwid`. +//! Provision fixed slots 9A (Ed25519) and 9D (X25519), then optionally write +//! public `.hwid` metadata. Choose on-device generation or mnemonic-derived +//! key import explicitly. +//! +//! Real-card generation/import can replace existing slot keys. These steps +//! are sequential, with no empty-slot guard or rollback: an error can leave +//! one slot changed, and a later file-write failure does not undo card changes. +//! The caller owns consent, credential handling and recovery of partial work. +//! Provisioning does not change the card PIN, PUK or management key, or verify +//! attestation. `config.pin` is used only by `provision_mock`. use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; @@ -26,7 +35,9 @@ pub struct ProvisionResult { #[derive(Debug, Clone)] pub struct ProvisionConfig { - /// PIV PIN (6-8 chars). + /// PIN used by `provision_mock`. Real provisioning helpers do not read this + /// field or verify/change the card PIN. This ordinary `String` is not + /// automatically wiped; the caller owns its lifetime and input validation. pub pin: String, pub touch_signing: TouchPolicy, pub touch_encryption: TouchPolicy, @@ -152,9 +163,11 @@ fn touch_str(tp: TouchPolicy) -> &'static str { } } -/// Recoverable provision / restore: derive the identity from `mnemonic`, import -/// both keys into the token (PIN-once + configured touch policy), and write the -/// `.hwid`. Requires the management key. The session must already be connected. +/// Derive private keys from `mnemonic` on the host and import them into +/// 9A/9D with PIN-once and the requested touch policies. Requires a connected +/// session and valid management key. Writes `.hwid` only when a directory is +/// configured. Existing keys can be replaced, and partial failure is not +/// rolled back; see the module's provisioning boundary. pub fn import_recoverable_identity( session: &mut PivSession, mgmt_key: &[u8], @@ -179,8 +192,9 @@ pub fn import_recoverable_identity( finalize_provision(session, config, derived.ed25519_pub, derived.x25519_pub) } -/// On-device provisioning (no seed backup): authenticate, generate both keys on -/// the token, and write the `.hwid`. Requires the management key. +/// Authenticate with the management key and generate new 9A/9D keys on the +/// token, without a seed backup. Write `.hwid` only when configured. This can +/// replace existing keys and has no rollback after partial failure. pub fn provision_hardware_only( session: &mut PivSession, mgmt_key: &[u8], @@ -200,8 +214,10 @@ pub fn provision_hardware_only( finalize_provision(session, config, ed_pub, x_pub) } -/// Register an already-provisioned token: read its slot public keys and write a -/// `.hwid` for it (import-existing). No key material is created; no mgmt key needed. +/// Read fixed 9A/9D public keys and optionally write `.hwid`; no keys are +/// created and no management key is required. The recorded touch policies +/// come from `config`, not a readback of the token's actual policy. +/// This requires the token's public-key metadata extension. pub fn read_existing( session: &mut PivSession, config: &ProvisionConfig, @@ -275,8 +291,9 @@ fn finalize_provision( }) } -/// Recoverable provisioning: generate a fresh 12-word mnemonic, import the -/// derived identity, and return both the result and the mnemonic to show once. +/// Generate a 12-word mnemonic and import its derived identity using +/// [`import_recoverable_identity`]. The returned phrase is an ordinary +/// `String`; the caller controls its display, backup and eventual wiping. pub fn provision_recoverable( session: &mut PivSession, mgmt_key: &[u8], diff --git a/crates/rns-ratkey/src/seed.rs b/crates/rns-ratkey/src/seed.rs index 058e942..35a597e 100644 --- a/crates/rns-ratkey/src/seed.rs +++ b/crates/rns-ratkey/src/seed.rs @@ -1,15 +1,18 @@ -//! BIP-39 recoverable backup: a deterministic Reticulum identity derived from a -//! 12-word mnemonic. Interop-compatible with ratkey-py (derivation scheme v1): +//! Derive Reticulum identity keys from a 12-word BIP-39 English mnemonic. +//! The salts and HKDF info match Ratkey derivation scheme v1, but Rust +//! validates exactly 12 words while the Python Ratkey backup API validates +//! 24. Their public restore inputs are therefore not interchangeable. //! //! ```text //! mnemonic (12 words) -//! -> PBKDF2-SHA512 (BIP-39, passphrase="") -> 64-byte seed -//! -> HKDF-SHA256(seed, salt="ratkey-ed25519-v1", info) -> 32-byte Ed25519 seed -//! -> HKDF-SHA256(seed, salt="ratkey-x25519-v1", info) -> 32-byte X25519 secret +//! -> PBKDF2-SHA512 (BIP-39, empty passphrase) -> 64-byte seed +//! -> HKDF-SHA256(seed, salt="ratkey-ed25519-v1", info) -> Ed25519 seed +//! -> HKDF-SHA256(seed, salt="ratkey-x25519-v1", info) -> X25519 secret +//! info = "ratkey identity key derivation" //! ``` //! -//! The seed phrase is a second attack surface (it reconstructs the private keys -//! and is not protected by the device PIN). Callers must surface that tradeoff. +//! The phrase reconstructs the private keys without the device PIN. Callers +//! must protect it separately and make this recovery tradeoff clear. use bip39::{Language, Mnemonic}; use hkdf::Hkdf; @@ -27,7 +30,8 @@ const HKDF_INFO: &[u8] = b"ratkey identity key derivation"; const MNEMONIC_WORDS: usize = 12; const MNEMONIC_ENTROPY_BYTES: usize = 16; -/// Key material derived from a mnemonic. The two secret fields are zeroized on drop. +/// Key material derived from a mnemonic. Its two secret fields are zeroized +/// on drop; caller-created copies and the source phrase have separate lifetimes. pub struct DerivedIdentity { pub ed25519_seed: [u8; 32], pub x25519_secret: [u8; 32], diff --git a/crates/rns-ratkey/src/session.rs b/crates/rns-ratkey/src/session.rs index ea9e8c5..77b35d7 100644 --- a/crates/rns-ratkey/src/session.rs +++ b/crates/rns-ratkey/src/session.rs @@ -1,6 +1,11 @@ -//! Transport-agnostic PIV session. Every PIV operation is built on `apdu` plus a -//! `PivTransport`; the transport is the only platform-specific part (see `transport`). -//! `hardware` feature adds the PC/SC `connect()` entry points. +//! Transport-agnostic PIV session built on [`crate::apdu`] and +//! [`PivTransport`]. The `hardware` feature adds PC/SC connection helpers. +//! A caller-supplied transport must already have selected the PIV application. +//! +//! PIN caching enables one verification/retry when a command returns `0x6982`. +//! Expiry does not clear an authorized card session or wipe the cached PIN; +//! use `lock` and handle its result for application session policy. Input +//! length/character validation and secret-buffer ownership remain with callers. use crate::apdu; use crate::detect::DeviceType; @@ -51,10 +56,10 @@ impl PivSession { self.transport.is_connected() } - /// Re-locks the card: re-selects the PIV applet (resetting the on-card PIN - /// verification) and clears the cached PIN, so the next private-key op needs - /// a fresh `verify_pin`. This is the mechanism behind the app-side session - /// timeout / lock-on-quit. + /// Reselect the PIV application, then clear the host PIN cache on success. + /// A transport/status error returns before the cache is cleared. The owner + /// must handle the result; this method does not schedule a lock timer, and + /// subsequent PIN requirements depend on the card and key policy. pub fn lock(&mut self) -> Result<(), RatkeyError> { let resp = self.transport.transmit(&apdu::select_piv())?; apdu::check_response(&resp)?; @@ -62,6 +67,9 @@ impl PivSession { Ok(()) } + /// Verify the supplied PIN and cache it on success. Validate the card's PIN + /// policy first (normally 6–8 ASCII bytes); the APDU builder truncates at + /// eight bytes. Failed verification can consume a card retry. pub fn verify_pin(&mut self, pin: &str) -> Result<(), RatkeyError> { // PIN-bearing APDU buffers are wiped once transmitted. let cmd = zeroize::Zeroizing::new(apdu::verify_pin(pin)); @@ -71,6 +79,9 @@ impl PivSession { Ok(()) } + /// Change the card PIN and cache the new value on success. Validate both + /// inputs first; the APDU builder truncates at eight bytes. A wrong old PIN + /// can consume a retry. pub fn change_pin(&mut self, old_pin: &str, new_pin: &str) -> Result<(), RatkeyError> { let cmd = zeroize::Zeroizing::new(apdu::change_pin(old_pin, new_pin)); let resp = self.transport.transmit(&cmd)?; @@ -79,6 +90,9 @@ impl PivSession { Ok(()) } + /// Set a new PIN using the PUK, preserving the stored keys. A wrong PUK + /// can consume its retry counter. Validate both inputs before calling; + /// this does not recover private keys from a reset or lost token. pub fn unblock_pin(&mut self, puk: &str, new_pin: &str) -> Result<(), RatkeyError> { let cmd = zeroize::Zeroizing::new(apdu::reset_retry(puk, new_pin)); let resp = self.transport.transmit(&cmd)?; @@ -93,6 +107,9 @@ impl PivSession { } } + /// Send the destructive PIV reset command; see [`crate::apdu::reset_piv`] + /// for scope and prerequisites. This method does not first block the PIN + /// or PUK. It clears the host PIN cache only after the card reports success. pub fn reset_piv(&mut self) -> Result<(), RatkeyError> { let resp = self.transport.transmit(&apdu::reset_piv())?; match apdu::check_response(&resp) { @@ -108,6 +125,9 @@ impl PivSession { } } + /// Generate an Ed25519 key in `slot` after management authentication. + /// This can overwrite an existing key; no backup, empty-slot guard or + /// rollback is provided. pub fn generate_ed25519( &mut self, slot: u8, @@ -124,6 +144,9 @@ impl PivSession { apdu::parse_generate_response(data) } + /// Generate an X25519 key in `slot` after management authentication. + /// This can overwrite an existing key; no backup, empty-slot guard or + /// rollback is provided. pub fn generate_x25519( &mut self, slot: u8, @@ -140,8 +163,10 @@ impl PivSession { apdu::parse_generate_response(data) } - /// Import an off-device Ed25519 key (recoverable provisioning / restore). - /// Requires prior `authenticate_management_key`. + /// Import an off-device Ed25519 key into `slot`. Requires prior management + /// authentication and can replace the slot's existing key; there is no + /// empty-slot guard or rollback. The caller retains responsibility for the + /// private-key input and any copies made during provisioning. pub fn import_ed25519( &mut self, slot: u8, @@ -159,7 +184,9 @@ impl PivSession { Ok(()) } - /// Import an off-device X25519 key. Requires prior `authenticate_management_key`. + /// Import an off-device X25519 key into `slot`, potentially replacing an + /// existing key. Requires prior management authentication. No empty-slot + /// guard or rollback is provided; treat the private-key input as secret. pub fn import_x25519( &mut self, slot: u8, @@ -219,7 +246,9 @@ impl PivSession { apdu::parse_ecdh_response(&data) } - /// Returns DER-encoded X.509 attestation certificate. + /// Request the target slot's DER X.509 attestation statement (command `F9`, + /// not attestation slot F9). On YubiKey this is available for keys generated + /// on-device, not imported recovery keys. The returned bytes are not verified. pub fn attest_key(&mut self, slot: u8) -> Result, RatkeyError> { let resp = self.transport.transmit(&apdu::attest_key(slot))?; Ok(apdu::check_response(&resp)?.to_vec()) @@ -250,18 +279,18 @@ impl PivSession { Ok(apdu::check_response(&resp)?.to_vec()) } - /// Reads the slot's 32-byte public key from GET METADATA. The metadata byte - /// layout is pending confirmation against a real device — see - /// `apdu::parse_metadata_public_key`. Yubico 5.3+ only (Nitrokey 3 has no - /// GET METADATA). + /// Read a 32-byte slot public key through Yubico GET METADATA and + /// [`crate::apdu::parse_metadata_public_key`]. This requires the corresponding + /// extension and algorithm support; reader detection alone is insufficient. pub fn read_public_key(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> { let metadata = self.read_metadata(slot)?; apdu::parse_metadata_public_key(&metadata) } - /// Authenticate the PIV management key (slot 9B) via witness/challenge mutual - /// auth — required before on-device key generation. The algorithm is read - /// from the card (YubiKey 5.7 default: AES-192). + /// Authenticate the management key (9B) with witness/challenge mutual auth + /// before key generation or import. Reads the algorithm through GET METADATA + /// and supports TDES/AES variants. This path requires that extension; it does + /// not infer the algorithm from key length or fall back for other cards. pub fn authenticate_management_key(&mut self, key: &[u8]) -> Result<(), RatkeyError> { let meta = self.read_metadata(apdu::SLOT_CARD_MANAGEMENT)?; let alg = apdu::parse_metadata_algorithm(&meta)?; diff --git a/crates/rns-ratkey/src/transport.rs b/crates/rns-ratkey/src/transport.rs index 7d7b3aa..1251c50 100644 --- a/crates/rns-ratkey/src/transport.rs +++ b/crates/rns-ratkey/src/transport.rs @@ -1,7 +1,7 @@ //! Transport seam for PIV. The PIV protocol logic lives in `PivSession`; this //! trait is the only platform-specific part: APDU bytes in, response bytes out. -//! Desktop PC/SC ships here behind the `hardware` feature. Mobile NFC/USB -//! transports live in the application layer and implement the same trait. +//! Desktop PC/SC ships here behind the `hardware` feature. Applications can +//! implement mobile NFC/USB transports through this trait. use crate::error::RatkeyError; @@ -9,7 +9,9 @@ pub trait PivTransport { /// Send one ISO 7816-4 APDU; return the full response including SW1/SW2. fn transmit(&mut self, apdu: &[u8]) -> Result, RatkeyError>; - /// Cheap liveness probe — token still present and responding. + /// Best-effort liveness probe, not an authentication or capability check. + /// The PC/SC implementation only checks whether a metadata command can be + /// transmitted; it does not require a successful APDU status. fn is_connected(&self) -> bool; } @@ -29,8 +31,10 @@ mod pcsc_transport { const MAX_RESPONSE: usize = 4096; - /// Real PIV transport over PC/SC (YubiKey 5, Nitrokey 3). Requires a PC/SC - /// daemon: macOS CryptoTokenKit / Linux pcscd / Windows WinSCard. + /// PC/SC APDU transport, enabled by `hardware`. Requires the platform + /// PC/SC library/service (system smart-card support on macOS/Windows, + /// libpcsclite and pcscd on Linux). Connection does not establish that + /// the card supports the required key algorithms or vendor extensions. pub struct PcscTransport { card: pcsc::Card, } diff --git a/crates/rns-runtime/examples/README.md b/crates/rns-runtime/examples/README.md index 35bd389..6e5b62e 100644 --- a/crates/rns-runtime/examples/README.md +++ b/crates/rns-runtime/examples/README.md @@ -1,28 +1,83 @@ # Reticulum runtime examples -These examples mirror the application-facing subjects in the upstream Python -Reticulum examples while using explicit Rust runtime ownership. +These examples use the 1.4 source API and `rns_runtime::prelude`. Run them from +the rsReticulum repository root after installing the [build prerequisites](../../../README.md#build-it). +They demonstrate application ownership; they are not ready-made services. -Most networked examples have `server` and `client` modes: +## Run a client and server -```console -cargo run -p rns-runtime --example link -- server -cargo run -p rns-runtime --example link -- client "hello" +Most examples have `server` and `client` modes. Start the server in one terminal: + +```sh +cargo run -p rns-runtime --example link -- server --config /path/to/server-config ``` -Pass `--config ` to either mode to select a Reticulum config -directory. Servers print their destination hash and announce once at startup. +Copy the printed 32-character destination hash, then run the client from another +terminal or host connected to the same Reticulum network: -The `ratchets` example is a local composition recipe because ratchet files and -identity files are application-owned secrets: +```sh +cargo run -p rns-runtime --example link -- client "DESTINATION_HASH" "hello" --config /path/to/client-config +``` -```console +Replace the paths and hash. `--config` selects a directory containing a Reticulum +`config` file. Without it, the example uses the normal rsReticulum configuration +and may attach to its shared instance. Two standalone owners on one host need +different shared-instance ports or sharing disabled. An empty or disconnected +configuration does not provide a path between the examples. + +Each server creates a temporary identity on startup, prints its destination and +announces once; its address changes after a restart. `announce` is different: +it announces when you press Enter. Networked examples use the configured +interfaces, so run demonstrations on a network you control. Stop servers with +Ctrl-C. + +## Choose an example + +All commands start with `cargo run -p rns-runtime --example NAME --`. Arguments +below follow the `--`; networked examples also accept `--config DIRECTORY`. + +| Example | Arguments and result | +| --- | --- | +| `minimal` | No positional arguments. Announces and prints received packets with automatic proofs enabled. | +| `announce` | No positional arguments. Observes matching announces; Enter sends an announce with `Peach` app data. | +| `broadcast` | Optional message. Sends a PLAIN broadcast without encryption or a delivery receipt. | +| `echo` | `server`, or `client HASH [MESSAGE]`. The client waits for a packet proof, not an echoed message. | +| `link` | `server`, or `client HASH [MESSAGE]`. Exchanges a message and reply over a Link. | +| `identify` | `server`, or `client HASH`. Demonstrates initiator identification on a Link. | +| `request` | `server`, or `client HASH [MESSAGE]`. Requests `/echo`; the example handler allows all callers. | +| `channel` | `server`, or `client HASH [MESSAGE]`. Exchanges a custom Channel message. | +| `buffer` | `server`, or `client HASH [MESSAGE]`. Exchanges a short UTF-8 string using Buffer/stream frames. Use the default short message; this example adds a reply prefix per received frame and is not an arbitrary-length echo protocol. | +| `resource` | `server`, or `client HASH [MESSAGE]`. Transfers a Resource with progress reporting. | +| `filetransfer` | `server NEW_OUTPUT_FILE`, or `client HASH INPUT_FILE`. Writes the first completed Resource to a new file and refuses to replace an existing file. | +| `speedtest` | `server`, or `client HASH [BYTE_COUNT]`. Queues Link packets; the default is 2 MiB. | +| `ratchets` | `IDENTITY_FILE RATCHET_FILE [MESSAGE]`. Local key persistence and encrypt/decrypt composition; it does not start a network runtime. | + +Resource and file-transfer servers accept incoming Resources without a caller +allow-list. The file-transfer destination is a demonstration endpoint, not an +authenticated file-sharing service. A Resource completion is a transport result; +it does not acknowledge the receiving application's later file write. + +The speed-test client's rate measures local queue submission, not delivered +network throughput. Its server prints a rate measured from server startup, +including idle time; after its counter resets, that rate is not a per-batch +benchmark. Use a dedicated benchmark with receiver-confirmed bytes for network +capacity measurements. + +## Local ratchet example + +The ratchet example creates missing identity and ratchet files and reuses +existing ones: + +```sh cargo run -p rns-runtime --example ratchets -- identity.key ratchets.bin ``` -Use private, access-controlled paths for both files in a real application. +Use new test paths for a demonstration and private, access-controlled paths in +a real application. Ratchet files and identity files are application-owned +secrets. The example retains its ratchet key; demonstrating encryption with +that key alone does not demonstrate key retirement or forward secrecy. -Python's `ExampleInterface.py` demonstrates runtime-loaded Python classes. -Rust instead integrates third-party interfaces at compile time through -`rns_interface::InterfaceHandle` and the runtime's interface factory. This is -an intentional ownership and type-safety difference, not a wire-protocol gap. +Python's `ExampleInterface.py` loads Python classes at runtime. Rust integrates +third-party interfaces at compile time through `rns_interface::InterfaceHandle` +and the interface factory. Custom drivers on the 1.4 line must also follow the +[interface ownership and capacity contract](../../../api/migrations/capacity-and-receipts.md). diff --git a/crates/rns-runtime/examples/echo.rs b/crates/rns-runtime/examples/echo.rs index 5eed1e8..9666aa0 100644 --- a/crates/rns-runtime/examples/echo.rs +++ b/crates/rns-runtime/examples/echo.rs @@ -38,7 +38,7 @@ async fn server(args: ExampleArgs) -> ExampleResult { _ = runtime.shutdown.wait() => break, packet = destination.events.packets.recv() => { let Some(packet) = packet else { break }; - println!("Proved {} bytes: {}", packet.data.len(), String::from_utf8_lossy(&packet.data)); + println!("Received {} bytes (automatic proof enabled): {}", packet.data.len(), String::from_utf8_lossy(&packet.data)); } } } diff --git a/crates/rns-runtime/src/buffer_stream.rs b/crates/rns-runtime/src/buffer_stream.rs index c0f6f5e..9e7e9a5 100644 --- a/crates/rns-runtime/src/buffer_stream.rs +++ b/crates/rns-runtime/src/buffer_stream.rs @@ -22,7 +22,8 @@ use crate::link_session::{LinkSessionChannelError, LinkSessionChannelHandle}; /// Maximum unread data retained by the default channel Buffer reader. pub const DEFAULT_READER_CAPACITY: usize = 1024 * 1024; -/// Maximum time an orderly writer shutdown waits for channel headroom. +/// Maximum wait to enqueue EOF once earlier writer frames have been queued. +/// This does not bound an earlier pending write or wait for remote delivery. pub const DEFAULT_CLOSE_TIMEOUT: Duration = Duration::from_secs(15); const CHANNEL_RETRY_INTERVAL: Duration = Duration::from_millis(10); @@ -181,9 +182,11 @@ enum WriterState { /// Write half of a channel-backed Reticulum Buffer stream. /// -/// Writes are split and compressed by the protocol layer. Shutdown queues EOF -/// only after all earlier writer frames have entered the reliable channel -/// sequence and the channel has headroom for EOF. +/// Writes are split and compressed by the protocol layer. Flush waits for +/// local channel admission, not remote delivery. Shutdown then queues EOF +/// when the channel has headroom; it does not wait for an EOF receipt. +/// The close timeout covers EOF admission only. Apply an outer deadline if +/// an earlier pending write must also be bounded. pub struct LinkSessionBufferWriter { channel: LinkSessionChannelHandle, writer: StreamWriter, diff --git a/crates/rns-runtime/src/config.rs b/crates/rns-runtime/src/config.rs index 665d4ee..184058b 100644 --- a/crates/rns-runtime/src/config.rs +++ b/crates/rns-runtime/src/config.rs @@ -74,8 +74,9 @@ impl ConfigSection { self.get_bool(key).unwrap_or(default) } - /// Upstream's interface rule (Reticulum.py): enabled only when - /// `interface_enabled` or `enabled` is present and true. + /// Whether either `interface_enabled` or `enabled` parses as true. Missing + /// or invalid boolean values do not enable an interface; callers that reject + /// malformed enable settings must also check `invalid_enable_key`. pub fn interface_enabled(&self) -> bool { self.get_bool("interface_enabled") == Some(true) || self.get_bool("enabled") == Some(true) } @@ -85,7 +86,8 @@ impl ConfigSection { self.has("interface_enabled") || self.has("enabled") } - /// An enable key whose value is not a boolean, which upstream rejects. + /// The first present enable key that does not parse as a boolean, including + /// a list value. Returns `None` when both are absent or valid. pub fn invalid_enable_key(&self) -> Option<&'static str> { ["interface_enabled", "enabled"] .into_iter() @@ -182,8 +184,9 @@ impl Config { Self::default() } - /// Mirrors Python ConfigObj file loading, including normal OS symlink - /// following. Security policy for config paths must be enforced by callers. + /// Read and parse a UTF-8 config, then validate the configured remote + /// management, blackhole and interface-discovery identity hash lists. + /// Normal OS symlink following applies; callers enforce config-path policy. pub fn from_file(path: &Path) -> Result { let content = std::fs::read_to_string(path)?; let mut config = Self::parse(&content)?; diff --git a/crates/rns-runtime/src/config/ifac.rs b/crates/rns-runtime/src/config/ifac.rs index 4b21735..d918250 100644 --- a/crates/rns-runtime/src/config/ifac.rs +++ b/crates/rns-runtime/src/config/ifac.rs @@ -49,8 +49,12 @@ fn integer(section: &ConfigSection, key: &'static str) -> Result, .transpose() } -/// Decode file units without changing credential activation or class defaults. -/// A legacy byte escape must be diagnosed by the caller when present. +/// Decode an IFAC size into bytes, or return `None` for the class default. +/// `ifac_size` is 8..=512 bits in multiples of eight; values 1..=64 require +/// explicit `ifac_size_unit = bits` because legacy files used bytes. +/// `ifac_size_bytes` accepts 1..=64 bytes and cannot coexist with either +/// other size key. This parser does not activate IFAC credentials; callers +/// must diagnose use of the legacy byte escape. pub fn parse_ifac_size(section: &ConfigSection) -> Result, IfacConfigError> { let has_bits = section.has("ifac_size"); let has_unit = section.has("ifac_size_unit"); @@ -365,7 +369,9 @@ pub fn plan_ifac_unit_migration( }) } -/// Redacted status consumed by configuration editors. Credentials never enter it. +/// List interfaces whose IFAC size needs an explicit units decision, without +/// copying credential fields. `effective_bytes` initially repeats the raw +/// value as the legacy-byte interpretation; it is not a resolved size. pub fn migration_candidates(config: &Config) -> Vec { config .subsections("interfaces") diff --git a/crates/rns-runtime/src/deferred_request.rs b/crates/rns-runtime/src/deferred_request.rs index e2d9aa6..b437764 100644 --- a/crates/rns-runtime/src/deferred_request.rs +++ b/crates/rns-runtime/src/deferred_request.rs @@ -83,9 +83,10 @@ impl DeferredRequestResponder { pub fn is_cancelled(&self) -> bool { !self.state.alive.load(Ordering::Acquire) || Instant::now() >= self.state.deadline } - /// Queues one result. `Sent` acknowledges transport queue acceptance or - /// Resource initiation, not remote delivery. No response is emitted for a - /// closed/replaced Link, a dropped manager or an expired request. + /// Queues one result. `Sent` acknowledges local response staging in the + /// transport mailbox or manager retry queue, or Resource initiation. It + /// does not acknowledge endpoint dispatch or remote delivery. No response + /// is emitted for a closed/replaced Link, dropped manager or expired request. pub fn respond( mut self, outcome: RequestOutcome, diff --git a/crates/rns-runtime/src/destination_resolver.rs b/crates/rns-runtime/src/destination_resolver.rs index 485abb6..a7dbe05 100644 --- a/crates/rns-runtime/src/destination_resolver.rs +++ b/crates/rns-runtime/src/destination_resolver.rs @@ -1,7 +1,5 @@ -//! Deadline-aware, handler-free destination identity resolution. -//! -//! Python applications resolve finite destinations through validated identity -//! recall and path requests. They do not install temporary announce handlers. +//! Deadline-aware destination identity resolution through transport recall +//! and path-request commands, without temporary announce handlers. use std::time::Duration; @@ -18,11 +16,11 @@ pub struct DestinationResolveOptions { /// Complete command admission, path request and recall before this budget. pub timeout: Duration, /// Remove an existing route before requesting a fresh path response when - /// the validated identity is not already cached. + /// identity metadata is not already cached. pub drop_existing_path: bool, - /// Request a path refresh even when validated identity data is cached. - /// The cached identity remains immediately usable, matching upstream - /// applications that refresh routing separately from identity recall. + /// Queue a path-refresh request even when identity metadata is cached. + /// The call waits for command admission, then returns the cached identity + /// without waiting for a fresh path response. pub refresh_cached_path: bool, } @@ -46,12 +44,14 @@ pub enum DestinationResolveError { UnexpectedResponse(&'static str), } -/// Resolve one validated destination without installing an announce handler. +/// Resolve cached announce identity metadata from the transport. This helper +/// trusts the transport and its persistent cache; it does not freshly verify +/// an announce signature or establish current on-network presence. /// -/// A missing identity always emits an explicit path request. This deliberately -/// covers the state where a route exists but its validated announce metadata -/// is absent: `AwaitPath` alone would return immediately and never repair the -/// identity cache. +/// When identity data is absent, queue an explicit path-request command even +/// if a route already exists, then poll recall until the deadline. Command +/// admission does not establish that the request reached the network; the +/// transport handles routing and request suppression. pub async fn resolve_destination_on_transport( transport_tx: &mpsc::Sender, destination_hash: [u8; 16], diff --git a/crates/rns-runtime/src/destination_runtime.rs b/crates/rns-runtime/src/destination_runtime.rs index 69e16be..71bbd58 100644 --- a/crates/rns-runtime/src/destination_runtime.rs +++ b/crates/rns-runtime/src/destination_runtime.rs @@ -1,10 +1,9 @@ //! App-facing ownership for an inbound SINGLE destination. //! -//! Python binds Destination construction, transport registration, Link -//! handling, and callbacks to process-global state. This facade keeps those -//! responsibilities explicit: one registration owns one responder -//! [`LinkManager`], exposes bounded event receivers, and deregisters when -//! closed. +//! One registration owns one responder [`LinkManager`] and its event receivers. +//! Most receivers are bounded; ordinary Link packet delivery uses an unbounded +//! queue. Close the registration explicitly to wait for manager shutdown and +//! submission of destination deregistration. use rns_identity::destination::{ AllowPolicy, DefaultAppData, DestType, Destination, DestinationError, Direction, ProofStrategy, @@ -41,7 +40,7 @@ pub struct DestinationRuntimeOptions { /// Announce app data used whenever an announce (including a path /// response) carries none explicitly. pub default_app_data: Option>, - /// Per-advertisement acceptance policy consulted when + /// Per-advertisement acceptance policy for ordinary Resources, consulted when /// `resource_strategy` is `AcceptApp`. pub resource_accept: Option, /// Synchronous LinkIdentify gate; returning false closes the link. @@ -65,7 +64,10 @@ impl Default for DestinationRuntimeOptions { } } -/// Clonable per-advertisement inbound Resource acceptance policy. +/// Clonable per-advertisement acceptance policy for ordinary inbound Resources. +/// Request/response transfers use their own handling. The callback +/// receives `(link_id, advertisement)` and runs synchronously on the manager; +/// it is consulted only with `ResourceStrategy::AcceptApp`. #[derive(Clone)] pub struct ResourceAcceptPolicy(Arc); @@ -83,8 +85,10 @@ impl fmt::Debug for ResourceAcceptPolicy { } } -/// Clonable synchronous LinkIdentify gate, consulted before any later -/// resource advertisement can race the admission decision. +/// Clonable synchronous gate for a verified LinkIdentify message. The callback +/// receives `(link_id, identity_hash)`; false closes that Link before later +/// packets are processed. This does not require peers to identify before +/// sending data or Resource advertisements; enforce that separately. #[derive(Clone)] pub struct IdentityGatePolicy(Arc bool + Send + Sync>); @@ -100,10 +104,13 @@ impl fmt::Debug for IdentityGatePolicy { } } -/// Persistent forward-secrecy settings for a live inbound destination. +/// Persistent ratchet settings for inbound destination packets. Key retention +/// and expiry determine the history exposed by compromise of the stored ring. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DestinationRatchetOptions { - /// Signed Python-compatible ratchet-ring file. + /// Persistent ratchet-ring file. Legacy files may authenticate only the + /// current public key; see `PersistentRatchetRing::open` before accepting + /// an existing file. pub path: PathBuf, /// Reject packets encrypted only to the base identity key. pub enforce: bool, @@ -125,9 +132,11 @@ pub struct DestinationPacket { pub raw: Vec, } -/// Event receivers owned by one registered destination. All are bounded by -/// `event_capacity` except `link_packets`: inbound link data is proved to the -/// peer on receipt, so its local delivery is lossless and must be drained. +/// Event receivers owned by one registered destination. Receivers are bounded +/// by `event_capacity` except `link_packets`, which is unbounded and must be +/// drained to avoid memory growth. Notification queues can drop events when +/// full. Link proof policy is independent of application consumption; receipt +/// of a proof does not establish that the application processed the payload. pub struct DestinationEvents { pub packets: mpsc::Receiver, pub links_established: mpsc::Receiver<[u8; 16]>, @@ -384,6 +393,9 @@ impl DestinationHandle { } /// Owns one live inbound destination and its responder Link manager. +/// Use `close` to await shutdown; dropping requests it on a best-effort basis. +/// These mailbox-based registration methods reject `ProofStrategy::ProveApp` +/// because they do not carry exact endpoint-dispatch authority. pub struct RegisteredDestination { pub handle: DestinationHandle, pub events: DestinationEvents, @@ -400,8 +412,10 @@ impl RegisteredDestination { Self::register_inner(transport_tx, identity, app_name, options, None).await } - /// Register a live destination whose announce rotation and inbound - /// decryption are backed by one verified persistent ratchet ring. + /// Register a destination whose announce rotation and inbound decryption + /// use a persistent ratchet ring. A current ratchet is ensured before use. + /// Existing legacy files are accepted with the authentication limits of + /// `PersistentRatchetRing::open`; this method does not expose their format. pub async fn register_ratcheted( transport_tx: mpsc::Sender, identity: Identity, diff --git a/crates/rns-runtime/src/inbound_link_packet.rs b/crates/rns-runtime/src/inbound_link_packet.rs index 05c79cc..db3a196 100644 --- a/crates/rns-runtime/src/inbound_link_packet.rs +++ b/crates/rns-runtime/src/inbound_link_packet.rs @@ -185,8 +185,9 @@ impl InboundLinkPacket { } } -/// Non-cloneable authority for one exact received packet. Resolution does not -/// imply admission until its returned receiver reports `Sent`. +/// Non-cloneable authority for one exact received packet. For acceptance or +/// rejection, the returned receiver reports `Sent` only after matching endpoint +/// dispatch of the proof or rejection. It does not confirm peer reception. #[derive(Debug)] pub struct LinkPacketReceipt { resolver: Option>, @@ -222,9 +223,10 @@ impl LinkPacketReceipt { pub fn drop_without_proof(self) { drop(self); } - /// Close only this receipt's still-current Link without a delivery proof or - /// an invalid-stamp error. `Closed` confirms local closure, not peer receipt - /// of the best-effort teardown. Stale authority cannot close a replacement. + /// Request closure of this receipt's still-current Link without a delivery + /// proof or invalid-stamp error. `Closed` reports the local close decision or + /// already-stale authority, not peer receipt of a best-effort teardown. + /// Stale authority cannot close a replacement Link. pub fn close_without_proof(self) -> oneshot::Receiver { self.resolve(Decision::Close) } diff --git a/crates/rns-runtime/src/interface_factory.rs b/crates/rns-runtime/src/interface_factory.rs index c9a2c16..7ea37a9 100644 --- a/crates/rns-runtime/src/interface_factory.rs +++ b/crates/rns-runtime/src/interface_factory.rs @@ -1,5 +1,7 @@ -//! Mirrors `Reticulum._synthesize_interface` in the Python reference but -//! rejects external-program interfaces. +//! Parse built-in interface configurations and shared post-construction +//! settings. Driver availability depends on enabled Cargo features and the +//! target platform. `PipeInterface` is supported and runs a configured +//! subprocess when started; this factory itself only constructs configuration. use std::time::Duration; @@ -68,14 +70,17 @@ pub struct KissSerialConfig { pub parity: String, pub stop_bits: u8, pub mode: InterfaceMode, - /// TNC timing, config units are milliseconds (Python defaults 350/20/64/20; - /// persistence is a raw 0-255 CSMA p-value, not ms). + /// TNC preamble in milliseconds. Parser defaults for preamble, TX tail, + /// persistence and slot time are 350 ms, 20 ms, 64 and 20 ms respectively; + /// persistence is a raw 0..=255 CSMA value, not a duration. pub preamble_ms: u32, pub txtail_ms: u32, pub persistence: u8, pub slottime_ms: u32, pub flow_control: bool, - /// Station-ID beacon: seconds between IDs, sent only after data TX. + /// Station-ID interval in seconds after data TX. Current KISS beacons + /// with callsigns shorter than 15 bytes can repeat on each one-second + /// idle poll. Omit either this option or `id_callsign` to disable beacons. pub id_interval: Option, pub id_callsign: Option, } @@ -99,8 +104,9 @@ pub struct AutoInterfaceConfig { pub struct RNodeInterfaceConfig { pub name: String, pub port: String, - /// Android USB stable identity. These are ignored for non-AndroidUSB - /// ports, and serial remains optional because Android hides it pre-grant. + /// Optional Android USB matching metadata. Vendor/product IDs must be + /// supplied together; the serial may be absent. Other backends do not + /// use these values for device selection. pub usb_vendor_id: Option, pub usb_product_id: Option, pub usb_serial_number: Option, @@ -111,11 +117,13 @@ pub struct RNodeInterfaceConfig { pub coding_rate: u8, pub tx_power: i8, pub mode: InterfaceMode, - /// Gate each TX on the radio's CMD_READY. Python default: off. + /// Gate TX on radio CMD_READY flow control. Parser default: false. 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 for this setting; it does not explicitly clear a prior limit. pub st_alock: Option, - /// Long-term airtime cap, percent (0.0..=100.0). `None` = unlimited. + /// Long-term airtime cap, percent (0.0..=100.0). `None` sends no + /// command for this setting; it does not explicitly clear a prior limit. pub lt_alock: Option, /// Station-ID beacon: seconds between IDs, sent only after data TX. pub id_interval: Option, @@ -165,7 +173,10 @@ impl RNodeInterfaceConfig { #[derive(Debug, Clone)] pub struct BleRNodeInterfaceConfig { pub name: String, - /// `ble://` URI: MAC, adapter-local name, or empty for any RNode. + /// `ble://` followed by a platform peripheral identifier or advertised + /// name. An empty suffix selects a discovered NUS advertiser, or an + /// RNode-named peripheral whose service list is empty. Identifier forms + /// depend on the platform; this is discovery, not identity authentication. pub port: String, pub frequency: u32, pub bandwidth: u32, @@ -173,11 +184,13 @@ pub struct BleRNodeInterfaceConfig { pub coding_rate: u8, pub tx_power: i8, pub mode: InterfaceMode, - /// Gate each TX on the radio's CMD_READY. Python default: off. + /// Gate TX on radio CMD_READY flow control. Parser default: false. 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 for this setting; it does not explicitly clear a prior limit. pub st_alock: Option, - /// Long-term airtime cap, percent (0.0..=100.0). `None` = unlimited. + /// Long-term airtime cap, percent (0.0..=100.0). `None` sends no + /// command for this setting; it does not explicitly clear a prior limit. pub lt_alock: Option, /// Station-ID beacon: seconds between IDs, sent only after data TX. pub id_interval: Option, @@ -191,7 +204,8 @@ pub struct LocalInterfaceConfig { pub mode: InterfaceMode, } -/// Requires a local I2P router reachable via the SAM API. +/// Requires an I2P router reachable through its SAM API. The parser defaults +/// to `127.0.0.1:7656`; the host and port can be configured. #[derive(Debug, Clone)] pub struct I2PInterfaceConfig { pub name: String, @@ -202,12 +216,15 @@ pub struct I2PInterfaceConfig { pub mode: InterfaceMode, } -/// Subprocess; frames carried over its stdio. +/// Subprocess interface carrying HDLC-framed packets over stdin/stdout. +/// The driver splits `command` on whitespace into executable and arguments; +/// it does not interpret shell quoting, expansion or redirection. #[derive(Debug, Clone)] pub struct PipeInterfaceConfig { pub name: String, pub command: String, - /// Respawn delay after EOF, seconds. + /// Delay in seconds before retrying after spawn failure, stdout EOF or + /// read failure. Parser default: 5. pub respawn_delay: u64, pub mode: InterfaceMode, } @@ -222,7 +239,8 @@ pub struct RNodeMultiInterfaceConfig { pub flow_control: bool, pub subinterfaces: Vec, pub mode: InterfaceMode, - /// Parent-level station-ID beacon (sent on all subinterfaces when due). + /// Parent-level station-ID interval in seconds. Due beacons target all + /// configured subinterfaces, including those with `outgoing = false`. pub id_interval: Option, pub id_callsign: Option, } @@ -245,8 +263,8 @@ pub struct RNodeSubInterfaceConfig { pub mode: InterfaceMode, } -/// KISS serial wrapped in AX.25 frames for amateur-radio compliance; prefer -/// plain `KISSInterface` when AX.25 isn't required. +/// AX.25-framed packets carried over a KISS serial TNC, with a configured +/// callsign and SSID. #[cfg(feature = "serial")] #[derive(Debug, Clone)] pub struct AX25KISSInterfaceConfig { @@ -266,8 +284,8 @@ pub struct AX25KISSInterfaceConfig { pub mode: InterfaceMode, } -/// Wire-compatible with Python `BackboneInterface`. Per-peer TCP keepalive + -/// `TCP_USER_TIMEOUT` tuning matches Python `set_timeouts_linux()`. +/// TCP Backbone configuration. `target_host` selects client mode; otherwise +/// the interface listens. Socket timeout support is platform-dependent. #[derive(Debug, Clone)] pub struct BackboneInterfaceConfig { pub name: String, @@ -277,19 +295,21 @@ pub struct BackboneInterfaceConfig { pub device: Option, pub prefer_ipv6: bool, pub mode: InterfaceMode, - /// Initial connect timeout (seconds). Python default: 5. + /// Initial connect timeout in seconds. Parser default: 5. pub connect_timeout: u64, - /// Client reconnection budget. `None` = retry forever (Python default). + /// Client reconnection budget. `None` means retry without a count limit + /// while the interface remains active; this is the parser default. pub max_reconnect_tries: Option, /// Parsed for Python config compatibility; advisory only. pub i2p_tunneled: bool, - /// Listener-only fast-flap blocking switch. Python default: enabled. + /// Listener-only fast-flap blocking switch. Parser default: enabled. pub block_fast_flapping: bool, - /// Listener-only short-connection threshold. Python default: 20 seconds. + /// Listener-only short-connection threshold. Parser default: 20 seconds. pub fast_flapping_threshold: Duration, - /// Listener-only tolerated short-connection count. Python default: 5. + /// Listener-only tolerated short-connection count. Parser default: 5. pub fast_flapping_grace: u64, - /// Listener-only block time. Configured in minutes; Python default: 720. + /// Listener-only block duration. The configuration file uses minutes; + /// the runtime field is a `Duration`. Parser default: 720 minutes. pub fast_flapping_block_time: Duration, } @@ -414,6 +434,10 @@ fn parse_duration_strict( }) } +/// Parse an enabled interface section into a built-in driver configuration. +/// No device, socket or subprocess is opened here. Performs IFAC-size and +/// ingress-override validation; callers starting a driver must also apply +/// `InterfacePostInit` and the driver's own validation. pub fn synthesize_interface( name: &str, section: &ConfigSection, @@ -594,9 +618,10 @@ fn synthesize_tcp_client( Ok(config) } -/// Validate explicit capacity promises before starting a driver. Automatic -/// budgets are attenuated by the registered wire/IFAC capacity; an explicit TCP -/// fixed MTU must instead be wholly supportable or fail configuration. +/// Validate explicit IFAC byte sizes and TCP client `fixed_mtu` before driver +/// startup. A fixed MTU must be at least 500 and fit the driver wire budget +/// after active IFAC overhead. This does not validate every interface field; +/// automatic capacity selection happens during runtime registration. pub fn validate_config_capacity( config: &InterfaceConfig, post_init: &InterfacePostInit, @@ -1102,7 +1127,7 @@ fn parse_generic_rnode_airtime_value( /// Radio parameters are deliberately required: Python errors when they are /// absent (RNodeInterface validation fails on the 0 fallbacks), and silently /// inventing RF parameters — especially TX power — risks misconfigured -/// transmissions. Documented in fix-registry (final sweep decision items). +/// transmissions. #[cfg(any(feature = "serial", feature = "ble"))] fn require_rnode_radio_params( name: &str, @@ -1612,24 +1637,33 @@ fn synthesize_backbone( pub struct InterfacePostInit { pub outgoing: bool, pub bitrate: Option, + /// Normalized fraction of interface bitrate, parsed from file percentages. + /// `None` uses the runtime default; for example, file value `2` becomes `0.02`. pub announce_cap: Option, pub announce_rate_target: Option, pub announce_rate_grace: Option, pub announce_rate_penalty: Option, pub ifac_network_name: Option, - /// Wiped when dropped. + /// This owned copy is wiped on drop. The input `ConfigSection` retains its + /// separate ordinary `String` copy. pub ifac_passphrase: Option>, + /// Effective IFAC tag length in bytes, already decoded from file units. pub ifac_size: Option, - /// Fallback when `ifac_size` is unset; per-class in Python. + /// IFAC size in bytes used when `ifac_size` is unset. `try_from_section` + /// starts at 8; apply `with_default_ifac_size(default_ifac_size_for(config))` + /// for the selected interface class. pub default_ifac_size: usize, pub ingress_control: bool, - /// Per-interface overrides for Python `ic_*` ingress knobs. + /// Per-interface ingress/egress overrides parsed from `ic_*`, `ec_pr_freq` + /// and `egress_control` settings. pub ingress_overrides: rns_transport::ingress::IngressOverrides, - /// Python 1.3.8 `recursive_prs` (Reticulum.py:808-809, default false): - /// force unknown-path discovery on path requests regardless of mode. + /// Allow recursive discovery of unknown destinations regardless of interface + /// mode. Transport enablement, ingress limiting and discovery admission + /// still apply. Parser default: false. pub recursive_prs: bool, - /// Python 1.3.8 `announces_from_internal` (Reticulum.py:811-812, default - /// true): rebroadcast announces learned via MODE_INTERNAL interfaces. + /// Allow relaying non-local announces whose next hop is an Internal-mode + /// interface. Other relay policy gates still apply; locally originated + /// announces bypass this option. Parser default: true. pub announces_from_internal: bool, } @@ -1728,7 +1762,8 @@ fn normalize_announce_cap_percent(value: f64) -> Option { } } -/// Python `DEFAULT_IFAC_SIZE`: network interfaces 16 bytes, serial/packet-radio 8. +/// Default IFAC tag length in bytes: 16 for TCP, UDP, Auto, I2P and Backbone; +/// 8 for the remaining built-in interface classes. This does not activate IFAC. pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize { match config { InterfaceConfig::TcpClient(_) diff --git a/crates/rns-runtime/src/jobs.rs b/crates/rns-runtime/src/jobs.rs index 28dbdcd..0c6e5ba 100644 --- a/crates/rns-runtime/src/jobs.rs +++ b/crates/rns-runtime/src/jobs.rs @@ -1,5 +1,7 @@ -//! Cache cleaning every 15 minutes, persistence every 12 hours (or next -//! 5-minute gracious interval on explicit request). Python: `Reticulum.py`. +//! Poll-driven scheduling of cache cleaning after 15 minutes and persistence +//! after 12 hours. Explicit persistence requests can emit a job once five +//! minutes have elapsed since the last gracious persist. Callers must poll +//! `tick` and execute the returned jobs; this module starts no timer or I/O. use std::time::{Duration, Instant}; diff --git a/crates/rns-runtime/src/lifecycle.rs b/crates/rns-runtime/src/lifecycle.rs index 73fbeca..618f5ae 100644 --- a/crates/rns-runtime/src/lifecycle.rs +++ b/crates/rns-runtime/src/lifecycle.rs @@ -1,5 +1,6 @@ -//! Ctrl-C / SIGTERM flip a shared flag that all runtime tasks observe, -//! allowing them to detach interfaces and flush state cleanly before exit. +//! Shared shutdown signalling and process-signal integration. Consumers must +//! observe the signal and perform their own interface teardown and persistence; +//! triggering the flag does not itself wait for cleanup. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -80,15 +81,13 @@ impl Default for ExitHandler { } } -/// Install process-signal handlers that trip `shutdown`. On Unix this covers -/// both SIGINT and SIGTERM; other platforms use the runtime's Ctrl-C handler. -/// The returned receiver yields once on the first signal for await-based -/// callers. -/// -/// On unix the OS-level registration happens synchronously in this call — a -/// handler registered inside a spawned task only takes effect once that task -/// is first polled, leaving a window where a signal kills the process via the -/// default disposition. +/// Install signal handlers that trigger `shutdown` and try to notify the +/// returned receiver. Requires an active Tokio runtime with signal support. +/// On Unix, SIGINT and SIGTERM registrations are attempted synchronously; +/// each spawned handler waits once, so callers may receive more than one +/// notification. SIGINT registration failure falls back to Ctrl-C; SIGTERM +/// registration failure is logged. Other platforms use Ctrl-C. A Ctrl-C +/// listener error also triggers shutdown. pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> { let (tx, rx) = mpsc::channel(1); diff --git a/crates/rns-runtime/src/link_client.rs b/crates/rns-runtime/src/link_client.rs index d26eda9..9759bd1 100644 --- a/crates/rns-runtime/src/link_client.rs +++ b/crates/rns-runtime/src/link_client.rs @@ -1,6 +1,7 @@ -//! Initiator-side Link client for `rnstatus -R` / `rnpath -R`. Each `query` -//! does the full handshake (pubkey discovery → link → identify → request → -//! response → close) over its own destination channel. +//! Initiator-side Link client used by `rnstatus-rs -R` and `rnpath-rs -R`. +//! Each query recalls or discovers remote identity metadata, establishes a +//! Link, identifies the local identity, sends one request and attempts teardown. +//! It uses its own temporary destination channel; it does not reuse a Link. use std::collections::HashMap; use std::sync::Arc; @@ -68,8 +69,14 @@ impl LinkClient { } } - /// Open a Link to `app_name` on `remote_transport_hash`, send one - /// request, return the response. + /// Open a Link to `app_name` on the supplied identity hash, identify the local + /// identity, send one request and return its response bytes. For the current + /// remote-management service, this is the remote transport identity hash. + /// + /// `overall_timeout` supplies remaining budgets for discovery, Link proof and + /// response waits. Registration, endpoint binding, sends and teardown can + /// await transport admission/replies outside that budget. Wrap the call in + /// an outer timeout when the entire operation needs a deadline. pub async fn query( &self, remote_transport_hash: [u8; 16], diff --git a/crates/rns-runtime/src/link_manager.rs b/crates/rns-runtime/src/link_manager.rs index 1d2598a..223b30c 100644 --- a/crates/rns-runtime/src/link_manager.rs +++ b/crates/rns-runtime/src/link_manager.rs @@ -1,6 +1,11 @@ -//! Responder side of Reticulum links: accepts link requests, holds per-link -//! state (session keys, channel, in/outbound transfers), drives keepalives -//! and teardown. Lives here to break the rns-transport ↔ rns-link cycle. +//! Responder-side Reticulum Links: handshakes, encrypted packets, Channels, +//! requests and Resources. [`LinkManager`] owns the per-Link state and timers. +//! Run it continuously, or combine `step`/`try_step` with periodic `tick` calls. +//! +//! Configure application admission and event receivers before running. Request +//! allow-lists, ordinary-packet proof policy and ordinary-Resource acceptance +//! are separate controls; verifying a LinkIdentify does not authorize every +//! operation. Callbacks run on the manager task and must return promptly. use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::{Arc, Mutex}; @@ -208,11 +213,13 @@ pub struct LinkResourceProof { pub resource_hash: [u8; 32], } -/// Valid delivery proof for a non-Link packet registered by an application. +/// Valid delivery proof for an application-registered non-Link packet. /// -/// The transport actor authenticates the proof before emitting this event. -/// The message identifier is the opaque value supplied with -/// [`TransportMessage::RegisterReceipt`]. +/// The transport verifies the proof against the receipt's destination signing +/// key before emitting this event. The message identifier is the opaque value +/// supplied with [`TransportMessage::RegisterReceipt`] or +/// [`TransportMessage::RegisterReceiptWithProof`]. This does not acknowledge +/// remote application processing or persistence. #[derive(Debug, Clone)] pub struct DestinationDeliveryProof { pub msg_id: String, @@ -329,10 +336,12 @@ pub enum LinkManagerCommand { reason: CloseReason, send_teardown: bool, }, - /// Broadcast an announce using the manager's owned Destination. + /// Request an announce through the custom announce handler, if installed, + /// otherwise through the owned Destination. Announce, - /// Broadcast an announce with the same options exposed by Python's - /// `Destination.announce`. + /// Build an announce with explicit app data, path-response, tag, + /// interface and ratchet options. Success means local staging, possibly + /// in the manager retry queue; it does not confirm transmission. AnnounceWith { options: DestinationAnnounceOptions, result_tx: Option>>, @@ -348,7 +357,8 @@ pub enum LinkManagerCommand { app_data: Option>, result_tx: Option>>, }, - /// Register or replace a Python-compatible per-path request handler. + /// Register or replace a per-path handler with its own admission policy. + /// See [`LinkManager::register_request_handler`]. RegisterRequestHandler { path: String, allow: AllowPolicy, @@ -371,7 +381,8 @@ pub struct DestinationAnnounceOptions { pub path_response: bool, pub attached_interface: Option, pub tag: Option>, - /// Public ratchet key to advertise, when the caller manages a ratchet ring. + /// Public ratchet key to advertise. With a manager-owned persistent ring, + /// an explicitly supplied key must match its current key. pub ratchet: Option<[u8; 32]>, } @@ -391,32 +402,36 @@ pub enum DestinationControlError { TransportUnavailable, } -/// Resource hash + sender metadata (e.g. rncp filename). +/// Completed inbound payload with its logical Resource hash and optional +/// sender metadata. Automatic completion stages a proof before application +/// processing; the application still owns validation and persistence. #[derive(Debug, Clone)] pub struct ResourceCompletion { pub link_id: [u8; 16], pub resource_hash: [u8; 32], pub data: Vec, - /// msgpack-encoded metadata, if the sender attached any. + /// Opaque metadata bytes, if supplied by the sender. Applications such + /// as rncp use MessagePack; this type does not validate that encoding. pub metadata: Option>, } -/// Ordered, capacity-lossless Link accounting notifications. +/// Ordered Link accounting notifications on an opt-in unbounded channel. /// -/// This opt-in stream contains validated ordinary Link-packet proofs, Resource -/// starts and conclusions, ordinary inbound completion payloads, and Link -/// closure in manager-observation order. It also observes exact bounded -/// outbound wait windows. UI progress remains available only through the -/// bounded best-effort Resource event channel. Delivery is -/// guaranteed while the unbounded receiver remains alive. Request Resources -/// retain their start and conclusion events but dispatch inline and never -/// produce a [`LinkManagerAccountingEvent::ResourceCompletion`]. +/// The stream includes ordinary Link-packet proofs, Resource starts and +/// conclusions, inbound completion payloads, Link closure and outbound wait +/// windows in manager-observation order. Progress uses the separate bounded +/// Resource-event channel. A live receiver prevents capacity drops, but does +/// not guarantee consumption or persistence; drain it to avoid memory growth. +/// Request Resources retain lifecycle events and dispatch to request handlers, +/// without a [`LinkManagerAccountingEvent::ResourceCompletion`]. #[derive(Clone)] #[non_exhaustive] pub enum LinkManagerAccountingEvent { - /// Exact bounded wait for an ordinary outbound packet: local command - /// admission first, then the Link RTT proof window on endpoint acceptance. - /// Endpoint acceptance is not radio transmission or remote delivery. + /// A local-admission or peer-proof wait window for an ordinary packet. + /// Retain `started_at` when consuming a delayed event. Exact dispatch + /// starts the proof window at driver admission; the legacy queued path + /// uses an allowance and retains `awaiting_admission`. These observations + /// are not on-air or remote-delivery acknowledgments. OutboundPacketWait { receipt: LinkPacketSendReceipt, started_at: std::time::Instant, @@ -424,9 +439,9 @@ pub enum LinkManagerAccountingEvent { awaiting_admission: bool, cancellation: Option, }, - /// Exact bounded wait currently owned by an outbound logical Resource. - /// Emitted only when its protocol deadline changes. Delayed consumers - /// must retain `started_at` rather than restarting the clock on receipt. + /// The current protocol wait window for an outbound logical Resource. + /// Emitted when its deadline changes. Delayed consumers must retain + /// `started_at` rather than restarting the clock on receipt. OutboundResourceWait { link_id: [u8; 16], resource_id: [u8; 32], @@ -496,24 +511,31 @@ impl std::fmt::Debug for LinkManagerAccountingEvent { } } -/// Result of an extended request handler. `Reply` is the ordinary response; -/// `ReplyWithResource` sends an inline ack followed by a resource transfer -/// (rncp --fetch). Python: `RNS.Resource(..., target_link=link)`. +/// Request-handler response. `Reply` uses a RESPONSE packet or, when the packed +/// response exceeds the Link MDU, a response Resource. `ReplyWithResource` +/// stages the acknowledgment and a separate ordinary Resource, as used by rncp +/// fetch. Neither staging +/// operation confirms delivery; arrival order is not guaranteed. #[derive(Debug, Clone)] pub enum RequestOutcome { Reply(Vec), ReplyWithResource { ack: Vec, data: Vec, - /// Optional msgpack-encoded metadata (e.g. `{"name": "file.bin"}`). + /// Optional opaque Resource metadata. rncp expects a MessagePack map + /// such as `{"name": "file.bin"}`; the manager does not validate it. metadata: Option>, auto_compress: bool, }, - /// Silently drop; caller sees a timeout. Useful for ACL denies. + /// Send no response. A waiting requester can time out; no explicit denial + /// is sent. Drop, } -/// Python-compatible context supplied to a per-path Destination request handler. +/// Context for a per-path Destination request handler. `remote_identity` +/// comes from verified LinkIdentify, when present; the registered `AllowPolicy` +/// is applied separately. `requested_at` is the sender's timestamp, not a +/// trusted local arrival time. #[derive(Clone)] pub struct DestinationRequest { pub path: String, @@ -572,6 +594,10 @@ struct ResourceTransferStart { allow_handshake: bool, } +/// Owns responder Links for one destination. Configure admission policies and +/// receivers before `run` or `run_with_commands`; callbacks execute on this +/// manager task. Ordinary Resources default to `AcceptAll`, independently of +/// LinkIdentify and per-path request authorization. pub struct LinkManager { endpoint_dispatch: Option, endpoint_dispatch_tokens: @@ -639,7 +665,7 @@ pub struct LinkManager { resource_accept_handler: Option, /// Fires when a link reaches the active state. link_established_tx: Option>, - /// Fires on LinkIdentify before a resource ADV can race it. + /// Best-effort notification on the first verified LinkIdentify. link_identified_tx: Option>, /// Synchronous LinkIdentify gate. Returning false closes the link before /// later resource packets can be accepted. @@ -695,6 +721,10 @@ impl LinkManager { self.endpoint_dispatch = Some(handle); } + /// Create a manager for an already-known destination hash, without owning + /// its [`Destination`] or registering it with the transport. Supply a signing + /// key to answer Link requests; use `with_destination` for destination + /// callbacks, announcements and a backend-aware identity. pub fn new( transport_tx: mpsc::Sender, event_rx: mpsc::Receiver, @@ -767,7 +797,13 @@ impl LinkManager { } } - /// Wraps its own [`Destination`] so acceptance gating + dest callbacks are active. + /// Create a manager with an inbound SINGLE [`Destination`] and its + /// callbacks. This does not register the destination with the transport. + /// Check `destination()` before use: invalid destination construction is + /// logged and leaves `None` with an all-zero `destination_hash`. + /// + /// A software private identity or hardware backend is retained for signing. + /// A public-only identity alone cannot supply that signer. pub fn with_destination( transport_tx: mpsc::Sender, event_rx: mpsc::Receiver, @@ -859,10 +895,14 @@ impl LinkManager { self.backchannel_links.get(identity_hash).copied() } - /// Enable a verified, persistent ratchet ring for the owned destination. + /// Enable a persistent ratchet ring for the owned destination. A current + /// ratchet is persisted before it is advertised or enforced. /// - /// A current ratchet is persisted before the destination starts - /// advertising or enforcing it. + /// This uses [`PersistentRatchetRing::open`], which also accepts the legacy + /// format whose signature covers only its current public key. If full-ring + /// authentication is required, first use + /// [`rns_identity::ratchet::RatchetRing::load_verified`] and inspect its format; + /// this wrapper does not expose that distinction. pub fn enable_persistent_ratchets( &mut self, path: impl AsRef, @@ -900,12 +940,17 @@ impl LinkManager { self.use_implicit_proof = use_implicit_proof; } - /// Shared auth map for sync request handlers (which can't borrow `self`). - /// Populated on `LinkIdentify`, pruned on link close. + /// Shared Link-id to peer-identity-hash map, populated on verified + /// LinkIdentify and pruned on close. This is identity bookkeeping, not an + /// authorization result: insertion precedes closing a rejected identity, + /// and callers can mutate the returned map. pub fn link_identities_handle(&self) -> Arc>> { Arc::clone(&self.link_identities) } + /// Poll local completions and handle at most one queued destination event. + /// False can mean either no progress or a disconnected receiver; it is not + /// a shutdown signal. Call `tick` periodically to advance protocol timers. pub fn try_step(&mut self) -> bool { let endpoint_progress = self.poll_link_endpoints(); self.flush_pending_link_control(); @@ -922,6 +967,9 @@ impl LinkManager { } } + /// Wait for a destination event or local completion. False indicates a + /// closed receive branch. This does not schedule periodic protocol ticks; + /// call `tick` separately, or use `run`/`run_with_commands`. pub async fn step(&mut self) -> bool { let endpoint_progress = self.poll_link_endpoints(); self.flush_pending_link_control(); @@ -950,6 +998,9 @@ impl LinkManager { } } + /// Poll completions and advance Link, Channel and Resource timers. + /// Manual event loops should call this regularly (the built-in loops target + /// one second); a blocked callback delays timer work. pub fn tick(&mut self) { self.poll_link_endpoints(); self.flush_pending_link_control(); @@ -983,6 +1034,9 @@ impl LinkManager { self.outbound_resource_waits = current; } + /// Run event handling with one-second protocol ticks until the destination + /// event channel closes, then close Links and drain endpoint ownership. + /// Shutdown waits for transport cleanup without its own deadline. pub async fn run(mut self) { let mut tick_interval = tokio::time::interval(std::time::Duration::from_secs(1)); @@ -1016,6 +1070,10 @@ impl LinkManager { self.drain_shutdown_link_ownership().await; } + /// Run events, commands and protocol ticks until `Shutdown` or command + /// channel closure. Losing the destination event channel closes live Links + /// but leaves destination commands available. Final endpoint cleanup has + /// no deadline; keep the transport running until this future completes. pub async fn run_with_commands(mut self, mut command_rx: mpsc::Receiver) { let mut last_tick = std::time::Instant::now(); let mut events_closed = false; @@ -5611,6 +5669,9 @@ impl LinkManager { progressed } + /// Install a synchronous fallback `(link_id, path_hash, data)` handler. + /// Per-path handlers and `set_request_handler_ex` take precedence. This + /// fallback must check authorization itself; `None` sends no response. pub fn set_request_handler(&mut self, handler: F) where F: Fn([u8; 16], [u8; 16], Vec) -> Option> + Send + 'static, @@ -5618,8 +5679,10 @@ impl LinkManager { self.request_handler = Some(Box::new(handler)); } - /// Handler that may schedule a follow-up resource transfer (rncp --fetch). - /// Takes precedence over [`Self::set_request_handler`]. + /// Synchronous fallback handler `(link_id, path_hash, data)` that can + /// schedule a follow-up Resource. A registered per-path handler takes + /// precedence; otherwise this overrides [`Self::set_request_handler`]. + /// The fallback must perform its own authorization and return promptly. pub fn set_request_handler_ex(&mut self, handler: F) where F: Fn([u8; 16], [u8; 16], Vec) -> RequestOutcome + Send + 'static, @@ -5627,11 +5690,14 @@ impl LinkManager { self.request_handler_ex = Some(Box::new(handler)); } - /// Register or replace a request handler for `path`. + /// Register or replace a synchronous handler keyed by the truncated hash + /// of `path`. Returns false for an empty path. A matching per-path handler + /// takes precedence over both fallback handlers, even when it denies access. /// - /// The callback receives the same request context as Python Reticulum's - /// `Destination.register_request_handler`: path, data, request id, Link id, - /// authenticated remote identity (when identified), and request timestamp. + /// `AllowAll` permits unidentified peers; `AllowList` requires a verified + /// identity in `allowed_list` (missing means empty); `AllowNone` denies all. + /// `auto_compress` applies to response Resources. The callback runs on the + /// manager task and must return promptly. pub fn register_request_handler( &mut self, path: &str, @@ -5686,13 +5752,15 @@ impl LinkManager { true } - /// Register a bounded worker-backed handler. Admission occurs before the - /// callback, so rejected requests cannot start I/O or mutate durable state. - /// Requires an installed exact endpoint dispatch handle; registration fails - /// without it. Resource packets retain that generation through actor egress. - /// The callback must return promptly and retain its responder in the actual - /// worker. At most four process-wide jobs/Resources retain 256 MiB of - /// conservative reservations; the token reports its effective byte limit. + /// Register a handler that can hand its responder to an application worker. + /// The manager checks the request policy and reserves capacity before calling + /// it, but does not spawn the worker. Return promptly and retain the responder + /// in the worker until completion; the token reports its effective byte limit. + /// + /// Registration fails without exact endpoint dispatch, for an empty path, or + /// for a zero or greater-than-64-MiB response limit. At most four process-wide jobs or + /// Resources share 256 MiB of conservative reservations. This is an admission + /// budget, not a limit on arbitrary worker allocations or side effects. pub fn register_deferred_request_handler( &mut self, path: &str, @@ -5747,6 +5815,8 @@ impl LinkManager { .is_some() } + /// Override ordinary announce requests with a synchronous callback. + /// Path responses and `AnnounceWith` still use the owned Destination. pub fn set_announce_handler(&mut self, handler: F) where F: FnMut() + Send + 'static, @@ -5754,6 +5824,9 @@ impl LinkManager { self.announce_handler = Some(Box::new(handler)); } + /// Install a best-effort channel for packet-sized responses. A full or + /// closed receiver loses notifications; response Resources use Resource + /// completion handling instead. pub fn set_response_channel(&mut self, tx: mpsc::Sender) { self.response_tx = Some(tx); } @@ -5768,11 +5841,10 @@ impl LinkManager { self.resource_completion_tx = Some(tx); } - /// Set the inbound Resource policy for current and future responder Links. - /// - /// Request and response Resources remain protocol-owned and bypass this - /// policy, matching Python Reticulum. The manager defaults to - /// [`ResourceStrategy::AcceptAll`] for LXMF compatibility. + /// Set the ordinary inbound Resource policy for current and future Links. + /// Request and response Resources bypass this policy. The default is + /// [`ResourceStrategy::AcceptAll`]; it does not require peer identification. + /// Use `AcceptApp` with a decision hook for application admission. pub fn set_resource_strategy(&mut self, strategy: ResourceStrategy) { self.resource_strategy = strategy; for active in self.active_links.values_mut() { @@ -5780,8 +5852,10 @@ impl LinkManager { } } - /// Install the per-advertisement decision hook used by - /// [`ResourceStrategy::AcceptApp`]. + /// Install the synchronous decision hook `(link_id, advertisement)` for + /// each ordinary Resource segment under [`ResourceStrategy::AcceptApp`]. + /// Set that strategy separately. True accepts; a missing hook or caught + /// panic rejects. Request and response Resources bypass this hook. pub fn set_resource_accept_handler(&mut self, handler: F) where F: Fn([u8; 16], &ResourceAdvertisement) -> bool + Send + 'static, @@ -5793,16 +5867,24 @@ impl LinkManager { self.resource_accept_handler = None; } - /// Fires when a link reaches the active state. + /// Install a best-effort active-Link notification channel. A full or + /// closed receiver loses the event. pub fn set_link_established_channel(&mut self, tx: mpsc::Sender<[u8; 16]>) { self.link_established_tx = Some(tx); } - /// Fires on LinkIdentify before any resource ADV can race it. + /// Install a best-effort `(link_id, identity_hash)` notification channel + /// for the first verified LinkIdentify. Full or closed channels lose the + /// event. This notification neither requires prior identification for + /// Resources nor waits for the application's receiver to act. pub fn set_link_identified_channel(&mut self, tx: mpsc::Sender<([u8; 16], [u8; 16])>) { self.link_identified_tx = Some(tx); } + /// Install a synchronous `(link_id, identity_hash)` check after successful + /// LinkIdentify; false closes that Link. This does not require identification + /// before ordinary packets or Resources. Configure their admission policies + /// separately; an identity notification can precede closure of a rejected peer. pub fn set_link_identity_gate(&mut self, gate: F) where F: Fn([u8; 16], [u8; 16]) -> bool + Send + 'static, @@ -5823,6 +5905,11 @@ impl LinkManager { Ok(()) } + /// Install the bounded typed ordinary-packet receiver. In `ProveApp` mode, + /// each packet carries an application-controlled receipt; call `accept` only after + /// the application's acceptance boundary. Installation fails if a legacy + /// packet channel is already present. + /// Install exact dispatch and this channel before selecting `ProveApp`. pub fn set_inbound_link_packet_channel( &mut self, tx: mpsc::Sender, @@ -5834,6 +5921,10 @@ impl LinkManager { Ok(()) } + /// Select the proof policy for ordinary Link packets, separately from + /// Resource or Channel policy. `ProveApp` requires exact endpoint dispatch, + /// a typed receiver and no legacy packet channel. Without an explicit + /// override, the owned Destination's policy applies, or `ProveNone`. pub fn set_ordinary_packet_proof_strategy( &mut self, strategy: ProofStrategy, @@ -5867,16 +5958,25 @@ impl LinkManager { self.inbound_packet_overloads } + /// Receive verified ordinary packet proofs, excluding proofs consumed by + /// the Channel. Full-channel events share the retained legacy terminal + /// queue with Resource proofs and Link closure; closed receivers discard + /// notifications. Proofs do not attest to remote application processing. pub fn set_link_packet_proof_channel(&mut self, tx: mpsc::Sender) { self.link_packet_proof_tx = Some(tx); } + /// Receive a proof notification after all segments of an outbound Resource + /// are proved. Full channels use the retained legacy terminal queue; + /// shutdown need not drain it. Proof does not establish remote persistence. pub fn set_outbound_resource_proof_channel(&mut self, tx: mpsc::Sender) { self.outbound_resource_proof_tx = Some(tx); } - /// Install the lossless application receiver for validated non-Link packet - /// delivery proofs. + /// Install an unbounded receiver for validated non-Link delivery proofs. + /// Drain it to avoid memory growth. Queue admission does not establish + /// application consumption; legacy transport broadcast can lose events + /// before they reach this manager. pub fn set_destination_delivery_proof_channel( &mut self, tx: mpsc::UnboundedSender, @@ -5889,13 +5989,11 @@ impl LinkManager { self.resource_event_tx = Some(tx); } - /// Install one ordered, capacity-lossless accounting stream. - /// - /// The receiver must be drained for the manager's lifetime. Existing - /// bounded completion, Resource-event, and Link-close channels remain - /// independent compatibility notifications. - /// Protocol deadline observations are coalesced to at most one changed - /// window per active Resource per tick; UI progress is not sent here. + /// Install the ordered unbounded accounting stream described by + /// [`LinkManagerAccountingEvent`]. Drain it for the manager's lifetime to + /// avoid memory growth. Compatibility notifications remain independent. + /// Resource wait observations emit at most one changed window per active + /// Resource per tick; progress is not sent here. pub fn set_accounting_event_channel( &mut self, tx: mpsc::UnboundedSender, @@ -5904,6 +6002,9 @@ impl LinkManager { self.outbound_resource_waits.clear(); } + /// Receive decoded Channel messages through a best-effort bounded queue. + /// The manager can prove Channel packets before this application delivery; + /// a full receiver may lose a message despite the peer receiving a proof. pub fn set_channel_message_channel(&mut self, tx: mpsc::Sender) { self.channel_message_tx = Some(tx); } @@ -5929,12 +6030,19 @@ impl LinkManager { Ok(()) } - /// Install the bounded best-effort Link-close channel. + /// Install the bounded Link-close channel. While the manager is running, + /// full-channel notifications are retained and retried in order alongside + /// legacy proof notifications; a stalled receiver can delay that queue. + /// Closed receivers discard their notifications. Shutdown does not promise + /// to drain this application queue. pub fn set_link_closed_channel(&mut self, tx: mpsc::Sender<[u8; 16]>) { self.link_closed_tx = Some(tx); } - /// Raw destination-encrypted packets for app-level decryption (opportunistic LXMF). + /// Install a best-effort raw non-Link packet channel. Parsed packets are + /// copied here after destination dispatch, even if decryption or application + /// handling failed. They are not necessarily encrypted or valid app data; + /// a full or closed channel loses the copy. pub fn set_inbound_raw_channel(&mut self, tx: mpsc::Sender>) { self.inbound_raw_tx = Some(tx); } @@ -5960,10 +6068,10 @@ impl LinkManager { .map(|active| active._interface_id) } - /// Emit an initiator identity proof over this Link's typed endpoint. - /// - /// Responder Links reject identification, matching Reticulum's rule that - /// LINKIDENTIFY reveals only the initiator to the responder. + /// Stage an initiator identity proof through this Link's typed endpoint. + /// The returned receipt records local queue admission, not transmission or + /// remote authorization. Responder Links reject this operation because + /// LINKIDENTIFY reveals the initiator to the responder. pub fn send_link_identify( &mut self, link_id: &[u8; 16], @@ -6012,8 +6120,9 @@ impl LinkManager { }) } - /// Close exactly the requested Link owner, optionally sending LINKCLOSE - /// before the endpoint is unbound. + /// Remove the requested Link locally and start endpoint cleanup, optionally + /// staging LINKCLOSE. True means local ownership was removed; it does not + /// wait for teardown delivery or completion of asynchronous cleanup. pub fn close_link( &mut self, link_id: [u8; 16], @@ -6028,6 +6137,9 @@ impl LinkManager { Self::ensure_link_channel(active, *link_id, &self.channel_message_types) } + /// Prepare and enqueue a Channel message. Success records local transport + /// command admission, not driver dispatch or peer delivery. Continue driving + /// the manager so the Channel can process proofs and retransmissions. pub fn send_channel_message( &mut self, link_id: &[u8; 16], @@ -6090,6 +6202,10 @@ impl LinkManager { }) } + /// Encrypt and enqueue an ordinary packet. The returned receipt records + /// local command admission, not peer delivery. Keep payloads within the Link + /// MDU (or use `send_link_payload`); endpoint rejection can occur later. + /// Ordinary packets are not automatically retransmitted. pub fn send_link_packet( &mut self, link_id: &[u8; 16], @@ -6222,12 +6338,11 @@ impl LinkManager { } } - /// Send realtime Link data on the Link's exact bound interface without - /// entering the lossless per-Link control FIFO. - /// - /// Backpressure is reported as [`LinkEndpointSendResult::DroppedBackpressure`] - /// so media callers can account for an intentional drop without delaying - /// later frames. This API never falls back to destination routing. + /// Send realtime Link data on the bound interface, without entering the + /// per-Link control retry queue or falling back to destination routing. + /// Inspect the returned [`LinkEndpointSendResult`]: `Ok` can contain a drop, + /// invalid-packet or terminated-endpoint result. `Sent` is local driver + /// admission, not peer delivery. There is no whole-call timeout here. pub async fn send_link_packet_best_effort( &mut self, link_id: &[u8; 16], @@ -6285,6 +6400,9 @@ impl LinkManager { )) } + /// Prepare and start a Resource, returning its logical hash after local + /// advertisement staging. Observe lifecycle/proof notifications for the + /// terminal result; successful return alone does not establish delivery. pub fn send_link_resource( &mut self, link_id: &[u8; 16], @@ -6312,6 +6430,9 @@ impl LinkManager { }) } + /// Send a packet when the payload fits the Link MDU, otherwise a Resource. + /// Both receipt variants identify locally admitted work; delivery is observed + /// separately through proof and Resource lifecycle notifications. pub fn send_link_payload( &mut self, link_id: &[u8; 16], @@ -6335,8 +6456,9 @@ impl LinkManager { } } - /// Cancel an active Resource by the logical id returned in lifecycle - /// events or [`LinkResourceSendReceipt`]. + /// Cancel using a logical Resource id or an active segment hash. True + /// means a local transfer was removed; it does not acknowledge peer + /// cancellation. Sending the cancel control packet can fail independently. pub fn cancel_link_resource( &mut self, link_id: &[u8; 16], @@ -6533,7 +6655,10 @@ impl LinkManager { true } - /// Sends ADV + initial window, registers transfer so later HMU drives the rest. + /// Prepare all Resource segments in memory and stage the first + /// advertisement. Receiver requests drive part transmission. Returns the + /// logical Resource hash after local start, not a delivery proof. Preparation + /// is synchronous; use bounded payloads to avoid stalling the manager. pub fn start_resource_transfer( &mut self, link_id: &[u8; 16], @@ -6543,8 +6668,9 @@ impl LinkManager { self.start_resource_transfer_with_metadata(link_id, data, None, auto_compress) } - /// As [`Self::start_resource_transfer`] but attaches msgpack metadata - /// (e.g. `{"name": "file.bin"}`). Used by rncp --fetch. + /// As [`Self::start_resource_transfer`], with opaque metadata bytes. + /// For rncp fetch, supply its expected MessagePack metadata map; this + /// method does not validate the application encoding. pub fn start_resource_transfer_with_metadata( &mut self, link_id: &[u8; 16], @@ -6763,11 +6889,12 @@ impl LinkManager { Some(resource_hash) } - /// Legacy pull-style completion for a single inbound Resource. + /// Legacy pull completion for an unsplit inbound Resource. Returns data + /// and proof bytes without transmitting the proof, and supplies no decryptor. /// - /// The actor normally completes Resources while handling their final part. - /// Split Resources require that actor path so proofs and coordinator state - /// remain ordered. + /// The actor normally completes Resources with the Link decryptor on their + /// final part. Use that path for encrypted or split transfers and consume + /// the completion/accounting channel; this helper cannot replace it. #[deprecated(note = "Resources complete automatically; consume the accounting stream instead")] pub fn complete_resource( &mut self, @@ -6867,6 +6994,12 @@ fn unix_now() -> f64 { .as_secs_f64() } +/// Try to register a destination and return its bounded 256-event receiver. +/// This helper does not await transport acknowledgment. If command admission +/// fails it logs the error and still returns a receiver, which then closes; +/// use [`crate::reticulum::ReticulumHandle::register_destination`] for awaited +/// command admission and an owned destination lifecycle. That API also does +/// not wait for actor acknowledgment. pub fn register_destination( transport_tx: &mpsc::Sender, dest_hash: [u8; 16], diff --git a/crates/rns-runtime/src/link_session.rs b/crates/rns-runtime/src/link_session.rs index a0ddf64..9af0f69 100644 --- a/crates/rns-runtime/src/link_session.rs +++ b/crates/rns-runtime/src/link_session.rs @@ -1,8 +1,10 @@ //! Persistent initiator-side Reticulum Link sessions for applications. //! -//! Unlike [`crate::link_client::LinkClient`], which opens a Link for one -//! request/response exchange, this module keeps the Link alive and exposes -//! ordinary encrypted Link packets until either peer closes the session. +//! A session carries encrypted packets, request/response exchanges, Channels +//! and Resources until closed or timed out. [`crate::link_client::LinkClient`] +//! provides a separate convenience API for one request/response exchange. +//! Keep draining [`LinkSession::events`] while using the handles; a full event +//! queue can stall the actor, including its protocol timers and close handling. use std::collections::{HashMap, HashSet, VecDeque}; use std::io::Cursor; @@ -43,6 +45,15 @@ const RESOURCE_OFFER_TIMEOUT: Duration = Duration::from_secs(30); const RESOURCE_REJECTION_TTL: Duration = Duration::from_secs(60); #[derive(Debug, Clone)] +/// Remote destination and establishment options. The caller must supply a +/// trusted association between `destination_hash` and `remote_public_key`; +/// connection verifies the Link proof with the supplied signing key, without +/// re-deriving a destination from an application name. +/// +/// `identified` defaults to one hop, a 30-second establishment timeout, +/// LinkIdentify enabled and physical-stat tracking disabled. The timeout +/// covers request admission and proof waiting, not every registration, binding +/// or identification operation; see `LinkSession::connect`. pub struct LinkSessionConfig { pub destination_hash: [u8; 16], pub remote_public_key: [u8; 64], @@ -80,6 +91,11 @@ pub enum LinkSessionCloseReason { } #[derive(Debug, Clone, PartialEq, Eq)] +/// Session observations. Packet and state events can backpressure the actor; +/// request/Resource lifecycle notifications use best-effort sends and may be +/// dropped if the event queue is full. Use returned request/Resource handles +/// for their terminal outcomes. `PacketDelivered` means a valid peer packet +/// proof, not application processing or durable storage. pub enum LinkSessionEvent { Packet { data: Vec, @@ -117,6 +133,9 @@ pub enum LinkSessionEvent { } #[derive(Debug, Clone, PartialEq, Eq)] +/// Local send result for an ordinary packet. The endpoint accepted it as sent +/// or queued; this is not an on-air or peer-delivery acknowledgment. A later +/// `LinkSessionEvent::PacketDelivered` carries a verified peer proof. pub struct LinkSessionPacketReceipt { pub link_id: [u8; 16], pub packet_hash: [u8; 32], @@ -132,6 +151,9 @@ pub struct LinkSessionResponse { } #[derive(Debug, Clone, PartialEq, Eq)] +/// Local sent-or-queued result for a Channel packet. The Channel continues +/// tracking proofs and retries after this return; this receipt does not +/// establish peer application consumption. pub struct LinkSessionChannelReceipt { pub link_id: [u8; 16], pub sequence: u16, @@ -145,6 +167,8 @@ pub enum LinkSessionResourceDirection { } #[derive(Debug, Clone, PartialEq, Eq)] +/// Successful outbound Resource conclusion after valid proofs for every +/// segment. This does not attest to remote file writes or durable storage. pub struct LinkSessionResourceReceipt { pub link_id: [u8; 16], pub resource_id: [u8; 32], @@ -157,6 +181,10 @@ pub struct LinkSessionResourceReceipt { /// The transfer itself remains owned by the Link session actor. Cloning the /// progress receiver does not duplicate transfer state, and dropping this /// handle does not implicitly cancel the transfer. +/// +/// `cancel` reports whether the actor removed an active or queued transfer; +/// it does not confirm cancellation at the peer. Progress can reach its end +/// before final proof; use `concluded` for the protocol outcome. pub struct LinkSessionResourceHandle { link_id: [u8; 16], resource_id: [u8; 32], @@ -223,11 +251,15 @@ pub struct LinkSessionReceivedResource { pub is_response: bool, } -/// A bounded inbound Resource advertisement awaiting an application decision. +/// An inbound Resource advertisement awaiting an application decision. /// -/// Offers are rejected after 30 seconds if the application does not decide. -/// Accepting creates a lifecycle handle; dropping an offer leaves that timeout -/// in force rather than accepting data implicitly. +/// The actor keeps up to eight undecided offers. Its periodic timer rejects +/// undecided offers after 30 seconds; an occupied actor can delay that check. +/// Dropping an offer leaves this expiry in force and does not accept data. +/// Acceptance covers the logical transfer and valid follow-up segments. +/// Response Resources for pending requests are accepted internally, without an +/// offer. Inspect advertised size before accepting; completed inbound data is +/// assembled in memory. pub struct LinkSessionResourceOffer { link_id: [u8; 16], resource_id: [u8; 32], @@ -322,6 +354,12 @@ impl LinkSessionResourceOffer { } } +/// Lifecycle handle for an accepted inbound Resource. `concluded` returns the +/// complete in-memory payload after assembly and local proof admission; the +/// application still owns processing and persistence. Dropping this handle +/// does not cancel reception. `cancel` returns whether a live logical transfer +/// was removed locally, not an acknowledgment from its sender. Progress is a +/// coalescing estimate; only `concluded` establishes success. pub struct LinkSessionInboundResourceHandle { link_id: [u8; 16], resource_id: [u8; 32], @@ -664,9 +702,12 @@ impl MessageBase for PackedChannelMessage { } } -/// Cloneable app-facing handle for the reliable channel owned by a Link -/// session. Sequencing, proofs, retransmissions, and callbacks remain -/// serialized inside the session actor. +/// Cloneable handle to the session's reliable Channel. Sequencing, proofs, +/// retransmissions and callbacks run in the session actor. Register incoming +/// message types and a handler before expecting application delivery. +/// Callbacks run synchronously in registration order; returning true stops the +/// callback chain. They must not block or wait for another command on this +/// session. Peer packet proofs do not establish application consumption. #[derive(Clone)] pub struct LinkSessionChannelHandle { link_id: [u8; 16], @@ -778,12 +819,16 @@ impl LinkSessionChannelHandle { .await } - /// True when all previously-sent channel messages have been acknowledged. + /// True when the Channel's transmit ring is empty. Normal acknowledgments + /// empty it, but `shutdown` also discards the ring. This result alone does + /// not prove delivery or application consumption. pub async fn is_drained(&self) -> Result { self.invoke(|result_tx| LinkSessionChannelCommand::IsDrained { result_tx }) .await } + /// Shut down this Channel and discard buffered messages and handlers. + /// This does not drain delivery or close the containing Link session. pub async fn shutdown(&self) -> Result<(), LinkSessionChannelError> { self.invoke(|result_tx| LinkSessionChannelCommand::Shutdown { result_tx }) .await @@ -815,7 +860,8 @@ impl LinkSessionHandle { *self.phy_stats_rx.borrow() } - /// Subscribe to physical-layer measurement updates for this Link. + /// Subscribe to the latest physical-layer snapshot. Watch receivers may + /// coalesce updates; this is not a record of every received packet. pub fn watch_phy_stats(&self) -> watch::Receiver { self.phy_stats_rx.clone() } @@ -828,6 +874,9 @@ impl LinkSessionHandle { } } + /// Encrypt and submit one ordinary packet within the Link MDU. The result + /// is local sent-or-queued admission; observe packet proofs separately. + /// This path does not retransmit ordinary packets automatically. pub async fn send_packet( &self, payload: Vec, @@ -848,10 +897,15 @@ impl LinkSessionHandle { .map_err(|_| LinkSessionError::SessionClosed)? } - /// Send a request and wait for its response. + /// Send a request and wait for its response. A packed request above the + /// Link MDU uses a Resource; matching response Resources are accepted + /// internally without an application Resource offer. /// - /// Requests and responses larger than the current Link MDU transparently - /// use Reticulum Resource transfer, matching Python RNS. + /// `None` selects the Link's RTT-based response timeout. For a Resource + /// request, that timeout starts after the request Resource is proved; it + /// does not bound queueing, transfer or every transport wait. Apply a caller + /// deadline when needed. Dropping this future does not cancel an admitted + /// request or its remote work. At most 64 requests may be pending. pub async fn request( &self, path: &str, @@ -873,11 +927,17 @@ impl LinkSessionHandle { .map_err(|_| LinkSessionError::SessionClosed)? } - /// Start a bounded-memory Link Resource transfer. + /// Prepare and start or queue a Link Resource transfer. Source inspection + /// and hashing run on the blocking pool before queue admission. The actor + /// allows one active outbound Resource and up to eight queued Resources. /// - /// Source inspection and hashing run on the blocking pool. Large sources - /// are then read one bounded segment at a time as each preceding segment - /// is proved by the peer. + /// Each queued transfer retains its source and first prepared segment. + /// Later segments are read synchronously in the session actor after the + /// previous segment is proved; use a stable, finite source whose reads do + /// not stall the actor. This bounds segment buffering per transfer, not + /// memory across concurrent preparation calls or caller-owned sources. + /// Dropping the returned handle does not cancel the transfer; use its + /// `cancel` and `concluded` methods for explicit lifecycle handling. pub async fn send_resource( &self, source: S, @@ -926,11 +986,19 @@ impl LinkSessionHandle { self.send_resource(Cursor::new(data), options).await } + /// Queue a request to close the session. Return does not wait for teardown, + /// cleanup or the `Closed` event; it also hides an already-closed command + /// channel. Continue draining events while waiting for closure. pub async fn close(&self) { let _ = self.command_tx.send(LinkSessionCommand::Close).await; } } +/// Session handles and receive queues. The background actor retains its own +/// command sender, so dropping application handles alone does not reliably +/// stop it. Call `handle.close()` explicitly and keep draining `events`. +/// Ordinary inbound packets are proved before application event delivery; +/// this API does not provide application-controlled packet proof receipts. pub struct LinkSession { pub handle: LinkSessionHandle, pub events: mpsc::Receiver, @@ -938,6 +1006,14 @@ pub struct LinkSession { } impl LinkSession { + /// Establish a Link using the configured remote key and spawn its actor. + /// No destination discovery is performed here. When `identify` is enabled, + /// the local identity must be able to sign; success is not remote application + /// authorization of that identity. + /// + /// The establishment timeout bounds request admission and proof waiting. + /// Some transport operations and identification delays are outside it; use + /// an outer timeout for a deadline on the entire call. pub async fn connect( transport_tx: mpsc::Sender, identity: Identity, @@ -1097,6 +1173,10 @@ impl LinkSession { } } +/// Resolve destination identity metadata, requesting a path if needed, then +/// read the announce-cache entry with its public key. Cache hits do not prove +/// current reachability or perform fresh signature verification. The final +/// cache lookup has no timeout; use an outer deadline to bound the whole call. pub async fn discover_destination( transport_tx: &mpsc::Sender, destination_hash: [u8; 16], @@ -1130,6 +1210,9 @@ pub async fn discover_destination( Ok(entry) } +/// Read matching metadata from the transport's recent-announce cache. This +/// issues no path request, performs no fresh signature verification, and has +/// no timeout of its own. `None` can also mean an unexpected RPC response. pub async fn lookup_destination( transport_tx: &mpsc::Sender, destination_hash: [u8; 16], diff --git a/crates/rns-runtime/src/platform.rs b/crates/rns-runtime/src/platform.rs index 8510b4a..bc9036a 100644 --- a/crates/rns-runtime/src/platform.rs +++ b/crates/rns-runtime/src/platform.rs @@ -65,11 +65,13 @@ impl Platform { } } -/// Explicit `configdir` wins. Without one, use rsReticulum-specific defaults: -/// `/etc/rsReticulum/config`, then `~/.config/rsReticulum/config`, then -/// `~/.rsReticulum` on Unix-like systems. Windows uses the appdata -/// `rsReticulum` directory. Pass `--config ~/.reticulum` explicitly when -/// intentionally sharing a Python Reticulum config. +/// Return an explicit `configdir` unchanged, without shell or tilde expansion. +/// Otherwise, on non-Windows/non-Android targets, select `/etc/rsReticulum` +/// or `$HOME/.config/rsReticulum` only if its `config` file exists, then fall +/// back to `$HOME/.rsReticulum` (or relative `.rsReticulum` without `HOME`). +/// Windows uses `$APPDATA/rsReticulum`, or relative `.rsReticulum`. Android +/// falls back to `/data/local/tmp/.rsReticulum` with a warning; applications +/// should supply their own writable config directory. pub fn resolve_config_dir(configdir: Option<&str>) -> PathBuf { match configdir { Some(dir) => PathBuf::from(dir), diff --git a/crates/rns-runtime/src/probe.rs b/crates/rns-runtime/src/probe.rs index 06f1de4..2ba145f 100644 --- a/crates/rns-runtime/src/probe.rs +++ b/crates/rns-runtime/src/probe.rs @@ -1,4 +1,6 @@ -//! Wire-compatible with Python `rnprobe.py`. +//! Encrypted SINGLE-packet probes and signed delivery-proof responses, used +//! by `rnprobe-rs`. A valid proof confirms receipt of the packet; it is not an +//! application-payload processing acknowledgment. use std::sync::Arc; use std::time::{Duration, Instant}; @@ -48,16 +50,19 @@ pub enum ProbeError { #[derive(Debug, Clone)] pub struct ProbeOutcome { pub rtt: Duration, - /// 0 for direct. + /// Path-table hop count captured before sending. Defaults to zero when + /// path metadata is unavailable; zero alone does not establish a direct route. pub hops: u8, pub via: Option<[u8; 16]>, pub interface: Option, pub destination_hash: [u8; 16], } -/// Signs every inbound DATA with a PROOF (Python `PROVE_ALL`). Callers must -/// persist `identity` (canonical `/probe_identity`) for a stable -/// destination hash across restarts. +/// Register a SINGLE destination that attempts an implicit signed proof for +/// received DATA packets. The responder hashes and signs the packet without +/// decrypting or validating its application payload. Persist `identity` +/// (normally `/probe_identity`) to retain its destination hash +/// across restarts. pub async fn spawn_probe_responder( transport_tx: mpsc::Sender, identity: Identity, @@ -249,8 +254,16 @@ impl Drop for DeliveryProofWaiter { } } -/// `None` waits mirror Python rnprobe: `DEFAULT_TIMEOUT + -/// get_first_hop_timeout(dest)`, resolved fresh at each wait. +/// Send `size` bytes of random plaintext to a matching SINGLE destination +/// and wait for its signed delivery proof. `app_name` and the cached identity +/// must derive `dest_hash`; callers supply that binding. The encrypted packet +/// including headers must fit the MTU, so the maximum plaintext is smaller. +/// +/// Path and proof waits are separate budgets. `None` selects 12 seconds plus +/// the current first-hop timeout for each phase. Transport queries and mailbox +/// admission are outside those waits; use an outer timeout for a whole-call +/// deadline. `use_implicit_proof` is retained for compatibility and ignored; +/// proof validation belongs to the transport receipt handler. pub async fn probe_once( transport_tx: mpsc::Sender, dest_hash: [u8; 16], @@ -781,7 +794,8 @@ mod tests { } } -/// Validate local CLI/API timeout input before starting networking. +/// Convert finite, nonnegative seconds into a duration whose deadline fits +/// `Instant`. Zero is allowed. This performs no networking. pub fn checked_probe_timeout(seconds: f64) -> Result { let duration = Duration::try_from_secs_f64(seconds).map_err(|_| ProbeError::InvalidTimeout)?; std::time::Instant::now() diff --git a/crates/rns-runtime/src/remote_management.rs b/crates/rns-runtime/src/remote_management.rs index 5fe602b..bd05ff0 100644 --- a/crates/rns-runtime/src/remote_management.rs +++ b/crates/rns-runtime/src/remote_management.rs @@ -1,12 +1,11 @@ -//! Authenticated RPC over Reticulum links (`rnstatus -R`, `rnpath -R`). -//! Registers `rnstransport.remote.management` with `/status` + `/path`. +//! Remote-management requests over Reticulum Links, used by `rnstatus-rs -R` +//! and `rnpath-rs -R`. Registers `rnstransport.remote.management` with `/status` +//! and `/path` handlers. Requests require prior Link identification and an +//! identity in the supplied allow-list; an empty list denies every peer. +//! Denied and unknown requests receive no response. //! -//! Auth: requires prior `LinkIdentify`, then checks identity against -//! `remote_management_allowed`. This mirrors Python `Destination.ALLOW_LIST`: -//! an empty allow-list denies all peers. -//! -//! REQUIRES a multi-threaded Tokio runtime — sync handler calls -//! `block_in_place`. Tests must use `#[tokio::test(flavor = "multi_thread")]`. +//! Requires a multithreaded Tokio runtime: synchronous handlers use +//! `block_in_place` while awaiting transport queries. use std::sync::Arc; @@ -24,10 +23,11 @@ use crate::rpc_server::{TransportStatsSource, stat_entries}; const STATUS_PATH: &str = "/status"; const PATH_PATH: &str = "/path"; -/// Python registers this destination on `Transport.identity` -/// (Transport.py:367-368), so `rnstatus -R` and `rnpath -R` find it from the -/// transport identity hash. Empty `allowed_identities` denies all peers, -/// matching Python's `Destination.ALLOW_LIST` semantics. +/// Start remote management using the supplied identity and return its +/// application destination hash. Pass the runtime transport identity for +/// clients that address the service by transport identity hash. The caller +/// provides the allow-list; an empty list denies every peer. Return success +/// indicates manager startup, not an advertised or remotely reachable service. pub async fn start_remote_management( transport_tx: mpsc::Sender, identity: &Identity, diff --git a/crates/rns-runtime/src/resource_source.rs b/crates/rns-runtime/src/resource_source.rs index d85a4ef..e130f81 100644 --- a/crates/rns-runtime/src/resource_source.rs +++ b/crates/rns-runtime/src/resource_source.rs @@ -1,4 +1,6 @@ -//! Bounded-memory sources for Link Resource transfers. +//! Seekable sources for Link Resource transfers, prepared one segment at a +//! time for large inputs. The source must satisfy the stability contract in +//! [`ResourceSource`]; custom reader allocations are outside this memory bound. use std::io::{self, Read, Seek, SeekFrom}; use std::time::Duration; @@ -11,6 +13,12 @@ use rns_protocol::resource::{ use sha2::{Digest, Sha256}; /// Seekable source accepted by the high-level Resource API. +/// +/// Keep contents and length stable throughout preparation and transfer. The +/// runtime seeks to the end to measure length, rewinds to zero, and may read +/// the entire source to hash it before reading segments again. It does not +/// snapshot or lock a file against concurrent writers. `Read` and `Seek` are +/// synchronous; implementations must return finite, consistent data. pub trait ResourceSource: Read + Seek + Send {} impl ResourceSource for T where T: Read + Seek + Send {} diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index 776dfc1..ec3641c 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -1,7 +1,14 @@ -//! Reticulum runtime singleton, init and lifecycle. Three operating modes: -//! **Shared** owns hardware and serves RPC to siblings; **Client** connects -//! to a Shared instance over a local socket; **Standalone** owns its -//! interfaces and exposes no IPC. Python: `RNS/Reticulum.py`. +//! Runtime construction, application operations and interface lifecycle. +//! Shared mode owns interfaces and serves local packet IPC and control RPC; +//! Client mode uses an existing shared owner; Standalone owns its interfaces +//! without serving shared-instance IPC. +//! +//! Start with [`init`] or [`init_with_policy`], retain the returned handle and +//! call [`ReticulumHandle::shutdown_and_wait`] before stopping Tokio. Configure +//! receivers before sending application traffic. Runtime interface creation +//! is rejected in Client mode and once shutdown begins. Successful interface +//! registration does not promise a connected peer or RNode protocol readiness, +//! and runtime-spawned interfaces are not written back to the config file. use rns_identity::ifac::IfacKey; use std::collections::HashMap; @@ -440,6 +447,10 @@ impl Drop for TransportActorCompletionGuard { } #[derive(Clone)] +/// Cloneable access to one running runtime. Clones share actor and interface +/// ownership; configuration fields are snapshots, not a general live +/// reconfiguration API. Dropping handles alone does not stop a runtime; +/// use `shutdown_and_wait` while Tokio is still running. pub struct ReticulumHandle { pub transport_tx: mpsc::Sender, path_recovery: rns_transport::path_recovery::PathRecoveryHandle, @@ -459,10 +470,9 @@ pub struct ReticulumHandle { /// Mobile builds throttle tick rates when the app is backgrounded. pub is_foreground: Arc, pub shutdown: ShutdownSignal, - /// Wire-facing transport identity (Python `Transport.identity`): on - /// non-transport nodes this is a fresh per-boot identity unless - /// `static_transport_identity` is set (Transport.py:234-238); RPC-key - /// derivation stays on the persisted identity. + /// Wire-facing identity. A non-transport node gets a fresh identity on + /// startup unless `static_transport_identity` is enabled. The default + /// local RPC key is derived from the separate persisted identity. pub transport_identity: Arc, pub network_identity: Option>, /// Present even when `discover_interfaces = No` so a downstream can @@ -477,7 +487,9 @@ pub struct ReticulumHandle { started_at: std::time::Instant, } -/// Identity and announce metadata recalled from the live transport cache. +/// Identity and announce metadata from this process's transport cache. +/// Entries can have been restored from storage; this value does not establish +/// fresh signature verification or current reachability. #[derive(Clone)] pub struct RecalledDestination { pub destination_hash: [u8; 16], @@ -515,7 +527,9 @@ impl AnnounceSubscription { self.dropped_events.load(Ordering::Relaxed) } - /// Deterministically deregister this subscription. + /// Request exact deregistration and wait for the actor's acknowledgment. + /// False means already closed or no matching subscription. This has no + /// whole-call timeout and does not consume events already in the queue. pub async fn close(&mut self) -> Result { let Some(id) = self.id else { return Ok(false); @@ -641,10 +655,11 @@ impl RNodeRuntimeObserver { self.state.changed().await } - /// Wait up to `timeout` for complete protocol readiness. - /// - /// One absolute deadline spans reconnects. Dropping this future has no - /// effect on the driver or registry. + /// Wait for this driver's current `Ready` phase with a nonzero connection + /// generation. One absolute deadline spans reconnects; dropping the future + /// does not affect the driver. A currently ready snapshot returns immediately. + /// A duration too large for Tokio's deadline representation waits without + /// a timeout. Readiness does not attest to RF range or peer reachability. pub async fn await_ready( &self, timeout: Duration, @@ -807,9 +822,11 @@ impl RNodeReadinessError { /// Options for [`ReticulumHandle::send_to`]. #[derive(Debug, Clone)] pub struct SendOptions { - /// Track the packet until a proof arrives or its receipt expires. + /// Request a receipt for a non-PLAIN packet. PLAIN ignores this option; + /// tracked destinations must have identity metadata in the local cache. pub create_receipt: bool, - /// Override the route-derived receipt timeout. + /// Override the receipt's proof timeout, not the duration of `send_to`. + /// `None` uses route timing, with a 180-second fallback if lookup fails. pub timeout: Option, /// Restrict dispatch to one interface. pub attached_interface: Option, @@ -825,7 +842,9 @@ impl Default for SendOptions { } } -/// Immediate result of a successful packet dispatch. +/// Local dispatch result: an interface queue accepted the packet. This is +/// not on-air confirmation or a peer-delivery proof; inspect `receipt` when +/// present for a terminal protocol outcome. #[derive(Debug, Clone)] pub struct SendResult { pub packet_hash: [u8; 32], @@ -833,9 +852,10 @@ pub struct SendResult { } /// Stateful non-Link application packet that can be sent and re-sent. -/// -/// Re-sending runs the normal destination encryption path again, producing -/// fresh ciphertext, a new packet hash, and a new receipt when requested. +/// Re-sending repeats destination packet construction. Encrypted destinations +/// produce fresh ciphertext; PLAIN data is not encrypted and can retain its +/// packet hash. A new receipt is requested only when the options and +/// destination type support one. pub struct OutboundPacket<'a> { runtime: &'a ReticulumHandle, destination: &'a Destination, @@ -856,6 +876,8 @@ impl std::fmt::Debug for OutboundPacket<'_> { } impl OutboundPacket<'_> { + /// Whether the wrapper's latest send state is successful local dispatch. + /// This is not peer delivery; a failed `resend` resets the flag. pub fn is_sent(&self) -> bool { self.sent } @@ -873,7 +895,9 @@ impl OutboundPacket<'_> { Ok(result) } - /// Re-send a previously-sent packet with fresh destination encryption. + /// Repeat a previously successful send using destination packet construction. + /// On failure this wrapper resets its sent flag; call `send` for the next + /// attempt. Success still means local dispatch, not remote delivery. pub async fn resend(&mut self) -> Result { if !self.sent { return Err(SendError::NotSent); @@ -924,10 +948,9 @@ impl PacketReceiptHandle { self.status_rx.clone() } - /// Change the timeout of this receipt while it is still pending. - /// - /// The new duration is measured from the original send time, matching - /// Python `PacketReceipt.set_timeout`. + /// Change the timeout while the receipt remains pending, measured from + /// its original actor-side receipt creation time. This does not restart + /// the clock. Admission and acknowledgment have no timeout of their own. pub async fn set_timeout(&self, timeout: Duration) -> Result<(), ReceiptError> { if self.status() != ReceiptUpdate::Sent { return Err(ReceiptError::NoLongerTracked); @@ -948,7 +971,9 @@ impl PacketReceiptHandle { } } - /// Wait until the packet is delivered or reaches another terminal state. + /// Wait for a valid destination-signed proof or another terminal receipt + /// state. Delivery does not attest to application processing or persistence. + /// This waiter relies on the actor's receipt timer; it adds no outer deadline. pub async fn delivered(mut self) -> Result { loop { match self.status() { @@ -1014,13 +1039,13 @@ pub enum SendError { /// Options for opening a persistent application Link. #[derive(Debug, Clone)] pub struct LinkConnectOptions { - /// How long path discovery may run when no validated announce is cached. + /// Path-resolution budget when required identity/path metadata is absent. + /// A cache hit need not trigger fresh discovery or signature verification. pub path_timeout: Duration, - /// Explicit deadline for the Link handshake itself. - /// - /// When omitted, the runtime derives Python-compatible timing from the - /// destination's first-hop timeout and current path hop count. - /// `Some(Duration::ZERO)` deliberately requests an immediate deadline. + /// Timeout for Link request admission and proof waiting, not the entire + /// connection call. When omitted, it is first-hop timeout plus the default + /// per-hop timeout times at least one hop. `Some(Duration::ZERO)` selects + /// zero for this phase; other setup/cleanup work can still take time. pub establishment_timeout: Option, /// Registration label used for the temporary Link destination. pub client_label: String, @@ -1107,9 +1132,10 @@ pub enum ControlError { InvalidIdentity(#[from] rns_identity::identity::IdentityError), } -/// Shared discovery state behind one `Arc` so cloning [`ReticulumHandle`] -/// doesn't proliferate state. Holds inputs for the eventual announce tick / -/// subscriber loop. +/// Discovery state shared by cloned runtime handles. Install a +/// [`DiscoveryStamper`] through [`ReticulumHandle::enable_on_network_discovery`] +/// to start configured receiving and publication; constructing this state +/// alone does not start either service. pub struct DiscoveryRuntime { stamper: Mutex>>, store: Mutex>>, @@ -1163,9 +1189,10 @@ impl ReticulumHandle { self.link_endpoint_dispatch.clone() } - /// Non-fatal configured-interface startup failures, as `(name, reason)`. - /// Other interfaces remain usable. Empty for shared clients, which do not - /// start the caller's configured interfaces. + /// Recorded non-fatal failures after interface configuration synthesis, + /// as `(name, reason)`. Other interfaces can remain usable. Earlier parsing + /// or synthesis failures may be logged without appearing here. Shared + /// clients do not spawn configured interfaces and return an empty slice. pub fn startup_interface_failures(&self) -> &[(String, String)] { &self.startup_interface_failures } @@ -1294,15 +1321,20 @@ impl ReticulumHandle { self.config.link_mtu_discovery } - /// Trigger orderly runtime shutdown and wait until the transport actor has - /// synchronously flushed its persisted state. Dropping this future does - /// not cancel the runtime-owned drain operation. + /// Start runtime-owned shutdown and wait for interface ownership cleanup + /// and transport termination. Normal transport shutdown attempts synchronous + /// state persistence; this API returns no persistence error or durability + /// receipt. Dropping the future does not cancel cleanup. Some stop/transport + /// waits are outside the interface-task join deadline; there is no whole-call + /// timeout. pub async fn shutdown_and_wait(&self) { self.shutdown_coordinator.start_and_wait().await; } - /// Wait up to `timeout` for the transport actor to resolve a path. - /// Python: `Transport.await_path` (RNS/Transport.py:2524). + /// Wait for the local actor to confirm a current path, requesting one if + /// needed. One deadline covers mailbox admission and reply waiting. Success + /// is a routing observation, not proof that the destination application + /// will respond. pub async fn await_path( &self, destination_hash: [u8; 16], @@ -1311,12 +1343,14 @@ impl ReticulumHandle { await_path(&self.transport_tx, destination_hash, timeout).await } - /// Resolve a destination and open a persistent encrypted Link. + /// Resolve cached identity/path metadata and open a persistent encrypted + /// [`LinkSession`], requesting a path when needed. Cache data is trusted + /// without fresh announce-signature verification. The Link proof is checked + /// against the resolved signing key. /// - /// This is the app-facing counterpart to Python's `Link(destination)`: - /// it uses the validated announce cache for the remote public key, starts - /// path discovery when necessary, and then hands ownership to - /// [`LinkSession`]. + /// Path and establishment options bound particular phases, not the complete + /// call. Use a caller deadline when needed, and keep draining the returned + /// session's events. pub async fn connect_link( &self, destination_hash: [u8; 16], @@ -1363,6 +1397,9 @@ impl ReticulumHandle { }) } + /// Subscribe to matching validated announce events with capacity 128. + /// Use the returned stream's dropped counter to detect capacity loss. + /// Registration waits for acknowledgment without a whole-call deadline. pub async fn subscribe_announces( &self, aspect_filter: Option, @@ -1376,6 +1413,10 @@ impl ReticulumHandle { .await } + /// Register an announce subscription with nonzero capacity. The actor + /// verifies matching announces before dispatch; a full receiver drops events + /// and increments its counter. Registration waits for actor acknowledgment + /// without an outer timeout. Drop or close the subscription when finished. pub async fn subscribe_announces_with_capacity( &self, aspect_filter: Option, @@ -1409,12 +1450,9 @@ impl ReticulumHandle { }) } - /// Prepare one stateful non-Link application packet. - /// - /// [`OutboundPacket::send`] performs the same validated destination - /// resolution, encryption, receipt registration, and dispatch as - /// [`Self::send_to`]. [`OutboundPacket::resend`] repeats that complete - /// path so each attempt receives fresh ciphertext and receipt state. + /// Prepare a stateful wrapper around [`Self::send_to`]. No packet is sent + /// until `send` or `resend` is called. Each attempt repeats cache lookup and + /// packet construction; only encrypted destinations get fresh ciphertext. pub fn outbound_packet<'a>( &'a self, destination: &'a Destination, @@ -1430,10 +1468,15 @@ impl ReticulumHandle { } } - /// Encrypt and dispatch one non-Link application packet. + /// Build and dispatch a non-Link packet for an outbound destination. + /// SINGLE always needs identity metadata in this process's announce cache; + /// other tracked destinations also need it. This method does not discover a + /// missing identity. PLAIN is unencrypted and never gets a receipt. /// - /// Call [`Self::outbound_packet`] when the same logical packet may need - /// to be re-sent with fresh ciphertext. + /// Success means an interface queue accepted the packet. The optional receipt + /// reports a later peer proof, not application consumption. `options.timeout` + /// applies to that receipt; transport submission and dispatch reply have no + /// whole-call deadline. Use [`Self::outbound_packet`] for explicit resend state. pub async fn send_to( &self, destination: &Destination, @@ -1553,7 +1596,9 @@ impl ReticulumHandle { rns_wire::receipt::receipt_timeout_for_route(first_hop, hops) } - /// Query this process' transport actor directly. + /// Query this process's actor with a five-second admission-and-reply budget. + /// Errors become `None`; even in Client mode this does not query the shared + /// owner. Use `query_control_result` for typed control errors. pub async fn query_transport(&self, query: TransportQuery) -> Option { self.query_transport_result(query).await.ok() } @@ -1603,14 +1648,14 @@ impl ReticulumHandle { result } - /// Recall the identity and latest announce metadata for `destination_hash`. + /// Read identity and announce metadata from this process's transport cache + /// without extending its lifetime. This remains a local lookup in Client + /// mode, even when the shared owner knows more. /// - /// This reads this process' live, validated replicated announce cache in - /// O(1) without extending the entry's lifetime. In shared-instance client - /// mode it intentionally remains a process-local cache lookup, not an - /// authoritative control-plane query. It mirrors - /// `Identity.recall(destination_hash, _no_use=True)` and returns `None` - /// when no identity-bearing announce is known. + /// The helper does not verify a fresh signature or check current presence. + /// Stored cache metadata can be restored with structural checks alone; keep + /// its storage within the application's trust boundary. `None` means no + /// identity-bearing entry, not a failed on-network lookup. pub async fn recall( &self, destination_hash: [u8; 16], @@ -1715,11 +1760,10 @@ impl ReticulumHandle { } } - /// Return the effective MTU of the next-hop interface. - /// - /// Rust interfaces normalize fixed and auto-configured hardware MTUs into - /// one concrete value, so this is the counterpart to Python's - /// `next_hop_interface_hw_mtu()`. + /// Return the next-hop interface MTU in bytes, when available. In Client + /// mode the owner is queried by interface name; an ambiguous name or a zero + /// MTU yields `None`. This interface value is not a negotiated Link payload + /// budget or the MTU of every hop on the path. pub async fn next_hop_hardware_mtu( &self, destination_hash: [u8; 16], @@ -1774,10 +1818,10 @@ impl ReticulumHandle { .map(|latency| latency * 8.0)) } - /// Return the first-hop transmission timeout for `destination_hash`. - /// - /// Shared-instance clients include the configured simulated local-link - /// latency from `force_shared_instance_bitrate`, matching Python. + /// Return the first-hop timeout estimate. In Client mode, a positive + /// `force_shared_instance_bitrate` adds the estimated transmission time + /// of one Reticulum MTU over the shared link. This is a protocol timing + /// input, not a measured or guaranteed transmission duration. pub async fn first_hop_timeout( &self, destination_hash: [u8; 16], @@ -1801,7 +1845,9 @@ impl ReticulumHandle { } } - /// Request a network path, optionally on one interface with an explicit tag. + /// Enqueue a path request, optionally restricted to an interface and tag. + /// Success means mailbox admission, not path resolution. This method has + /// no submission timeout; use `await_path` to wait with a deadline. pub async fn request_path( &self, destination_hash: [u8; 16], @@ -1816,7 +1862,10 @@ impl ReticulumHandle { .map_err(|_| ControlError::ChannelClosed) } - /// Return the authoritative path table, optionally limited by hop count. + /// Return the control-plane path snapshot, optionally limited by hop count. + /// Client mode queries the shared owner, but its RPC format omits local + /// interface id/mode/role: these fields become `0`, `Full` and `Normal`. + /// Do not treat those fallback fields as observed owner configuration. pub async fn path_table( &self, max_hops: Option, @@ -1837,11 +1886,13 @@ impl ReticulumHandle { } } - /// Return a normalized interface-stat snapshot. + /// Return interface statistics from the local actor or shared owner's RPC. + /// Aggregate traffic counters use saturating sums of returned interface records. /// - /// Aggregate counters are calculated with saturating sums. Metadata that - /// the current runtime or a shared-instance RPC cannot supply remains - /// `None` rather than being replaced with sentinel values. + /// Transport identity/uptime metadata is available here only for a local + /// transport node; probe and process-memory fields are `None`. The RPC bridge + /// uses `0` for an absent IFAC size and does not retain parent ids, so it cannot + /// preserve every distinction present in local runtime records. pub async fn interface_stats(&self) -> Result { let interfaces = match self .query_control_result(TransportQuery::GetInterfaceStats) @@ -1940,10 +1991,10 @@ impl ReticulumHandle { Ok(matched) } - /// Result-returning control-plane query used by the typed facade. - /// - /// In client mode, a failed or unsupported shared-instance request never - /// falls back to this process' local actor. + /// Query the local actor, or the shared owner's authenticated control RPC + /// in Client mode. A failed or unsupported shared request does not fall back + /// to the local actor. Local queries have one five-second deadline; shared + /// RPC uses per-operation timeouts, not one whole-call deadline. pub async fn query_control_result( &self, query: TransportQuery, @@ -1979,21 +2030,20 @@ impl ReticulumHandle { Ok(self.apply_shared_instance_latency(&query, response)) } - /// Query the authoritative control plane. - /// - /// In client mode, Python proxies Reticulum control methods to the local - /// shared instance over the RPC listener. Only operations exposed by that - /// listener are available here; failures and unsupported queries return - /// `None` without consulting this process' local actor. Use + /// Query the local actor or shared-owner control plane, converting all errors + /// to `None`. Client mode supports only queries exposed by the RPC mapping. + /// Use [`Self::query_control_result`] to distinguish failures and /// [`Self::query_transport`] for explicit process-local access. pub async fn query_control(&self, query: TransportQuery) -> Option { self.query_control_result(query).await.ok() } - /// Install a [`DiscoveryStamper`] so this node can emit PoW-stamped - /// discovery announces. Inverts Python's hard `LXMF.LXStamper` import - /// (RNS/Discovery.py:41) — downstream apps install at startup. Idempotent; - /// without a stamper, discovery stays silently inert. + /// Install a [`DiscoveryStamper`] and start the configured discovery workers. + /// `discover_interfaces` enables receiving; discoverable local interfaces + /// can publish independently of that flag. Both need the stamp provider and + /// an available discovery store. Repeated calls do not duplicate running + /// workers, but replacing the provider does not replace their captured copy. + /// This method returns no worker-startup or publication acknowledgment. pub async fn enable_on_network_discovery( &self, stamper: Arc, @@ -2002,12 +2052,16 @@ impl ReticulumHandle { start_on_network_discovery(self.clone()).await; } + /// Return whether a stamp provider is installed. True does not mean a + /// receiver/publisher started successfully or that any interface was found. pub async fn discovery_enabled(&self) -> bool { self.discovery.stamper.lock().await.is_some() } - /// Snapshot of currently-known interfaces. Stale + disallowed entries - /// are purged on read. Python: `discovered_interfaces()`. + /// List stored discovery records. Listing removes corrupt, expired, + /// unlisted-type and disallowed-publisher records from disk; merely stale + /// records remain until the removal threshold. Missing storage or a listing + /// error returns an empty vector. This is not a live reachability probe. pub async fn discovered_interfaces(&self) -> Vec { let store = self.discovery.store.lock().await.clone(); let Some(store) = store else { @@ -2021,8 +2075,8 @@ impl ReticulumHandle { store.list(sources).unwrap_or_default() } - /// Identity hashes whose blackhole manifest this node subscribes to. - /// Python: `Reticulum.blackhole_sources()`. + /// Configured publisher identity hashes for blackhole-manifest pulls. + /// This slice does not establish whether a pull succeeded. pub fn blackhole_sources(&self) -> &[[u8; 16]] { &self.config.blackhole_sources } @@ -2290,9 +2344,9 @@ pub enum InstanceMode { Standalone, } -/// Shared-instance transport: TCP loopback or AF_UNIX socket. Python uses -/// AF_UNIX only on Linux/Android and TCP elsewhere. Python config key: -/// `shared_instance_type`. +/// Shared-instance transport. The default is AF_UNIX on Linux/Android and +/// TCP loopback elsewhere. Explicit Unix selection uses filesystem sockets +/// on other supported Unix hosts; abstract names are Linux/Android-specific. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SharedInstanceType { /// TCP loopback on [`ReticulumConfig::shared_instance_port`]. @@ -2358,6 +2412,9 @@ fn shared_unix_rpc_socket_path(instance_name: &str, socket_base: &Path) -> Strin } } +/// Build the RPC Unix-socket name. Linux/Android names begin with a NUL +/// byte for the abstract namespace; other hosts use a path under `socket_base`. +/// This function neither creates nor validates a socket. pub fn shared_instance_rpc_socket_path(instance_name: &str, socket_base: &Path) -> String { shared_unix_rpc_socket_path(instance_name, socket_base) } @@ -2385,6 +2442,9 @@ fn socket_path_display(path: &str) -> String { } #[derive(Debug, Clone)] +/// Parsed runtime settings. `Default` supplies values; `try_from_config` +/// overlays supported keys. Editing this struct after initialization does +/// not reconfigure already-running actors or interface tasks. pub struct ReticulumConfig { pub share_instance: bool, pub instance_name: String, @@ -2392,13 +2452,12 @@ pub struct ReticulumConfig { pub shared_instance_port: u16, pub control_port: u16, pub enable_transport: bool, - /// Python 1.3.8 `static_transport_identity` (Reticulum.py:255,502-504, - /// default false): opts a non-transport node out of the per-boot - /// ephemeral wire-facing transport identity. + /// Keep the persisted wire-facing transport identity on a non-transport + /// node instead of creating a fresh one at startup. Default false. pub static_transport_identity: bool, - /// Python 1.3.8 `local_hops_delta` (Reticulum.py:256,506-508, default - /// false): apply a per-boot random 2..=7 hop offset to locally-originated - /// packets (Transport.py:240,1356-1365). + /// Use a per-startup random hop offset of 2..=7 for eligible locally + /// originated packets. PLAIN/GROUP and shared-instance edges are excluded; + /// this is not a general anonymity guarantee. Default false. pub local_hops_delta: bool, pub respond_to_probes: bool, pub use_implicit_proof: bool, @@ -2407,8 +2466,9 @@ pub struct ReticulumConfig { pub enable_remote_management: bool, pub remote_management_allowed: Vec>, pub rpc_key: Option>, - /// Python `force_shared_instance_bitrate` (bps). Caps announce rate / - /// token bucket regardless of real link bitrate. + /// Simulated shared-link bitrate in bits per second. A positive value + /// replaces the reported bitrate/derived MTU and affects announce pacing + /// and first-hop timeout estimates; it does not throttle all socket traffic. pub force_shared_instance_bitrate: Option, pub default_ar_target: Option, pub default_ar_penalty: Option, @@ -2417,22 +2477,27 @@ pub struct ReticulumConfig { pub ingress_overrides: rns_transport::ingress::IngressOverrides, pub loglevel: i32, - /// Optional "network identity" file: discovery announce app_data is - /// encrypted to this identity's pubkey. Python `network_identity`. + /// Optional identity file, loaded or created at startup. It signs discovery + /// announces and supplies the key for per-interface `discovery_encrypt`. + /// Providing this path alone does not encrypt every discovery announce. pub network_identity_path: Option, - /// Publish periodic discovery announces. Python `discover_interfaces`. + /// Receive on-network interface discovery when a stamper is installed. + /// Publication is controlled separately by each interface's `discoverable`. pub discover_interfaces: bool, - /// Maximum number of discovered interfaces to auto-connect to. Python - /// `autoconnect_discovered_interfaces`. + /// Maximum discovered Backbone connections to retain; zero disables + /// auto-connect. Receiving discovery and installing a stamper are also + /// required. Other discovered interface types are not auto-connected. pub autoconnect_discovered_interfaces: usize, - /// Python `autoconnect_unverified_implementations`: also auto-connect - /// interfaces whose stack is not a trusted release, rsRNS included. + /// Permit Backbone auto-connect when advertised implementation/version + /// metadata does not pass the configured release floor, including rsRNS. + /// The default check is metadata matching, not software attestation. pub autoconnect_unverified_implementations: bool, - /// Minimum stamp value (leading-zero bits). Default 16 (LXStamper - /// `DEFAULT_STAMP_VALUE`). Python `required_discovery_value`. + /// Minimum received discovery stamp value in leading-zero bits; default 16. + /// This does not set generation cost, which comes from each interface's + /// `discovery_stamp_value` (or `stamp_value`). pub discover_interfaces_required_value: u8, - /// Accepted discovery publisher identities. Python - /// `interface_discovery_sources`. + /// Accepted discovery publisher identity hashes. An empty list permits + /// any publisher that otherwise passes receiver checks. pub interface_discovery_sources: Vec<[u8; 16]>, /// Identity hashes whose `rnstransport.info.blackhole` manifests this @@ -2441,15 +2506,17 @@ pub struct ReticulumConfig { /// Publish this node's local blackhole table on /// `rnstransport.info.blackhole`. Python `publish_blackhole`. pub publish_blackhole: bool, - /// Seconds between blackhole-source pulls. Python 1.3.8 - /// `blackhole_update_interval` (Reticulum.py:266,593-596): parsed as - /// float minutes, clamped to min 2, stored as seconds; default 3600. + /// Seconds between blackhole-source pulls. The configuration-file value + /// `blackhole_update_interval` is in minutes, clamped to at least two and + /// converted to seconds. The default is 3600 seconds. pub blackhole_update_interval: f64, - /// Python 1.3.8 `[logging] logtimestamps` (Reticulum.py:459-461, - /// RNS/__init__.py:85 default True): log lines carry a timestamp prefix. + /// Parsed `[logging] logtimestamps` preference, default true. The + /// application or CLI must apply it when configuring its logging subscriber. pub log_timestamps: bool, - /// Bootstrap config files loaded on startup. Python `bootstrap_configs`. + /// Parsed `bootstrap_configs` paths, retained in configuration. The current + /// runtime does not load or merge these files; declare active interfaces + /// in the primary configuration. pub bootstrap_configs: Vec, } @@ -2677,6 +2744,9 @@ fn expand_home_path(path: &str) -> PathBuf { } impl ReticulumConfig { + /// Overlay supported configuration keys onto defaults. Typed value errors + /// can fail parsing; unknown keys and unrecognized shared-instance transport + /// names are not rejected universally. No interfaces or services are started. pub fn try_from_config(config: &Config) -> Result { let mut rc = ReticulumConfig::default(); @@ -2801,6 +2871,8 @@ impl ReticulumConfig { Ok(rc) } + /// Parse configuration, panicking on a value error. Use `try_from_config` + /// when configuration comes from users or requires recoverable validation. pub fn from_config(config: &Config) -> Self { Self::try_from_config(config).expect("valid Reticulum configuration") } @@ -2819,8 +2891,11 @@ fn generate_local_hops_delta() -> u8 { (rns_crypto::random::random_bytes(1)[0] % 6) + 2 } -/// Bring up the Reticulum runtime: config dir, transport actor, interfaces, -/// instance mode, jobs runner, and optional RPC / remote-management / probe. +/// Create a runtime from the selected configuration directory, creating +/// default configuration, storage and identities as needed. Startup chooses +/// shared-owner, client or standalone mode and starts configured services. +/// A successful return does not mean every configured interface is online; +/// inspect startup failures and use RNode observers when readiness matters. pub async fn init( configdir: Option<&str>, socket_dir: Option, @@ -5735,6 +5810,11 @@ fn derive_ifac_key_from_post_init( } #[derive(Clone, Default)] +/// Optional IFAC settings for runtime-spawned TCP/Backbone interfaces. +/// `ifac_size` is bytes (1..=64), default 16 when active. Empty name and +/// passphrase disable IFAC. IFAC restricts interface access; it does not +/// provide application end-to-end encryption. `Debug` redacts the passphrase, +/// but the owned `String` is not itself a zeroizing container. pub struct RuntimeInterfaceIfacConfig { pub network_name: Option, pub passphrase: Option, @@ -5757,6 +5837,9 @@ impl std::fmt::Debug for RuntimeInterfaceIfacConfig { } #[derive(Clone, Debug)] +/// Runtime Backbone client options. `connect_timeout` is seconds for a +/// connection attempt, not the lifetime of the reconnect loop or this whole +/// registration call. Optional IFAC uses a 16-byte default tag. pub struct RuntimeBackboneClientConfig<'a> { pub name: &'a str, pub host: &'a str, @@ -7294,7 +7377,8 @@ pub async fn spawn_backbone_server_runtime_with_ifac( pub struct BleRnodeRuntimeArgs<'a> { /// Interface name registered with the transport actor. pub name: &'a str, - /// BLE device path or address. + /// BLE platform identifier, address or advertised name used by the driver. + /// This selector is not cryptographic device authentication. pub port: &'a str, /// Radio frequency in Hz. pub frequency: u32, @@ -7308,16 +7392,19 @@ pub struct BleRnodeRuntimeArgs<'a> { pub tx_power: i8, /// Reticulum interface routing/announce propagation mode. pub mode: rns_interface::traits::InterfaceMode, - /// Short-term airtime limit in percent (0.0..=100.0), None = no limit. + /// Short-term airtime limit in percent (0.0..=100.0). `None` sends no + /// limit command and does not clear a limit retained on the radio. pub st_alock: Option, - /// Long-term airtime limit in percent (0.0..=100.0), None = no limit. + /// Long-term airtime limit in percent (0.0..=100.0). `None` sends no + /// limit command and does not clear a limit retained on the radio. pub lt_alock: Option, /// Enable KISS flow control. pub flow_control: bool, } -/// Returns `(interface_id, online_flag)`; `online_flag` flips to `true` -/// after the first successful connect. +/// Return the interface id and compatibility online flag. This flag alone +/// is not a cross-transport protocol-readiness contract; use the observed +/// variant and [`RNodeRuntimeObserver::await_ready`] when readiness matters. #[cfg(feature = "ble")] pub async fn spawn_ble_rnode_runtime( handle: &ReticulumHandle, @@ -7448,9 +7535,11 @@ pub struct RnodeRuntimeArgs<'a> { pub tx_power: i8, /// Reticulum interface routing/announce propagation mode. pub mode: rns_interface::traits::InterfaceMode, - /// Short-term airtime limit in percent (0.0..=100.0), None = no limit. + /// Short-term airtime limit in percent (0.0..=100.0). `None` sends no + /// limit command and does not clear a limit retained on the radio. pub st_alock: Option, - /// Long-term airtime limit in percent (0.0..=100.0), None = no limit. + /// Long-term airtime limit in percent (0.0..=100.0). `None` sends no + /// limit command and does not clear a limit retained on the radio. pub lt_alock: Option, /// Enable KISS flow control. pub flow_control: bool, @@ -7763,8 +7852,10 @@ pub async fn spawn_auto_interface_runtime_with_config( Ok(id) } -/// Spawns an AutoInterface with defaults (Link scope, Temporary address, -/// no NIC filter, 10 Mbps bitrate); only the four positional knobs differ. +/// Spawn AutoInterface with Link scope, Temporary multicast address type, +/// no explicit NIC allow-list, and the default 10 Mbps bitrate estimate. +/// Platform NIC exclusions still apply. Name, group id and ports come from +/// the arguments. pub async fn spawn_auto_interface_runtime( handle: &ReticulumHandle, name: &str, @@ -7782,7 +7873,9 @@ pub async fn spawn_auto_interface_runtime( spawn_auto_interface_runtime_with_config(handle, config).await } -/// `event_tx` is a process-singleton dispatcher; each call replaces the prior sender. +/// Spawn BLE Peer using the process-wide driver. `Some(event_tx)` replaces +/// the global event dispatcher; `None` leaves the existing dispatcher in +/// place. Registration success does not establish a connected peer. #[cfg(feature = "ble")] pub async fn spawn_ble_peer_runtime( handle: &ReticulumHandle, @@ -7844,20 +7937,26 @@ pub fn teardown_ble_peer_events() { rns_interface::ble_peer::clear_event_dispatcher(); } -/// Stop peripheral (advertising + GATT server), clear dispatcher, deregister. +/// Tear down the current registration at `id` through [`teardown_interface`]. +/// For a BLE Peer registration this stops the process-wide peripheral and +/// clears its event dispatcher, affecting the singleton's users. #[cfg(feature = "ble")] pub async fn teardown_ble_peer_interface(handle: &ReticulumHandle, id: u64) { teardown_interface(handle, id).await; } -/// Stop per-id reconnect loop, then deregister. Per-id (multiple BLE RNode -/// interfaces coexist, each with its own `AtomicBool`); idempotent. +/// Tear down the current registration at `id` through [`teardown_interface`]. +/// Once acquired, cleanup stays bound to that driver rather than looking up +/// a later replacement. Keep the runtime's own id, not an id from a different +/// runtime or a stale registration. #[cfg(feature = "ble")] pub async fn teardown_ble_rnode_interface(handle: &ReticulumHandle, id: u64) { teardown_interface(handle, id).await; } -/// Stop the exact serial/TCP RNode driver before generic deregistration. +/// Stop the current serial/TCP RNode registration through +/// [`teardown_interface`], joining its captured driver before enqueuing +/// deregistration. #[cfg(any(feature = "serial", feature = "rnode-tcp"))] pub async fn teardown_rnode_interface(handle: &ReticulumHandle, id: u64) { teardown_interface(handle, id).await; @@ -8036,6 +8135,13 @@ pub async fn teardown_android_usb_rnode_interface(handle: &ReticulumHandle, id: teardown_interface(handle, id).await; } +/// Start retained cleanup for the current registration selected by `id`. +/// Driver shutdown/join precedes the deregistration command. Cancelling this +/// waiter does not cancel cleanup; the function has no whole-call timeout and +/// returns no cleanup error. If the whole runtime already owns the drain, +/// this can return before that drain finishes; use `shutdown_and_wait` for it. +/// Numeric ids are runtime-local and can be reused; a stale id is not an +/// exact ownership capability. pub async fn teardown_interface(handle: &ReticulumHandle, id: u64) { let transport_tx = handle.transport_tx.clone(); let interface_controls = handle.interface_controls.clone(); @@ -8558,6 +8664,10 @@ async fn spawn_interface_with_rnode_startup_options( } } +/// Return the first successfully initialized runtime retained in the +/// process-wide cell. Later `init` calls still construct separate runtimes; +/// this reference is not replaced or cleared on shutdown. Prefer the handle +/// returned by the initialization call that owns your runtime. pub fn get_instance() -> Option<&'static ReticulumHandle> { INSTANCE.get() } diff --git a/crates/rns-runtime/src/rncp.rs b/crates/rns-runtime/src/rncp.rs index 97cd58b..3ac43f5 100644 --- a/crates/rns-runtime/src/rncp.rs +++ b/crates/rns-runtime/src/rncp.rs @@ -1,5 +1,7 @@ -//! Wire-compatible with Python `RNS.Utilities.rncp`. Supports `-l` (listen), -//! send (default), and `-F` / `-f` (fetch serve / client). +//! File transfer over Reticulum Links and Resources: send, receive and fetch. +//! The default destination aspect is `rncp.receive`. See [`spawn_rncp_listener`] +//! for its current authorization and shutdown limits; a Resource proof alone +//! does not establish that the receiving application saved a file. use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -27,7 +29,7 @@ use tokio::sync::oneshot; use crate::link_manager::{LinkManager, RequestOutcome, ResourceCompletion}; -/// Python `REQ_FETCH_NOT_ALLOWED` sentinel (rncp.py:70). +/// Fetch-denial response byte (`0xF0`). pub const REQ_FETCH_NOT_ALLOWED: u8 = 0xF0; pub const FETCH_PATH_NAME: &str = "fetch_file"; @@ -110,7 +112,8 @@ pub enum RncpEvent { LinkEstablished { link_id: [u8; 16], }, - /// Zero `identity_hash` = remote never identified; only accepted under `allow_all`. + /// An identified sender passed the listener's identity check. The hash is + /// from LinkIdentify; unidentified peers do not emit this event. SenderIdentified { link_id: [u8; 16], identity_hash: [u8; 16], @@ -172,20 +175,33 @@ fn resolve_fetch_path(jail: Option<&Path>, data: &[u8]) -> Result, pub overwrite: bool, - /// Python `-F` / `--allow-fetch`. + /// Serve `fetch_file` requests as well as receiving pushed files. pub allow_fetch: bool, - /// Python `-j` / `--jail`. + /// Optional canonical-path containment check for fetched files. `None` + /// allows any readable path; this is not an OS sandbox or a race-free + /// filesystem boundary. Keep the jail tree under trusted local control. pub fetch_jail: Option, - /// Python default on; `--no-compress` disables. + /// Try compression when serving fetched files; enabled by default. pub fetch_auto_compress: bool, } @@ -214,12 +230,31 @@ impl RncpListenerHandle { pub fn destination_hash(&self) -> [u8; 16] { self.destination_hash } + /// Abort and join the listener's event/file-writing task. The separately + /// spawned LinkManager is not joined or stopped here, and the destination + /// is not deregistered. This is not a complete service shutdown. pub async fn shutdown(self) { self.task.abort(); let _ = self.task.await; } } +/// Register a file receiver and spawn its background tasks. This function +/// does not announce the destination; the caller owns reachability/publication. +/// Drain `events_tx` to avoid blocking completion processing. Fetch reads are +/// synchronous and load the requested file into memory. +/// +/// # Authorization limit +/// +/// The current push path checks peers when they identify, and discards +/// completions from links recorded as denied. It does not require identification +/// before accepting an ordinary Resource, so `allowed` is not a complete push +/// authorization boundary. Do not expose this receiver as an allow-list-enforced +/// file service. Fetch requests do check for an allowed identity unless +/// `allow_all` is enabled. +/// +/// Keep the handle and read [`RncpListenerHandle::shutdown`] before embedding this +/// listener in a longer-lived runtime. pub async fn spawn_rncp_listener( transport_tx: mpsc::Sender, cfg: RncpListenerConfig, @@ -500,6 +535,15 @@ fn build_link_close(link: &mut Link) -> Option { )) } +/// Send an in-memory file and its filename metadata, identifying the local +/// identity on the Link. Success means all Resource segments received valid +/// proofs, followed by a short settlement delay; it does not confirm a remote +/// file write or durable storage. +/// +/// `overall_timeout` covers protocol waits. Transport lookup/admission, +/// settlement and cleanup can extend beyond it; use an outer deadline when +/// the whole call needs a time bound. Progress notifications may be dropped +/// when their channel is full. pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result { let RncpSendRequest { transport_tx, @@ -1107,9 +1151,17 @@ pub struct RncpFetchRequest<'a> { pub progress_tx: Option>, } -/// Fetches a remote file via `rncp --fetch`. Wire flow: -/// link + identify → REQUEST `fetch_file` → ack byte (`0xC3` ok, `0xC2` not -/// found, [`REQ_FETCH_NOT_ALLOWED`] denied) → resource → write to `save_dir`. +/// Fetch a file over a Link, identify the local identity, and request +/// `fetch_file`. Responses use `0xC3` (ready), `0xC2` (unavailable) or +/// [`REQ_FETCH_NOT_ALLOWED`] (denied). A Resource advertisement can arrive +/// before the ready response. +/// +/// Success means the assembled file was written under `save_dir`; the Resource +/// proof is sent before this local write. Writes are not atomic or synced for +/// crash durability. Filename collision handling follows [`RncpListenerConfig`]. +/// `overall_timeout` covers protocol waits, but not all transport admission, +/// cleanup or file I/O. Use an outer deadline when the entire call must finish +/// within a fixed time. pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result { use rns_protocol::resource::{ InboundTransfer, MAX_SEGMENTS, MultiSegmentInbound, TransferAction, diff --git a/crates/rns-runtime/src/rnsh.rs b/crates/rns-runtime/src/rnsh.rs index d99d895..2f97d46 100644 --- a/crates/rns-runtime/src/rnsh.rs +++ b/crates/rns-runtime/src/rnsh.rs @@ -1,4 +1,7 @@ -//! Runtime support for `rnsh`, the Reticulum remote shell utility. +//! Remote command sessions over encrypted Reticulum Links and Channels. +//! Listeners execute processes with the host process's account and filesystem +//! access; they do not create a sandbox. Interactive PTYs require Unix; fully +//! piped stdin/stdout/stderr do not require a PTY. use std::collections::{HashMap, HashSet, VecDeque}; #[cfg(unix)] @@ -86,6 +89,16 @@ impl From for RnshError { } } +/// Client command, input/output channels and terminal options. `command` is +/// an argument vector interpreted under the listener's command policy. `no_id` +/// suppresses LinkIdentify, but this implementation still requires a signing +/// identity locally. +/// +/// When `stdin_rx` is supplied, it replaces `stdin_data`; an empty chunk or +/// channel close means EOF. Without it, `stdin_data` is sent only with +/// `pipe_stdin`. Drain supplied output channels: they apply backpressure, and +/// all received stdout/stderr bytes are also retained in the returned outcome. +/// `timeout` is a protocol deadline, not a bound on every channel/transport wait. pub struct RnshClientConfig { pub identity: Identity, pub destination_hash: [u8; 16], @@ -122,6 +135,20 @@ pub struct RnshClientOutcome { pub return_code: i64, } +/// Command and admission policy for a remote shell listener. With `allow_all` +/// false, a session must identify with a hash in `allowed` or in an identity +/// file before commands are accepted. Identity files are reread on identification; +/// each valid line is a 32-character hex hash. Unreadable files and invalid lines +/// are ignored. `allow_all` also admits unidentified sessions. +/// +/// `command` contains the executable and arguments; no implicit shell is used. +/// `allow_remote_command` permits a client-supplied argument vector to replace +/// it. With `remote_command_as_args`, that vector is appended to the configured +/// command instead, and still requires `allow_remote_command`. +/// +/// `announce_period` is in seconds. `None` disables initial/periodic announces; +/// `Some(0)` sends only the initial one, and positive values enable an interval. +/// Path-request announce responses are independent of that setting. pub struct RnshListenerConfig { pub identity: Identity, pub command: Vec, @@ -133,6 +160,9 @@ pub struct RnshListenerConfig { pub announce_period: Option, } +/// Run a remote command listener until its event streams close or an error +/// occurs. Use `run_rnsh_listener_with_shutdown` for an explicit stop signal. +/// Authorized commands run with this process's privileges. pub async fn run_rnsh_listener( transport_tx: mpsc::Sender, cfg: RnshListenerConfig, @@ -140,6 +170,10 @@ pub async fn run_rnsh_listener( run_rnsh_listener_inner(transport_tx, cfg, None).await } +/// Run a listener that also observes `shutdown` in its event loop. On that +/// path it requests manager shutdown and joins the manager, then drops sessions +/// to signal child cleanup. It does not wait for every child cleanup task or +/// guarantee a shutdown deadline; an awaited handler can delay signal handling. pub async fn run_rnsh_listener_with_shutdown( transport_tx: mpsc::Sender, cfg: RnshListenerConfig, @@ -300,6 +334,15 @@ async fn run_rnsh_listener_inner( Ok(()) } +/// Open a Link, negotiate rnsh and execute one remote command session. Return +/// captured stdout/stderr and the remote exit code; a nonzero exit code is still +/// an `Ok` outcome. Optional output channels receive the same bytes while the +/// received output is retained in memory. +/// +/// The configured timeout applies to protocol waits, but some transport and +/// output-channel operations are awaited without it. Use an outer deadline +/// when the entire call needs a time bound. An error or cancellation is not an +/// acknowledgment that the remote process has stopped. pub async fn rnsh_client_execute( transport_tx: mpsc::Sender, mut cfg: RnshClientConfig, diff --git a/crates/rns-runtime/src/rpc.rs b/crates/rns-runtime/src/rpc.rs index 0487747..1d51bca 100644 --- a/crates/rns-runtime/src/rpc.rs +++ b/crates/rns-runtime/src/rpc.rs @@ -1,12 +1,10 @@ -//! Shared-instance control RPC over TCP. +//! Shared-instance control RPC codecs and clients for TCP loopback or Unix +//! sockets. Frames use Python multiprocessing-compatible lengths and mutual +//! HMAC challenge/response, followed by MessagePack requests and responses. +//! Tagged SHA-256 and legacy MD5 HMAC challenges are supported; pickle is not. //! -//! Python Reticulum uses `multiprocessing.connection.Listener/Client` for the -//! local control port. Keep the Rust control socket wire-compatible with that: -//! framed auth challenge (`#CHALLENGE#`), then framed msgpack request -//! dictionaries and responses, byte-exact with the vendored umsgpack -//! (Python >=1.3.4, commit a2ef9782 — hard cutover from pickle, no fallback). -//! Python 3.12+ uses tagged SHA-256 auth challenges, while Python 3.11 and -//! older use raw MD5 HMAC responses. +//! Authentication proves possession of the shared RPC key. It does not encrypt +//! request/response frames or authenticate the separate packet-IPC socket. use serde::{Deserialize, Serialize}; @@ -81,7 +79,7 @@ pub enum RpcRequest { packet_hash: Vec, }, GetBlackholedIdentities, - /// Python 1.3.8 `is_blackholed()` RPC verb (Reticulum.py:1649-1661). + /// Query whether the transport currently blackholes an identity hash. IsBlackholed { identity_hash: Vec, }, @@ -177,7 +175,9 @@ pub struct InterfaceStatEntry { pub announce_rate_grace: Option, pub announce_rate_penalty: Option, pub announce_cap: f64, - /// Python's IFAC fields, all `None` for an interface without IFAC. + /// IFAC signature supplied by runtime records. IFAC fields can also be + /// `None` when the stats provider has no IFAC records; absence is not proof + /// that the interface has no IFAC protection. #[serde(default)] pub ifac_signature: Option>, #[serde(default)] @@ -187,7 +187,9 @@ pub struct InterfaceStatEntry { pub tx_drops: u64, #[serde(default)] pub tx_dropped_bytes: u64, - /// Python `arxc`/`atxc`/`prxc`/`ptxc`. + /// Count of received announces, encoded as Python-compatible `arxc`. + /// The following sent-announce and received/sent-path-request counters map + /// to `atxc`, `prxc` and `ptxc` respectively. #[serde(default)] pub announces_received: u64, #[serde(default)] @@ -252,11 +254,17 @@ pub fn encode_response(resp: &RpcResponse) -> Result, RpcError> { encode_umsgpack(&response_to_py_value(resp)) } +/// Decode one response by its MessagePack shape. Empty lists are ambiguous +/// and become an empty path table; prefer `decode_response_for_request` when +/// the originating request is known. Trailing bytes are ignored. pub fn decode_response(data: &[u8]) -> Result { let value = decode_umsgpack(data)?; py_value_to_response(&value) } +/// Decode one MessagePack response using the originating request to select +/// its result type, including empty lists and nil values. Trailing bytes are +/// ignored; the caller owns framing and peer authentication. pub fn decode_response_for_request( data: &[u8], request: &RpcRequest, @@ -289,15 +297,17 @@ pub fn compute_legacy_auth_hmac(key: &[u8], challenge: &[u8]) -> [u8; 16] { out } -/// Constant-time comparison; handshake MUST NOT leak via timing. +/// Compare the computed HMAC-SHA-256 with a fixed 32-byte response using +/// constant-time equality. This is not a timing guarantee for an entire RPC session. pub fn verify_auth_hmac(key: &[u8], challenge: &[u8], provided: &[u8; 32]) -> bool { use subtle::ConstantTimeEq; let expected = compute_auth_hmac(key, challenge); expected.ct_eq(provided).into() } -/// Derived from the transport identity so server + local CLI share a secret -/// without extra on-disk state. +/// SHA-256 of the supplied private-key bytes, used as the default shared RPC +/// secret. The caller supplies the correct transport private-key material; +/// this helper does not validate its representation or length. pub fn derive_rpc_key(identity_private_key: &[u8]) -> [u8; 32] { rns_crypto::sha::sha256(identity_private_key) } @@ -1633,6 +1643,8 @@ pub(crate) fn new_python_challenge_for(protocol: PythonAuthProtocol) -> Vec message } +/// Write a signed 32-bit big-endian length followed by the payload. Rejects +/// lengths above `i32::MAX`; this helper imposes no I/O timeout. pub async fn write_mp_frame(stream: &mut S, data: &[u8]) -> Result<(), RpcError> where S: tokio::io::AsyncWrite + Unpin, @@ -1647,6 +1659,9 @@ where stream.write_all(data).await.map_err(RpcError::Io) } +/// Read one multiprocessing frame, accepting the 32-bit length or `-1` +/// followed by a 64-bit length. Reject a length above `max_size` before +/// allocating the payload. The caller supplies any I/O timeout. pub async fn read_mp_frame(stream: &mut S, max_size: usize) -> Result, RpcError> where S: tokio::io::AsyncRead + Unpin, @@ -1683,7 +1698,11 @@ where Ok(data) } -/// Every I/O step is bounded by `timeout` so a stuck daemon never hangs the CLI. +/// Connect to `127.0.0.1:port`, mutually authenticate and issue one request. +/// `timeout` is reapplied to individual connection, handshake and request I/O +/// operations; it is not a total-call deadline. The authentication-failure +/// notification write is currently unbounded. Use an outer timeout when the +/// whole operation needs a deadline. pub async fn connect_and_request( port: u16, rpc_key: &[u8], diff --git a/crates/rns-runtime/src/rpc_server.rs b/crates/rns-runtime/src/rpc_server.rs index 6c7c133..cf37d35 100644 --- a/crates/rns-runtime/src/rpc_server.rs +++ b/crates/rns-runtime/src/rpc_server.rs @@ -1,5 +1,7 @@ -//! Local control port for CLI tools (rnstatus, rnpath). Default 37429. -//! Wire-compatible with Python `multiprocessing.connection`. +//! Local control servers for CLI tools such as `rnstatus-rs` and `rnpath-rs`. +//! TCP binds to IPv4 loopback; Unix sockets are also supported. Connections +//! use mutual RPC-key authentication and framed MessagePack, with a 30-second +//! session budget and up to 64 concurrent clients. RPC frames are not encrypted. use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::TcpListener; @@ -143,8 +145,9 @@ pub(crate) fn stat_entries( .collect() } -/// Serve the control port from a bare transport; interface stats then carry -/// no IFAC fields. +/// Serve a TCP control endpoint on IPv4 loopback using a bare transport. +/// IFAC fields in interface stats are absent because no runtime IFAC records +/// are supplied; that does not establish whether an interface uses IFAC. pub async fn run_rpc_server( port: u16, rpc_key: Vec, @@ -166,8 +169,10 @@ pub(crate) async fn serve_rpc_port( run_rpc_server_with_listener(listener, rpc_key, backend, shutdown).await } -/// Serve the control socket from a bare transport; interface stats then carry -/// no IFAC fields. +/// Serve a Unix control endpoint using a bare transport, without runtime IFAC +/// records in interface stats. A filesystem socket path is removed before +/// binding; supply a path owned by this service. A leading NUL selects an +/// abstract name, supported on Linux and Android. #[cfg(unix)] pub async fn run_unix_rpc_server( socket_path: &str, diff --git a/crates/rns-runtime/src/shared_instance.rs b/crates/rns-runtime/src/shared_instance.rs index ebf7e8b..d33670e 100644 --- a/crates/rns-runtime/src/shared_instance.rs +++ b/crates/rns-runtime/src/shared_instance.rs @@ -1,10 +1,11 @@ //! Explicit local shared-instance admission for applications that require RPC. //! -//! This is an opt-in application policy, not a change to Python-compatible -//! automatic sharing. Packet IPC is not authenticated by upstream's protocol; -//! RPC authenticates the control endpoint, not the identity of a packet socket. -//! Both endpoints must be selected by the caller. Every reconnect revalidates -//! RPC before resuming packet traffic. No local interface fallback is performed. +//! `SharedClient` authenticates the selected control endpoint before packet +//! traffic starts and on every reconnect. The separate packet socket has no +//! cryptographic binding to that RPC authentication. Both endpoints must be +//! selected by the caller; this policy does not fall back to local interfaces. +//! Queued outbound packets are discarded while reconnecting, so higher +//! protocol layers must handle retries. `Configured` retains automatic sharing. use std::path::Path; use std::sync::Arc; @@ -116,7 +117,9 @@ impl std::fmt::Debug for SharedInstanceCredentials { } impl SharedInstanceCredentials { - /// Keys are opaque HMAC bytes, not necessarily the default 32-byte hash. + /// Validate the endpoint and accept 1..=1024 opaque HMAC-key bytes. The key + /// need not be the default 32-byte hash; construction does not contact or + /// authenticate the service. pub fn new( endpoint: SharedInstanceEndpoint, rpc_key: Vec, @@ -138,8 +141,9 @@ impl SharedInstanceCredentials { config.rpc_key = Some(self.rpc_key.to_vec()); } - /// Test packet availability and authenticated interface-status RPC without - /// starting a Reticulum runtime or persisting the credential. + /// Connect to the packet socket, authenticate the control socket and request + /// interface status, then close the connections. This does not exchange a + /// Reticulum packet, start a runtime or persist the credential. pub async fn test(&self) -> Result<(), SharedInstanceError> { self.connect().await.map(|_| ()) } @@ -238,7 +242,7 @@ pub enum SharedInstanceState { Stopped, } -/// Bounded, credential-free shared admission failures. +/// Credential-free shared-admission errors with fixed variants and messages. #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] pub enum SharedInstanceError { #[error("invalid local shared-instance endpoint")] @@ -265,7 +269,7 @@ pub enum SharedInstanceError { ControlBindFailed, } -/// Policy startup errors are additive; the existing `ReticulumError` stays intact. +/// Runtime-initialization or explicit shared-instance admission failure. #[derive(Debug, thiserror::Error)] pub enum InstanceStartupError { #[error(transparent)] diff --git a/crates/rns-tools/src/commands/ifac_migration.rs b/crates/rns-tools/src/commands/ifac_migration.rs index dd2fc5b..9e1967a 100644 --- a/crates/rns-tools/src/commands/ifac_migration.rs +++ b/crates/rns-tools/src/commands/ifac_migration.rs @@ -22,7 +22,8 @@ pub(super) enum ConfigCommand { /// Interpret the selected unmarked sizes using their known original units. #[arg(long = "source-units", value_enum)] units: Units, - /// Publish the previewed conversion with a private immutable backup. + /// Save the original config to a new backup and publish the conversion. + /// The backup includes credentials; protect access to the config directory. #[arg(long = "write")] apply: bool, }, diff --git a/crates/rns-tools/src/commands/rncp.rs b/crates/rns-tools/src/commands/rncp.rs index a4a70b6..835f7bd 100644 --- a/crates/rns-tools/src/commands/rncp.rs +++ b/crates/rns-tools/src/commands/rncp.rs @@ -8,10 +8,12 @@ //! Exit codes: 0 success, 1 generic failure, 2 identity unreadable, //! 3 output dir missing, 4 output dir not writable. //! -//! Security: listener mode follows Python rncp auth semantics. By default it -//! accepts only identities from `-a` or the standard rncp allow-list files. -//! `-n` / `--no-auth` explicitly accepts anyone. Use `-j ` with `-F` -//! unless you intentionally want upstream-compatible unrestricted fetch paths. +//! The current listener checks `-a` and allow-list files when a peer identifies, +//! but does not require identification before receiving a pushed file. Do not +//! rely on the allow-list to exclude unidentified senders. Fetch requests require +//! an allowed identity unless `-n` / `--no-auth` is used. `-F` also leaves push +//! reception enabled. Use `-j ` to constrain fetched paths to a directory +//! under trusted local control; it is not an OS sandbox. use std::path::PathBuf; use std::process; @@ -75,7 +77,8 @@ struct Args { #[arg(short = 'C', long)] no_compress: bool, - /// Allow clients to fetch files from this listener (use -a or -n; -j is recommended) + /// Allow clients to fetch files from this listener (use -a or -n; -j is recommended). + /// Pushed-file reception remains enabled. #[arg(short = 'F', long)] allow_fetch: bool, @@ -84,12 +87,12 @@ struct Args { #[arg(short = 'f', long)] fetch: bool, - /// Restrict fetch requests to the specified directory (absolute path). - /// Used with -F on listener side, or with -f on fetch client side. + /// Restrict served fetch paths to this directory (-l -F only; ignored with -f). + /// Keep the directory under trusted local control; this is not an OS sandbox. #[arg(short = 'j', long, value_name = "path")] jail: Option, - /// Save received files in specified path (listen mode) + /// Save received files in this directory (listen or fetch mode; default: current directory) #[arg(short = 's', long, value_name = "path")] save: Option, @@ -101,7 +104,8 @@ struct Args { #[arg(short = 'b', value_name = "seconds", default_value_t = -1)] announce_interval: i64, - /// Allowed sender identity hash (repeat for multiple). 32 hex chars each. + /// Allowed identity hash (repeat for multiple). 32 hex chars each. + /// The listener does not require identification before accepting pushed files. #[arg(short = 'a', value_name = "hash", action = clap::ArgAction::Append)] allowed: Vec, @@ -117,11 +121,11 @@ struct Args { #[arg(short = 'i', value_name = "identity")] identity_path: Option, - /// Timeout before giving up (seconds) + /// Protocol wait budget in seconds (minimum 1); transport work and file I/O can add time #[arg(short = 'w', value_name = "seconds", default_value_t = DEFAULT_TIMEOUT_SECS)] timeout: f64, - /// Display physical layer transfer rates. + /// Request physical-layer rates (currently unsupported; exits with an error). #[arg(short = 'P', long = "phy-rates")] phy_rates: bool, @@ -580,7 +584,7 @@ async fn run_listen(args: Args) -> ! { }; let allow_all = args.no_auth; if allowed.is_empty() && !allow_all && !args.print_identity { - eprintln!("Warning: No allowed identities configured, rncp will not accept any files!"); + eprintln!("Warning: No allowed identities configured. This listener does not require identification before receiving pushed files; do not rely on the allow-list to exclude unidentified senders."); } let handle = start_reticulum(args.config.as_deref(), shutdown.clone()).await; diff --git a/crates/rns-tools/src/commands/rnid/hw_commands.rs b/crates/rns-tools/src/commands/rnid/hw_commands.rs index fd0a2c1..0322269 100644 --- a/crates/rns-tools/src/commands/rnid/hw_commands.rs +++ b/crates/rns-tools/src/commands/rnid/hw_commands.rs @@ -57,7 +57,7 @@ fn cmd_attest() { Ok(v) => { println!("Slot {label}:"); println!(" chain_verified: {}", v.chain_verified); - println!(" root CA: {}", v.root_ca); + println!(" firmware-derived CA label: {}", v.root_ca); println!(" {}", v.description); all_ok &= v.chain_verified; } @@ -88,13 +88,13 @@ fn cmd_detect() { match rns_ratkey::detect::detect_devices() { Ok(devices) => { if devices.is_empty() { - println!("No compatible hardware tokens found."); - println!("\nSupported devices:"); + println!("No recognized PIV devices found."); + println!("\nReader families checked (capabilities vary):"); println!(" - YubiKey 5 (firmware 5.7.0+)"); println!(" - Nitrokey 3"); println!("\nOn Linux, ensure pcscd is running: sudo systemctl start pcscd"); } else { - println!("Found {} device(s):\n", devices.len()); + println!("Found {} recognized PIV device(s):\n", devices.len()); for (i, dev) in devices.iter().enumerate() { println!(" {}. {} ({})", i + 1, dev.device_type, dev.reader_name); if let Some(serial) = dev.serial { @@ -106,17 +106,17 @@ fn cmd_detect() { println!( " Slot 9A (signing): {}", if dev.has_signing_key { - "occupied" + "metadata available" } else { - "empty" + "metadata unavailable (empty slot or read failure)" } ); println!( " Slot 9D (encryption): {}", if dev.has_encryption_key { - "occupied" + "metadata available" } else { - "empty" + "metadata unavailable (empty slot or read failure)" } ); println!(); @@ -251,7 +251,7 @@ fn cmd_provision( println!(" Ed25519 public: {}", hex::encode(ed_pub)); println!(" X25519 public: {}", hex::encode(x_pub)); println!(" Device: {}", session.device_type().as_str()); - println!(" Attestation: chain_verified={}", attestation.verified); + println!(" Ed25519 attestation chain verified: {}", attestation.verified); if let Some(dir) = output { let identity_dir = dir.join(&hash_hex); @@ -299,8 +299,8 @@ fn cmd_provision( } } - println!("\nWARNING: No backup exists. If you lose this device, this identity"); - println!("is gone forever. Run `rnid-rs hw backup` to create a backup."); + println!("\nNo private-key backup was created. Losing this token can make the identity unusable."); + println!("This utility has no command to export or back up these on-device keys."); } fn cmd_list(dir: Option) { @@ -357,7 +357,7 @@ fn cmd_info(hwid_path: PathBuf) { } }; - println!("Hardware Identity Information:"); + println!("Saved Hardware Identity Metadata:"); println!(" Hash: {}", config.identity.hash); println!( " Nickname: {}", @@ -372,7 +372,7 @@ fn cmd_info(hwid_path: PathBuf) { config.identity.created_at ); println!(); - println!("Device:"); + println!("Device (saved metadata):"); println!(" Type: {}", config.device.device_type); println!(" Serial: {}", config.device.serial); println!(" Firmware: {}", config.device.firmware); @@ -385,7 +385,7 @@ fn cmd_info(hwid_path: PathBuf) { println!(" Signing: {}", config.slots.signing); println!(" Encryption: {}", config.slots.encryption); println!(); - println!("Policy:"); + println!("Policy (saved metadata):"); println!(" PIN cache: {}s", config.policy.pin_cache_timeout); println!(" Touch (sign): {}", config.policy.touch_signing); println!(" Touch (encrypt): {}", config.policy.touch_encryption); @@ -394,11 +394,11 @@ fn cmd_info(hwid_path: PathBuf) { println!(" Tier: {}", config.backup.tier); if !config.attestation.ed25519_cert.is_empty() { println!( - " Attestation: chain_verified={}", + " Saved Ed25519 attestation flag: {} (not verified by this command)", config.attestation.verified ); } else { - println!(" Attestation: (none)"); + println!(" Saved attestation: (none)"); } } @@ -464,9 +464,9 @@ fn cmd_verify(hwid_path: PathBuf) { } if ok { - println!("\nVerified: connected token matches this .hwid."); + println!("\nVerified: slot 9A/9D public keys match this .hwid."); } else { - println!("\nVerification FAILED: token does not match this .hwid."); + println!("\nPublic-key comparison failed; see the slot results above."); std::process::exit(1); } } diff --git a/crates/rns-tools/src/commands/rnid/main.rs b/crates/rns-tools/src/commands/rnid/main.rs index c4e5b3d..f7596e9 100644 --- a/crates/rns-tools/src/commands/rnid/main.rs +++ b/crates/rns-tools/src/commands/rnid/main.rs @@ -59,11 +59,11 @@ struct Args { #[arg(short = 'g', long)] generate: Option, - /// Import public Identity data in hex, base32 or base64 format, or from file. + /// Import 64 public-key bytes from a raw file, hex, base32 or URL-safe base64. #[arg(short = 'm', long = "import-pub", value_name = "identity_data")] import_pub: Option, - /// Import private Identity data in hex, base32 or base64 format, or from file. + /// Import 64 private-key bytes from a raw file, hex, base32 or URL-safe base64. #[arg( short = 'M', long = "import-prv", @@ -94,7 +94,7 @@ struct Args { #[arg(short = 'q', long, action = clap::ArgAction::Count)] quiet: u8, - /// Announce a destination based on this Identity. + /// Queue a destination announce for this private Identity (default aspects: rns.id). #[arg(short = 'a', long, num_args = 0..=1, default_missing_value = DEFAULT_ASPECTS)] announce: Option, @@ -114,27 +114,29 @@ struct Args { #[arg(short = 's', long, num_args = 0.., value_name = "path")] sign: Option>, - /// Validate signature. + /// Validate an RSG signature or RSM signed message. Use --identity to require a particular signer. #[arg(short = 'V', long = "validate", num_args = 0.., value_name = "path")] validate: Option>, - /// Create embedded signed message. + /// Sign embedded message text, a --read file, or editor input if neither is supplied. + /// Binary output requires --write; an encoding option prints an armored message. #[arg(short = 'S', long = "sign-message", num_args = 0..=1, value_name = "text")] sign_message: Option>, - /// Embed metadata structure from file. + /// Embed metadata from a file with --sign-message. #[arg(short = 'E', long = "embed-meta", value_name = "path")] embed_meta: Option, - /// Validate metadata for embedding with spec from file. + /// Metadata specification for --sign-message/--embed-meta; defaults to .spec. + /// A missing specification file skips validation, including when an explicit path is supplied. #[arg(long = "meta-spec", num_args = 0..=1, value_name = "path")] meta_spec: Option>, - /// Sign raw input data instead of hashing first. + /// With --sign, sign file bytes directly instead of an RSG envelope containing the file hash. #[arg(long)] raw: bool, - /// Input file path for operations with optional file input. + /// UTF-8 input file for --sign-message; cannot be combined with inline message text. #[arg(short = 'r', long, value_name = "path")] read: Option, @@ -146,39 +148,40 @@ struct Args { #[arg(short = 'f', long)] force: bool, - /// Request unknown Identities from the network. + /// Request an unknown --identity hash from the network (unless --no-cache is set). #[arg(short = 'R', long = "request")] request: bool, - /// Never use cached or network-sourced information. + /// Skip cached/network resolution of --identity; explicit identity files and imports still work. #[arg(short = 'N', long = "no-cache")] no_cache: bool, - /// Identity request timeout before giving up. + /// Identity-request polling budget in seconds after requests are submitted. + /// Runtime startup and awaited transport queries can add time. #[arg(short = 't', value_name = "seconds", default_value_t = rns_transport::constants::PATH_REQUEST_TIMEOUT)] timeout: f64, - /// Print identity info and exit. + /// Print identity information; other selected operations may still run. #[arg(short = 'p', long = "print-identity")] print_identity: bool, - /// Allow displaying private keys. + /// Include private keys in --print-identity output; --export-prv has its own output. #[arg(short = 'P', long = "print-private")] print_private: bool, - /// Use base64-encoded input and output. + /// Use URL-safe base64 for key display/export and armored signature/message output. #[arg(short = 'b', long)] base64: bool, - /// Use base32-encoded input and output. + /// Use base32 for key display/export and armored signature/message output. #[arg(short = 'B', long)] base32: bool, - /// Use base256-encoded input and output. + /// Use base256 for armored signature/message output; key display/export stays hexadecimal. #[arg(short = 'U', long)] base256: bool, - /// Use hex-encoded input and output. + /// Use hexadecimal key display/export and armored signature/message output. #[arg(short = 'F', long)] hex: bool, @@ -190,11 +193,11 @@ struct Args { #[arg(long)] version: bool, - /// Parsed for Python CLI parity. + /// Compatibility flag; file operations still read their named paths. #[arg(short = 'I', long = "stdin", hide = true)] stdin: bool, - /// Parsed for Python CLI parity. + /// Compatibility flag; file operations still write their named paths. #[arg(short = 'O', long = "stdout", hide = true)] stdout: bool, } @@ -202,35 +205,52 @@ struct Args { #[cfg(feature = "hardware")] #[derive(Subcommand)] enum HwCommands { + /// List recognized PC/SC PIV readers and metadata availability; this is not a capability test. Detect, + /// Generate Ed25519/X25519 keys in slots 9A/9D of the selected token. + /// This writes the slots without an overwrite confirmation; existing keys can be replaced. + /// Use --output to save public .hwid metadata; no hardware-key backup is created. Provision { + /// Current token PIN, required by this command; no interactive PIN prompt. #[arg(long)] pin: Option, + /// Nickname stored in the optional .hwid output. #[arg(short, long)] nickname: Option, + /// Output directory; writes /identity.hwid. Omit to save no file. #[arg(short, long)] output: Option, /// PIV management key (hex). Defaults to the factory key. #[arg(long)] mgmt_key: Option, }, + /// List saved identity.hwid files in the immediate subdirectories of --dir. List { + /// Parent directory of identity folders; required by the command. #[arg(short, long)] dir: Option, }, + /// Show saved .hwid metadata without contacting a token or verifying attestation. Info { + /// Path to a saved public .hwid metadata file. hwid: PathBuf, }, + /// Compare the token's 9A/9D public keys with a .hwid file; no signing or attestation test. Verify { + /// Path to a saved public .hwid metadata file. hwid: PathBuf, }, + /// Test signing, X25519 agreement and decryption against a .hwid identity; requires --pin. Test { + /// Path to a saved public .hwid metadata file. hwid: PathBuf, + /// Current token PIN, required by this command; no interactive PIN prompt. #[arg(long)] pin: Option, }, /// Fetch the on-card attestation (slots 9A/9D + device F9) and verify the /// certificate chain to a bundled Yubico root. No PIN required. + /// Checks certificate signatures and validity, not revocation or binding to an expected identity. Attest, } diff --git a/crates/rns-tools/src/commands/rnodeconf.rs b/crates/rns-tools/src/commands/rnodeconf.rs index 9aa2cea..d6c13a7 100644 --- a/crates/rns-tools/src/commands/rnodeconf.rs +++ b/crates/rns-tools/src/commands/rnodeconf.rs @@ -1,8 +1,8 @@ //! rnodeconf-rs - RNode configuration and firmware utility. //! -//! The safe inspection/configuration paths are implemented first. Firmware -//! flashing, ROM bootstrap, and full signing-key management remain -//! hardware-gated work. +//! Supports inspection, EEPROM backup, and saved TNC/normal startup configuration. +//! Firmware installation, signing/trust enrollment, and Bluetooth, Wi-Fi, +//! display and interference-avoidance mutations are disabled in this build. use std::fs; use std::path::PathBuf; @@ -56,121 +56,175 @@ use session::{FrameSession, SerialFrameSession}; disable_version_flag = true )] struct Args { + /// Read device identification, firmware version and EEPROM summary. #[arg(short = 'i', long)] info: bool, + /// Unavailable: firmware installation is not implemented. #[arg(short = 'a', long)] autoinstall: bool, + /// Unavailable: firmware updating is not implemented. #[arg(short = 'u', long)] update: bool, + /// Unavailable: firmware updating is not implemented. #[arg(short = 'U', long = "force-update")] force_update: bool, + /// Unavailable: firmware selection/planning is not implemented. #[arg(long = "fw-version")] fw_version: Option, + /// Unavailable: firmware download/planning is not implemented. #[arg(long = "fw-url")] fw_url: Option, + /// Unavailable: firmware planning options are not implemented. #[arg(long)] nocheck: bool, + /// Unavailable: firmware extraction is not implemented. #[arg(short = 'e', long)] extract: bool, + /// Unavailable: flashing extracted firmware is not implemented. #[arg(short = 'E', long = "use-extracted")] use_extracted: bool, + /// Remove and recreate the local update and extracted-cache directories, then exit. #[arg(short = 'C', long = "clear-cache")] clear_cache: bool, + /// Reserved flashing baud rate; non-default values are rejected and flashing is disabled. #[arg(long = "baud-flash", default_value = "921600")] baud_flash: String, + /// Delete the saved TNC startup configuration and check EEPROM readback. #[arg(short = 'N', long)] normal: bool, + /// Apply and save a complete RF tuple; requires --freq, --bw, --sf, --cr and --txp. #[arg(short = 'T', long)] tnc: bool, + /// Unavailable: Bluetooth mutations are disabled. #[arg(short = 'b', long = "bluetooth-on")] bluetooth_on: bool, + /// Unavailable: Bluetooth mutations are disabled. #[arg(short = 'B', long = "bluetooth-off")] bluetooth_off: bool, + /// Unavailable: Bluetooth mutations are disabled. #[arg(short = 'p', long = "bluetooth-pair")] bluetooth_pair: bool, + /// Unavailable: Wi-Fi mode mutations are disabled. #[arg(short = 'w', long = "wifi")] wifi: Option, + /// Unavailable: Wi-Fi channel mutations are disabled. #[arg(long)] channel: Option, + /// Unavailable: Wi-Fi SSID mutations are disabled. #[arg(long)] ssid: Option, + /// Unavailable: Wi-Fi password mutations are disabled. #[arg(long)] psk: Option, + /// Include password bytes in the configuration-sector hex dump; requires --config. #[arg(long = "show-psk")] show_psk: bool, + /// Unavailable: Wi-Fi IP address mutations are disabled. #[arg(long)] ip: Option, + /// Unavailable: Wi-Fi netmask mutations are disabled. #[arg(long)] nm: Option, + /// Unavailable: display mutations are disabled. #[arg(short = 'D', long = "display")] display: Option, + /// Unavailable: display-timeout mutations are disabled; this is not a command timeout. #[arg(short = 't', long = "timeout")] timeout: Option, + /// Unavailable: display-rotation mutations are disabled. #[arg(short = 'R', long = "rotation")] rotation: Option, + /// Unavailable: display-address mutations are disabled. #[arg(long = "display-addr")] display_addr: Option, + /// Unavailable: display reconditioning is disabled. #[arg(long = "recondition-display")] recondition_display: bool, + /// Unavailable: NeoPixel mutations are disabled. #[arg(long = "np")] neopixel: Option, + /// RF centre frequency in hertz; requires the complete --tnc tuple. #[arg(long = "freq")] freq: Option, + /// RF bandwidth in hertz; requires the complete --tnc tuple. #[arg(long = "bw")] bandwidth: Option, + /// Requested TX power in dBm; requires the complete --tnc tuple. #[arg(long = "txp")] tx_power: Option, + /// LoRa spreading factor; requires the complete --tnc tuple. #[arg(long = "sf")] spreading_factor: Option, + /// LoRa coding-rate denominator (5 means 4/5); requires the complete --tnc tuple. #[arg(long = "cr")] coding_rate: Option, + /// Unavailable: interference-avoidance mutations are disabled. #[arg(short = 'x', long = "ia-enable")] ia_enable: bool, + /// Unavailable: interference-avoidance mutations are disabled. #[arg(short = 'X', long = "ia-disable")] ia_disable: bool, + /// Read the configuration sector as hex, with password bytes redacted by default. #[arg(short = 'c', long = "config")] config: bool, + /// Read EEPROM and save a timestamped .eeprom file in the local rnodeconf data directory. #[arg(long = "eeprom-backup")] eeprom_backup: bool, + /// Read EEPROM and print its raw hex bytes and summary. #[arg(long = "eeprom-dump")] eeprom_dump: bool, + /// Unavailable: EEPROM wiping is disabled until provisioning is implemented. #[arg(long = "eeprom-wipe")] eeprom_wipe: bool, + /// Unavailable: signing-key management is not implemented. #[arg(short = 'P', long = "public")] public: bool, + /// Unavailable: trusted-key enrollment is disabled. #[arg(long = "trust-key")] trust_key: Option, + /// Print the utility version and exit. #[arg(long)] version: bool, + /// Unavailable: firmware flashing is not implemented. #[arg(short = 'f', long)] flash: bool, + /// Unavailable: ROM bootstrap is not implemented. #[arg(short = 'r', long)] rom: bool, + /// Unavailable: signing-key management is not implemented. #[arg(short = 'k', long)] key: bool, + /// Unavailable: signing/provisioning is not implemented. #[arg(short = 'S', long)] sign: bool, + /// Unavailable: writing device trust state is disabled. #[arg(short = 'H', long = "firmware-hash")] firmware_hash: Option, + /// Read the device-reported target firmware hash. #[arg(short = 'K', long = "get-target-firmware-hash", hide = true)] get_target_firmware_hash: bool, + /// Read the device-reported firmware hash. #[arg(short = 'L', long = "get-firmware-hash", hide = true)] get_firmware_hash: bool, + /// Unavailable: firmware platform selection is not implemented. #[arg(long)] platform: Option, + /// Unavailable: firmware product selection is not implemented. #[arg(long)] product: Option, + /// Unavailable: firmware model selection is not implemented. #[arg(long)] model: Option, + /// Unavailable: firmware hardware-revision selection is not implemented. #[arg(long)] hwrev: Option, diff --git a/crates/rns-tools/src/commands/rnpath.rs b/crates/rns-tools/src/commands/rnpath.rs index a095210..31347ad 100644 --- a/crates/rns-tools/src/commands/rnpath.rs +++ b/crates/rns-tools/src/commands/rnpath.rs @@ -36,7 +36,7 @@ use rns_tools::RS_RETICULUM_VERSION; disable_version_flag = true )] struct Args { - /// Destination hash to request a path to. + /// Destination hash for a path request or table/rate filter; with -p, the remote transport hash. destination: Option, /// Show the full path table. @@ -67,7 +67,7 @@ struct Args { #[arg(short, long)] blackholed: bool, - /// View published blackhole list for remote transport instance. + /// View a remote transport's published blackhole list; supply its hash as DESTINATION or with -R. #[arg(short = 'p', long = "blackholed-list")] blackholed_list: bool, @@ -87,7 +87,8 @@ struct Args { #[arg(long)] reason: Option, - /// JSON output (machine-readable). + /// Print table and list results as JSON. + /// Known limitation: interface names and blackhole reasons are not fully JSON-escaped. #[arg(short, long)] json: bool, @@ -96,20 +97,21 @@ struct Args { config: Option, /// Remote transport hash (32 hex chars). Query that node over Reticulum. - /// Only `--table` and `--rates` are supported in remote mode; mutations - /// are local-only. + /// Remote management supports --table and --rates; -p queries the published + /// blackhole list instead. Mutations are local-only. #[arg(short = 'R', long = "remote")] remote: Option, - /// Identity file for remote authentication (used with `-R`). + /// Identity for remote authentication (required for -R management; optional with -p). #[arg(short = 'i', long)] identity: Option, - /// Seconds to wait for local shared-instance responses. + /// Local RPC wait in seconds; also sets path-request wait and the remote-query fallback. + /// Defaults without this option: 5 seconds for local RPC, 15 for path requests, 30 remote. #[arg(short = 'w', long)] timeout: Option, - /// Seconds to wait for remote management responses. + /// Remote query protocol budget in seconds; overrides -w. Transport work can add time. #[arg(short = 'W', long = "remote-timeout")] remote_timeout: Option, @@ -121,7 +123,7 @@ struct Args { #[arg(short, action = clap::ArgAction::Count)] verbose: u8, - /// Filter for remote blackhole list view. + /// Case-sensitive substring in identity, reason or source for the remote blackhole list. list_filter: Option, } diff --git a/crates/rns-tools/src/commands/rnprobe.rs b/crates/rns-tools/src/commands/rnprobe.rs index 92a6aa4..d2735d5 100644 --- a/crates/rns-tools/src/commands/rnprobe.rs +++ b/crates/rns-tools/src/commands/rnprobe.rs @@ -24,7 +24,7 @@ struct Args { #[arg(long)] config: Option, - /// Size of probe packet payload in bytes + /// Plaintext probe payload size in bytes (default: 16) #[arg(short = 's', long)] size: Option, @@ -32,15 +32,17 @@ struct Args { #[arg(short = 'n', long, default_value_t = 1)] probes: u32, - /// Timeout before giving up (seconds) + /// Seconds to wait separately for a path and each probe proof. + /// Default: 12 seconds plus the first-hop timeout; transport work can add time. #[arg(short = 't', long, value_name = "seconds")] timeout: Option, - /// Time between each probe (seconds) + /// Delay after one probe completes before starting the next (seconds) #[arg(short = 'w', long, default_value_t = 0.0, value_name = "seconds")] wait: f64, - /// Output one JSON object per probe to stdout (machine-readable) + /// Print probe results as JSON; some fatal errors are reported only on stderr. + /// Known limitation: destination and interface names are not JSON-escaped. #[arg(long)] json: bool, diff --git a/crates/rns-tools/src/commands/rnsd.rs b/crates/rns-tools/src/commands/rnsd.rs index cd23403..de542b4 100644 --- a/crates/rns-tools/src/commands/rnsd.rs +++ b/crates/rns-tools/src/commands/rnsd.rs @@ -127,19 +127,21 @@ struct Args { #[arg(long, short = 'c', hide_short_help = true)] config: Option, - /// Increase verbosity. + /// Increase verbosity (repeatable; ignored with --service). #[arg(short = 'v', long, action = clap::ArgAction::Count)] verbose: u8, - /// Decrease verbosity. + /// Decrease verbosity (repeatable; ignored with --service). #[arg(short = 'q', long, action = clap::ArgAction::Count)] quiet: u8, - /// Run as service and log to `/logfile`. + /// Log to `/logfile` using the configured log level. + /// The process remains in the foreground. #[arg(short = 's', long)] service: bool, - /// Drop into an interactive shell after initialisation. + /// Open the built-in status console after initialisation. + /// Supports the listed status names, not arbitrary shell or Python commands. #[arg(short = 'i', long)] interactive: bool, diff --git a/crates/rns-tools/src/commands/rnsh.rs b/crates/rns-tools/src/commands/rnsh.rs index 572f583..4a3b485 100644 --- a/crates/rns-tools/src/commands/rnsh.rs +++ b/crates/rns-tools/src/commands/rnsh.rs @@ -38,43 +38,61 @@ const IDENTITY_HASH_HEX_LEN: usize = 32; after_help = "When specifying a command to execute, separate rnsh-rs options from the command and its arguments with --\n\nFor example:\n rnsh-rs -l -- /bin/bash --login\n rnsh-rs -- ls -la /tmp" )] struct Args { + /// Alternative Reticulum config directory. #[arg(short = 'c', long = "config")] config: Option, + /// Identity file to load or create; overrides the default stored identity. #[arg(short = 'i', long = "identity")] identity: Option, + /// Increase log verbosity (repeatable). #[arg(short = 'v', long = "verbose", action = ArgAction::Count)] verbose: u8, + /// Decrease log verbosity (repeatable). #[arg(short = 'q', long = "quiet", action = ArgAction::Count)] quiet: u8, + /// Print identity information and exit; creates the identity if absent. #[arg(short = 'p', long = "print-identity")] print_identity: bool, + /// Print version and exit. #[arg(long = "version")] version: bool, + /// Listen for remote commands using this process's privileges. #[arg(short = 'l', long = "listen")] listen: bool, + /// Listener identity suffix (default: default); keeps only ASCII letters, digits and underscores. #[arg(short = 's', long = "service")] service: Option, + /// Listener announce interval in seconds; 0 announces once, omitted disables scheduled announces. #[arg(short = 'b', long = "announce", value_name = "PERIOD")] announce: Option, + /// Listener: allow this client identity hash (32 hex characters); repeat for multiple clients. #[arg(short = 'a', long = "allowed", value_name = "HASH")] allowed: Vec, + /// Listener: accept clients without identity authorization. #[arg(short = 'n', long = "no-auth")] no_auth: bool, + /// Listener: append the remote argument vector to the configured command. #[arg(short = 'A', long = "remote-command-as-args")] remote_command_as_args: bool, + /// Listener: reject client-supplied commands; run the configured command only. #[arg(short = 'C', long = "no-remote-command")] no_remote_command: bool, + /// Client: do not identify to the listener; a local identity is still loaded or created. #[arg(short = 'N', long = "no-id")] no_id: bool, + /// Return the remote exit code clamped to 0-255; otherwise completed sessions return 0. #[arg(short = 'm', long = "mirror")] mirror: bool, + /// Client protocol wait budget in seconds (default: 15, minimum: 1); I/O can add time. #[arg(short = 'w', long = "timeout", value_name = "SECONDS")] timeout: Option, + /// Remote rnsh destination hash (32 hex characters); omit in listen mode. destination: Option, + /// Command and arguments after --; in listen mode this sets the default command (otherwise the local shell). #[arg(last = true)] command: Vec, } diff --git a/crates/rns-tools/src/commands/rnstatus.rs b/crates/rns-tools/src/commands/rnstatus.rs index 3a799a7..94059a5 100644 --- a/crates/rns-tools/src/commands/rnstatus.rs +++ b/crates/rns-tools/src/commands/rnstatus.rs @@ -36,7 +36,7 @@ use rns_tools::RS_RETICULUM_VERSION; disable_version_flag = true )] struct Args { - /// Show all interfaces (including internal / disabled). + /// Include internal and peer interface entries normally hidden. #[arg(short, long)] all: bool, @@ -52,7 +52,7 @@ struct Args { #[arg(short, long)] link_stats: bool, - /// Only show interfaces with active announce or path request bursts. + /// Show interfaces with active announce or path request bursts, plus FILTER matches. #[arg(short = 'B', long)] burst: bool, @@ -101,7 +101,7 @@ struct Args { #[arg(short = 'm', long)] monitor: bool, - /// Refresh interval for monitor mode, in seconds. + /// Target monitor refresh interval in seconds; each refresh sleeps at least 0.2 seconds. #[arg(short = 'I', long = "monitor-interval", default_value_t = 1.0)] monitor_interval: f64, @@ -109,7 +109,7 @@ struct Args { #[arg(long)] version: bool, - /// Increase verbosity (info level by default; `-vv` for debug). + /// Increase verbosity (default: warnings; -v for info, -vv for debug). #[arg(short, action = clap::ArgAction::Count)] verbose: u8, @@ -117,7 +117,7 @@ struct Args { #[arg(short, action = clap::ArgAction::Count)] quiet: u8, - /// Only display interfaces with names including this filter. + /// Case-insensitive interface-name substring; with --burst, also include matching interfaces. filter: Option, } diff --git a/crates/rns-tools/src/format.rs b/crates/rns-tools/src/format.rs index 77fa2dc..addb34c 100644 --- a/crates/rns-tools/src/format.rs +++ b/crates/rns-tools/src/format.rs @@ -1,5 +1,9 @@ -//! Python ref: `RNS/__init__.py` (`prettyspeed`, `prettysize`, `prettytime`). +//! Human-readable CLI formatting for byte counts, bit rates, elapsed time, +//! frequencies and hexadecimal values. Size/rate prefixes use powers of 1000. +//! Python reference functions: `prettyspeed`, `prettysize` and `prettytime` +//! in `RNS/__init__.py`; this module defines its own output precision/layout. +/// Format bytes with decimal prefixes (`1000` becomes `1.00 KB`, not `KiB`). pub fn pretty_size(num: u64) -> String { let units = ["", "K", "M", "G", "T", "P", "E", "Z"]; let mut val = num as f64; @@ -16,6 +20,7 @@ pub fn pretty_size(num: u64) -> String { format!("{val:.2}YB") } +/// Format bits per second with decimal prefixes. Convert byte rates before calling. pub fn pretty_speed(bps: u64) -> String { let units = ["", "K", "M", "G", "T", "P", "E", "Z"]; let mut val = bps as f64; @@ -32,6 +37,8 @@ pub fn pretty_speed(bps: u64) -> String { format!("{val:.2}Ybps") } +/// Format finite seconds using seconds, minutes/seconds, hours/minutes or +/// days/hours. Fractional seconds are truncated; negative input returns `unknown`. pub fn pretty_time(seconds: f64) -> String { if seconds < 0.0 { return "unknown".to_string(); diff --git a/crates/rns-tools/src/hash.rs b/crates/rns-tools/src/hash.rs index c41279b..60991ab 100644 --- a/crates/rns-tools/src/hash.rs +++ b/crates/rns-tools/src/hash.rs @@ -1,4 +1,6 @@ -/// Accepts `aabbcc...` or `aa:bb:cc:...`; must decode to 16 bytes. +/// Trim surrounding whitespace, remove colons, and decode exactly 16 bytes +/// of hex. This checks representation and length, not a destination's identity +/// or application binding; angle brackets and a `0x` prefix are not accepted. pub fn parse_dest_hash(input: &str) -> Result<[u8; 16], String> { let clean = input.trim().replace(':', ""); let bytes = hex::decode(&clean).map_err(|e| format!("invalid hex: {e}"))?; diff --git a/crates/rns-tools/src/lib.rs b/crates/rns-tools/src/lib.rs index 8b1ab59..8dcfc24 100644 --- a/crates/rns-tools/src/lib.rs +++ b/crates/rns-tools/src/lib.rs @@ -6,13 +6,14 @@ pub mod hash; /// rsReticulum package version printed by CLI `--version` output. pub const RS_RETICULUM_VERSION: &str = env!("CARGO_PKG_VERSION"); -/// Python Reticulum release baseline exposed by compatibility-oriented CLI -/// surfaces such as the `rnsd-rs` interactive console. +/// Python compatibility-baseline label used by selected CLI surfaces, +/// including the `rnsd-rs` interactive console. It is distinct from this +/// package's release version and is not a Python installation requirement. pub const RETICULUM_COMPAT_VERSION: &str = "1.4.2"; -/// Python 1.3.2 `[logging] logtimestamps` (Reticulum.py:459-461, -/// RNS/__init__.py:85 default True): whether log lines carry a timestamp -/// prefix. Read pre-init from the config file, like the loglevel. +/// Read `[logging] logtimestamps` from `/config` before tracing +/// initialization. Returns true when the file cannot be read/parsed or the +/// setting is absent or not a recognized boolean. pub fn config_log_timestamps(config_dir: &std::path::Path) -> bool { rns_runtime::config::Config::from_file(&config_dir.join("config")) .ok() @@ -20,8 +21,10 @@ pub fn config_log_timestamps(config_dir: &std::path::Path) -> bool { .unwrap_or(true) } -/// Shared tracing-subscriber setup for the CLI binaries; omits the timestamp -/// field when `logtimestamps` is disabled (Python RNS.log parity). +/// Attempt to install the CLI's global tracing subscriber with the supplied +/// level, timestamp, ANSI and writer settings. A false `timestamps` omits the +/// time field. Initialization failure is ignored, so an existing global +/// subscriber is left in place. pub fn init_tracing(level: tracing::Level, timestamps: bool, ansi: bool, writer: W) where W: for<'a> tracing_subscriber::fmt::MakeWriter<'a> + Send + Sync + 'static, diff --git a/crates/rns-transport/src/actor/announce_admission.rs b/crates/rns-transport/src/actor/announce_admission.rs index 4624652..101385f 100644 --- a/crates/rns-transport/src/actor/announce_admission.rs +++ b/crates/rns-transport/src/actor/announce_admission.rs @@ -97,7 +97,8 @@ impl TransportActor { ); } - /// Additive finite local-announcement admission lane. Obtain before run. + /// Obtain a handle to the bounded local-announcement admission queue before + /// moving this actor into `run`. The handle does not start actor processing. pub fn announce_dispatch_handle(&self) -> crate::announce_dispatch::AnnounceDispatchHandle { crate::announce_dispatch::AnnounceDispatchHandle { tx: self.announce_dispatch_tx.clone(), diff --git a/crates/rns-transport/src/actor/mod.rs b/crates/rns-transport/src/actor/mod.rs index 77dbb5f..3fd32af 100644 --- a/crates/rns-transport/src/actor/mod.rs +++ b/crates/rns-transport/src/actor/mod.rs @@ -75,10 +75,14 @@ struct LinkEndpointQueuedPacket { completion: Option, } -/// Owns every routing table and drains the `TransportMessage` channel in one -/// task. The single-owner model means the hot path has no shared state and no -/// locks — callers drive the actor by sending typed commands rather than -/// reaching into the tables directly. +/// Owns transport routing tables and processes mailbox/control-channel work +/// on one task. Configure it before calling `run`; use commands and replies +/// for running operations. Public table mutations do not automatically perform +/// command-side housekeeping, mark persistence dirty or refresh shared snapshots. +/// +/// Driver counters, the blackhole snapshot and background persistence state +/// use shared atomics or locks. Sequential command handling is not a claim +/// that the entire transport has no shared state or locking. pub struct TransportActor { rx: mpsc::Receiver, announce_dispatch_tx: mpsc::Sender, @@ -101,8 +105,8 @@ pub struct TransportActor { pub path_table: PathTable, pub link_table: LinkTable, pub announce_table: AnnounceTable, - /// Python `held_announces`: normal queued announces temporarily displaced - /// while a known-path response occupies `announce_table`. + /// Queued announces temporarily displaced while a known-path response + /// occupies `announce_table`. pub held_announces: HashMap<[u8; 16], crate::announce::AnnounceEntry>, pub reverse_table: ReverseTable, pub tunnel_table: TunnelTable, @@ -110,18 +114,20 @@ pub struct TransportActor { pub rate_table: RateTable, pub blackhole_table: BlackholeTable, pub traffic: TrafficCounter, + /// Optional driver observations keyed by packet hash. Actor insertion keeps + /// at most 512 entries; metrics are not normalized or independently validated. pub packet_metrics: HashMap<[u8; 32], PacketMetrics>, pub packet_metrics_order: VecDeque<[u8; 32]>, pub receipt_table: HashMap<[u8; 16], PacketReceipt>, - /// Truncated packet hash → LXMF msg_id for pairing delivery proofs back - /// to their originating outbound message. + /// Truncated packet hash to caller-supplied message ID for proof notifications. pub receipt_msg_ids: HashMap<[u8; 16], String>, - /// Direct application proof sinks for receipt owners that cannot tolerate - /// loss through the legacy bounded destination-event fan-out. + /// Unbounded direct application proof sinks. They avoid bounded destination + /// mailbox pressure, but a closed receiver still loses its notification. pub receipt_proof_txs: HashMap<[u8; 16], mpsc::UnboundedSender>, - /// Direct per-send receipt observers used by the high-level runtime API. + /// Latest per-send receipt state for runtime observers. Watch receivers can + /// skip intermediate updates; this is not an event log. pub receipt_updates: HashMap<[u8; 16], tokio::sync::watch::Sender>, @@ -144,28 +150,29 @@ pub struct TransportActor { pub path_requests: HashMap<[u8; 16], f64>, // One canonical owner; detached public snapshots cannot mutate registrations. discovery_path_requests: HashMap<[u8; 16], recursive_discovery::DiscoveryOperation>, - /// Python `discovery_pr_tags`: destination hash plus truncated path-request tag. + /// Destination hash plus truncated request tag, mapped to observation time + /// in Unix seconds for duplicate-request admission. pub discovery_pr_tags: HashMap, f64>, - /// Python `pending_discovery_prs`: failed-link rediscovery requests queued - /// for throttled emission. + /// Failed-Link rediscovery requests awaiting throttled emission. pub pending_discovery_prs: VecDeque, // Only rejected driver admissions live here; successfully admitted targets // are never replayed by this owner. The public discovery records stay ABI/API // compatible and continue to describe operation scheduling, not radio TX. pending_path_request_admissions: VecDeque, - /// Destination/interface pairs temporarily barred from installing paths. - /// Used when a Direct LinkRequest timed out on one route, so the next - /// path request can discover alternates instead of instantly reusing it. + /// Destination/interface pairs barred from new path installation until their + /// Unix-seconds deadline. Suppression does not remove an existing path or + /// guarantee discovery of an alternative. pub path_interface_suppressions: HashMap<([u8; 16], InterfaceId), f64>, last_discovery_pr_tx: f64, /// External interface waiting for a path response from a local shared client. - /// Python calls this `pending_local_path_requests`. pub pending_local_path_requests: HashMap<[u8; 16], InterfaceId>, + /// Legacy separate path-state map, cleared on shared-connection reset. + /// Current path-state queries use `PathTable`'s state instead. pub path_states: HashMap<[u8; 16], PathState>, - /// Tasks blocked on `AwaitPath`. Each entry pairs the oneshot reply with - /// the registration timestamp so `expire_path_waiters` can bound how long - /// a caller can wait before receiving a negative result. + /// AwaitPath reply channels and registration times in Unix seconds. + /// Maintenance expires pending waiters after 15 seconds; callers needing a + /// strict deadline must bound mailbox admission and reply waiting themselves. pub path_waiters: HashMap<[u8; 16], Vec<(tokio::sync::oneshot::Sender, f64)>>, last_tables_cull: f64, @@ -182,49 +189,46 @@ pub struct TransportActor { last_held_announce_check: f64, pub is_transport_enabled: bool, - /// Wire-facing transport identity (Python `Transport.identity`): HEADER_2 - /// path responses, link-request transport_id matching, local next-hop - /// answers. On non-transport nodes this rotates per boot by default — - /// see `apply_transport_identity_policy`. + /// Hash used for wire-facing transport identifiers and local next-hop + /// answers. Derived from the internal or ephemeral hash by identity policy; + /// it is not itself a signing key. pub transport_identity_hash: Option<[u8; 16]>, - /// Persisted transport identity (Python 1.3.8 `Transport._identity`, - /// Transport.py:211-215). RPC-key derivation and operator identification - /// stay bound to this; never emitted on the wire when the ephemeral - /// policy is active. + /// Configured internal identity hash supplied by `SetTransportIdentity`. + /// Identity policy uses it directly when forwarding or static identity is + /// enabled. This actor does not derive RPC keys from it or retain a private key. pub internal_identity_hash: Option<[u8; 16]>, - /// Per-boot ephemeral identity hash substituted for the persisted one - /// when transport is disabled and `static_transport_identity` is unset - /// (Python 1.3.8 Transport.py:234-238). Generated lazily once per boot; - /// the runtime may pre-seed it with the hash of a full ephemeral - /// `Identity` so runtime-side consumers (discovery announcer, blackhole - /// publisher) share the same value. + /// Optional ephemeral hash used when forwarding and static identity are + /// disabled. Policy lazily generates it once per actor if not pre-seeded. + /// The runtime can supply a hash from an identity it owns; this field alone + /// contains no key and makes no claim about other services' identity choices. pub ephemeral_identity_hash: Option<[u8; 16]>, - /// Python 1.3.8 `static_transport_identity` config key (Reticulum.py:502-504, - /// default false): opts a non-transport node out of the per-boot ephemeral - /// transport identity. Set by the runtime before spawn. + /// Use the configured internal hash even when forwarding is disabled. + /// Default false; configure before identity policy is applied by + /// `SetTransportIdentity` or `SetTransportEnabled`. pub static_transport_identity: bool, - /// Python 1.3.8 `Transport.local_hops_delta` (Transport.py:167,240): when - /// the `local_hops_delta` config key is set, a per-boot random 2..=7 - /// replaces the hops byte of locally-originated packets at egress - /// (`should_apply_delta`/`mangle_hops`). 0 = disabled (the default). Set - /// by the runtime before spawn. + /// Replacement hop byte for eligible locally originated egress; zero disables + /// it. The actor stores this byte without choosing or validating a random + /// range. Not every packet or interface is eligible for replacement. pub local_hops_delta: u8, + /// Allowed external source hashes for on-disk blackhole loading. Changing + /// this vector alone does not reload or purge the table. pub blackhole_sources: Vec<[u8; 16]>, - /// Live snapshot of currently blackholed identity hashes, shared with the - /// runtime's link layer so the LINKIDENTIFY handler can tear down links - /// from blackholed identities (Python 1.3.8 Link.py:966-968) without an - /// actor round-trip. Rebuilt on every blackhole-table mutation. + /// Shared set of currently blackholed identity hashes for runtime Link checks. + /// Managed mutation/cull paths rebuild it and filter expired entries. Direct + /// public table mutation does not publish a snapshot; a poisoned snapshot + /// lock prevents publication. pub blackholed_snapshot: Arc>>, - /// True when connected to a shared Reticulum instance — the transport - /// defers to the shared instance for routing decisions rather than - /// originating them locally. + /// Whether this actor currently uses a shared-instance peer. Routing policy + /// uses that peer and reconnect handling invalidates prior routing state. pub is_shared_instance: bool, /// Sticky process-mode marker for shared-instance clients. It remains true /// after a shared connection drops so shutdown cannot persist an empty /// local routing table over the real shared instance's cache. pub shared_instance_client_mode: bool, + /// Trusted persistence root. Prefer `initialize_storage` to assigning this + /// field when saved state must also be loaded. pub storage_dir: Option, /// One-shot guard for lazy packet-hashlist restore. The hashlist is only /// authoritative on an enabled transport node that is not a shared @@ -232,15 +236,17 @@ pub struct TransportActor { /// known. hashlist_load_attempted: bool, - /// Last save (Unix seconds) — gates the periodic save tick. 0 forces an - /// initial baseline write after storage initialisation. + /// Unix time of the last routing-save request or attempt, not confirmation + /// of successful persistence. Zero makes the first dirty periodic save eligible. pub last_state_save: f64, - /// Set when persisted-state mutates; cleared after each `save_state`. - /// Gates the periodic tick so idle devices don't spin disk uselessly. + /// Requests a periodic routing-state save. Maintenance and managed mutations + /// set it; queued/synchronous save paths can clear it before success is known. + /// It is not a reliable comparison between memory and durable disk state. pub state_dirty: bool, - /// Guards the blocking-pool routing-state writer; concurrent writers - /// would race on the shared `.tmp` paths. + /// Whether an asynchronous routing writer is in flight. The separate + /// publication lock and generation counter coordinate queued and synchronous + /// snapshots; this flag alone is not a cross-process writer lock. pub routing_save_in_flight: std::sync::Arc, /// Monotonic claim used to prevent an older queued routing snapshot from /// replacing a newer synchronous/shutdown snapshot. @@ -249,15 +255,17 @@ pub struct TransportActor { /// decides whether a queued writer is still current. pub routing_save_lock: std::sync::Arc>, pub hashlist_save_in_flight: std::sync::Arc, - /// Guards the blocking-pool announce-cache sweep (Python parity with the - /// non-blocking `cache_clean_lock`: an in-flight sweep skips the pass). + /// Whether an asynchronous announce-cache sweep is in flight. Scheduling + /// skips another sweep while this flag is set. pub announce_sweep_in_flight: std::sync::Arc, /// Persisted path entries waiting on their interface to re-register. /// Drained by `drain_pending_for_interface` on `RegisterInterface`. pub pending_path_entries: Vec, - /// Cache of recently learnt announces, keyed by dest_hash for O(1) upsert. + /// Announce metadata keyed by destination hash. Fresh network input is + /// validated before caching, but restored local metadata is trusted and queries + /// do not re-verify signatures. pub recent_announces: HashMap<[u8; 16], RecentAnnounce>, /// Grace window before cache cleaning runs — protects freshly restored @@ -265,31 +273,32 @@ pub struct TransportActor { startup_complete: bool, startup_time: f64, - /// Try_send failures into destination channels (diagnostic gauge). + /// Cumulative counted failures when trying destination delivery channels. + /// This is not a complete transport-loss counter. pub channel_drops: u64, announce_handlers: Vec, next_announce_handler_id: u64, - /// Foreground/background flag shared with the app layer. Flipping to - /// background switches the maintenance tick to the long interval so the - /// actor stops burning CPU (and battery) while the app is suspended. + /// Shared foreground flag, observed on maintenance ticks. A falling edge + /// requests asynchronous persistence and a rising edge resets maintenance + /// checks. Only the `mobile-throttle` feature changes the background tick + /// period to 2 seconds; neither transition guarantees completed disk writes. pub is_foreground: Arc, } -/// Cached announce metadata for diagnostics + CacheRequest replay. Raw -/// announce bytes live on disk (`cache/announces/`, written -/// event-driven at receive — Python `Transport.cache` parity) and are fetched -/// via `packet_hash`; keeping them in RAM doubled per-destination retention -/// and dominated the periodic state snapshot. `retained` pins the entry -/// against the cull sweep (`RetainDestination` / `UnretainDestination`). +/// Cached announce metadata used by diagnostics and path/identity lookups. +/// Raw announce packets, when saved, live under `cache/announces/` +/// and can be replayed by cache requests. This record itself carries no +/// signature-verification evidence: local persistence is a trusted input. +/// `retained` prevents age-based cleanup, not explicit cache clearing. #[derive(Debug, Clone)] pub struct RecentAnnounce { pub dest_hash: [u8; 16], pub hops: u8, pub app_data: Option>, - /// Announce receive time (Python `known_destinations[0]`). Not bumped on - /// use — see `last_used`. + /// Announce receive time in Unix seconds; using the destination does not + /// refresh it. See `last_used`. pub timestamp: f64, pub public_key: Option<[u8; 64]>, pub ratchet: Option<[u8; 32]>, @@ -299,14 +308,20 @@ pub struct RecentAnnounce { /// Captured at receive so RPC consumers don't re-parse the raw packet. pub is_path_response: bool, pub retained: bool, - /// Last `UseDestination` touch (Python `known_destinations[4]`). Drives - /// the `UNUSED_DESTINATION_LINGER` sweep for pathless entries. + /// Last `UseDestination` time in Unix seconds. Never-used pathless entries + /// use the short linger threshold; used entries use the longer destination + /// timeout. Retained or currently routed entries are preserved by age cleanup. pub last_used: Option, - /// `SHA-256(app_name)[:10]` so cache consumers can filter by aspect - /// without re-parsing the announce. Zeroed if the announce had no payload. + /// Ten-byte announce name hash from the destination's expanded hash name, + /// which can include aspects and a generated-identity suffix. Legacy restored + /// entries can contain zero when metadata is unavailable; fresh announces + /// without valid payloads are rejected. pub name_hash: [u8; 10], } +/// One automatic rediscovery queue entry after a failed Link attempt. +/// `blocked_interface` is excluded from that queued request's targets; this +/// record does not send traffic or remove a cached route by itself. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PendingDiscoveryPathRequest { pub destination_hash: [u8; 16], @@ -330,31 +345,41 @@ enum AnnounceHandlerOwnership { Subscription, } -/// Dedicated trigger for scheduled full-state persistence. -/// -/// Keeping this control outside [`TransportMessage`] avoids expanding the -/// public transport command enum for a runtime-lifecycle concern. Requests -/// are serialized by the owning actor. +/// Cloneable handle to the actor's one-slot full-state persistence request +/// channel. The actor serializes request handling, but writes may be queued +/// on blocking workers and errors are logged rather than returned here. #[derive(Clone)] pub struct PersistenceTrigger { tx: mpsc::Sender<()>, } impl PersistenceTrigger { - /// Request a full asynchronous persistence pass. Returns `false` only - /// after the owning transport actor has stopped. + /// Admit a full-state save request to the one-slot control mailbox. True + /// means queue admission, not save completion or success. False means the + /// receiver is closed. There is no internal timeout; apply a caller deadline + /// when admission must be bounded. pub async fn request(&self) -> bool { self.tx.send(()).await.is_ok() } } impl TransportActor { + /// Construct an unstarted actor with a 4096-command mailbox, default two-million + /// hash insertion capacity, no interfaces/storage/identity, and forwarding + /// disabled. Configure the returned actor before running it; retain the sender + /// for commands. No task or network interface is started here. pub fn new() -> (Self, mpsc::Sender) { Self::new_with_capacity(4096, HASHLIST_MAXSIZE) } - /// Benchmarks at scale override both caps to avoid running the host out of - /// memory with synthetic traffic. + /// Construct an unstarted actor with a caller-sized ordinary mailbox and + /// duplicate-hash insertion capacity. Dedicated control queues have their + /// own fixed bounds. Hash restoration does not enforce `hashlist_cap`. + /// + /// # Panics + /// + /// Panics if `channel_cap` is zero or exceeds Tokio's maximum semaphore + /// permits, as required by its bounded channel constructor. pub fn new_with_capacity( channel_cap: usize, hashlist_cap: usize, @@ -475,20 +500,25 @@ impl TransportActor { } } - /// Load persisted state before the actor starts draining live traffic. - /// - /// Startup restore can touch thousands of Python cache files on slow - /// storage. Doing that work after `run()` starts blocks interface - /// registration, RPC queries and inbound packet processing behind a - /// synchronous `SetStoragePaths` message. + /// Set a trusted local storage directory and synchronously load persisted + /// state. Call before `run` to keep restore work out of live command handling. + /// Read/parse failures are logged instead of returned, and loading may write + /// legacy cache migrations. Repeated calls do not reset the actor to an empty + /// state; this is not a storage-isolation or identity-switch operation. pub fn initialize_storage(&mut self, storage_dir: PathBuf) { self.storage_dir = Some(storage_dir); self.load_state(); self.maybe_load_hashlist(); } - /// Run the actor event loop. Messages are processed sequentially so no - /// routing state is ever touched from two tasks at once. + /// Consume the actor and service ordinary commands, dedicated control lanes + /// and an internal maintenance timer. A foreground change is observed on a + /// tick; `mobile-throttle` changes tick cadence, not channel admission policy. + /// + /// An ordinary `Shutdown` or closure of the ordinary mailbox runs the + /// synchronous shutdown save path and exits. Save errors are logged, and + /// returning does not join every previously started background writer/sweep + /// or confirm durable storage. The caller must supply a Tokio timer runtime. pub async fn run(mut self) { let mut tick_interval = tokio::time::interval(Duration::from_millis(JOB_INTERVAL_MS)); let mut was_foreground = true; @@ -2131,10 +2161,12 @@ impl TransportActor { Some(raw) } + /// Whether a non-expired path is cached. This does not probe reachability. pub fn has_path(&self, dest_hash: &[u8; 16]) -> bool { self.path_table.has_path(dest_hash) } + /// Return hops for a non-expired cached path, or None if absent/expired. pub fn hops_to(&self, dest_hash: &[u8; 16]) -> Option { self.path_table.hops_to(dest_hash) } diff --git a/crates/rns-transport/src/actor/path_recovery.rs b/crates/rns-transport/src/actor/path_recovery.rs index 062afe9..b8f82eb 100644 --- a/crates/rns-transport/src/actor/path_recovery.rs +++ b/crates/rns-transport/src/actor/path_recovery.rs @@ -46,7 +46,8 @@ impl TransportActor { /// Enable bounded local-Link route observations and obtain an owned /// recovery handle. A handle from a retired actor cannot mutate its - /// replacement. Explicit legacy suppression operations are unaffected. + /// replacement. Recovery does not suppress an interface; observation + /// retention and queue limits are documented on `PathRecoveryHandle`. pub fn path_recovery_handle(&mut self) -> crate::path_recovery::PathRecoveryHandle { self.observe_local_link_routes = true; crate::path_recovery::PathRecoveryHandle { diff --git a/crates/rns-transport/src/announce.rs b/crates/rns-transport/src/announce.rs index 484f735..07eb229 100644 --- a/crates/rns-transport/src/announce.rs +++ b/crates/rns-transport/src/announce.rs @@ -15,18 +15,23 @@ pub struct AnnounceEntry { pub received_from: [u8; 16], /// Hop count as observed on receipt. pub hops: u8, - /// Outbound packet bytes with the Python-parity inbound-adjusted hop count. + /// Complete inner announce packet with the actor-adjusted hop count. + /// Interface IFAC and framing are applied later on egress. pub packet_raw: Vec, /// Count of duplicate rebroadcasts heard from neighbours — used to suppress flooding. pub local_rebroadcasts: u32, pub block_rebroadcast: bool, - /// Restrict rebroadcast to one interface; `None` broadcasts on all. + /// Cached-response target when `block_rebroadcast` is true. Ordinary + /// rebroadcasts use the actor's eligible-interface policy instead. pub attached_interface: Option, - /// Interface the announce arrived on; excluded from rebroadcast to avoid echo. + /// Receiving interface used by egress policy. Shared IPC peers are excluded + /// from an echo; an eligible broadcast radio may relay on the same interface. pub source_interface: Option, } -/// Table of pending announce rebroadcasts, keyed by destination hash. +/// Destination-keyed rebroadcast records. Insertions replace matching entries; +/// this helper neither sends packets nor validates their contents. Retry updates, +/// interface selection and cleanup are performed by the caller. pub struct AnnounceTable { entries: HashMap, } @@ -62,8 +67,9 @@ impl AnnounceTable { self.entries.is_empty() } - /// Destination hashes whose retransmit_timeout has elapsed and whose - /// rebroadcast is not blocked. + /// Return hashes with `now >= retransmit_timeout` that are unblocked or + /// have an attached interface. This does not check retry exhaustion, + /// interface eligibility or packet validity, and does not update records. pub fn due_for_retransmit(&self, now: f64) -> Vec { self.entries .iter() diff --git a/crates/rns-transport/src/announce_dispatch.rs b/crates/rns-transport/src/announce_dispatch.rs index 6e76c7f..500d49a 100644 --- a/crates/rns-transport/src/announce_dispatch.rs +++ b/crates/rns-transport/src/announce_dispatch.rs @@ -1,21 +1,31 @@ -//! Finite, exact-target admission of locally produced announcements. +//! Bounded admission intents for locally produced announcements. //! -//! An admitted result means a driver accepted bytes, never radio delivery. +//! `Admitted` means one interface queue accepted bytes. Results do not report +//! every target, physical transmission or delivery. The actor owns retry state +//! until its deadline or retirement; callers must bound their own reply wait. use bytes::Bytes; use std::time::Duration; use tokio::sync::{mpsc, oneshot}; pub(crate) const CAPACITY: usize = 256; +/// First reported result for an intent, not a complete per-interface report. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub enum AnnounceDispatchResult { + /// At least one target's interface queue accepted bytes. Admitted, + /// The intent expired, was coalesced or lost admission eligibility. A + /// coalesced target can resolve this before other targets are processed, + /// so it does not prove that no bytes were or will be admitted. Expired, + /// Initial target selection found no eligible interface. NoEligibleInterface, + /// The header could not be parsed or the packet was not an announce. Invalid, } +/// The intent could not enter the actor's bounded dispatch queue. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub enum AnnounceDispatchError { @@ -23,6 +33,8 @@ pub enum AnnounceDispatchError { Closed, } +/// Cloneable handle to the actor's 256-intent admission queue. The actor must +/// be running to process requests; cloning does not create another queue. #[derive(Clone, Debug)] pub struct AnnounceDispatchHandle { pub(crate) tx: mpsc::Sender, @@ -36,10 +48,20 @@ pub(crate) struct AnnounceDispatchRequest { } impl AnnounceDispatchHandle { - /// Queue an admission intent for at most 120 seconds. The reply resolves - /// on the first driver acceptance; refused targets remain owned until the - /// original deadline. Accepted targets are never replayed. Dropping the - /// receiver before its first result cancels unadmitted work. + /// Queue a complete inner announce packet with a lifetime capped at 120 + /// seconds. The actor checks its header/type, not its announce signature; + /// callers must construct a valid payload. An attached interface is an + /// explicit outbound target; otherwise normal announce egress policy applies. + /// + /// The first reported result resolves the reply. Refused targets can remain + /// pending until the original deadline even after another target is admitted. + /// Accepted targets are not retried by this intent. `Expired` can also mean + /// one target was coalesced while other targets continue. A dropped receiver + /// is checked before initial processing and during retries until the first + /// result; dropping it cannot recall queued bytes or interrupt processing + /// already underway. Bound the reply wait separately from work lifetime. + /// On `Full`/`Closed`, the intent was not queued and its input bytes are not + /// returned; retain a copy if retrying. pub fn try_dispatch( &self, raw: Bytes, diff --git a/crates/rns-transport/src/await_path.rs b/crates/rns-transport/src/await_path.rs index b866d1c..113e59b 100644 --- a/crates/rns-transport/src/await_path.rs +++ b/crates/rns-transport/src/await_path.rs @@ -1,10 +1,9 @@ //! Wait for a destination's path to be learned (or time out). //! -//! Mirrors Python `Transport.await_path(destination_hash, timeout=None)` -//! (RNS/Transport.py:2524). The helper sends an [`AwaitPath`] actor -//! message and applies one caller-supplied deadline to both actor submission -//! and the oneshot reply. The actor emits the upstream-compatible path request -//! before parking the waiter. +//! Sends an [`AwaitPath`] actor message with one caller-supplied deadline +//! covering both channel admission and the reply. The actor answers from a +//! nonexpired cached path when available; otherwise it requests discovery and +//! parks a waiter. Success does not establish current end-to-end reachability. //! //! [`AwaitPath`]: crate::messages::TransportMessage::AwaitPath @@ -17,23 +16,23 @@ use crate::messages::TransportMessage; /// Error returned by [`await_path`] when the path cannot be resolved. #[derive(Debug, Error, PartialEq)] pub enum AwaitPathError { - /// The transport actor's receive channel closed before we could - /// submit the request — the actor has shut down. + /// The transport command channel closed before request admission. #[error("transport actor is not running")] TransportDown, - /// The caller's timeout fired before the actor answered, or the - /// actor's internal 15s sweep expired the waiter first (returns - /// `Ok(false)` on the reply channel). + /// The caller's deadline elapsed, the actor replied `false`, or the reply + /// sender was dropped. Actor maintenance expires parked waiters after + /// at least 15 seconds; this is not a guaranteed sweep completion time. #[error("timed out waiting for path")] Timeout, } -/// Wait up to `timeout` for the transport actor to resolve (or already -/// know) a path to `destination_hash`. +/// Wait up to `timeout` for a cached or newly learned path to `destination_hash`. +/// The deadline includes waiting to submit the command, not just its reply. +/// Success reflects actor path state and does not probe the remote application. /// -/// Returns `Ok(())` as soon as the actor confirms the path exists. A -/// dropped reply sender without a preceding `true` is indistinguishable -/// from a timeout, so both surface as `Err(Timeout)`. +/// A `false` reply or dropped reply sender is reported as [`AwaitPathError::Timeout`]. +/// Timing out drops this waiter receiver but does not retract an admitted actor +/// command or path request; the actor later removes closed waiters. pub async fn await_path( tx: &mpsc::Sender, destination_hash: [u8; 16], diff --git a/crates/rns-transport/src/background_egress.rs b/crates/rns-transport/src/background_egress.rs index e427463..4ed87fb 100644 --- a/crates/rns-transport/src/background_egress.rs +++ b/crates/rns-transport/src/background_egress.rs @@ -1,9 +1,11 @@ //! Optional complete-packet background handoff to an interface's final writer. //! //! The scheduler retains the bulk backlog. This lane owns at most one offer or -//! started packet, independently of all ordinary packet FIFOs. Drivers apply -//! KISS/BLE framing exactly once after selection. Registration uses weak exact -//! channel identities and does not change exhaustive interface structures. +//! started packet, independently of ordinary packet queues. The caller must +//! check ordinary backlog and carrier readiness before selection, then apply +//! its interface framing. Selection records a local start time, not a write, +//! radio acknowledgment or delivery. Registration uses weak references to an +//! exact channel and is limited to 4096 live lanes per process. use bytes::Bytes; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; @@ -16,6 +18,7 @@ fn registry() -> &'static Registry { REGISTRY.get_or_init(|| Mutex::new(Vec::new())) } +/// A lane already exists for this channel, or the process-wide registry is full. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub enum BackgroundRegistrationError { @@ -41,8 +44,9 @@ struct Offer { generation: u64, } -/// Driver-owned final-writer endpoint. Clone only for a joined physical writer; -/// call `retire_generation` before handing a reconnected carrier any offers. +/// Driver-owned final-writer endpoint. Clones share one lane; they do not create +/// separate packet queues. Call `retire_generation` before handing a reconnected +/// carrier any offers, and coordinate all clones with the physical writer. #[derive(Clone)] pub struct BackgroundAnnounceReceiver { shared: Arc, @@ -64,7 +68,8 @@ impl Drop for BackgroundOfferReceipt { } /// Owns one already-selected complete RNS/IFAC packet. Keep this guard until -/// the whole write/acknowledgement (including an ambiguous retry) retires. +/// the whole write/acknowledgment (including an ambiguous retry) retires. +/// Dropping it releases the lane; it neither writes nor cancels a driver write. pub struct BackgroundPacket { raw: Bytes, shared: Arc, @@ -81,8 +86,9 @@ impl Drop for BackgroundPacket { } impl BackgroundAnnounceReceiver { - /// Attach a background lane to exactly `ordinary`. Failure is explicit; - /// built-in drivers must fail startup rather than silently omit this lane. + /// Attach one lane to exactly this ordinary channel, removing dead weak + /// registrations first. Duplicate channels and a full registry return an + /// error. This does not start a driver or drain the ordinary channel. pub fn register(ordinary: &mpsc::Sender) -> Result { let mut registry = registry().lock().unwrap(); registry.retain(|(channel, owner)| channel.strong_count() > 0 && owner.strong_count() > 0); @@ -118,14 +124,19 @@ impl BackgroundAnnounceReceiver { } } - /// Select only after ordinary work, carrier readiness and the radio permit - /// have been checked, immediately before a complete packet write. + /// Take a valid offer using an always-true permit predicate. The caller + /// must first check ordinary work, carrier readiness and any radio permit; + /// this method does not perform those checks. Supply wall-clock Unix seconds + /// consistent with the scheduler's expiry values. pub fn try_start(&self, now: f64) -> Option { self.try_start_when(now, || true) } - /// Atomically select a still-valid offer only when the final writer can - /// consume its permit. A false predicate leaves the offer unstarted. + /// Check expiry, cancellation, generation and owner validity, then call + /// `permit` while holding the lane mutex. A false predicate retains the + /// offer; the callback must not reenter this lane. Ordinary backlog and + /// carrier readiness remain caller responsibilities. Returning a packet + /// signals its local selection time to the scheduler before any write. pub fn try_start_when( &self, now: f64, @@ -156,7 +167,9 @@ impl BackgroundAnnounceReceiver { }) } - /// Ordinary outer-channel backlog has priority over background selection. + /// Whether the ordinary channel still exists and all its capacity is free. + /// This is a snapshot, not a reservation; in-progress driver work is not + /// represented. The caller must use it to prioritize ordinary traffic. pub fn ordinary_is_empty(&self) -> bool { self.shared .ordinary @@ -164,7 +177,8 @@ impl BackgroundAnnounceReceiver { .is_some_and(|tx| tx.capacity() == tx.max_capacity()) } - /// Whether a non-cancelled offer exists. Selection still rechecks expiry. + /// Whether an offer occupies the slot, even if expired, cancelled or stale. + /// Selection rechecks those conditions; a started packet is not an offer. pub fn has_offer(&self) -> bool { self.shared.state.lock().unwrap().offer.is_some() } diff --git a/crates/rns-transport/src/blackhole.rs b/crates/rns-transport/src/blackhole.rs index f1f9993..e130c8d 100644 --- a/crates/rns-transport/src/blackhole.rs +++ b/crates/rns-transport/src/blackhole.rs @@ -3,9 +3,9 @@ use std::collections::HashMap; use rns_wire::types::IdentityHash; use serde::{Deserialize, Serialize}; -/// Why an identity ended up in the blackhole table. `Manual` is an operator -/// add; the other variants are system-populated. UIs distinguish operator -/// blocks from automatic defences. +/// Caller-supplied classification for an identity block. `Manual` is the +/// default; [`BlackholeTable::clear_system_entries`] removes all other +/// variants. The value itself is not evidence of a particular violation. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] pub enum BlackholeReason { #[default] @@ -27,8 +27,8 @@ impl BlackholeReason { } /// Parse the stable identifier (case-insensitive). Unknown values fall back - /// to `Manual`; never silently promote to a system reason that would hide - /// the entry from an operator view. + /// to `Manual`. This also accepts `ratelimit` and `protocolviolation`; + /// whitespace is not trimmed. pub fn parse(s: &str) -> Self { match s.to_ascii_lowercase().as_str() { "malformed" => Self::Malformed, @@ -41,17 +41,18 @@ impl BlackholeReason { #[derive(Debug, Clone)] pub struct BlackholeEntry { - /// Insertion time (Unix seconds). + /// Creation time (Unix seconds), supplied by the caller for restored or + /// source-provided entries. pub created: f64, - /// Lifetime relative to `created`; `None` is permanent. + /// Lifetime in seconds relative to `created`; `None` has no automatic + /// expiry. External timestamps and TTLs are not validated by this table. pub ttl: Option, pub reason: BlackholeReason, - /// Original operator/source reason string when it is more specific than - /// the internal reason enum. Python preserves arbitrary reason labels. + /// Optional reason text, used by `reason_str` in preference to the enum. pub reason_label: Option, - /// Identity hash of the publisher that issued this entry; `None` if local. - /// The distributed blackhole updater uses it to filter locally-issued - /// entries for publication and to key remote entries on ingest. + /// Caller-supplied publisher identity hash; `None` marks a local entry. + /// This is metadata, not verified provenance. Entries are keyed by the + /// blocked identity alone, so different sources do not get separate rows. pub source: Option, } @@ -63,6 +64,10 @@ impl BlackholeEntry { } } +/// In-memory identity block entries. Each insertion replaces any entry for +/// the same identity. Expiry is checked by `is_blackholed`, but expired rows +/// remain in counts and iteration until removed or culled. This table does +/// not authenticate sources, enforce packet policy or persist itself. #[derive(Clone)] pub struct BlackholeTable { entries: HashMap, @@ -122,11 +127,10 @@ impl BlackholeTable { ); } - /// Add an entry that was pulled from a remote blackhole source. The - /// `source` field is retained so local publication filters it out of - /// our own manifest (parity with Python `Transport.persist_blackhole` - /// which only persists entries whose source matches the local - /// identity, Discovery.py:3253-3258). + /// Insert or replace an entry with the supplied source and creation time. + /// The source is retained as metadata; this method neither authenticates + /// it nor merges competing claims. Callers must validate external data + /// and choose their source/override policy before insertion. pub fn add_from_source( &mut self, identity_hash: impl Into, @@ -153,6 +157,8 @@ impl BlackholeTable { self.entries.insert(identity_hash.into(), entry); } + /// Check whether an entry has no expiry or its elapsed wall-clock time is + /// less than its TTL. Expired entries are not removed by this lookup. pub fn is_blackholed(&self, identity_hash: &[u8; 16]) -> bool { match self.entries.get(identity_hash) { Some(entry) => { diff --git a/crates/rns-transport/src/constants.rs b/crates/rns-transport/src/constants.rs index 1747689..4d29675 100644 --- a/crates/rns-transport/src/constants.rs +++ b/crates/rns-transport/src/constants.rs @@ -1,5 +1,6 @@ -/// Maximum hop count. Announces and forwarded packets exceeding this are -/// dropped at the inbound boundary. Mirrors Python `Transport.PATHFINDER_M`. +/// Exclusive upper bound for the on-wire hop count. Inbound packets of every +/// packet type are rejected when their raw hop count is at least 128, before +/// the receiving hop adjustment. pub const PATHFINDER_M: u8 = 128; /// Number of retransmit retries for announces. @@ -8,7 +9,7 @@ pub const PATHFINDER_R: u8 = 1; /// Grace period (seconds) before announce retry. pub const PATHFINDER_G: f64 = 5.0; -/// Random window for announce rebroadcast jitter. +/// Announce rebroadcast jitter window, in seconds. pub const PATHFINDER_RW: f64 = 0.5; /// Default path expiry (7 days, in seconds). @@ -20,13 +21,14 @@ pub const AP_PATH_TIME: u64 = 86_400; /// Roaming path expiry (6 hours). pub const ROAMING_PATH_TIME: u64 = 21_600; -/// Default destination timeout (7 days). Matches Python -/// `Transport.DESTINATION_TIMEOUT`. Drives both `path_table` and -/// `recent_announces` eviction. +/// Default path lifetime, in seconds (7 days), except for interface modes +/// with shorter lifetimes. Announce metadata cleanup also uses this value: +/// steady-state cleanup allows 1.25 times this duration for used, pathless +/// entries, while loading applies the base duration to stale, unretained entries. pub const DESTINATION_TIMEOUT: u64 = 604_800; -/// Transport link-table timeout for validated links (15 min). -/// Equals `Link::STALE_TIME (720s) * 1.25`. +/// Transport link-table timeout for validated links, in seconds (15 minutes). +/// This is transport bookkeeping, not an application-level Link keepalive deadline. pub const LINK_TIMEOUT: f64 = 900.0; /// Maximum packets retained for one locally-owned established Link while its @@ -37,7 +39,8 @@ pub const LINK_ENDPOINT_EGRESS_QUEUE_CAPACITY: usize = 256; /// Reverse table entry timeout (8 minutes). pub const REVERSE_TIMEOUT: u64 = 480; -/// Maximum packet receipts tracked. +/// Receipt-count ceiling applied during periodic maintenance. Registration can +/// temporarily exceed it; maintenance culls the oldest receipts. pub const MAX_RECEIPTS: usize = 1024; /// Rate timestamps per destination. @@ -52,7 +55,8 @@ pub const MAX_RANDOM_BLOBS: usize = 64; /// Max local rebroadcasts before stopping. pub const LOCAL_REBROADCASTS_MAX: u32 = 2; -/// Path request timeout (seconds). +/// Base timeout for recursive path discovery, in seconds. A discovered +/// slow-media return budget can extend the actual admission deadline. pub const PATH_REQUEST_TIMEOUT: f64 = 15.0; /// Duplicate inbound path request tag retention (seconds). @@ -61,7 +65,8 @@ pub const PATH_REQUEST_GATE_TIMEOUT: f64 = 120.0; /// Maximum queued automatic discovery path requests after failed link setup. pub const MAX_QUEUED_DISCOVERY_PRS: usize = 32; -/// Minimum spacing between queued discovery path-request transmissions. +/// Minimum spacing in seconds between dequeuing automatic discovery requests. +/// One dequeued request can be offered to several eligible interfaces. pub const DISCOVERY_PR_TX_THROTTLE: f64 = 0.5; /// Grace before path response (seconds). @@ -70,107 +75,100 @@ pub const PATH_REQUEST_GRACE: f64 = 0.4; /// Extra grace for roaming interfaces (seconds). pub const PATH_REQUEST_RG: f64 = 1.5; -/// Minimum interval between path requests (seconds). +/// Minimum interval in seconds used to suppress repeated automatic path +/// requests. Explicit caller requests have their own admission rules. pub const PATH_REQUEST_MI: f64 = 20.0; -/// Maximum packet hashes retained across both generations. -/// -/// Python retains roughly one million hashes. Rust deliberately retains up -/// to two million for a longer bounded replay window; see RNS-D0056. +/// Default two-generation duplicate-packet hash capacity used by normal +/// insertion. Restoring saved generations does not enforce this bound. pub const HASHLIST_MAXSIZE: usize = 2_000_000; /// Job loop period (250ms). pub const JOB_INTERVAL_MS: u64 = 250; -/// Job loop period in background mode (2s). Inbound packet processing is -/// unaffected — it runs on the channel branch at full speed. +/// Maintenance tick period in background mode, in milliseconds (2 seconds), +/// when the `mobile-throttle` feature is enabled. Message channels remain +/// serviced; this constant does not impose a packet-processing rate. pub const JOB_INTERVAL_BG_MS: u64 = 2000; -/// Cadence at which `on_tick` flushes routing-state files (path_table, -/// announce_cache, blackhole, tunnel_table) when dirty. Hashlist is excluded -/// (multi-MB on busy hubs); it saves on shutdown + foreground→background. -/// Matches Python `Reticulum.GRACIOUS_PERSIST_INTERVAL` (5 min). On a live -/// announce feed the dirty bit is effectively always set, so this interval -/// IS the flush rate — at 10s the full-state clone+serialize+fsync cycle -/// dominated daemon RSS via allocator churn. Abrupt-exit safety comes from -/// the falling-edge save and `on_shutdown`, not from this cadence. +/// Minimum interval in seconds between dirty routing-state save requests. +/// Periodic saves cover paths, announce metadata, blackholes and tunnels, but +/// exclude the packet hash list. Saves can run on a blocking worker; requesting +/// one is not confirmation of completion or durability. Shutdown and observed +/// foreground-to-background transitions also request saves. Only the background +/// tick cadence change is gated by `mobile-throttle`. pub const STATE_SAVE_INTERVAL_SECS: f64 = 300.0; -/// Python `Transport.UNUSED_DESTINATION_LINGER`: never-used destinations -/// without a path are dropped from the announce cache after this idle time. +/// Age in seconds after which never-used, pathless, unretained destinations +/// are eligible for announce-metadata cleanup. pub const UNUSED_DESTINATION_LINGER: f64 = 360.0; -/// Python `Transport.max_pr_tags`: hard count cap on the discovery -/// path-request tag gate, on top of the time-based retain. +/// Discovery path-request tag count ceiling applied during maintenance, in +/// addition to time-based expiry. It is not an insertion-time hard bound. pub const MAX_DISCOVERY_PR_TAGS: usize = 32_000; -/// Link table check interval. +/// Traffic-rate sampling interval, in seconds. Despite the name, transport +/// link-table culling uses `TABLES_CULL_INTERVAL`. pub const LINKS_CHECK_INTERVAL: f64 = 1.0; -/// Receipt timeout check interval. +/// Receipt timeout and count-limit check interval, in seconds. pub const RECEIPTS_CHECK_INTERVAL: f64 = 1.0; -/// Announce rebroadcast check interval. +/// Announce rebroadcast check interval, in seconds. pub const ANNOUNCES_CHECK_INTERVAL: f64 = 1.0; -/// Pending path request cleanup interval. +/// Exported pending-path-request interval, in seconds. The current transport +/// actor does not use this constant to schedule cleanup. pub const PENDING_PRS_CHECK_INTERVAL: f64 = 30.0; -/// Cache cleanup interval (5 minutes). +/// In-memory hash rotation and announce-metadata cleanup interval, in seconds +/// (5 minutes), after the interface-startup grace period has completed. pub const CACHE_CLEAN_INTERVAL: f64 = 300.0; -/// On-disk announce cache sweep cadence — Python's 15-minute -/// `clean_announce_cache` interval. Independent of the RAM-cache clean -/// gate: Python's jobs thread cleans regardless of interface presence, so a -/// node that boots with no interfaces still collects backlog. +/// On-disk announce cache sweep interval, in seconds (15 minutes). Scheduling +/// does not require the interface-startup grace period; it requires storage, +/// non-client ownership and no sweep already in flight. pub const ANNOUNCE_CACHE_SWEEP_INTERVAL: f64 = 900.0; -/// Never delete announce-cache files younger than this. The keep-set is -/// snapshotted on the actor while the cache writer keeps running on the -/// blocking pool, so a fresh announce can exist on disk before its path -/// entry does. Python accepts that race; we close it. +/// Minimum age in seconds before an unreferenced announce-cache file is +/// eligible for removal. This grace reduces races with a keep-set snapshot; +/// it is not a transaction between cache writers and the sweep. pub const ANNOUNCE_CACHE_SWEEP_GRACE_SECS: u64 = 300; -/// Table culling interval. +/// Routing-table and link-table culling interval, in seconds. pub const TABLES_CULL_INTERVAL: f64 = 5.0; -/// Interface job processing interval. +/// Exported interface-job interval, in seconds. The current transport actor +/// does not use this constant to schedule interface work. pub const INTERFACE_JOBS_INTERVAL: f64 = 5.0; -/// Management announce interval (2 hours). +/// Exported management-announce interval, in seconds (2 hours). The current +/// transport actor does not schedule management announces from this constant. pub const MGMT_ANNOUNCE_INTERVAL: f64 = 7200.0; -/// Blackhole expiry check interval. +/// Blackhole expiry check interval, in seconds. pub const BLACKHOLE_CHECK_INTERVAL: f64 = 60.0; -/// Announce bandwidth cap as a fraction of interface bitrate (2%). -/// -/// The Python reference stores `ANNOUNCE_CAP = 2` and divides by 100 at use -/// sites; we store the fraction directly. UIs may show the percentage. +/// Default announce bandwidth fraction of the declared interface bitrate +/// (0.02 means 2%). Supply a fraction, not a percentage, to transport APIs. pub const ANNOUNCE_CAP: f64 = 0.02; /// Maximum ingress-limited announces to hold per interface. -/// Matches Python `Interface.MAX_HELD_ANNOUNCES = 256`. pub const MAX_HELD_ANNOUNCES: usize = 256; /// Held announce release interval (seconds). -/// Matches Python 1.2.5 `Interface.IC_HELD_RELEASE_INTERVAL = 5`. pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0; /// Incoming announce frequency window samples. -/// Matches Python 1.2.5 `Interface.IA_FREQ_SAMPLES = 48`. pub const IA_FREQ_SAMPLES: usize = 48; /// Outgoing announce frequency window samples. -/// Matches Python 1.2.5 `Interface.OA_FREQ_SAMPLES = 48`. pub const OA_FREQ_SAMPLES: usize = 48; /// Incoming path-request frequency window samples. -/// Matches Python 1.2.5 `Interface.IP_FREQ_SAMPLES = 48`. pub const IP_FREQ_SAMPLES: usize = 48; /// Outgoing path-request frequency window samples. -/// Matches Python 1.2.5 `Interface.OP_FREQ_SAMPLES = 48`. pub const OP_FREQ_SAMPLES: usize = 48; /// Minimum non-zero announce frequency represented by the decay window. @@ -186,23 +184,18 @@ pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ; pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ; /// Minimum samples required before frequency is considered defined. -/// Matches Python 1.2.5 `Interface.IC_DEQUE_MIN_SAMPLE = 2`. pub const IC_DEQUE_MIN_SAMPLE: usize = 2; /// Minimum samples required for burst state clearing / egress PR limiting. -/// Matches Python 1.2.5 `Interface.IC_BURST_MIN_SAMPLES = 6`. pub const IC_BURST_MIN_SAMPLES: usize = 6; /// Duration interface is treated as "new" (seconds). -/// Matches Python `Interface.IC_NEW_TIME = 2*60*60`. pub const IC_NEW_TIME: f64 = 7200.0; /// Burst threshold for new interfaces (announces/sec). -/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ_NEW = 3`. pub const IC_BURST_FREQ_NEW: f64 = 3.0; /// Burst threshold for established interfaces (announces/sec). -/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ = 10`. pub const IC_BURST_FREQ: f64 = 10.0; /// Path-request burst threshold for new interfaces (requests/sec). @@ -212,11 +205,9 @@ pub const IC_PR_BURST_FREQ_NEW: f64 = 3.0; pub const IC_PR_BURST_FREQ: f64 = 8.0; /// Burst detection active duration (seconds). -/// Matches Python 1.2.5 `Interface.IC_BURST_HOLD = 15`. pub const IC_BURST_HOLD: f64 = 15.0; /// Burst penalty delay (seconds). -/// Matches Python 1.2.5 `Interface.IC_BURST_PENALTY = 15`. pub const IC_BURST_PENALTY: f64 = 15.0; /// Optional outgoing path-request limiter threshold (requests/sec). @@ -226,29 +217,26 @@ pub const EC_PR_FREQ: f64 = 5.0; pub const EGRESS_CONTROL: bool = false; /// Tunnel timeout (8 hours, in seconds). -/// Matches Python 1.1.6 `Transport.TUNNEL_TIMEOUT = 60*60*8`. pub const TUNNEL_TIMEOUT: u64 = 28_800; /// Tunnel path timeout (8 hours, in seconds). -/// Matches Python 1.1.6 `Transport.TUNNEL_PATH_TIMEOUT = 60*60*8`. pub const TUNNEL_PATH_TIMEOUT: u64 = 28_800; -/// Announce queue processing interval (seconds). +/// Exported announce-queue interval, in seconds. The current actor processes +/// interface announce queues on its maintenance tick instead. pub const ANNOUNCE_QUEUE_INTERVAL: f64 = 1.0; -/// Local client cache max size. +/// Maximum number of packet-metric cache entries retained by the actor. pub const LOCAL_CLIENT_CACHE_MAXSIZE: usize = 512; /// Maximum lifetime for queued announces (24 hours, in seconds). -/// Matches Python `Reticulum.QUEUED_ANNOUNCE_LIFE = 60*60*24`. pub const QUEUED_ANNOUNCE_LIFE: f64 = 86_400.0; /// Maximum number of queued announces per interface. -/// Matches Python `Reticulum.MAX_QUEUED_ANNOUNCES = 16384`. pub const MAX_QUEUED_ANNOUNCES: usize = 16_384; -/// Startup grace period (seconds) before cache cleaning runs. -/// Allows interfaces to come online before pruning stale cache entries. +/// Grace period in seconds after the first interface registration before +/// startup-gated in-memory cache cleanup becomes eligible. pub const STARTUP_GRACE_PERIOD: f64 = 3.0; /// Wire transport mode carried in the packet header. @@ -261,7 +249,8 @@ pub enum TransportMode { Tunnel = 0x03, } -/// Reachability state recorded for a destination. +/// Exported reachability labels. The current transport actor does not +/// maintain a value of this enum for each destination. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum Reachability { @@ -270,7 +259,8 @@ pub enum Reachability { Transport = 0x02, } -/// Liveness state for a known path. +/// Locally recorded path response state. A stored value alone does not +/// establish present reachability or authenticate a peer. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum PathState { @@ -279,7 +269,8 @@ pub enum PathState { Responsive = 0x02, } -/// Configured operating mode for an interface. +/// Local interface policy used for announce forwarding and path discovery. +/// These modes are not a reachability signal transmitted to upstream peers. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum InterfaceMode { Full, @@ -288,20 +279,23 @@ pub enum InterfaceMode { AccessPoint, Roaming, Boundary, - /// Python 1.3.8 `MODE_INTERNAL` (Interface.py:51) — local/shared-instance - /// interfaces. Default path expiry (`path_expiry` wildcard arm) and a - /// discovery mode (`mode_discovers_unknown_paths`), like upstream. + /// Internal-interface policy: default path expiry and eligibility for + /// unknown-path discovery. Interface role separately identifies IPC peers. Internal, } -/// Which directions an interface carries traffic in. +/// Configured traffic-direction flags. These flags do not open an interface +/// or establish that its driver is online. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct InterfaceDirection { + /// Whether inbound traffic is enabled. pub inbound: bool, + /// Whether outbound traffic is enabled. pub outbound: bool, } impl InterfaceDirection { + /// Enable both direction flags. pub fn bidirectional() -> Self { Self { inbound: true, @@ -309,6 +303,7 @@ impl InterfaceDirection { } } + /// Enable inbound traffic and disable outbound traffic. pub fn inbound_only() -> Self { Self { inbound: true, @@ -316,6 +311,7 @@ impl InterfaceDirection { } } + /// Enable outbound traffic and disable inbound traffic. pub fn outbound_only() -> Self { Self { inbound: false, diff --git a/crates/rns-transport/src/discovery/announcer.rs b/crates/rns-transport/src/discovery/announcer.rs index f7e86f3..975ad71 100644 --- a/crates/rns-transport/src/discovery/announcer.rs +++ b/crates/rns-transport/src/discovery/announcer.rs @@ -1,8 +1,10 @@ -//! Periodic discovery announce scheduler. Pure-data: `tick(now)` returns -//! one [`AnnounceRequest`] per due interface. Runtime owners use `prepare` and -//! `commit` to advance the interval only after driver admission. The runtime owns the timer + -//! identity-signed emit. Memoises `(infohash, stamp)` per interface so an -//! unchanged info doesn't redo PoW. +//! Discovery publication scheduler, driven by caller-supplied timestamps. +//! +//! Use [`Announcer::prepare`] to obtain app-data, then [`Announcer::commit`] +//! when the caller's required admission condition is met. This module neither +//! sends a packet nor verifies driver admission. The caller supplies the timer, +//! outer signed announce and egress handling. Preparation may synchronously +//! generate proof of work; unchanged info bytes reuse a cached stamp. use std::collections::HashMap; use std::sync::Arc; @@ -23,20 +25,27 @@ use super::stamper::DiscoveryStamper; pub struct DiscoveryInterfaceConfig { /// Interface type — must be in [`DISCOVERABLE_INTERFACE_TYPES`]. pub interface_type: String, + /// Whether preparation may publish this interface's metadata. pub discoverable: bool, /// Name advertised in the announce. pub name: String, + /// Advertised routing state; this does not enable transport itself. pub transport_enabled: bool, - /// Seconds between announces; defaults to [`ANNOUNCE_JOB_INTERVAL_SECS`]. + /// Minimum seconds after the last successful commit. The backbone helper + /// uses [`ANNOUNCE_JOB_INTERVAL_SECS`]; zero permits immediate preparation. pub announce_interval_secs: u64, - /// Stamp target value required by the receiver; defaults to [`DEFAULT_STAMP_VALUE`]. + /// Sender's generation target; receivers choose their own requirement. + /// The backbone helper uses [`DEFAULT_STAMP_VALUE`]. Raising this through + /// `reconfigure` alone does not invalidate an unchanged info map's stamp. pub stamp_value: u8, /// Endpoint address (IP / host / I2P b32) — optional. pub reachable_on: Option, - /// TCP/Backbone bind port, if applicable. + /// Advertised TCP/Backbone port, if applicable. pub port: Option, - /// IFAC virtual-network overlay (name / key). + /// Advertised IFAC network name. pub ifac_netname: Option, + /// Advertised IFAC passphrase. Without discovery-body encryption this is + /// cleartext in the announce; omit it when it must remain undisclosed. pub ifac_netkey: Option, /// Radio-link parameters for RNode / KISS / Weave. pub frequency: Option, @@ -49,16 +58,19 @@ pub struct DiscoveryInterfaceConfig { pub latitude: Option, pub longitude: Option, pub height: Option, - /// Set the `FLAG_ENCRYPTED` bit; caller supplies `encrypt` closure at - /// announce time via [`Announcer::tick`]. + /// Encrypt the info/stamp body and set `FLAG_ENCRYPTED`; the caller must + /// supply an encryptor to [`Announcer::prepare`] or [`Announcer::tick`]. pub encrypt: bool, - /// Set the `FLAG_SIGNED` bit (independent of `encrypt`). + /// Set `FLAG_SIGNED` independently of encryption. This flag does not + /// create a signature; the caller constructs the outer signed announce. pub signed: bool, } impl DiscoveryInterfaceConfig { - /// Minimal config: discoverable backbone interface with default - /// stamp + interval. + /// Build discoverable Backbone metadata: transport advertised as enabled, + /// 60-second interval, stamp target 16, signed flag set and no body + /// encryption. Optional IFAC, radio and location fields start absent. + /// This does not open an interface or validate the endpoint. pub fn backbone(name: String, reachable_on: String, port: u16) -> Self { Self { interface_type: "BackboneInterface".into(), @@ -85,7 +97,8 @@ impl DiscoveryInterfaceConfig { } } - /// True iff `interface_type` is in [`DISCOVERABLE_INTERFACE_TYPES`]. + /// Check only whether the type is in [`DISCOVERABLE_INTERFACE_TYPES`]. + /// This does not check `discoverable`, endpoint fields or runtime support. pub fn is_advertisable(&self) -> bool { DISCOVERABLE_INTERFACE_TYPES .iter() @@ -106,9 +119,11 @@ struct InterfaceAnnounceState { stamp_cache: Option<([u8; 32], Vec)>, } -/// One "interface wants to announce now" output from [`Announcer::tick`]. +/// Prepared discovery app-data for one interface. The caller still needs to +/// construct and send the outer Reticulum announce. #[derive(Debug, Clone)] pub struct AnnounceRequest { + /// Local interface whose metadata this publication describes. pub interface_id: InterfaceId, /// Fully assembled `app_data` bytes (flags followed by the optionally /// encrypted body). @@ -117,8 +132,9 @@ pub struct AnnounceRequest { pub stamp_value: u8, } -/// One cached publication for an exact registered configuration. Its opaque -/// generation prevents a late admission from committing a replaced interface. +/// One cached publication tied to its announcer instance and configuration +/// generation. Clones refer to the same publication; a stale or already +/// committed token cannot advance the current publication's interval. #[derive(Debug, Clone)] pub struct PreparedAnnounce { owner: Arc<()>, @@ -127,6 +143,7 @@ pub struct PreparedAnnounce { } impl PreparedAnnounce { + /// Read the cached publication bytes and achieved stamp value. pub fn request(&self) -> &AnnounceRequest { &self.request } @@ -139,20 +156,25 @@ pub enum SkipReason { NotDiscoverable, /// Interface type not in [`DISCOVERABLE_INTERFACE_TYPES`]. TypeNotAdvertisable, - /// Too soon after the last announce. + /// Too soon after the last successful commit; remaining seconds truncate + /// the fractional part of the computed interval. RateLimited { remaining_secs: u64 }, - /// Stamper refused to generate (LXStamper cancelled or missing key). + /// Encoding failed, the stamper returned no result, or its stamp had + /// the wrong length. This variant does not identify a specific cause. StampGenerationFailed, - /// `FLAG_ENCRYPTED` requested but no encryptor supplied to `tick`. + /// Encryption requested but no encryptor supplied to preparation. EncryptorMissing, /// Encryptor returned `None` for this payload. EncryptionFailed, } -/// Optional encryptor closure; the announcer holds no identity material. +/// Per-call body encryptor. Return `None` if encryption cannot be performed. pub type EncryptFn<'a> = &'a dyn Fn(&[u8]) -> Option>; -/// Pure-data scheduler. Not async, holds no timer — drive via `tick`. +/// Synchronous scheduler with no timer or network I/O. Drive publication with +/// [`Self::prepare`] and [`Self::commit`]; custom stamper/encryptor callbacks +/// may perform expensive work. Supply finite timestamps in one consistent +/// clock domain; they are not validated here. pub struct Announcer { owner: Arc<()>, stamper: Arc, @@ -161,6 +183,7 @@ pub struct Announcer { } impl Announcer { + /// Create an empty scheduler using the supplied stamp implementation. pub fn new(stamper: Arc) -> Self { Self { owner: Arc::new(()), @@ -170,8 +193,10 @@ impl Announcer { } } - /// Register (or replace) an interface's discovery config. - /// `transport_id` = 16-byte identity hash carried in `TRANSPORT_ID`. + /// Register or replace an interface's metadata. `transport_id` is copied + /// into the advertised info; its relationship to the outer signer is the + /// caller's responsibility. Replacement clears the success timestamp, + /// cached stamp and prepared publication, making this entry due immediately. pub fn register( &mut self, interface_id: InterfaceId, @@ -195,9 +220,14 @@ impl Announcer { ); } - /// Replace a registered interface's config but keep its announce interval, - /// so new information goes out with the next due announce. Returns `false` - /// for an unregistered interface. + /// Replace config while keeping the last successful commit time. The new + /// interval determines when the replacement is due; any prepared token is + /// invalidated. Returns `false` for an unregistered interface. + /// + /// The cached stamp is retained and reused if the encoded info is unchanged. + /// Since the generation target is not in that info, raising only + /// `stamp_value` can reuse a lower-work stamp. Use [`Self::register`] to + /// clear the cache when changing that requirement; it also resets timing. pub fn reconfigure( &mut self, interface_id: InterfaceId, @@ -216,23 +246,25 @@ impl Announcer { true } - /// Drop an interface from the announcer (called on deregister). + /// Remove the interface's scheduler state and invalidate its prepared token. + /// This does not remove an actual network interface. pub fn deregister(&mut self, interface_id: InterfaceId) { self.interfaces.remove(&interface_id); } - /// Inspect registered interfaces (for tests / introspection). + /// Number of registered configs, including entries not marked discoverable. pub fn len(&self) -> usize { self.interfaces.len() } + /// Whether no interface configs are registered. pub fn is_empty(&self) -> bool { self.interfaces.is_empty() } - /// Compatibility convenience: prepare and immediately commit every result. - /// Runtime publishers should use [`Self::prepare`] and [`Self::commit`] so - /// a failed egress does not consume the success interval. + /// Prepare and immediately commit every result before returning it. + /// No transmission is attempted. Use [`Self::prepare`] and [`Self::commit`] + /// separately when failed egress must not consume the success interval. pub fn tick( &mut self, now: f64, @@ -250,8 +282,13 @@ impl Announcer { } /// Prepare due publications without advancing their success interval. - /// Repeated calls return the same bytes (including ciphertext) until commit - /// or replacement; callers keep at most one dispatch per prepared result. + /// Repeated calls return cached bytes, including ciphertext, until commit + /// or replacement. A different encryptor alone does not replace cached + /// ciphertext. Keep at most one active dispatch per prepared token. + /// + /// Stamp generation and encryption run synchronously here. Returned stamps + /// are length-checked but not revalidated against the target; the stamper + /// must honor its contract. Per-interface result ordering is unspecified. pub fn prepare( &mut self, now: f64, @@ -362,8 +399,13 @@ impl Announcer { (out, skips) } - /// Record first actual driver admission for this exact publication. - /// A duplicate or replaced-generation result cannot restart the interval. + /// Mark this exact publication successful at `now`. Returns `false` for + /// another announcer's token, a removed/replaced entry, or a token already + /// committed. A successful commit clears prepared bytes and advances the + /// generation while retaining the stamp cache. + /// + /// This trusts the caller's admission decision; it does not check driver + /// queues, dispatch or delivery. The timestamp is stored without validation. pub fn commit(&mut self, prepared: &PreparedAnnounce, now: f64) -> bool { let Some(state) = self.interfaces.get_mut(&prepared.request.interface_id) else { return false; diff --git a/crates/rns-transport/src/discovery/app_data.rs b/crates/rns-transport/src/discovery/app_data.rs index 15d2bb5..590ad65 100644 --- a/crates/rns-transport/src/discovery/app_data.rs +++ b/crates/rns-transport/src/discovery/app_data.rs @@ -1,7 +1,6 @@ //! Discovery announce app_data — msgpack encode/decode. //! -//! Wire format (matches Python `Discovery.py` `get_interface_announce_data` -//! / `InterfaceAnnounceHandler.received_announce`): +//! Python-compatible discovery framing: //! //! ```text //! app_data = flags_byte(1) || payload @@ -13,9 +12,9 @@ //! stamp = STAMP_SIZE (32) bytes, produced by the configured DiscoveryStamper //! ``` //! -//! The map keys are byte values (not strings). Python encodes them via -//! `umsgpack.packb`, which uses fixint or uint8 depending on range; rmpv -//! produces the same bytes in both cases. +//! Map keys are unsigned integer values, not strings. These helpers perform +//! framing and field conversion; they do not validate the outer Reticulum +//! announce, its signature or the stamp. Callers must supply those checks. use std::io::Cursor; @@ -24,16 +23,17 @@ use thiserror::Error; use super::constants::{DISCOVERABLE_INTERFACE_TYPES, FLAG_ENCRYPTED, STAMP_SIZE, key}; -/// A decoded discovery info payload. Mirrors the Python `info` dict. +/// Advertised interface metadata, before any endpoint or identity trust decision. /// -/// Location keys are always emitted, with `nil` for each unknown component. -/// Missing location keys and integer numbers are accepted for compatibility -/// with older Rust callers; Python requires present keys with nil or floats. +/// Encoding always emits location keys, using `nil` for unknown components. +/// Decoding also accepts missing locations and integer coordinates. This type +/// can hold out-of-range radio/location values; encoding is not validation. #[derive(Debug, Clone, Default, PartialEq)] pub struct DiscoveryInfo { /// Human-readable interface name (key `0xFF`). pub name: String, - /// Transport identity hash of the announcer (key `0xFE`, 16 bytes). + /// Claimed transport identity hash (key `0xFE`, 16 bytes). Decoding does + /// not authenticate its association with the announce sender. pub transport_id: [u8; 16], /// The announcing stack and its version (keys `0xFD` / `0xFC`), when it /// names them as strings. @@ -50,15 +50,21 @@ pub struct DiscoveryInfo { pub latitude: Option, pub longitude: Option, pub height: Option, - /// TCP/Backbone bind port (key `0x06`). + /// Advertised TCP/Backbone port (key `0x06`), not necessarily a local bind port. pub port: Option, - /// IFAC virtual-network overlay (keys `0x07` / `0x08`). + /// Advertised IFAC network name (key `0x07`). pub ifac_netname: Option, + /// Advertised IFAC network passphrase (key `0x08`). It is serialized in + /// the info map; use appropriate discovery encryption or omit it when + /// it must not be disclosed to every recipient of the announce. pub ifac_netkey: Option, - /// Radio-link parameters (keys `0x09` / `0x0A` / `0x0B` / `0x0C`). + /// Radio frequency in Hz (key `0x09`). Encoding does not validate RF settings. pub frequency: Option, + /// Radio bandwidth in Hz (key `0x0A`). pub bandwidth: Option, + /// LoRa spreading-factor value (key `0x0B`). pub spreading_factor: Option, + /// LoRa coding-rate parameter (key `0x0C`). pub coding_rate: Option, /// Modulation name for Weave / KISS (key `0x0D`). pub modulation: Option, @@ -88,9 +94,9 @@ pub enum AppDataError { InvalidReachableOn(String), } -/// Encoded payload — separates the stamp from the raw msgpack map so the -/// caller can stamp it separately (stamper wraps the info-hash, not the full -/// app_data). Call [`Encoded::assemble`] once a stamp is in hand. +/// Serialized info bytes and their hash, ready for a separately generated +/// stamp. Call [`Encoded::assemble`] to add framing. The fields are public; +/// after changing `packed`, recompute its hash and stamp before assembling. pub struct Encoded { /// The msgpack-encoded info map. pub packed: Vec, @@ -99,13 +105,14 @@ pub struct Encoded { } impl Encoded { - /// Combine `packed_info || stamp`, optionally encrypt, prefix flags byte. + /// Append a 32-byte stamp to `packed`, optionally encrypt that body, and + /// prefix one flags byte. Returns `None` for another stamp length, a missing + /// required encryptor or an encryptor returning `None`. /// - /// `encrypt` is a closure so discovery doesn't need to carry the network - /// identity type — the caller composes with - /// `Identity::encrypt(&self.network_identity, ...)` when - /// `flag_encrypted` is set. When `encrypt` is `None` and - /// `flag_encrypted` is true, the function returns `None`. + /// `flag_signed` only sets a bit; it neither creates nor verifies a + /// signature. The stamp's work value and `infohash` are not checked here. + /// When encryption is disabled, the encryptor is not called and all info + /// fields remain cleartext. The callback determines encryption semantics. pub fn assemble( self, stamp: &[u8], @@ -139,11 +146,14 @@ impl Encoded { } } -/// Optional network-identity encryptor used when assembling discovery app-data. +/// Optional body-encryption callback for discovery app-data. Receives +/// `packed_info || stamp`; return `None` to fail assembly. pub type DiscoveryEncryptor<'a> = dyn Fn(&[u8]) -> Option> + 'a; -/// Serialize the info dict to the `(packed, infohash)` pair used by the -/// stamper. Matches Python `msgpack.packb(info)` + `Identity.full_hash(packed)`. +/// Serialize an info map and compute its full SHA-256 hash for stamping. +/// Unknown location components and unset parameters required by the selected +/// radio type are emitted as `nil`. Fields are not range-checked or sanitized; +/// this can encode metadata that [`decode_info`] would reject. pub fn encode_info(info: &DiscoveryInfo) -> Result { let map = info_to_map(info); let value = Value::Map(map); @@ -252,14 +262,16 @@ fn u8_key(k: u8) -> Value { /// Split an inbound app_data blob into `(flags, payload_body)` where /// `payload_body` is everything after the flags byte. The body is still -/// `msgpack_info || stamp` (optionally still-encrypted). +/// `msgpack_info || stamp` (optionally encrypted). Only empty input fails; +/// flag bits and body contents are not validated. pub fn split_flags(app_data: &[u8]) -> Result<(u8, &[u8]), AppDataError> { let (first, rest) = app_data.split_first().ok_or(AppDataError::Empty)?; Ok((*first, rest)) } /// Split the decrypted/cleartext body into `(packed_info, stamp)`. The -/// stamp is always the trailing [`STAMP_SIZE`] bytes. +/// stamp is always the trailing [`STAMP_SIZE`] bytes. At least one preceding +/// info byte is required; neither portion is decoded or authenticated here. pub fn split_stamp(body: &[u8]) -> Result<(&[u8], &[u8]), AppDataError> { if body.len() <= STAMP_SIZE { return Err(AppDataError::TooSmall { @@ -271,7 +283,19 @@ pub fn split_stamp(body: &[u8]) -> Result<(&[u8], &[u8]), AppDataError> { Ok((&body[..split_at], &body[split_at..])) } -/// Decode a msgpack info map back into [`DiscoveryInfo`]. +/// Decode the first MessagePack value as an info map. Interface type and a +/// 16-byte transport ID are required; absent other fields retain defaults. +/// Unknown/non-numeric keys are ignored. Recognized keys are processed in +/// order, so later values replace earlier ones. Most recognized-field type +/// errors reject the entire decode; a nonstring implementation name/version +/// instead clears that optional field. Trailing bytes after the first map +/// are not rejected. +/// +/// The type must be in `DISCOVERABLE_INTERFACE_TYPES`, the name is sanitized, +/// and a supplied endpoint must pass the local IP/hostname syntax check. +/// This does not resolve the endpoint, authenticate the transport ID, validate +/// radio/location ranges or verify a stamp. Oversized port/channel and SF/CR +/// integers are clamped to their destination integer width, not rejected. pub fn decode_info(packed: &[u8]) -> Result { let value = rmpv::decode::read_value(&mut Cursor::new(packed)) .map_err(|e| AppDataError::Msgpack(e.to_string()))?; @@ -361,6 +385,9 @@ pub fn decode_info(packed: &[u8]) -> Result { Ok(info) } +/// Remove non-ASCII and control characters, collapse remaining whitespace, +/// trim, and remove trailing characters after the final ASCII letter, digit +/// or `)`. This is display cleanup, not general HTML or shell escaping. pub fn sanitize_name(name: &str) -> String { let ascii = name .chars() diff --git a/crates/rns-transport/src/discovery/autoconnect.rs b/crates/rns-transport/src/discovery/autoconnect.rs index 5e32dbc..c6931ea 100644 --- a/crates/rns-transport/src/discovery/autoconnect.rs +++ b/crates/rns-transport/src/discovery/autoconnect.rs @@ -1,12 +1,19 @@ -//! Which discovered interfaces may be auto-connected -//! (`InterfaceDiscovery.autoconnect_qualified`, Discovery.py:782-798). +//! Interface-type and advertised-version filter for automatic connections. +//! This module decides eligibility only; it does not open a connection. use super::app_data::DiscoveryInfo; use super::constants::{AUTOCONNECT_INTERFACE_TYPES, AUTOCONNECT_MINIMUM_VERSIONS}; -/// A Backbone interface whose stack is at least the trusted release of its -/// implementation, or any Backbone interface when `allow_unverified` -/// (`autoconnect_unverified_implementations`) is set. +/// Check the advertised type and implementation/version against the local +/// auto-connect policy. Currently only `BackboneInterface` is eligible. +/// With `allow_unverified`, any advertised implementation/version qualifies +/// for that type; otherwise `RNS` must advertise at least version `1.5.2`. +/// `rsRNS`, unknown implementations and missing versions require the opt-in. +/// +/// Comparison uses leading numeric components, not full semantic-version +/// rules: for example, `1.5.2rc1` compares as `1.5.2`. These are sender-supplied +/// claims, not attestation. This helper does not check transport-enabled state, +/// freshness, endpoint validity, source permissions or available connection slots. pub fn qualifies(info: &DiscoveryInfo, allow_unverified: bool) -> bool { if !AUTOCONNECT_INTERFACE_TYPES.contains(&info.interface_type.as_str()) { return false; diff --git a/crates/rns-transport/src/discovery/blackhole_manifest.rs b/crates/rns-transport/src/discovery/blackhole_manifest.rs index e41c1ba..f076cc2 100644 --- a/crates/rns-transport/src/discovery/blackhole_manifest.rs +++ b/crates/rns-transport/src/discovery/blackhole_manifest.rs @@ -1,8 +1,8 @@ //! Wire-format codec for the distributed blackhole manifest. //! -//! Mirrors the msgpack payload served by Python's -//! `rnstransport.info.blackhole` request handler (Transport.py:3243) and -//! consumed by the subscriber side of `BlackholeUpdater` (Discovery.py:658). +//! Encodes and decodes the MessagePack body for the +//! `rnstransport.info.blackhole` service's `/list` request. The codec does +//! not authenticate a publisher or verify the truth of its blackhole reasons. //! //! # Wire shape //! @@ -17,18 +17,17 @@ //! } //! ``` //! -//! Python uses absolute-deadline `until` on the wire; the Rust table keeps -//! relative `ttl`. Conversions happen at the boundary: -//! - **encode**: `until = created + ttl` when `ttl.is_some()`, else `nil`. -//! - **decode**: `created = now`, `ttl = max(0, until - now)`. This mirrors -//! the semantics in Transport.py:3212 — expired entries are skipped. +//! The wire carries absolute `until` deadlines; the table keeps relative TTLs: +//! - **build**: `until = created + ttl`, or `nil` without a TTL. +//! - **apply**: skip deadlines at or before `now`, then use `created = now` +//! and `ttl = max(0, until - now)`. Decoding alone does not apply expiry. //! //! # Publication filter //! -//! A node only publishes entries it issued itself. In-memory: entries with -//! `source == None`. Python's equivalent filter (Transport.py:3256) is -//! `source == Transport.identity.hash`; we keep `None` as a marker so the -//! table does not need to know its own identity. +//! [`build_local_manifest`] includes only entries with `source == None`. +//! This marker is a caller-controlled provenance convention, not cryptographic +//! evidence. Applying a manifest preserves its claimed inner source fields; +//! callers must authorize the publisher and any delegated-source policy. use std::collections::BTreeMap; @@ -38,15 +37,17 @@ use thiserror::Error; use crate::blackhole::{BlackholeEntry, BlackholeReason, BlackholeTable}; -/// A single manifest entry on the wire. `created` is not transmitted — -/// Python stores `until` (absolute deadline) instead. +/// One decoded manifest entry. The wire carries an absolute `until` deadline +/// rather than `created`; field decoding does not establish trusted provenance. #[derive(Debug, Clone, PartialEq)] pub struct BlackholeManifestEntry { /// Absolute unix-second deadline, or `None` for permanent entries. pub until: Option, - /// Stable string identifier (see [`BlackholeReason::as_str`]). + /// Publisher-supplied reason label. Empty represents a wire `nil` reason; + /// unknown labels remain available alongside the parsed reason enum. pub reason: String, - /// Identity hash of the source that issued this entry. + /// Claimed source identity. The codec does not bind it to the responding + /// publisher or verify delegation. pub source: IdentityHash, } @@ -68,19 +69,13 @@ pub enum ManifestError { Encode(String), } -/// Build the msgpack manifest payload of **locally-issued** blackhole -/// entries. Used by the `/list` request handler on -/// `rnstransport.info.blackhole`. +/// Build a manifest from entries marked local (`source == None`), writing +/// `our_identity_hash` into every source field. Remote-marked entries are +/// excluded, but expired entries are not filtered here. /// -/// `our_identity_hash` is injected into every entry's `source` field so -/// subscribers can correctly key entries by publisher. -/// -/// `verified_ids`, when `Some(_)`, restricts the published entries to those -/// whose identity hash is in the set — typically the set of identity hashes -/// derivable from current `recent_announces` public keys. This refuses to -/// republish unverifiable entries (e.g., garbage from a buggy caller, or -/// identities whose announces have been pruned). When `None`, no filtering -/// is applied — used by tests that want to inspect the raw round-trip. +/// `verified_ids`, when supplied, restricts output to hashes in that set. +/// The helper trusts the set; it does not verify identities itself. `None` +/// disables this additional filter. The returned body is not signed here. pub fn build_local_manifest( table: &BlackholeTable, our_identity_hash: IdentityHash, @@ -126,9 +121,15 @@ fn encode_entry_map(until: Option, reason: &str, source: IdentityHash) -> V ]) } -/// Parse a msgpack manifest payload into `(identity_hash, entry)` pairs. -/// Sorted for deterministic iteration in tests; order is not load-bearing -/// otherwise. +/// Decode the first MessagePack map and return entries sorted by identity hash. +/// Required field types and 16-byte hashes are checked; malformed entries fail +/// the whole load. Repeated identities keep their last decoded entry, repeated +/// recognized fields keep their last decoded value, and unknown fields are +/// ignored. Trailing bytes after the map are not rejected. +/// +/// This neither authenticates source claims nor filters expired entries. +/// Floating-point deadlines need not be finite; validate that policy before +/// applying untrusted input. No input-size or entry-count bound is imposed here. pub fn decode_manifest( bytes: &[u8], ) -> Result, ManifestError> { @@ -210,17 +211,18 @@ fn decode_entry_map(v: Value) -> Result { }) } -/// Merge a decoded manifest into `table`. `source_identity_hash` is the -/// publisher that answered the `/list` request; each entry's inner -/// `source` field is preserved so a chain of republishers stays -/// traceable (Python parity: Discovery.py:672-675). +/// Merge entries into `table`, trusting their inner source fields. There is +/// no publisher parameter or authentication check: the caller must authorize +/// the manifest before applying it and supply finite time values. /// -/// Skips: -/// - entries whose local-table source is `None` (locally-issued always wins); -/// - entries whose `until` deadline has already passed (matches -/// Transport.py:3212). +/// Entries with `until <= now` are skipped. Any existing entry marked local +/// (`source == None`) wins, even if it is expired but not yet culled. Otherwise +/// the incoming entry replaces the identity's record, retaining its reason +/// label and claimed source and converting the deadline to a remaining TTL. +/// Entries absent from the manifest are not removed. /// -/// Returns the number of entries actually inserted or updated. +/// Returns the number of insert/update operations, which can exceed the number +/// of unique identities if the supplied slice repeats them. pub fn apply_manifest( table: &mut BlackholeTable, manifest: &[([u8; 16], BlackholeManifestEntry)], diff --git a/crates/rns-transport/src/discovery/blackhole_subscriber.rs b/crates/rns-transport/src/discovery/blackhole_subscriber.rs index a942e3a..4882c9a 100644 --- a/crates/rns-transport/src/discovery/blackhole_subscriber.rs +++ b/crates/rns-transport/src/discovery/blackhole_subscriber.rs @@ -1,40 +1,32 @@ -//! Pure-data subscriber state machine for the distributed blackhole list. +//! Per-source scheduling state for distributed blackhole-list updates. //! -//! Tracks per-source "last pulled at" timestamps and decides which sources -//! are due for a refresh on the current tick. The actual link -//! establishment + `/list` request lives in the runtime layer; this module -//! is intentionally free of tokio so the due-source logic can be unit -//! tested without timers or fakes. -//! -//! Mirrors the scheduling half of Python's `BlackholeUpdater.job()` loop -//! (RNS/Discovery.py:693) with the same constants: -//! `INITIAL_WAIT=20s`, `JOB_INTERVAL=60s`, `UPDATE_INTERVAL=3600s`. +//! The runtime owns waiting, Link establishment, `/list` requests and applying +//! the response. This module only compares caller-supplied timestamps and +//! records caller-reported successful updates; it performs no network I/O. use std::collections::HashMap; use std::time::Duration; use rns_wire::types::IdentityHash; -/// Python `BlackholeUpdater.INITIAL_WAIT` — delay before the first job tick. +/// Runtime delay before the first subscriber sweep (20 seconds). pub const INITIAL_WAIT: Duration = Duration::from_secs(20); -/// Python `BlackholeUpdater.JOB_INTERVAL` — time between scheduling sweeps. +/// Runtime scheduling interval (60 seconds), after processing the current +/// sweep's sources; request time can extend the observed interval. pub const JOB_INTERVAL: Duration = Duration::from_secs(60); -/// Python `BlackholeUpdater.UPDATE_INTERVAL` — default minimum gap between -/// successful pulls from the same source (1 hour). Python 1.3.8 makes this -/// configurable via `blackhole_update_interval` (Reticulum.py:593-596, -/// consumed at Discovery.py:749); the config-side minutes→seconds conversion -/// and 2-minute clamp live at the parse site, this module takes seconds. +/// Default minimum elapsed time after a source's last successful update +/// (one hour). [`SubscriberState::with_update_interval`] overrides it. pub const UPDATE_INTERVAL: Duration = Duration::from_secs(60 * 60); -/// Python `BlackholeUpdater.SOURCE_TIMEOUT` — kept here for parity but -/// currently unused; the runtime wrapper races it against the link -/// establishment / request when it lands. +/// Timeout budget supplied by the runtime to each blackhole `/list` query +/// (25 seconds). This state machine itself does not enforce timeouts. pub const SOURCE_TIMEOUT: Duration = Duration::from_secs(25); -/// Per-process subscriber state. Cheap to clone for inspection; the runtime -/// owner holds the authoritative copy. +/// In-memory per-source update cursors. Cloning copies the cursors and interval; +/// clones do not share subsequent updates. Use finite Unix-second timestamps +/// consistently; they are stored and compared without validation. #[derive(Debug, Clone)] pub struct SubscriberState { /// Unix-seconds timestamp of the most recent successful pull, keyed by @@ -56,40 +48,42 @@ impl Default for SubscriberState { } impl SubscriberState { + /// Start with no update cursors and the one-hour default interval. pub fn new() -> Self { Self::default() } - /// Override the per-source pull interval. The caller passes seconds - /// already clamped at config parse (min 2 minutes, Reticulum.py:593-596). + /// Set the minimum elapsed time after each successful update. No minimum + /// is enforced here; zero makes a source due whenever `now >= last_update`. pub fn with_update_interval(mut self, interval: Duration) -> Self { self.update_interval = interval; self } + /// Return the currently configured interval. pub fn update_interval(&self) -> Duration { self.update_interval } - /// Record a successful pull from `source` at `now` (Unix seconds). + /// Record caller-reported success at `now`, replacing any prior timestamp. + /// This does not validate or apply the source's manifest. pub fn mark_updated(&mut self, source: IdentityHash, now: f64) { self.last_updates.insert(source, now); } - /// Clear the last-update cursor for `source`, forcing the next tick - /// to re-pull even if `UPDATE_INTERVAL` has not elapsed. Useful when - /// an operator edits `blackhole_sources` and wants an immediate - /// refresh. + /// Remove a source's cursor. Subsequent scheduling treats its last update + /// as Unix time zero; no network request is issued by this method. pub fn forget(&mut self, source: &IdentityHash) { self.last_updates.remove(source); } - /// Returns the list of sources that should be pulled on this tick, - /// given the configured source list and the current time. + /// Return configured sources for which `now - last_update >= interval`, + /// sorted by identity hash and deduplicated. Missing cursors use zero, so + /// they are due only once `now >= interval`. /// - /// Order is deterministic (sorted by identity hash) so the runtime - /// does not accidentally thundering-herd one source ahead of another - /// after a restart. + /// This does not advance cursors, reserve in-flight work, back off failures + /// or stagger sources. Repeated calls can return the same due list until + /// the caller records successful updates. pub fn due_sources(&self, configured: &[IdentityHash], now: f64) -> Vec { let mut due: Vec = configured .iter() @@ -104,9 +98,8 @@ impl SubscriberState { due } - /// Drop cursors for sources that no longer appear in `configured`. - /// Keeps the table bounded when an operator rotates their source - /// list. + /// Drop cursors whose identities are absent from `configured`. No source + /// count limit is otherwise enforced by this state machine. pub fn prune(&mut self, configured: &[IdentityHash]) { self.last_updates .retain(|src, _| configured.iter().any(|c| c == src)); diff --git a/crates/rns-transport/src/discovery/constants.rs b/crates/rns-transport/src/discovery/constants.rs index c32a665..4d1bd06 100644 --- a/crates/rns-transport/src/discovery/constants.rs +++ b/crates/rns-transport/src/discovery/constants.rs @@ -1,5 +1,6 @@ -//! Wire-level constants for on-network discovery. Values mirror -//! `RNS/Discovery.py` 1:1; do not renumber. +//! Discovery wire identifiers, default work/timing values and local listing +//! policy. Wire key and flag changes affect interoperability; timing defaults +//! and accepted types are separate policy choices. /// Application name used in the discovery destination /// `rnstransport.discovery.interface`. @@ -17,28 +18,29 @@ pub const BLACKHOLE_ASPECTS: &[&str] = &["info", "blackhole"]; /// `rnstransport.info.blackhole` — joined for `aspect_filter` lookups. pub const BLACKHOLE_ASPECT_FILTER: &str = "rnstransport.info.blackhole"; -/// Announce job tick (seconds). Matches Python `InterfaceAnnouncer.JOB_INTERVAL`. +/// Default publication interval in seconds (60), used by the Backbone config helper. pub const ANNOUNCE_JOB_INTERVAL_SECS: u64 = 60; -/// Default stamp-value requirement used by both sender (when an interface -/// leaves `discovery_stamp_value` unset) and receiver. Matches Python -/// `InterfaceAnnouncer.DEFAULT_STAMP_VALUE`. +/// Default discovery work target/requirement (16 leading zero bits). Sender +/// generation targets and receiver requirements are configured independently. pub const DEFAULT_STAMP_VALUE: u8 = 16; -/// Rounds used when deriving the stamp workblock. Matches Python -/// `InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS`. +/// Discovery stamp-workblock expansion rounds (20). A custom stamper must use +/// the compatible algorithm; the trait does not enforce this constant itself. pub const WORKBLOCK_EXPAND_ROUNDS: u32 = 20; -/// Fixed stamp length (bytes) emitted by the LXMF stamper. Matches Python -/// `LXStamper.STAMP_SIZE`. +/// Fixed discovery stamp length in bytes (32). pub const STAMP_SIZE: usize = 32; -/// Discovery app_data is prefixed with one flags byte. +/// Signed marker in the leading app-data flags byte. Setting it does not +/// create a signature; outer announce authentication is separate. pub const FLAG_SIGNED: u8 = 0b0000_0001; +/// Marker selecting encrypted body processing after the flags byte. pub const FLAG_ENCRYPTED: u8 = 0b0000_0010; -/// Interface types that announce themselves via discovery, and that a -/// receiver accepts. Mirrors `InterfaceAnnouncer.DISCOVERABLE_INTERFACE_TYPES`. +/// Types allowed by the announcer's type check and info-map decoder. This +/// list does not establish runtime interface support or listing eligibility; +/// the receiver additionally applies [`DISCOVERED_INTERFACE_TYPES`]. pub const DISCOVERABLE_INTERFACE_TYPES: &[&str] = &[ "BackboneInterface", "TCPServerInterface", @@ -49,8 +51,8 @@ pub const DISCOVERABLE_INTERFACE_TYPES: &[&str] = &[ "KISSInterface", ]; -/// Discovered interface types that are listed; stored records of other types -/// are removed. Mirrors `InterfaceDiscovery.DISCOVERABLE_TYPES`. +/// Types retained by discovery reception and store listing. The store's +/// `list` method attempts to remove records of other types. pub const DISCOVERED_INTERFACE_TYPES: &[&str] = &[ "BackboneInterface", "TCPServerInterface", @@ -60,42 +62,48 @@ pub const DISCOVERED_INTERFACE_TYPES: &[&str] = &[ "KISSInterface", ]; -/// Interface types eligible for auto-connect. Mirrors -/// `InterfaceDiscovery.AUTOCONNECT_TYPES`. +/// Types eligible for the auto-connect version filter. Endpoint and other +/// runtime checks are separate. pub const AUTOCONNECT_INTERFACE_TYPES: &[&str] = &["BackboneInterface"]; -/// The implementation name this stack announces (`0xFD`); Python announces -/// "RNS" (`IMPLEMENTATION_NAME`). +/// Implementation name emitted in this stack's discovery info (`0xFD`). pub const IMPLEMENTATION_NAME: &str = "rsRNS"; -/// The version this stack announces (`0xFC`): its own, never Python's. +/// This transport crate's package version, emitted in discovery info (`0xFC`). pub const IMPLEMENTATION_VERSION: &str = env!("CARGO_PKG_VERSION"); -/// The oldest release of each implementation that auto-connect trusts: -/// Python's floor for "RNS" (Discovery.py:486-487), and none for rsRNS, which -/// qualifies only with `autoconnect_unverified_implementations`. +/// Advertised-version floors for automatic connections. `RNS` has a `1.5.2` +/// floor; `rsRNS` has none and requires the unverified-implementation opt-in. +/// This policy checks sender claims, not authenticated software provenance. pub const AUTOCONNECT_MINIMUM_VERSIONS: &[(&str, Option<&str>)] = &[("RNS", Some("1.5.2")), (IMPLEMENTATION_NAME, None)]; -/// Freshness tiers for discovered interfaces (seconds). Match -/// `InterfaceDiscovery.THRESHOLD_*`. +/// Age in seconds above which a record becomes `Unknown` (24 hours). +/// Equality remains `Available`. pub const THRESHOLD_UNKNOWN_SECS: u64 = 24 * 60 * 60; +/// Age in seconds above which a record becomes `Stale` (three days). pub const THRESHOLD_STALE_SECS: u64 = 3 * 24 * 60 * 60; +/// Age in seconds above which store listing attempts removal (seven days). pub const THRESHOLD_REMOVE_SECS: u64 = 7 * 24 * 60 * 60; -/// Monitor-job cadence and detach threshold (Python -/// `InterfaceDiscovery.MONITOR_INTERVAL` / `DETACH_THRESHOLD`). +/// Exported monitor-interval value in seconds (5). The discovery helpers +/// do not start a monitor or enforce this cadence. pub const MONITOR_INTERVAL_SECS: u64 = 5; +/// Exported monitor-detachment threshold in ticks (12). The discovery +/// helpers do not implement a detachment monitor. pub const DETACH_THRESHOLD_TICKS: u64 = 12; -/// Blackhole updater timings (`BlackholeUpdater.*`). +/// Default blackhole subscriber initial wait, in seconds. pub const BLACKHOLE_INITIAL_WAIT_SECS: u64 = 20; +/// Default blackhole subscriber sweep interval, in seconds. pub const BLACKHOLE_JOB_INTERVAL_SECS: u64 = 60; +/// Default per-source blackhole update interval, in seconds. pub const BLACKHOLE_UPDATE_INTERVAL_SECS: u64 = 60 * 60; +/// Default blackhole source-query timeout budget, in seconds. pub const BLACKHOLE_SOURCE_TIMEOUT_SECS: u64 = 25; -/// msgpack map keys — byte values, must match Python `Discovery.py` exactly. -/// These ride on the wire; renumbering is a breaking protocol change. +/// Numeric MessagePack map keys for discovery info. These are wire identifiers; +/// renumbering them changes the protocol. pub mod key { pub const NAME: u8 = 0xFF; pub const TRANSPORT_ID: u8 = 0xFE; diff --git a/crates/rns-transport/src/discovery/mod.rs b/crates/rns-transport/src/discovery/mod.rs index a78ce00..7bb9fe5 100644 --- a/crates/rns-transport/src/discovery/mod.rs +++ b/crates/rns-transport/src/discovery/mod.rs @@ -1,17 +1,17 @@ -//! On-network interface discovery — Rust port of Python `RNS/Discovery.py`. +//! Interface-discovery metadata, publication scheduling and reception. //! -//! The announcer periodically posts PoW-stamped discovery announces on -//! `rnstransport.discovery.interface`. The receiver validates stamps, stores -//! learned interfaces, and (optionally) auto-connects to eligible transport -//! nodes. A separate blackhole updater fetches blackhole manifests from -//! configured sources via link request. +//! The announcer prepares stamped app-data for +//! `rnstransport.discovery.interface`; its runtime owner supplies the timer, +//! signed outer announce and transmission. The receiver validates work and +//! stores observations. Auto-connect helpers check advertised eligibility; +//! the runtime owns actual connections. Blackhole manifest codecs and update +//! cursors support the separate `rnstransport.info.blackhole` service. //! -//! # Stamper indirection -//! -//! Python imports `LXMF.LXStamper` at startup. rsReticulum avoids an upward -//! dependency on rsLXMF, so discovery takes a [`DiscoveryStamper`] trait object; -//! the concrete implementation lives in `lxmf-core::discovery_stamper`. -//! Without a stamper installed, discovery is silent. +//! Discovery accepts a [`DiscoveryStamper`] so transport need not depend on +//! LXMF. An embedding application can supply the concrete implementation from +//! `lxmf-core::discovery_stamper`. [`NullStamper`] generates no work and rejects +//! inbound stamps; it does not disable the separate blackhole helpers or erase +//! previously stored discovery records. pub mod announcer; pub mod app_data; diff --git a/crates/rns-transport/src/discovery/receiver.rs b/crates/rns-transport/src/discovery/receiver.rs index ef4519e..47781bf 100644 --- a/crates/rns-transport/src/discovery/receiver.rs +++ b/crates/rns-transport/src/discovery/receiver.rs @@ -10,9 +10,15 @@ //! drop types that are never listed, //! 5. upsert into [`DiscoveryStore`] and notify any observer. //! -//! Mirrors Python `Discovery.InterfaceAnnounceHandler.received_announce`. -//! The spawned path uses a bounded blocking-worker set so slow stamp -//! validation cannot stall the transport actor or a Tokio runtime worker. +//! The caller must supply correctly routed, validated outer announce events. +//! This module does not verify their signature, aspect or relationship between +//! the event identity and the transport ID claimed in app-data. Only the +//! encrypted flag changes processing; other flag bits are not authenticated here. +//! +//! The spawned path uses bounded blocking workers and caches stamp-validation +//! results. Decoded metadata, including any advertised IFAC passphrase, can be +//! retained in the validation cache, store and observer event. Operational +//! metrics contain counters only. use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet, VecDeque}; @@ -34,45 +40,54 @@ const VALID_CACHE_CAPACITY: usize = 2_048; const INVALID_CACHE_CAPACITY: usize = 2_048; const MAX_IN_FLIGHT_EVENTS: usize = 32; -/// Pluggable decryptor for discovery announces whose flags byte has -/// `FLAG_ENCRYPTED` set. The concrete impl wraps the `network_identity` -/// (Python `RNS.Identity.decrypt`). +/// Body decryptor for announces with `FLAG_ENCRYPTED` set. Return the clear +/// `packed_info || stamp` body, or `None` to reject it. /// -/// Returning `None` means the ciphertext could not be decrypted with the -/// held identity — the receiver treats that as "not for us" and drops the -/// announce silently. +/// Spawned receivers bind cached validation to the decryptor object's identity, +/// not its internal key state. Keep that state stable for the receiver's lifetime; +/// restart the receiver when changing keys so old cached plaintext is not reused. pub trait DiscoveryDecryptor: Send + Sync { + /// Decrypt synchronously. The callback determines encryption/authentication + /// semantics; `None` becomes [`Reason::DecryptFailed`]. fn decrypt(&self, ciphertext: &[u8]) -> Option>; } -/// Configuration passed to [`spawn`]. Cheap to clone into the task. +/// Owned configuration consumed by [`spawn`], or used directly through +/// [`Self::process_event`]. Keep stamp-validation and decryptor behavior stable +/// while a spawned receiver caches their results. pub struct ReceiverConfig { + /// Work validation and value calculation; a successful cache hit reuses + /// earlier results without calling this implementation again. pub stamper: Arc, + /// Local record store. The spawned receiver serializes its own writes; + /// direct callers or other store users need their own coordination. pub store: Arc, - /// Minimum stamp value required to accept an announce. Mirrors Python - /// `discover_interfaces_required_value`. + /// Work requirement passed to the stamper. It is independent of the + /// sender's configured generation target. pub required_value: u8, - /// When `Some`, only announces whose source transport-id is in the - /// list are accepted (Python `interface_discovery_sources`). `None` - /// accepts any stamped source. + /// Allowed source identities. The filter uses `event.identity_hash` when + /// present, otherwise the info map's claimed transport ID. `Some(vec![])` + /// rejects every source; `None` applies no source restriction. The caller + /// remains responsible for the trustworthiness of the supplied event. pub discovery_sources: Option>, - /// Optional decryptor for `FLAG_ENCRYPTED` announces. `None` means - /// encrypted announces are silently ignored. + /// Body decryptor. Encrypted input without one is rejected as + /// [`Reason::EncryptedWithoutKey`]. pub decryptor: Option>, - /// Optional observer channel — every successful upsert is published. - /// The sender is never blocked (uses `try_send`), so a slow consumer - /// drops events rather than stalling the receiver. + /// Best-effort observation after a successful store write. `try_send` + /// drops the event when full or closed without changing acceptance. + /// This is the newly received record, before the store merges history: + /// `heard_count` is zero and `status` is `None`; reload for stored totals. + /// Decoded fields, including any IFAC passphrase, are included. pub observer: Option>, } -/// Result of a single announce classification. Returned by -/// [`ReceiverConfig::process_event`] so tests can assert on decisions without -/// needing a live tokio task. +/// Result of synchronously processing one supplied announce event. #[derive(Debug, PartialEq)] pub enum Outcome { - /// Announce accepted and upserted. + /// The record was written to the store. This does not guarantee observer + /// delivery, a reachable endpoint or an automatic connection. Accepted, - /// Announce rejected before upsert. `Reason` carries the why. + /// Input was rejected or its store write failed; the reason describes why. Rejected(Reason), } @@ -81,11 +96,12 @@ pub enum Outcome { pub enum Reason { /// No `app_data` on the announce — discovery announces always carry one. MissingAppData, - /// `app_data` too small to even contain a flags byte + stamp. + /// Missing flags, or a body (after decryption when applicable) too short + /// to contain nonempty info followed by the 32-byte stamp. Malformed, /// `FLAG_ENCRYPTED` set without a configured decryptor. EncryptedWithoutKey, - /// Decryptor returned `None` (ciphertext not addressed to us). + /// Decryptor returned `None`; the specific cause is not available here. DecryptFailed, /// Another ingress worker is already performing stamp validation. ValidationBusy, @@ -93,11 +109,11 @@ pub enum Reason { StampInvalid, /// Info map did not decode. DecodeFailed, - /// Source (transport_id) not in the configured discovery_sources list. + /// Selected source identity is absent from the configured allow-list. UnauthorizedSource, /// An announceable type that is never listed ([`DISCOVERED_INTERFACE_TYPES`]). UnlistedType, - /// Upsert into the on-disk store failed (io error). + /// Store encoding or filesystem write failed. StorageFailed, } @@ -114,17 +130,24 @@ pub struct ReceiverMetrics { invalid_cache_evictions: AtomicU64, } -/// Point-in-time snapshot of [`ReceiverMetrics`]. +/// Individually read counter values from [`ReceiverMetrics`]. Concurrent +/// updates can occur between reads; this is not a single atomic snapshot. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct ReceiverMetricsSnapshot { + /// Successful lookups of cached decoded/stamp-validated material. pub valid_cache_hits: u64, + /// Lookups of cached stamp-invalid material. pub invalid_cache_hits: u64, + /// Uncached validations rejected because the validation gate was busy. pub validation_busy_drops: u64, + /// Valid-cache insertions that evicted an older entry. pub valid_cache_evictions: u64, + /// Invalid-cache insertions that evicted an older entry. pub invalid_cache_evictions: u64, } impl ReceiverMetrics { + /// Read saturating counters without retaining event content. pub fn snapshot(&self) -> ReceiverMetricsSnapshot { ReceiverMetricsSnapshot { valid_cache_hits: self.valid_cache_hits.load(Ordering::Relaxed), @@ -286,10 +309,12 @@ struct ReceiverState { } impl ReceiverConfig { - /// Classify a single announce event, upsert on accept, emit on observer. + /// Process one event synchronously, including decryption, stamp work and + /// filesystem I/O. Success writes the record and attempts observer delivery. /// - /// Synchronous so unit tests can drive it without a task. Returns an - /// [`Outcome`] describing the decision. + /// This direct path has no validation cache, worker bound or persistence + /// lock. Coordinate concurrent callers writing the same store. As with + /// [`spawn`], the caller supplies a validated outer announce event. pub fn process_event(&self, event: &AnnounceHandlerEvent) -> Outcome { self.process_event_inner(event, None) } @@ -572,17 +597,30 @@ fn lock_unpoisoned(mutex: &Mutex) -> MutexGuard<'_, T> { mutex.lock().unwrap_or_else(|err| err.into_inner()) } -/// Spawn the receiver task. Returns the sender to register with -/// `TransportMessage::RegisterAnnounceHandler { aspect_filter: -/// Some("rnstransport.discovery.interface"), callback_tx }` and the -/// [`JoinHandle`] for shutdown. +/// Spawn a receiver inside a Tokio runtime. Register the returned sender with +/// the transport announce handler using aspect filter +/// `rnstransport.discovery.interface`; this helper does not register it. +/// +/// To finish normally, unregister/drop every sender and await the task. It +/// drains queued events and waits for its workers. A blocking callback can +/// delay completion. See [`spawn_with_metrics`] for queue and cache behavior. pub fn spawn(config: ReceiverConfig) -> (JoinHandle<()>, mpsc::Sender) { let (handle, tx, _metrics) = spawn_with_metrics(config); (handle, tx) } -/// Spawn the receiver and retain a handle to its payload-free operational -/// counters. +/// Spawn the receiver and expose its counter-only metrics. +/// +/// The event channel holds 128 events, and at most 32 blocking workers are +/// tracked at once. One uncached stamp validation runs at a time; another +/// uncached attempt meeting a busy gate is rejected rather than queued there. +/// Cache hits can proceed, and this receiver serializes its store writes. +/// +/// Separate valid and stamp-invalid caches hold up to 2,048 entries each, +/// keyed by exact wire app-data (plus decryptor object identity when encrypted). +/// Successful hits still apply source/type filtering and update the store. +/// These are entry-count bounds, not byte limits. Callbacks have no execution +/// timeout here, and cached decoded fields remain until eviction or teardown. pub fn spawn_with_metrics( config: ReceiverConfig, ) -> ( diff --git a/crates/rns-transport/src/discovery/stamper.rs b/crates/rns-transport/src/discovery/stamper.rs index 6871bcf..7fd3934 100644 --- a/crates/rns-transport/src/discovery/stamper.rs +++ b/crates/rns-transport/src/discovery/stamper.rs @@ -1,38 +1,40 @@ //! Pluggable proof-of-work stamper for discovery announces. //! -//! Python `RNS.Discovery.InterfaceAnnouncer` imports `LXMF.LXStamper`. -//! rsReticulum avoids an upward dependency on rsLXMF, so discovery accepts a -//! trait object. The concrete implementation lives in -//! `lxmf-core::discovery_stamper::LxmfDiscoveryStamper` and is wired at startup -//! by the embedding application. +//! Discovery accepts a trait object so transport does not depend on LXMF. +//! Embedding applications can install +//! `lxmf-core::discovery_stamper::LxmfDiscoveryStamper`, which supplies the +//! discovery workblock and stamp algorithm. These methods are synchronous; +//! callers choose where to run potentially expensive generation/validation. /// Minimal PoW stamp interface consumed by the discovery subsystem. /// -/// A stamper must be **deterministic for a given `(infohash, target_value)` -/// pair** and independent across calls — the announcer caches its last -/// successful stamp per info-hash and reuses it until the payload changes. +/// Generation may search randomly and return different valid stamps for the +/// same inputs. Validation and value calculation must use the same discovery +/// algorithm: the announcer caches a successful stamp for unchanged info bytes, +/// and receivers must be able to validate it independently. pub trait DiscoveryStamper: Send + Sync { - /// Generate a `STAMP_SIZE`-byte stamp whose SHA-256-derived value meets - /// or exceeds `target_value` (number of leading zero bits, as in the - /// Python `LXStamper.generate_stamp` contract). + /// Generate a 32-byte stamp meeting `target_value` for this info hash. + /// The discovery algorithm hashes a derived workblock with the stamp; + /// the target is the required number of leading zero bits. /// - /// Returns `None` if generation was cancelled or failed. + /// Return `None` when generation fails or its implementation-specific + /// budget is exhausted. This trait supplies no cancellation or time limit. fn generate(&self, infohash: &[u8; 32], target_value: u8) -> Option>; - /// Compute the stamp's current value (Python `LXStamper.stamp_value`). - /// Used by the receiver to log the learned stamp quality. + /// Compute the stamp's value for this info hash, expressed as leading + /// zero bits and limited to this method's `u8` range. This describes work + /// quality, not the trustworthiness of the advertised endpoint. fn value(&self, infohash: &[u8; 32], stamp: &[u8]) -> u8; - /// Validate a stamp against `required_value` (Python - /// `LXStamper.stamp_valid`). Returns true iff the stamp meets the bar. + /// Decide whether the stamp meets the required work value for this info + /// hash. Implementations define zero-cost and malformed-stamp handling; + /// callers must still validate framing and the advertised fields. fn valid(&self, infohash: &[u8; 32], stamp: &[u8], required_value: u8) -> bool; } -/// A no-op stamper used when on-network discovery is not enabled. -/// -/// Never generates a stamp — so the announcer short-circuits each tick and -/// the receiver rejects every inbound stamp. This keeps discovery silent -/// when no stamper is installed (Python panics in this case; we don't). +/// Disabled stamper: generation always returns `None`, value is always zero, +/// and validation always returns `false`, including at a zero requirement. +/// It supplies no usable stamp for publication or accepted inbound work. pub struct NullStamper; impl DiscoveryStamper for NullStamper { diff --git a/crates/rns-transport/src/discovery/storage.rs b/crates/rns-transport/src/discovery/storage.rs index a578461..949d331 100644 --- a/crates/rns-transport/src/discovery/storage.rs +++ b/crates/rns-transport/src/discovery/storage.rs @@ -1,5 +1,8 @@ -//! Persistence for discovered interfaces — one msgpack file per learned -//! interface named after `discovery_hash` hex (matches Python `InterfaceDiscovery`). +//! Local discovered-interface records, stored as one MessagePack file per +//! [`discovery_hash`]. Files contain advertised fields, including any IFAC +//! passphrase, without storage encryption. Use a dedicated, trusted directory: +//! loading does not revalidate announce signatures or proof of work, and +//! [`DiscoveryStore::list`] may remove records while listing them. use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -13,7 +16,8 @@ use super::constants::{ THRESHOLD_UNKNOWN_SECS, }; -/// Freshness status for a learned interface. +/// Age bucket for the last heard announce. Even `Available` does not establish +/// a current connection or reachable endpoint. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DiscoveryStatus { Stale, @@ -31,6 +35,7 @@ impl DiscoveryStatus { } } + /// Lowercase status label: `stale`, `unknown` or `available`. pub fn as_str(self) -> &'static str { match self { Self::Stale => "stale", @@ -40,13 +45,16 @@ impl DiscoveryStatus { } } -/// A single learned interface. +/// Advertised interface metadata plus local observation history. Public fields +/// can also be supplied directly; the store does not authenticate their source. #[derive(Debug, Clone, PartialEq)] pub struct DiscoveredInterface { pub info: DiscoveryInfo, - /// Source transport ID — lets a reader filter by `interface_discovery_sources`. + /// Source identity used by the receiver's source filter. The receiver uses + /// the announce event's identity hash when present, otherwise the claimed + /// `info.transport_id`; the two values need not be equal. pub network_id: [u8; 16], - /// Distance hint when the announce was received (0 if unknown). + /// Hop count copied from the announce event; not a current path measurement. pub hops: u8, /// Stamp value observed on the latest announce. pub stamp_value: u8, @@ -56,14 +64,17 @@ pub struct DiscoveredInterface { pub discovered: u64, /// Unix seconds — most recent announce. pub last_heard: u64, - /// How many announces contributed to this record (includes the first). + /// Count of successful upserts for this key, including the first, + /// saturating at `u64::MAX`; not a count of distinct announce packets. pub heard_count: u64, - /// Cached status at read time (None until classified). + /// Age status assigned by [`DiscoveryStore::list`]. It is not persisted; + /// decoded records start with `None`. pub status: Option, } impl DiscoveredInterface { - /// Filename stem on disk: hex of `discovery_hash`. + /// Raw 32-byte storage key derived from `info.transport_id` and `info.name`. + /// Use [`Self::filename`] for the hexadecimal filename. pub fn discovery_hash(&self) -> [u8; 32] { discovery_hash(&self.info.transport_id, &self.info.name) } @@ -74,7 +85,9 @@ impl DiscoveredInterface { } } -/// `SHA-256(transport_id_hex_ascii || name_utf8)`. +/// `SHA-256(lowercase_hex(transport_id) || name_utf8)`, with no separator. +/// The name is used exactly as supplied; this helper does not sanitize it. +/// Changing the advertised name gives the same transport a different record key. pub fn discovery_hash(transport_id: &[u8; 16], name: &str) -> [u8; 32] { let mut material = String::with_capacity(32 + name.len()); material.push_str(&hex::encode(transport_id)); @@ -94,15 +107,19 @@ pub enum StorageError { Shape, } -/// Persistent store rooted at `/discovery/interfaces/`. +/// File store rooted at `/discovery/interfaces/`. /// -/// Writes atomically via a `.tmp` sidecar + rename. +/// Writes use a fixed `.tmp` sibling and rename, without fsync or an internal +/// writer lock. Serialize updates to the same key to avoid sidecar and merge +/// races. This is not a crash-durable transaction. Reads trust local field +/// values and load complete files without a size bound. pub struct DiscoveryStore { root: PathBuf, } impl DiscoveryStore { - /// Open (and create if absent) the store under `storage_root`. + /// Create the store directory if absent and return its path wrapper. + /// Existing records are not scanned or validated by this call. pub fn open(storage_root: &Path) -> Result { let root = storage_root.join("discovery").join("interfaces"); std::fs::create_dir_all(&root)?; @@ -114,7 +131,13 @@ impl DiscoveryStore { &self.root } - /// Write or update; existing `discovered` + `heard_count` are merged in. + /// Write the record, preserving a readable existing record's `discovered` + /// time and incrementing its count with saturation. If the previous file + /// cannot be read or decoded, use the supplied discovery time and count 1. + /// Other fields replace the old values; `status` is not serialized. + /// + /// This does not verify the stamp or prevent an older observation replacing + /// a newer one. Changing the key leaves any prior record under its old key. pub fn upsert(&self, mut record: DiscoveredInterface) -> Result<(), StorageError> { let path = self.root.join(record.filename()); @@ -137,7 +160,8 @@ impl DiscoveryStore { } } - /// Remove a single record; returns `true` if one was present. + /// Delete the exact transport/name record. Returns `false` when absent, + /// `true` after removal, and an error for other filesystem failures. pub fn remove(&self, transport_id: &[u8; 16], name: &str) -> Result { let fname = hex::encode(discovery_hash(transport_id, name)); let path = self.root.join(fname); @@ -148,10 +172,18 @@ impl DiscoveryStore { } } - /// List records sorted desc by `(status_code, stamp_value, last_heard)`. - /// Expired records, records of a type Python does not list, and records - /// whose `network_id` is not in `discovery_sources` (when set) are culled - /// from disk (Discovery.py:536-547). + /// Read and maintain the store, returning records sorted descending by + /// `(status_code, stamp_value, last_heard)`. This call mutates the directory. + /// + /// Files with extensions and non-files are skipped. Unreadable/undecodable + /// records, records older than seven days, unlisted interface types and + /// sources excluded by `discovery_sources` are omitted and removal is + /// attempted. Removal errors are ignored. `Some(&[])` excludes every source; + /// `None` applies no source filter. A missing directory returns an empty list. + /// + /// Field decoding supplies defaults for missing or invalid values; filenames, + /// signatures and stamps are not verified. Future `last_heard` values have + /// age zero. Age labels describe observations, not endpoint health. pub fn list( &self, discovery_sources: Option<&[[u8; 16]]>, @@ -220,8 +252,9 @@ impl DiscoveryStore { } } -/// Classify a (now - last_heard) delta into a status bucket. Exposed so -/// callers that already have a record in hand can avoid a re-read. +/// Classify elapsed seconds: `Available` through 24 hours, `Unknown` above +/// 24 hours through three days, and `Stale` above three days. This helper does +/// not apply the separate seven-day removal rule or probe an endpoint. pub fn classify(heard_delta_secs: u64) -> DiscoveryStatus { if heard_delta_secs > THRESHOLD_STALE_SECS { DiscoveryStatus::Stale diff --git a/crates/rns-transport/src/hashlist.rs b/crates/rns-transport/src/hashlist.rs index e5636f8..e3e3e58 100644 --- a/crates/rns-transport/src/hashlist.rs +++ b/crates/rns-transport/src/hashlist.rs @@ -4,9 +4,11 @@ use crate::constants::HASHLIST_MAXSIZE; /// Two-generation rotating hash set used for packet deduplication. /// -/// When the `current` set fills to `max_size / 2`, it is promoted to -/// `previous` and a new empty `current` begins — giving a bounded, amortised -/// O(1) membership structure with a window of up to `max_size` entries. +/// A new insertion rotates `current` into `previous` once `current` has at +/// least `max_size / 2` entries. With `max_size >= 2`, normal insertions retain +/// at most twice that half-capacity; capacities zero and one can retain two +/// entries. [`Self::load_from`] does not enforce this bound. The window is +/// count-based, with no time expiry, and lookups check both generations. #[derive(Clone)] pub struct PacketHashlist { current: HashSet<[u8; 32]>, @@ -19,8 +21,9 @@ impl PacketHashlist { Self::new_with_capacity(HASHLIST_MAXSIZE) } - /// Build a hashlist with a custom `max_size`, useful when the default - /// capacity would dominate memory (e.g. in benchmarks). + /// Set the rotation threshold to `max_size / 2`, without preallocating. + /// Use at least two for the normal capacity bound; zero does not disable + /// storage. Restored snapshots are not limited by this setting. pub fn new_with_capacity(max_size: usize) -> Self { Self { current: HashSet::new(), @@ -48,7 +51,8 @@ impl PacketHashlist { true } - /// Rotate: current becomes previous, new empty set becomes current. + /// Discard the old previous generation, move current to previous and + /// begin an empty current generation. pub fn force_rotate(&mut self) { self.previous = std::mem::take(&mut self.current); } @@ -66,7 +70,7 @@ impl PacketHashlist { self.previous.clear(); } - /// Snapshot the current generation for persistence. + /// Snapshot the current generation in unspecified order for persistence. /// /// The previous generation is deliberately transient. Persisting both /// generations would continually carry already-aged hashes across @@ -75,11 +79,10 @@ impl PacketHashlist { self.current.iter().copied().collect() } - /// Snapshot both in-memory generations. + /// Snapshot both in-memory generations in unspecified order. /// - /// This preserves the pre-1.4 public inspection API. Persistence must use - /// [`Self::current_hashes`] so the aged previous generation remains - /// transient. + /// Use [`Self::current_hashes`] for persistence so the aged previous + /// generation remains transient across restarts. pub fn all_hashes(&self) -> Vec<[u8; 32]> { self.current .iter() @@ -88,11 +91,11 @@ impl PacketHashlist { .collect() } - /// Rehydrate the current generation from a persisted snapshot. - /// - /// This mirrors Reticulum's canonical `packet_hashlist.raw` lifecycle: - /// the restored generation remains the one written at the next - /// persistence boundary, while the previous generation stays ephemeral. + /// Replace current with the distinct supplied hashes and clear previous. + /// The restored hashes are included by [`Self::current_hashes`]. This + /// method does not enforce `max_size`; bound untrusted snapshots before + /// loading them. A later new insertion can rotate an oversized current + /// generation into previous, where it remains until another rotation. pub fn load_from(&mut self, hashes: Vec<[u8; 32]>) { self.current = hashes.into_iter().collect(); self.previous.clear(); diff --git a/crates/rns-transport/src/ifac.rs b/crates/rns-transport/src/ifac.rs index 7a04099..c8557fd 100644 --- a/crates/rns-transport/src/ifac.rs +++ b/crates/rns-transport/src/ifac.rs @@ -1,15 +1,16 @@ -//! Interface Access Control (IFAC) signing and verification. +//! Interface Access Control (IFAC) packet encoding and verification. //! -//! IFAC authenticates every packet on a closed-membership interface. A shared -//! interface key drives both an Ed25519 signing key (the tag is the last -//! `ifac_size` bytes of the signature) and an HKDF-XOR mask over the header -//! and payload — the tag itself is left in the clear because receivers need it -//! to regenerate the mask. Packets without a valid tag are dropped before any -//! routing decision, so unauthorised peers can neither send nor decode traffic. +//! The shared interface key seeds an Ed25519 signer. The final `ifac_size` +//! signature bytes form a tag, which also drives an HKDF-XOR mask over the +//! packet. Before masking, the layout is `[flags|0x80, hops, tag, rest]`. +//! The tag stays clear and the IFAC presence bit remains set; the remaining +//! header bits and payload are masked. //! -//! Wire layout matches the Python reference (`Transport.transmit` / -//! `Transport.inbound`): `[flags|0x80, hops, tag(ifac_size), payload]` with -//! everything except the tag masked. +//! IFAC gates access to one configured interface. Members share its key, so +//! a valid tag does not identify an individual member or replace destination +//! or Link encryption. These helpers do not reject replays or validate the +//! complete inner packet. The transport actor drops failed IFAC verification +//! on wire ingress before parsing the inner packet. use rns_crypto::ed25519::Ed25519PrivateKey; use rns_crypto::hkdf::hkdf_sha256; @@ -34,8 +35,9 @@ pub enum IfacSignError { /// Stamp a packet with its IFAC tag and XOR mask. /// /// `ifac_key` is the 64-byte derived interface key: bytes [32..64) seed the -/// Ed25519 signer, and the full key acts as HKDF salt (Python uses -/// `interface.ifac_key` in both roles, so the split must not change). +/// Ed25519 signer, and the full key acts as HKDF salt. Supply an inner packet +/// with bit 7 of byte 0 clear. This wrapper performs the same checks as +/// [`try_ifac_sign`] and panics on its errors. /// /// # Panics /// @@ -46,7 +48,12 @@ pub fn ifac_sign(packet: &[u8], ifac_key: &[u8; 64], ifac_size: usize) -> Vec Option> { if ifac_size == 0 || ifac_size > 64 { return None; @@ -146,8 +156,8 @@ pub fn ifac_verify(raw: &[u8], ifac_key: &[u8; 64], ifac_size: usize) -> Option< } } -/// Whether a raw packet carries the IFAC flag. Cheap pre-check to avoid -/// running the full verify path on clear-interface traffic. +/// Whether a nonempty byte slice has the IFAC presence bit set. This does +/// not establish a valid tag, packet length or interface membership. pub fn has_ifac_flag(raw: &[u8]) -> bool { !raw.is_empty() && raw[0] & IFAC_FLAG != 0 } diff --git a/crates/rns-transport/src/ingress.rs b/crates/rns-transport/src/ingress.rs index 47d98f4..d6d85a5 100644 --- a/crates/rns-transport/src/ingress.rs +++ b/crates/rns-transport/src/ingress.rs @@ -1,13 +1,14 @@ //! Per-interface ingress/egress control for announce and path-request floods. //! -//! Each interface owns one `IngressController`. The inbound path consults it -//! on every announce — when the incoming rate crosses the burst threshold the -//! controller activates a hold state, shunts subsequent announces into a -//! per-destination hold buffer, and the maintenance tick releases them later -//! in hop-priority order. The split thresholds for freshly-seen vs. mature -//! interfaces (`IC_BURST_FREQ_NEW` vs. `IC_BURST_FREQ`) give newly-online -//! links time to catch up from the network backlog without triggering the -//! limiter on the first burst of announces. +//! A controller tracks explicitly recorded samples and provides limiter +//! decisions and a destination-keyed announce hold buffer. The actor applies +//! announce holding to unknown destinations, excluding local-client traffic +//! and replies to pending path requests. Held entries are released one at a +//! time by the caller, subject to a time gate, frequency and hop priority. +//! +//! New interfaces use lower default burst thresholds than established ones. +//! Ingress and optional outgoing path-request control have separate switches; +//! neither setting is a general packet bandwidth limit. use std::collections::{HashMap, VecDeque}; use std::time::{Duration, Instant}; @@ -21,8 +22,10 @@ use crate::constants::{ MAX_HELD_ANNOUNCES, OA_FREQ_SAMPLES, OP_FREQ_SAMPLES, PATHFINDER_M, PR_FREQ_DECAY, }; -/// Per-interface ingress overrides parsed from `[interface.] ic_*` keys. -/// Any field left `None` falls back to the corresponding crate-level constant. +/// Per-interface limiter settings. `None` keeps the controller default. +/// Frequencies are events per second, durations are seconds, and `max_held` +/// limits destination count rather than bytes. Validation accepts zero; +/// disable ingress with `enabled = Some(false)`, not zero thresholds. #[derive(Debug, Clone, Default)] pub struct IngressOverrides { pub enabled: Option, @@ -54,6 +57,9 @@ fn valid_time(value: f64) -> bool { } impl IngressOverrides { + /// Reject nonfinite or negative frequencies and durations that cannot be + /// added to the current monotonic clock. This does not cap `max_held` or + /// establish a maximum memory budget. pub fn validate(&self) -> Result<(), IngressOverrideError> { for (field, value) in [ ("ic_burst_freq_new", self.burst_freq_new), @@ -105,6 +111,10 @@ pub struct HeldAnnounce { pub receiving_interface_id: u64, } +/// Monotonic-clock samples and limiter state for one interface. Record events +/// through the `received_*`/`sent_*` methods before consulting limiters. Status +/// frequency getters ignore stale samples without mutation; limiter checks +/// trim at most one stale sample and can therefore calculate a different rate. #[derive(Debug)] pub struct IngressController { created: Instant, @@ -177,23 +187,25 @@ impl IngressController { } } - /// Always-permissive controller — use when ingress control is switched off - /// at the transport or interface level. The state machine still compiles - /// samples so operators can read frequency stats, but `should_ingress_limit` - /// is hard-wired to `false`. + /// Create default settings with ingress limiting disabled. Explicit sample + /// recording still works; both inbound limiter checks return false. The + /// default outgoing path-request limiter is also disabled. pub fn disabled() -> Self { let mut ctrl = Self::new(); ctrl.enabled = false; ctrl } - /// Controller with per-interface overrides applied; unset fields keep - /// their compile-time defaults. + /// Validate and apply settings to a new controller. Unset fields keep + /// defaults; ingress is enabled and outgoing path-request control is off. pub fn try_with_overrides(overrides: &IngressOverrides) -> Result { overrides.validate()?; Ok(Self::apply_overrides(overrides)) } + /// Compatibility constructor that discards invalid frequency/duration + /// overrides and keeps their defaults. Prefer [`Self::try_with_overrides`] + /// when invalid configuration must be reported. #[deprecated(note = "use try_with_overrides for configuration validation")] pub fn with_overrides(overrides: &IngressOverrides) -> Self { let mut safe = overrides.clone(); @@ -282,9 +294,9 @@ impl IngressController { self.held_release_interval } - /// Earliest instant at which the next held announce may be released. The - /// cooldown starts when burst mode activates (not deactivates) so a - /// prolonged burst cannot starve existing holds. + /// Time gate for the next held release, set on burst activation and after + /// each release. Reaching this instant is insufficient by itself: release + /// also requires the measured frequency to be below its threshold. pub fn held_release_at(&self) -> Instant { self.held_release } @@ -365,10 +377,11 @@ impl IngressController { ) } - /// Whether inbound announces should currently be held. Also updates the - /// internal burst state — an exit from burst only happens once the - /// frequency has dropped *and* `burst_hold` seconds have passed since - /// activation, preventing flapping on a noisy interface. + /// Update announce burst state and return whether selected inbound announces + /// should be held. Clearing a burst requires frequency below threshold, + /// elapsed time greater than `burst_hold`, and at least six samples in the + /// trimmed deque. The call that clears the state still returns true; a later + /// call can return false. Disabled ingress always returns false. pub fn should_ingress_limit(&mut self) -> bool { if !self.enabled { return false; @@ -408,8 +421,10 @@ impl IngressController { } } - /// Whether unknown recursive path-request discovery should be suppressed - /// on this ingress interface. + /// Update the separate path-request burst state for unknown recursive + /// discovery. Clearing requires frequency below threshold and elapsed + /// time greater than `burst_hold`; that clearing call still returns true. + /// Disabled ingress always returns false. pub fn should_ingress_limit_pr(&mut self) -> bool { if !self.enabled { return false; @@ -445,8 +460,9 @@ impl IngressController { } } - /// Whether outgoing path-request transmission should be skipped on this - /// interface. This limiter is off by default in Reticulum 1.2.5. + /// Whether outgoing path requests exceed `ec_pr_freq` with at least six + /// samples remaining. Controlled by `egress_control`, independently of + /// inbound `enabled`, and disabled by default in this implementation. pub fn should_egress_limit_pr(&mut self) -> bool { if !self.egress_control { return false; @@ -460,6 +476,10 @@ impl IngressController { op_freq > self.ec_pr_freq && self.op_freq_deque.len() >= IC_BURST_MIN_SAMPLES } + /// Store or replace an announce by destination hash, without validating + /// its packet. Discard hop counts of 127 or more and new destinations when + /// `max_held` is reached; existing destinations can still be replaced. + /// This does not consult the enabled flag or a limiter decision. pub fn hold_announce(&mut self, announce: HeldAnnounce) { // Python 1.3.8 Interface.py:221-222: announces already at the hop cap // would be dropped by every receiver on release — don't hold them. @@ -475,10 +495,11 @@ impl IngressController { } /// Release at most one held announce per call — the one with the lowest - /// hop count, so short-path announces win priority. This intentionally - /// does not consult `should_ingress_limit()`: upstream releases held - /// announces based on release time and current announce frequency, even if - /// the displayed burst state has not cleared yet. + /// hop count; ties have no defined order. Both the release time and a + /// frequency strictly below the current threshold are required. It does + /// not consult `should_ingress_limit` or the enabled flag, and can release + /// while burst state remains set. The returned entry is removed; the caller + /// must process it, since this helper does not send packets. pub fn try_release_held(&mut self) -> Option { if self.held_announces.is_empty() { return None; diff --git a/crates/rns-transport/src/interface_ownership.rs b/crates/rns-transport/src/interface_ownership.rs index 2ccb39e..b1c52e0 100644 --- a/crates/rns-transport/src/interface_ownership.rs +++ b/crates/rns-transport/src/interface_ownership.rs @@ -6,8 +6,9 @@ use std::sync::{ }; use tokio::sync::{Notify, mpsc}; -/// Copyable provenance for a pending handshake. Only comparison with the -/// current registration grants authority; it cannot revive a retired owner. +/// Process-local registration token for matching a pending handshake to its +/// current owner. It is not a network identity or peer authentication proof; +/// comparing it cannot revive a retired registration. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct InterfaceOwnerId { epoch: u64, @@ -19,8 +20,10 @@ impl InterfaceOwnerId { } } -/// Immutable identity captured before an interface starts producing events. -/// Carrier reconnects retain it; replacement registrations always mint a new one. +/// Registration identity captured before an interface starts producing events. +/// Clones share retirement and revision state. Carrier reconnects retain the +/// owner; replacements use a new epoch, while coordinated reconfiguration can +/// advance its revision. Equality alone does not imply current registration. #[derive(Debug, Clone)] pub struct InterfaceOwner { epoch: u64, @@ -41,6 +44,8 @@ impl PartialEq for InterfaceOwner { } impl Eq for InterfaceOwner {} impl InterfaceOwner { + /// Allocate a new process-local epoch, initially unregistered. Panics if + /// the epoch counter is exhausted. pub fn new() -> Self { static NEXT: AtomicU64 = AtomicU64::new(1); // `try_update` is the Rust 1.99 spelling; retain the identical atomic @@ -115,8 +120,10 @@ impl InterfaceOwner { notified.await; } } - /// A coordinated capacity/IFAC reconfiguration first invalidates the previous - /// revision, then binds producers and registers this returned identity. + /// Advance the revision and invalidate all clones of the old revision. + /// The returned owner is not registered yet: bind producers and install + /// its registration before use. Returns `None` if this owner is stale, + /// another caller advances it first, or the revision counter is exhausted. pub fn next_revision(&self) -> Option { if !self.is_current() { return None; @@ -144,11 +151,16 @@ impl Default for InterfaceOwner { } } -/// Complete Reticulum packet guarantees before framing/fragmentation. +/// Declared complete-packet budgets before interface framing or fragmentation. +/// Construction does not validate the numbers or measure hardware capability; +/// use `effective_clear_mtu` and `link_ceiling` for the checked derived limits. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct InterfacePacketCapacity { + /// Complete inner Reticulum packet bytes, including its header, before IFAC. pub max_clear_packet_bytes: u32, + /// Complete packet bytes including an active IFAC tag, before framing. pub max_wire_packet_bytes: u32, + /// Permit a Link ceiling above the 500-byte base; this does not negotiate it. pub link_mtu_upgrade: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] @@ -167,6 +179,7 @@ pub enum InterfaceCapacityError { }, } impl InterfacePacketCapacity { + /// Store declared budgets without validating them. pub const fn new(clear: u32, wire: u32, upgrade: bool) -> Self { Self { max_clear_packet_bytes: clear, @@ -174,9 +187,14 @@ impl InterfacePacketCapacity { link_mtu_upgrade: upgrade, } } + /// Use the same clear/wire budget and disable Link MTU upgrades. pub const fn base(mtu: u32) -> Self { Self::new(mtu, mtu, false) } + /// Return the smaller of the clear budget and the wire budget minus IFAC. + /// Zero IFAC bytes means inactive; 1..=64 is active and also limits wire + /// size to the 8160-byte mask bound. Reject invalid tag sizes, zero budgets + /// and budgets with no room after the tag. pub fn effective_clear_mtu( self, active_ifac_bytes: usize, @@ -206,6 +224,10 @@ impl InterfacePacketCapacity { } Ok(effective) } + /// Require at least 500 effective clear bytes. Return 500 with upgrades + /// disabled, or the effective clear budget capped at the 21-bit signalling + /// maximum with upgrades enabled. This is a complete packet ceiling, + /// not an application payload MDU or a measured end-to-end path limit. pub fn link_ceiling( self, interface_id: InterfaceId, @@ -229,7 +251,10 @@ impl InterfacePacketCapacity { /// Sender owned by one registration. Bind before spawning any producer and keep /// it through ordinary reconnects. Accepted children bind a fresh owner to the -/// underlying actor sender. The actor, not the sender, validates current ownership. +/// underlying actor sender. The sender checks readiness, and the actor checks +/// current ownership again when consuming each event. A successful send means +/// queue admission only; the actor can still reject a stale or unsupported event. +/// Capacity/closed queries describe the actor mailbox, not radio readiness. #[derive(Debug, Clone)] pub struct InterfaceTransportSender { id: InterfaceId, @@ -269,6 +294,10 @@ impl InterfaceTransportSender { pub async fn closed(&self) { self.tx.closed().await } + /// Wrap an event without sending it or checking registration. The actor + /// admits only supported interface events: inbound packets, deregistration, + /// shared-connection state, RPC and tunnel synthesis. Interface IDs must + /// match where present; wrapping a general command does not make it valid. pub fn event(&self, message: TransportMessage) -> TransportMessage { TransportMessage::InterfaceEvent { interface_id: self.id, @@ -276,8 +305,9 @@ impl InterfaceTransportSender { message: Box::new(message), } } - /// Wait for registration without losing the first received frame. Each - /// producer retains at most its current frame; no extra queue is created. + /// Wait for registration acknowledgment, returning false if the owner is + /// retired/revised or the actor mailbox closes. There is no timeout and + /// this method buffers no frames; a producer must retain its pending frame. pub async fn ready(&self) -> bool { tokio::select! { biased; @@ -285,6 +315,9 @@ impl InterfaceTransportSender { ready = self.owner.wait_registered() => ready, } } + /// Wait for registration, then enqueue the owned event. No whole-call + /// timeout or actor-completion acknowledgment is provided. On failure, + /// return the caller's original message for retry or disposal. // Preserve Tokio's by-value failure contract, including the original // owned message for retry, without a failure-only heap allocation. #[allow(clippy::result_large_err)] @@ -300,6 +333,10 @@ impl InterfaceTransportSender { .await .map_err(|e| mpsc::error::SendError(unwrap_event(e.0))) } + /// Attempt immediate admission. A stale owner returns `Closed`; a current + /// but unregistered owner returns `Full`, even if the mailbox has space. + /// Otherwise use the mailbox result, preserving the original message on + /// failure. Success still requires actor-side ownership and event checks. // Match Tokio's by-value failure contract so callers can retry the exact // original message without an additional heap allocation on refusal. #[allow(clippy::result_large_err)] diff --git a/crates/rns-transport/src/lib.rs b/crates/rns-transport/src/lib.rs index c2e9804..fc529c1 100644 --- a/crates/rns-transport/src/lib.rs +++ b/crates/rns-transport/src/lib.rs @@ -1,11 +1,13 @@ -//! Reticulum transport: routing actor, path tables, announces, blackhole, -//! rate limiting. The Rust replacement for Python's static `Transport` class -//! ([Transport.py](https://github.com/markqvist/Reticulum/blob/master/RNS/Transport.py)). -//! [`actor::TransportActor`] owns all mutable state; other crates send typed -//! [`messages::TransportMessage`]s over a Tokio mpsc channel. +//! Reticulum routing, announces, path tables, interface access control and +//! traffic accounting. [`actor::TransportActor`] drives routing through typed +//! [`messages::TransportMessage`]s on a Tokio mpsc channel. Queue admission +//! alone does not confirm command completion or packet delivery; use each +//! message's reply or protocol proof where available. Public helper tables can +//! also be used independently of the actor. -/// Unix time as f64 seconds — Python `time.time()` equivalent, the timebase -/// used across path/reverse/rate/blackhole/tunnel tables. +/// Wall-clock Unix time in fractional seconds, used by the transport tables. +/// This is not monotonic: clock adjustments affect time comparisons. Returns +/// zero when the system clock is before the Unix epoch. pub fn now_f64() -> f64 { #[cfg(test)] if let Some(now) = test_clock::NOW.with(std::cell::Cell::get) { diff --git a/crates/rns-transport/src/link_endpoint_dispatch.rs b/crates/rns-transport/src/link_endpoint_dispatch.rs index 0624138..a3e2af5 100644 --- a/crates/rns-transport/src/link_endpoint_dispatch.rs +++ b/crates/rns-transport/src/link_endpoint_dispatch.rs @@ -2,7 +2,9 @@ //! //! A receipt means the bound interface queue (or in-process peer queue) //! accepted the packet, never that a modem transmitted it or a peer received -//! it. Legacy mailbox sends retain their existing immediate `Queued` result. +//! it. Legacy mailbox sends can instead return `Queued` while the packet +//! remains in the actor backlog, before interface admission. They return +//! `Sent` when the interface accepts it immediately. use std::future::Future; use std::pin::Pin; @@ -19,14 +21,20 @@ use crate::messages::{ }; pub(crate) const DISPATCH_QUEUE_CAPACITY: usize = 64; -/// Maximum local admission lifetime, independent of network RTT. +/// Maximum future local-admission deadline (120 seconds), independent of +/// network RTT. Expiry is observed when the actor processes or drains work. pub const LINK_ENDPOINT_ADMISSION_TIMEOUT_MAX: Duration = Duration::from_secs(120); +/// Failure to enqueue a bind/send operation. These errors do not return owned +/// packet bytes; retain a copy before calling if retry needs them. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub enum LinkEndpointDispatchError { + /// The actor generation's 64-slot dispatch-control queue is full. Full, + /// The dispatch-control channel is closed. Closed, + /// The deadline is more than 120 seconds in the future. InvalidDeadline, } @@ -47,11 +55,16 @@ impl std::error::Error for LinkEndpointDispatchError {} #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub enum LinkEndpointDispatchOutcome { + /// The bound interface or in-process peer queue accepted this packet. Sent { + /// Protocol packet hash of the admitted inner packet, before IFAC framing. packet_hash: [u8; 32], + /// Local monotonic time observed immediately after queue admission. dispatched_at: Instant, }, + /// The actor rejected the packet or its endpoint became terminal. Rejected(LinkEndpointSendResult), + /// The immutable deadline was observed before local admission. Expired, /// Explicit or receiver cancellation was observed before local admission. Cancelled, @@ -108,16 +121,21 @@ impl LinkEndpointDispatchCompletion { } } -/// Cloneable control lane belonging to one transport actor generation. +/// Cloneable bounded control lane belonging to one actor generation. Obtaining +/// a handle does not start that actor or ensure its continued availability. #[derive(Debug, Clone)] pub struct LinkEndpointDispatchHandle { pub(crate) tx: mpsc::Sender, } impl LinkEndpointDispatchHandle { - /// Bind a new endpoint and obtain exact-generation send authority. Existing - /// bindings are never adopted. Dropping an unread receipt cancels and - /// retires only this unpublished binding, including after actor execution. + /// Enqueue a new endpoint binding without waiting for actor admission. + /// Await the receipt to obtain generation-specific send authority. Existing + /// bindings are rejected rather than adopted, including identical bindings. + /// + /// There is no internal bind deadline. Dropping an unread receipt marks + /// this unpublished binding for retirement when the actor observes it, + /// including if the bind already executed. pub fn try_bind( &self, binding: LinkEndpointBinding, @@ -173,6 +191,9 @@ impl LinkEndpointDispatchBindReceipt { } } + /// Consume an available reply without waiting. `Empty` keeps ownership + /// unpublished; consuming a successful token publishes it. Later dropping + /// the receipt or token does not unbind the endpoint. pub fn try_recv( &mut self, ) -> Result< @@ -215,7 +236,8 @@ impl Drop for LinkEndpointDispatchBindReceipt { } /// Send authority for one immutable endpoint binding generation. A later bind -/// with the same link ID, role and interface cannot revive an old token. +/// with the same Link ID, role and interface cannot revive an old token. +/// Clones share authority; dropping all token clones does not unbind the endpoint. #[derive(Debug, Clone)] pub struct LinkEndpointDispatchToken { pub(crate) handle: LinkEndpointDispatchHandle, @@ -224,15 +246,25 @@ pub struct LinkEndpointDispatchToken { } impl LinkEndpointDispatchToken { + /// Copy the binding metadata; this does not check whether it is still active. pub fn binding(&self) -> LinkEndpointBinding { self.binding } - /// Retain one packet in the endpoint's existing bounded FIFO until actual - /// local admission, cancellation or the immutable deadline. The actor checks - /// receiver cancellation immediately before admission; a concurrent drop - /// after that check cannot recall bytes accepted by the driver. The deadline - /// includes mailbox wait and must be no more than 120 seconds in the future. + /// Enqueue a packet operation for the endpoint's bounded FIFO. A returned + /// receiver is not admission: await its terminal outcome. The actor checks + /// receiver cancellation immediately before admission; a later drop cannot + /// recall bytes already accepted by the driver or in-process peer. + /// + /// The deadline includes command-queue wait and must be at most 120 seconds + /// ahead. A past deadline is allowed and expires when actor processing + /// observes it. Oversized input instead returns an immediately rejected + /// receipt. Other packet/binding checks happen in the actor. + /// + /// At most 256 packets are retained per endpoint, each limited to the + /// 500-byte inner wire MTU. Exhausting that FIFO terminates the endpoint + /// and rejects its pending tracked operations. This method consumes the + /// request even when control-queue admission fails. pub fn try_send( &self, request: OutboundRequest, diff --git a/crates/rns-transport/src/link_messages.rs b/crates/rns-transport/src/link_messages.rs index cdaaef5..9ec771a 100644 --- a/crates/rns-transport/src/link_messages.rs +++ b/crates/rns-transport/src/link_messages.rs @@ -1,20 +1,23 @@ -//! Link-layer message types routed between the transport actor and the -//! destinations that own registered identities. Kept in their own module so -//! the main `messages.rs` actor enum stays focused on transport primitives. +//! Destination events and Link request records used between transport and +//! destination owners. Data records alone perform no networking; the dispatch +//! helper reports local request admission, separately from Link establishment. use bytes::Bytes; use tokio::sync::oneshot; use crate::messages::InterfaceId; -/// Physical-layer measurements attached to one received packet. +/// Optional interface-supplied measurements for one received packet. This +/// record performs no normalization, range validation or freshness check. #[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct PacketMetrics { pub rssi: Option, pub snr: Option, + /// Interface-defined quality value; do not assume a normalized 0–1 range. pub q: Option, } +/// Metadata for asking a destination owner to construct an announce. #[derive(Debug, Clone)] pub struct AnnounceRequest { pub app_name: String, @@ -24,6 +27,7 @@ pub struct AnnounceRequest { } impl AnnounceRequest { + /// Request an ordinary announce with no path-response flag, tag or attached interface. pub fn normal(app_name: String) -> Self { Self { app_name, @@ -34,7 +38,9 @@ impl AnnounceRequest { } } -/// Events the transport actor pushes out to a registered destination. +/// Messages delivered to a registered destination owner. Packet bytes and +/// events still require the destination/Link handler's protocol processing; +/// constructing an event does not validate its contents. #[derive(Debug)] pub enum DestinationEvent { InboundPacket { @@ -59,19 +65,22 @@ pub enum DestinationEvent { msg_id: String, rtt: Option, }, - /// Transport asks the destination to announce itself — used when a shared - /// instance connects and needs the peer's current identity map. + /// Ask the owner to construct an announce, including ordinary announcements + /// or path responses. This is a request, not proof of publication. AnnounceRequested(AnnounceRequest), } -/// Request a new link to `dest_hash`. `result_tx` delivers either the link -/// id or a diagnostic message explaining why establishment failed. +/// Request record carrying a destination and a caller-owned establishment +/// reply channel. Constructing it does not send a request; the consuming +/// runtime must perform establishment and report the Link ID or an error. #[derive(Debug)] pub struct EstablishLinkRequest { pub dest_hash: [u8; 16], pub result_tx: oneshot::Sender>, } +/// Plain data record for a Link owner to process. It performs no encryption, +/// framing or transmission by itself. #[derive(Debug)] pub struct LinkDataRequest { pub link_id: [u8; 16], @@ -161,8 +170,8 @@ mod tests { } } -/// Result of one locally owned Link request's actual transport admission. -/// The oneshot reply belongs to that attempt, independently of Link ID reuse. +/// Failure to submit or locally admit one Link request. A successful dispatch +/// means local egress acceptance, not successful Link establishment. #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] pub enum LinkRequestDispatchError { #[error(transparent)] @@ -175,8 +184,14 @@ pub enum LinkRequestDispatchError { TransportUnavailable, } -/// Dispatch one Link request and await this exact attempt's admission result. -/// Wrap this future in the caller's existing establishment deadline. +/// Submit one Link request and await its exact attempt's local admission result. +/// The actor checks the request header and supported endpoint signalling before +/// egress. Success does not wait for a remote proof or Link establishment. +/// +/// This future has no internal timeout; use the caller's establishment deadline +/// around both submission and reply. Dropping it closes the reply receiver; the +/// actor checks that before starting dispatch, but cannot recall bytes already +/// admitted. The owned request is not returned on failure. pub async fn dispatch_link_request( transport: &tokio::sync::mpsc::Sender, request: crate::messages::OutboundRequest, diff --git a/crates/rns-transport/src/link_table.rs b/crates/rns-transport/src/link_table.rs index 89aa15d..9656bd0 100644 --- a/crates/rns-transport/src/link_table.rs +++ b/crates/rns-transport/src/link_table.rs @@ -3,21 +3,24 @@ use std::collections::HashMap; use crate::messages::InterfaceId; use rns_wire::types::LinkId; -/// Transport-level state for one forwarded or terminated link. +/// Transport bookkeeping for a forwarded Link or local endpoint. Fields are +/// supplied by callers; this record does not itself verify a handshake. #[derive(Debug, Clone)] pub struct LinkEntry { - /// Registration time (Unix seconds). + /// Registration or last routed-traffic timestamp (Unix seconds). pub timestamp: f64, - /// Next-hop transport id for a routed link; `None` when this node is the endpoint. + /// Optional next-hop transport ID copied from route metadata. `None` alone + /// does not distinguish a direct route from a local endpoint. pub next_hop: Option<[u8; 16]>, pub interface_id: InterfaceId, pub remaining_hops: u8, pub destination_hash: [u8; 16], - /// Handshake complete. + /// Local establishment bookkeeping flag. Transit proof processing updates + /// `validated` separately, so this is not a universal Link-health check. pub established: bool, - /// Proof received. Forwarding does not require this — unvalidated links - /// still forward while `now < proof_timeout` so in-flight traffic is not - /// stranded during the establishment window. + /// Transport validation state. A pending transit Link may still forward + /// before its finite `proof_timeout`, subject to owner, packet-size, hop + /// and interface checks. This is separate from application authorization. pub validated: bool, pub proof_timeout: f64, /// Interface the initial link request arrived on. @@ -86,6 +89,9 @@ pub(crate) fn transit_link_proof_deadline( /// Privileged callers retain the existing explicit LinkTable::insert API. pub(crate) const MAX_TRANSIT_LINK_TABLE_ENTRIES: usize = 4096; +/// Link-keyed metadata with explicit cleanup. `insert` does not validate fields +/// or enforce the actor's transit admission cap; getters include expired +/// entries. Callers must enforce ownership, forwarding and lifecycle policy. pub struct LinkTable { entries: HashMap, } @@ -135,10 +141,11 @@ impl LinkTable { self.entries.iter() } - /// Cull stale links with two different clocks: - /// - Validated links drop after `timeout` seconds of inactivity. - /// - Unvalidated links drop once their own `proof_timeout` elapses, since - /// proof never arrived during the establishment window. + /// Cull entries using two expiry rules on the wall clock: + /// - Validated entries are retained only while `timestamp > now - timeout`; + /// a NaN timestamp or timeout therefore removes a validated entry. + /// - Unvalidated entries drop once their own `proof_timeout` elapses, + /// or when that deadline is nonfinite. `established` is not consulted. /// /// Returns `(total_culled, expired_unvalidated_links)` — the caller can /// apply failed-link rediscovery rules using the retained route metadata. diff --git a/crates/rns-transport/src/link_transit.rs b/crates/rns-transport/src/link_transit.rs index 5366a48..b0272f0 100644 --- a/crates/rns-transport/src/link_transit.rs +++ b/crates/rns-transport/src/link_transit.rs @@ -1,17 +1,26 @@ -//! Request attenuation without changing Link identity or coercing opaque modes. +//! Internal transit checks for Link-request signalling. Capacity attenuation +//! changes only the unsigned request trailer, preserving the 64-byte request +//! body and Link identity. Unsupported opaque-mode transformations are rejected; +//! authenticated proof trailers are not rewritten. use crate::{InterfaceCapacityError, messages::InterfaceEntry}; use rns_wire::link_signalling::{ DEFAULT_LINK_MODE, LinkSignallingError, SignallingData, parse_request_signalling, }; +/// Why a transit Link request cannot be forwarded under the checked interface +/// generations and packet-capacity budgets. #[derive(Debug, thiserror::Error)] pub enum LinkTransitError { + /// Malformed or unsupported request signalling. #[error(transparent)] InvalidSignalling(#[from] LinkSignallingError), + /// An interface cannot carry the required Link packet capacity. #[error(transparent)] Capacity(#[from] InterfaceCapacityError), + /// Forwarding would change the raw MTU trailer of an opaque, non-default mode. #[error("non-default Link mode requires an unsupported transit transformation")] UnsupportedTransitModeTransform, + /// The ingress or egress interface owner is no longer current. #[error("interface registration no longer owns this route")] StaleInterface, } diff --git a/crates/rns-transport/src/messages.rs b/crates/rns-transport/src/messages.rs index 2e5cc4a..167a1f2 100644 --- a/crates/rns-transport/src/messages.rs +++ b/crates/rns-transport/src/messages.rs @@ -1,9 +1,12 @@ //! Actor-model interface for the transport. //! -//! Every routing state mutation flows through `TransportMessage` into the -//! single task that owns the routing tables. This eliminates shared mutable -//! state and its locking on the hot path; other components interact with the -//! transport exclusively via `mpsc` senders and `oneshot` reply channels. +//! Commands and queries for the task that owns transport routing state. +//! The actor also has dedicated control channels, public setup state and +//! driver-shared counters. Sending a command only admits it to a mailbox; +//! use the operation-specific reply when a local result is required. +//! +//! Debug output can contain packet bytes, names and query payloads. It is +//! not a sanitized diagnostic or aggregate-only interface. use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64}; @@ -21,29 +24,29 @@ pub use crate::interface_ownership::{ InterfaceTransportSender, }; -/// Privacy-bounded, aggregate-only inspection values supplied by an -/// interface driver. +/// Optional aggregate counts supplied by an interface driver. /// -/// This deliberately has no endpoint, address, name or free-form field. Keep -/// that property when extending it: inspection snapshots cross shared-instance -/// and authorized remote-management boundaries. +/// This record contains no endpoint, address, name or free-form field. That +/// restriction applies to this record, not to the surrounding interface stats, +/// which include names and other configuration metadata. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct InterfaceInspectionSnapshot { pub active_clients: Option, pub blocked_ips: Option, } -/// A driver-owned source for a live aggregate interface snapshot. +/// A driver-owned callback for live aggregate interface counts. /// -/// The callback is invoked synchronously once for each transport stats -/// snapshot. Implementations must therefore take only short-lived locks and -/// must not perform I/O. +/// `GetInterfaceStats` calls it synchronously once per inspected interface and +/// substitutes empty counts if it panics. Keep locks short and do not perform +/// I/O: the callback executes on the actor task. #[derive(Clone)] pub struct InterfaceInspectionSource { snapshot: Arc InterfaceInspectionSnapshot + Send + Sync>, } impl InterfaceInspectionSource { + /// Store a callback; this does not call it or start a polling task. pub fn new(snapshot: F) -> Self where F: Fn() -> InterfaceInspectionSnapshot + Send + Sync + 'static, @@ -53,6 +56,8 @@ impl InterfaceInspectionSource { } } + /// Call the callback synchronously. Unlike `GetInterfaceStats`, this method + /// does not catch callback panics. pub fn snapshot(&self) -> InterfaceInspectionSnapshot { (self.snapshot)() } @@ -69,21 +74,23 @@ impl std::fmt::Debug for InterfaceInspectionSource { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct AnnounceHandlerId(pub(crate) u64); -/// Transport-level role of an interface. Python Reticulum distinguishes -/// ordinary network interfaces, the local shared-instance listener, accepted -/// local clients behind that listener, and the one interface a leaf process uses -/// to reach an existing shared instance. Several routing rules depend on that -/// distinction. +/// Interface role used by routing and shared-instance policy. It is separate +/// from `InterfaceMode`, which controls forwarding/discovery policy. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum InterfaceRole { + /// Ordinary network interface. #[default] Normal, + /// Local shared-instance listener. SharedServer, + /// Accepted local client behind the shared listener. LocalClient, + /// Leaf process connection to an existing shared instance. SharedInstancePeer, } impl InterfaceRole { + /// Return the role label used by interface statistics. pub fn as_str(self) -> &'static str { match self { Self::Normal => "normal", @@ -94,6 +101,10 @@ impl InterfaceRole { } } +/// Raw driver input and optional physical-layer observations. Submit through +/// the current `InterfaceTransportSender`; the actor rejects an unwrapped +/// `TransportMessage::Inbound`. Metrics are interface-supplied, with no quality +/// normalization performed by this record. #[derive(Debug)] pub struct InboundPacket { pub raw: Bytes, @@ -103,13 +114,16 @@ pub struct InboundPacket { pub q: Option, } +/// Packet bytes and destination supplied by the caller for local dispatch. +/// This record does not construct, sign, encrypt or validate a packet. #[derive(Debug)] pub struct OutboundRequest { pub raw: Bytes, pub destination_hash: [u8; 16], } -/// State update for one explicitly tracked outbound packet. +/// Latest state of one explicitly tracked outbound packet. A watch channel +/// retains the latest state, not an event history; a slow reader may skip updates. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ReceiptUpdate { Sent, @@ -119,7 +133,11 @@ pub enum ReceiptUpdate { Culled, } -/// Receipt metadata installed atomically with an outbound packet. +/// Caller-supplied receipt metadata installed by `SendPacket` in the same +/// actor turn as dispatch. The caller must provide hashes and a destination +/// identity matching the packet; registration does not verify that binding. +/// `None` timeout uses 180 seconds. Initialize the watch channel to `Sent`; +/// terminal updates replace its current value. pub struct TrackedReceiptRegistration { pub truncated_hash: [u8; 16], pub full_hash: [u8; 32], @@ -139,7 +157,11 @@ impl std::fmt::Debug for TrackedReceiptRegistration { } } -/// Immediate outcome of dispatching a packet to the interface layer. +/// Immediate local dispatch outcome. `Sent` means at least one eligible +/// interface or in-process destination queue accepted the packet, not remote +/// delivery. `NoInterface` also covers invalid packets and failed immediate +/// admission; an announce may still be retained for a later retry. +/// `ReceiptCollision` means the truncated receipt key was already registered. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OutboundDispatchResult { Sent, @@ -194,28 +216,31 @@ pub enum LinkEndpointTerminalReason { TransportShutdown, } -/// Exactly-once terminal notification for an established-Link binding. +/// Terminal event attempted once when transport removes a Link binding. +/// The notification can be lost if its receiver has closed. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct LinkEndpointLifecycleEvent { pub binding: LinkEndpointBinding, pub reason: LinkEndpointTerminalReason, - /// Number of accepted packets that could not be emitted before teardown. + /// Packets retained in the endpoint FIFO, plus any packet counted during + /// terminal admission failure. This is not a count of over-the-air losses. pub dropped_packets: usize, } -/// Immediate result of handing one established-Link packet to transport. +/// Immediate result of handing an established-Link packet to transport. /// -/// `Queued` is successful admission to the bounded, per-Link FIFO. It is not -/// a claim that the interface driver has accepted the packet yet. Terminal -/// interface failures are delivered through the lifecycle channel. +/// `Sent` reports local driver/in-process queue admission. `Queued` reports +/// admission to the bounded per-Link FIFO, before driver acceptance. Neither +/// confirms remote delivery. Terminal interface failures use the lifecycle +/// channel; transport does not reroute this binding to another interface. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LinkEndpointSendResult { Sent, Queued { depth: usize, }, - /// A best-effort packet was intentionally discarded because ordered - /// control traffic or the exact interface queue was already full. + /// A best-effort packet was discarded because reliable traffic was + /// already queued or the exact interface queue was full. DroppedBackpressure, NotBound, RoleMismatch, @@ -231,15 +256,16 @@ pub enum LinkEndpointUnbindResult { RoleMismatch, } -/// Periodic maintenance tick. Drives cache culling, retransmit scheduling, -/// and rate-limit decay so the actor needs no internal timer. +/// Explicit maintenance trigger. The actor ignores `timestamp` and reads its +/// own current time. `TransportActor::run` also schedules maintenance internally. #[derive(Debug)] pub struct TimerTick { pub timestamp: f64, } -/// Metadata and TX handle for one registered interface. The actor owns the -/// sender; driver code holds only the matching receiver. +/// Registration metadata, capacity policy and TX sender for one interface. +/// Public fields and builder methods store caller values; they do not start a +/// driver. Registration and dispatch apply ownership/capacity checks separately. pub struct InterfaceEntry { pub owner: InterfaceOwner, pub packet_capacity: InterfacePacketCapacity, @@ -249,11 +275,15 @@ pub struct InterfaceEntry { /// The listener that accepted this interface; `None` for configured ones. pub parent_id: Option, pub direction: InterfaceDirection, + /// Declared bitrate in bits per second, used for timing estimates. pub bitrate: u64, + /// Reported hardware MTU in bytes. Admission uses `packet_capacity`. pub mtu: u32, pub tx: mpsc::Sender, pub ifac_key: Option, + /// Configured IFAC size in bytes; inactive when no key is set. pub ifac_size: usize, + /// Announce bitrate fraction: 0.02 represents 2%. pub announce_cap: f64, /// Earliest Unix time at which the next announce may be sent — enforces /// `ANNOUNCE_CAP` spacing in the outbound path. @@ -269,36 +299,30 @@ pub struct InterfaceEntry { pub txb: Option>, /// Optional driver-owned aggregate inspection source. pub inspection: Option, - /// Incremented when an outbound `try_send` cannot enqueue — surfaced in - /// interface stats to flag a driver whose receiver is falling behind. + /// Packets dropped by counted full-queue admission failures. This is not + /// a count of every send failure or of packets retained for later retry. pub tx_drops: Arc, - /// Bytes of the packets counted in `tx_drops` (Python `tx_dropped_bytes`). + /// Pre-IFAC bytes of the packets counted by transport as full-queue drops. pub tx_dropped_bytes: u64, - /// Inbound packets dropped as malformed or invalid (Python - /// `Interface.protocol_violation`, Interface.py:327-330). + /// Inbound packets counted as malformed or invalid by transport. pub protocol_violations: u64, /// Inbound packets dropped for a missing, invalid or unexpected IFAC. pub ifac_violations: u64, - /// Inbound packets the packet filter rejected (Transport.py:1795). + /// Inbound packets rejected by the transport packet filter. pub packet_filter_hits: u64, pub ingress: IngressController, /// Announces awaiting bandwidth-capped retransmission. Drained in /// hop-priority order (lowest hops first, oldest among ties). pub announce_queue: Vec, - /// Multipoint medium whose peers cannot hear each other (e.g. BLE Peer: - /// each peer is a separate point-to-point GATT link presented as one - /// interface). Unlike a shared broadcast medium, an announce arriving on - /// such an interface must be relayed back out the SAME interface to reach - /// its other peers. Loop safety comes from the announce-table dedup + hop - /// cap and the driver's own per-peer anti-loop filter. + /// Driver-supplied multipoint metadata. The current actor allows same-interface + /// announce relay for ordinary network roles independently of this flag; + /// setting it does not install a driver-level loop filter. pub multipoint: bool, - /// Python 1.3.8 `Interface.recursive_prs` (Interface.py:110): force - /// unknown-path discovery for path requests arriving on this interface, - /// independent of interface mode. + /// Enable unknown-path discovery for requests arriving on this interface, + /// independently of its mode. pub recursive_prs: bool, - /// Python 1.3.8 `Interface.announces_from_internal` (Interface.py:111): - /// when false, this interface does not rebroadcast announces whose - /// next-hop interface is `InterfaceMode::Internal`. + /// Whether to rebroadcast announces whose next-hop interface uses + /// `InterfaceMode::Internal`. pub announces_from_internal: bool, } @@ -349,14 +373,17 @@ impl InterfaceEntry { } } + /// Replace admission capacity without changing the separately reported `mtu`. pub fn with_packet_capacity(mut self, capacity: InterfacePacketCapacity) -> Self { self.packet_capacity = capacity; self } + /// Replace the registration owner; current-generation checks occur at admission. pub fn with_owner(mut self, owner: InterfaceOwner) -> Self { self.owner = owner; self } + /// Return configured IFAC bytes when a key exists, or zero without a key. pub fn active_ifac_bytes(&self) -> usize { if self.ifac_key.is_some() { self.ifac_size @@ -364,7 +391,8 @@ impl InterfaceEntry { 0 } } - /// Pre-allocation admission for a complete clear Reticulum packet. + /// Check current ownership and clear/wire byte capacity before allocation. + /// This does not parse a header or check direction or driver online state. pub fn accepts_clear_packet(&self, len: usize) -> bool { self.owner.is_current() && self @@ -374,6 +402,8 @@ impl InterfaceEntry { .checked_add(self.active_ifac_bytes()) .is_some_and(|wire| wire <= self.packet_capacity.max_wire_packet_bytes as usize) } + /// Compute clear-packet capacity after IFAC. An active key requires an IFAC + /// size in 1..=64 bytes; invalid capacity or IFAC returns an error. pub fn effective_clear_mtu(&self) -> Result { if self.ifac_key.is_some() && !(1..=64).contains(&self.ifac_size) { return Err(InterfaceCapacityError::InvalidIfac); @@ -382,17 +412,23 @@ impl InterfaceEntry { .effective_clear_mtu(self.active_ifac_bytes()) } + /// Store the multipoint metadata flag. pub fn with_multipoint(mut self, multipoint: bool) -> Self { self.multipoint = multipoint; self } + /// Store an IFAC key and size in bytes. This builder does not validate the + /// size; `effective_clear_mtu` rejects active sizes outside 1..=64. pub fn with_ifac(mut self, key: [u8; 64], size: usize) -> Self { self.ifac_key = Some(key.into()); self.ifac_size = size; self } + /// Store the minimum inter-announce interval and extra penalty in seconds, + /// plus the tolerated violation count. Values are not validated here. The + /// receive path uses these to suppress rebroadcast, not announce-cache updates. pub fn with_announce_rate(mut self, target: f64, grace: u32, penalty: f64) -> Self { self.announce_rate_target = Some(target); self.announce_rate_grace = Some(grace); @@ -400,11 +436,13 @@ impl InterfaceEntry { self } + /// Store the role used by shared-instance routing policy. pub fn with_role(mut self, role: InterfaceRole) -> Self { self.role = role; self } + /// Attach driver-owned online state and cumulative RX/TX byte counters. pub fn with_counters( mut self, online: Arc, @@ -461,16 +499,17 @@ pub struct AnnounceHandlerEvent { /// X25519 || Ed25519 public key from the announce payload. pub public_key: Option<[u8; 64]>, pub ratchet: Option<[u8; 32]>, - /// `SHA-256(app_name)[:10]` of the aspect this destination announced - /// under. Zero array if the announce arrived without a payload (degenerate - /// case — handlers with `aspect_filter == None` still receive it). + /// Ten-byte name hash from the destination's expanded hash name, including + /// any aspects or generated-identity suffix. The actor rejects missing or + /// invalid announce payloads before dispatching handlers. pub name_hash: [u8; 10], } /// Optional routing controls for an explicit path request. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct PathRequestOptions { - /// Send only on this interface. `None` broadcasts on all outbound interfaces. + /// Restrict requests to this interface. `None` offers them to eligible + /// outbound interfaces; it does not guarantee queue admission. pub on_interface: Option, /// Caller-supplied request tag. At most the first 16 bytes are transmitted. pub tag: Option>, @@ -478,9 +517,10 @@ pub struct PathRequestOptions { pub recursive: bool, } -/// Every mutation of transport state enters through this enum — the actor -/// dispatches on the variant, so adding a new operation is a matter of adding -/// a variant and a match arm rather than exposing a new lock or shared type. +/// Commands accepted by the transport actor. Some require a current +/// producer-bound `InterfaceEvent`; others are trusted application operations. +/// A mailbox send is not an operation acknowledgment. Unless a variant says +/// otherwise, dropping its reply receiver does not cancel admitted work. // This is the transport actor's public message surface. Boxing individual // variants would churn all senders/receivers for little runtime benefit. #[allow(clippy::large_enum_variant)] @@ -491,14 +531,21 @@ pub enum TransportMessage { owner: InterfaceOwner, message: Box, }, + /// Driver input; requires a current owner-bound `InterfaceEvent`. Inbound(InboundPacket), + /// Dispatch without a result reply. Eligible Data packets receive an automatic + /// receipt, using any cached destination key; failures are not replied. Outbound(OutboundRequest), + /// Validate and dispatch a Link request, replying with local admission only. + /// A closed reply receiver is checked before processing; later cancellation + /// cannot retract transmitted bytes. SendLinkRequest { request: OutboundRequest, result_tx: tokio::sync::oneshot::Sender< Result<(), crate::link_messages::LinkRequestDispatchError>, >, }, + /// Best-effort dispatch restricted to one interface, without a result reply. OutboundAttached { request: OutboundRequest, interface_id: InterfaceId, @@ -531,10 +578,10 @@ pub enum TransportMessage { request: OutboundRequest, result_tx: tokio::sync::oneshot::Sender, }, - /// Reliably admit a final packet, then remove the endpoint and temporary - /// Link destination only after its ordered FIFO has drained. This prevents - /// a queued LINKCLOSE from being discarded by an immediately following - /// unbind or destination deregistration. + /// Use the reliable send path for a final packet, then remove the endpoint + /// and temporary Link destination after a successful FIFO drain or terminal + /// failure. Failure can discard queued bytes; `Queued` does not guarantee + /// eventual interface admission. SendLinkEndpointAndUnbind { link_id: [u8; 16], role: LinkEndpointRole, @@ -549,44 +596,50 @@ pub enum TransportMessage { request: OutboundRequest, result_tx: tokio::sync::oneshot::Sender, }, - /// Dispatch an application packet and report whether an interface - /// accepted it. Optional receipt registration occurs in the same actor - /// turn, avoiding registration/send races. + /// Dispatch a packet and reply with its immediate local admission result. + /// Optional receipt registration occurs in the same actor turn. The result + /// is not remote delivery; see `OutboundDispatchResult` for retained announces. SendPacket { request: OutboundRequest, attached_interface: Option, receipt: Option, result_tx: tokio::sync::oneshot::Sender, }, - /// Change the timeout of one still-pending tracked packet. + /// Change a still-pending receipt duration relative to its original send time, + /// without restarting the timer. Reply is false if no pending receipt matches. SetReceiptTimeout { truncated_hash: [u8; 16], timeout: std::time::Duration, result_tx: tokio::sync::oneshot::Sender, }, Tick(TimerTick), - /// Read-only query paired with a oneshot reply channel — used for all - /// RPC and introspection so callers don't need direct state access. + /// Query or mutation paired with a reply. `TransportQuery` includes destructive + /// cache operations; admission is not an authorization check. Rpc { query: TransportQuery, response_tx: tokio::sync::oneshot::Sender, }, + /// Register a local destination without an acknowledgment. A supplied delivery + /// channel replaces the previous one; `None` leaves an existing channel intact. RegisterDestination { hash: [u8; 16], app_name: String, delivery_tx: Option>, }, + /// Remove the local destination registration and its delivery channel. DeregisterDestination { hash: [u8; 16], }, + /// Install a legacy bounded callback channel without a registration reply. + /// Full channels drop events; a closed channel is reaped. RegisterAnnounceHandler { aspect_filter: Option, receive_path_responses: bool, callback_tx: mpsc::Sender, }, /// Register one owned announce subscription and acknowledge once the actor - /// has installed it. `dropped_events` counts dispatches rejected by the - /// bounded callback channel. + /// has installed it. `dropped_events` counts full-channel dispatch failures. + /// If the registration reply cannot be delivered, the subscription is removed. RegisterAnnounceSubscription { aspect_filter: Option, receive_path_responses: bool, @@ -594,52 +647,72 @@ pub enum TransportMessage { dropped_events: Arc, result_tx: tokio::sync::oneshot::Sender, }, - /// Remove legacy handler(s) whose `aspect_filter` matches; `None` removes - /// every legacy handler. Exact subscriptions are never affected. Handlers - /// with closed senders are also reaped on dispatch. + /// Remove matching legacy handlers; `None` selects all legacy handlers. + /// Active exact subscriptions are not selected by this filter. Closed handlers + /// of either kind are also reaped. DeregisterAnnounceHandler { aspect_filter: Option, }, - /// Remove exactly the subscription backed by `callback_tx`. + /// Remove the exact subscription identified by `id`, and reap closed handlers. + /// An optional reply reports whether that ID was present. DeregisterAnnounceSubscription { id: AnnounceHandlerId, result_tx: Option>, }, - /// Ask the actor to satisfy a packet request: replay from its recent- - /// announce cache when possible, otherwise emit a CacheRequest packet. + /// Replay a matching packet from the local on-disk announce cache when + /// available. On a miss, a network CacheRequest is emitted only when transport + /// is enabled. This command has no success reply. CacheRequest { packet_hash: [u8; 32], destination_hash: [u8; 16], }, + /// Request discovery using default explicit-request options; no reply is sent. RequestPath { destination_hash: [u8; 16], }, + /// Request discovery with explicit interface/tag policy; no reply is sent. RequestPathWithOptions { destination_hash: [u8; 16], options: PathRequestOptions, }, + /// Register an interface with current ownership and valid packet capacity. + /// Replacement requires a newer owner generation. Rejected entries are + /// ignored without a reply. RegisterInterface { id: InterfaceId, entry: InterfaceEntry, }, + /// Remove an interface through its current owner-bound event; bare commands + /// are rejected so an old driver cannot remove a replacement. DeregisterInterface { id: InterfaceId, }, + /// Set trusted local storage and synchronously load saved state. File errors + /// are logged, not returned; initialization may also migrate legacy cache data. SetStoragePaths { storage_dir: std::path::PathBuf, }, + /// Change forwarding mode and identity/persistence policy. Disabling transport + /// also cancels pending background announce and recursive-discovery work. SetTransportEnabled { enabled: bool, }, + /// Set the internal identity hash and recompute the visible transport hash + /// according to forwarding/static-identity policy. SetTransportIdentity { identity_hash: [u8; 16], }, + /// Set accepted on-disk blackhole source filenames and load matching entries. + /// This does not purge entries already loaded from other sources. SetBlackholeSources { sources: Vec<[u8; 16]>, }, - /// Shared-instance connection dropped; pause packet processing until the - /// matching `SharedConnectionRestored` arrives. + /// Handle loss of the current shared-instance peer: invalidate routing state + /// and terminate peer-bound Link endpoints. This is not a blanket pause of + /// all packet processing. Submit through the current interface owner. SharedConnectionLost, + /// Restore the current shared-instance peer and invalidate prior routing + /// state. Submit through that interface owner. SharedConnectionRestored { interface_id: InterfaceId, }, @@ -650,23 +723,25 @@ pub enum TransportMessage { interface_id: InterfaceId, raw_packet: Bytes, }, - /// Register an outbound-packet receipt so the inbound path can match - /// arriving proofs back to `msg_id`. + /// Register a legacy receipt for later proof matching and destination fan-out. + /// An existing entry with the same truncated hash is replaced. The caller must + /// provide packet hashes and a trusted destination key that belong together. RegisterReceipt { truncated_hash: [u8; 16], full_hash: [u8; 32], - /// Destination and validated identity used to construct the outbound - /// packet. Delivery proofs must verify against this exact identity. + /// Destination used to construct the packet. The caller is responsible + /// for authenticating its supplied public key before registration. destination_hash: [u8; 16], destination_public_key: [u8; 64], msg_id: String, /// Override default 180s timeout when `Some`. timeout: Option, }, - /// Register an application-owned receipt with a direct, capacity-lossless - /// proof sink. Unlike the legacy destination fan-out, a validated terminal - /// proof cannot be discarded because an unrelated destination mailbox is - /// full. + /// Register a receipt with an unbounded direct proof sink, replacing an + /// existing entry with the same truncated hash. This avoids bounded mailbox + /// capacity loss, but a closed receiver can still lose the notification. + /// The caller must authenticate and bind the supplied key/hashes; `None` + /// timeout uses 180 seconds. RegisterReceiptWithProof { truncated_hash: [u8; 16], full_hash: [u8; 32], @@ -676,8 +751,10 @@ pub enum TransportMessage { timeout: Option, proof_tx: mpsc::UnboundedSender, }, - /// Record a new link in the table. `initiator=true` means we started the - /// handshake, so the entry is pending until `ActivateLink` arrives. + /// Record local Link bookkeeping after ownership/capacity checks. Initiators + /// remain pending until `ActivateLink`; responder entries start validated. + /// This command trusts the caller to have performed the corresponding protocol + /// checks and does not itself prove a handshake. RegisterLink { interface_owner: Option, link_id: [u8; 16], @@ -687,17 +764,21 @@ pub enum TransportMessage { remaining_hops: u8, initiator: bool, }, - /// Promote a pending (initiator) link to validated. + /// Mark an existing Link entry validated and established. This command + /// performs no cryptographic handshake verification itself. ActivateLink { link_id: [u8; 16], }, - /// Block the caller until a path to `dest` is learned or the caller's - /// timeout fires. Used by request APIs that must not return before - /// forwarding is possible. + /// Reply true if a non-expired path is cached or subsequently learned, and + /// otherwise initiate discovery and park a waiter. Maintenance expires waiters + /// after 15 seconds; that is not a strict caller deadline or reachability proof. + /// Use `await_path` to bound command admission plus the reply wait. AwaitPath { dest: [u8; 16], reply: tokio::sync::oneshot::Sender, }, + /// Request actor shutdown and its synchronous state-save path. There is no + /// completion reply, and this is not a durability acknowledgment. Shutdown, } @@ -748,16 +829,23 @@ pub fn msg_variant_name(msg: &TransportMessage) -> &'static str { } } -/// Read-mostly queries carried by `TransportMessage::Rpc`. +/// Local introspection and mutation operations carried by `TransportMessage::Rpc`. +/// These variants are not an access-control boundary. Responses describe local +/// state and command results, not remote presence or persistence guarantees. #[derive(Debug, Clone)] pub enum TransportQuery { + /// Return currently non-expired paths; presence is not proof of reachability. GetPathTable, + /// Read metadata, counters and optional synchronous driver inspection. + /// Missing counters report zero; absent online state reports true. Rate fields + /// are currently zero placeholders, not measured throughput. GetInterfaceStats, GetRateTable, GetLinkCount, GetRecentAnnounces, - /// Recall one validated announce-cache entry without mutating its - /// `last_used` timestamp. Python: `Identity.recall(..., _no_use=True)`. + /// Return cached identity metadata without updating `last_used`. Locally + /// restored cache metadata is trusted; this query performs no fresh signature + /// verification, age check or network presence check. RecallDestination { dest: [u8; 16], }, @@ -793,31 +881,31 @@ pub enum TransportQuery { GetPacketQ { packet_hash: [u8; 32], }, - /// First-hop timeout: `MTU * per_byte_latency + DEFAULT_PER_HOP_TIMEOUT`. + /// Return 500*8/declared first-hop bitrate + 6 seconds. A missing route, + /// interface or positive bitrate falls back to 6 seconds. This uses the + /// protocol 500-byte MTU, not the reported hardware MTU. FirstHopTimeout { dest: [u8; 16], }, - /// Python-compatible slow-interface timing query: `MTU * per_byte_latency`. - /// - /// Link sessions may use this as establishment policy. Unvalidated - /// transport-table retention deliberately remains bitrate-independent. + /// Return 500*8/declared interface bitrate in seconds, or zero when no positive + /// bitrate is available. This is a caller timing estimate; unvalidated + /// transport-table retention is separately bitrate-independent. ExtraLinkProofTimeout { interface_id: InterfaceId, }, DropPath { dest: [u8; 16], }, - /// Temporarily reject path-table installs for `dest` learned through - /// `interface_id`. Used after link establishment failure so rediscovery can - /// consider alternate interfaces instead of immediately reselecting the - /// path that just failed. + /// Temporarily reject new path installs through this interface for the + /// destination. Duration must be positive and finite. This does not remove + /// the current route or guarantee that an alternative will be learned. SuppressPathInterface { dest: [u8; 16], interface_id: InterfaceId, duration: f64, }, - /// Temporarily reject path-table installs for `dest` learned through the - /// interface that currently owns the path. + /// Apply suppression to the current non-expired path interface. Returns false + /// without such a path or for an invalid duration; the existing route remains. SuppressCurrentPathInterface { dest: [u8; 16], duration: f64, @@ -841,38 +929,51 @@ pub enum TransportQuery { /// Separate from unblackhole-by-hash so operators can flush auto-populated /// entries without losing their explicit blocks. ClearSystemBlackholes, - /// Build this node's distributed blackhole `/list` manifest. Response is - /// `Data(msgpack)`. + /// Build a MessagePack manifest from local entries whose identity public keys + /// are present in the announce cache. `publisher` is caller-supplied. This + /// operation neither signs the manifest nor freshly verifies cached identities. BuildBlackholeManifest { publisher: [u8; 16], }, - /// Merge a distributed blackhole `/list` manifest. Response is - /// `IntResult(count_applied)`. + /// Decode and merge a MessagePack manifest. Caller must authenticate its source + /// and apply authorization policy first: this query does not verify a publisher + /// or bind inner source fields to a trusted peer. Returns operation count or error. ApplyBlackholeManifest { payload: Vec, }, + /// Set a registered interface's shared online flag false if present. This does + /// not invoke a driver shutdown; an absent flag is still reported as `Ok`. HaltInterface { id: InterfaceId, }, + /// Set a registered interface's shared online flag true if present. This does + /// not reopen a driver; an absent flag is still reported as `Ok`. ResumeInterface { id: InterfaceId, }, + /// Remove paths using a next hop and return the removed count. This operation + /// does not itself mark routing state dirty or confirm a disk save. DropAllVia { next_hop: [u8; 16], }, - /// Drop every cached route from the path table and persist the empty table. - /// Response: `IntResult(count_cleared)`. + /// Clear cached routes and pending discovery state, then attempt a synchronous + /// routing-state save. `IntResult` is the removed route count; save failures + /// are logged and do not change that response. DropPathTable, - /// Drop every cached announce snapshot and persist the empty cache. - /// Response: `IntResult(count_cleared)`. + /// Clear cached announce metadata and attempt a synchronous routing-state + /// save. The returned count does not confirm persistence. Individual on-disk + /// packet-cache files are not removed by this operation. DropRecentAnnounces, - /// Remote-status RPC — interface stats + optional link count, wire-format - /// compatible with `Transport.remote_status_handler`. + /// Serialize the actor's status tuple: a list of interface key/value string + /// pairs and, optionally, Link count. This local helper is not the authenticated + /// remote-management service or a general wire-compatibility guarantee. RemoteStatus { include_link_count: bool, }, - /// Remote-path RPC — path table filtered by destination and hop limit, - /// wire-format compatible with `Transport.remote_path_handler`. + /// Serialize local path entries filtered by destination and hop limit. Each + /// entry contains hex destination, hops, timestamp and interface name. Expired + /// entries can remain until culling; `command` is currently ignored. This is + /// not the authenticated remote-management service. RemotePath { command: String, destination: Option<[u8; 16]>, @@ -888,10 +989,9 @@ pub enum TransportQuery { PathIsUnresponsive { dest: [u8; 16], }, - /// Pin / unpin a destination from the cache. While retained, the - /// maintenance sweep will not reap the entry regardless of age. - /// Returns `BoolResult(true)` when the destination is known to the - /// cache, `false` when not. + /// Pin known announce metadata against age-based maintenance cleanup. Returns + /// false if unknown. Explicit cache clearing still removes retained entries; + /// use `UnretainDestination` to release the pin. RetainDestination { dest: [u8; 16], }, @@ -904,13 +1004,12 @@ pub enum TransportQuery { UnretainDestination { dest: [u8; 16], }, - /// Immediate cleanup trigger. Returns `IntResult(entries_remaining)`. - /// The actor tick runs cleanup every 5 minutes regardless. + /// Run announce-metadata cleanup now and return the remaining count. Periodic + /// cleanup is additionally subject to its interval and startup-grace gates. CleanKnownDestinations, - /// Resolve a 16-byte hex blob — which may be either a destination hash or - /// an identity hash — to a canonical identity hash via `recent_announces`. - /// Returns `HashResult(Some(_))` on hit, `HashResult(None)` when the input - /// is neither a known destination nor a known identity. Read-only. + /// Resolve a raw 16-byte value as a destination first, then as an identity hash, + /// using cached public keys. Returns `HashResult(None)` on a miss. This does + /// not freshly authenticate the cache or contact a peer. ResolveIdentityHash { input: [u8; 16], }, @@ -921,12 +1020,14 @@ pub enum TransportQuery { FilterBlackholedDests { dests: Vec<[u8; 16]>, }, - /// Drop every Manual blackhole entry whose identity is not currently in - /// `recent_announces`. Returns `IntResult(count_purged)`. Use sparingly — - /// this can drop legit-but-unseen entries. + /// Remove Manual blackhole entries whose identity has no matching cached + /// public key. The returned count reflects cache presence, not identity validity; + /// a legitimate but unseen or pruned identity can be removed. PurgeUnverifiedBlackholes, } +/// Local actor results. `Ok` confirms handling only; individual operations +/// define their own admission, cache and persistence limits. #[derive(Debug)] pub enum TransportQueryResponse { PathTable(Vec), @@ -950,6 +1051,8 @@ pub enum TransportQueryResponse { Error(String), } +/// Snapshot of a cached route. Times are Unix seconds; returned interface +/// metadata can use fallback values if the interface is no longer registered. #[derive(Debug, Clone)] pub struct PathTableRpcEntry { pub hash: [u8; 16], @@ -963,6 +1066,12 @@ pub struct PathTableRpcEntry { pub interface_role: InterfaceRole, } +/// Interface metadata and sampled counters. Driver counters use independent +/// atomic reads, so this is not a coherent instant across all fields. Missing +/// counters become zero and missing online state becomes true; current +/// `rx_rate`/`tx_rate` values are zero placeholders. `bitrate` is declared bits +/// per second, `mtu` is reported bytes, `ifac_size` is configured bytes, and +/// `announce_cap` is a fraction. Names can contain caller-supplied text. #[derive(Debug, Clone, Default)] pub struct InterfaceStatRpcEntry { pub id: InterfaceId, @@ -995,7 +1104,7 @@ pub struct InterfaceStatRpcEntry { pub ifac_size: usize, pub tx_drops: u64, pub tx_dropped_bytes: u64, - /// Python `arxc`/`atxc`/`prxc`/`ptxc` (Interface.py:303-325). + /// Announces counted by the interface ingress controller. pub announces_received: u64, pub announces_sent: u64, pub path_requests_received: u64, @@ -1007,6 +1116,8 @@ pub struct InterfaceStatRpcEntry { pub parent_id: Option, } +/// Announce-rate state: rate is announces per second; timestamps, `last` and +/// `blocked_until` are Unix seconds. A zero deadline means no active penalty. #[derive(Debug, Clone)] pub struct RateTableRpcEntry { pub hash: [u8; 16], @@ -1017,6 +1128,8 @@ pub struct RateTableRpcEntry { pub timestamps: Vec, } +/// Cached announce metadata, possibly restored from trusted local storage. +/// This snapshot does not freshly verify a signature or establish a live path. #[derive(Debug, Clone)] pub struct AnnounceRpcEntry { pub dest_hash: [u8; 16], @@ -1025,7 +1138,8 @@ pub struct AnnounceRpcEntry { pub timestamp: f64, pub public_key: Option<[u8; 64]>, pub ratchet: Option<[u8; 32]>, - /// `SHA-256(app_name)[:10]` for the announced aspect. + /// Ten-byte announce name hash from the destination's expanded hash name, + /// which can include aspects and a generated-identity suffix. pub name_hash: [u8; 10], /// True when the cached announce arrived as a path response instead of a /// fresh network announce. @@ -1035,8 +1149,8 @@ pub struct AnnounceRpcEntry { pub retained: bool, } -/// The identity-bearing subset of a cached announce returned by -/// [`TransportQuery::RecallDestination`]. +/// Identity-bearing metadata returned by [`TransportQuery::RecallDestination`]. +/// It is trusted cache content, not a fresh signature or reachability result. #[derive(Debug, Clone)] pub struct RecalledDestinationRpcEntry { pub dest_hash: [u8; 16], @@ -1047,6 +1161,8 @@ pub struct RecalledDestinationRpcEntry { pub timestamp: f64, } +/// Blackhole-table snapshot. Times and TTL are seconds; source attribution +/// can come from stored metadata or the local transport identity fallback. #[derive(Debug, Clone)] pub struct BlackholeRpcEntry { pub identity_hash: [u8; 16], @@ -1056,10 +1172,9 @@ pub struct BlackholeRpcEntry { pub ttl: Option, pub reason: crate::blackhole::BlackholeReason, pub reason_label: Option, - /// True if `recent_announces` currently contains an announce whose public - /// key hashes to `identity_hash`. False means we cannot confirm this entry - /// is a real identity — it may be garbage from a pre-fix caller, or a real - /// identity whose announce we have not yet received / has been pruned. + /// Whether a currently cached public key hashes to `identity_hash`. This is + /// a cache-presence test, not fresh signature validation, proof of reachability + /// or a judgment that an absent identity is invalid. pub verified: bool, } diff --git a/crates/rns-transport/src/path_discovery.rs b/crates/rns-transport/src/path_discovery.rs index c5e1d83..12b73df 100644 --- a/crates/rns-transport/src/path_discovery.rs +++ b/crates/rns-transport/src/path_discovery.rs @@ -40,10 +40,9 @@ impl Eq for DiscoveryRequester {} /// Detached read-only snapshot of one pending recursive search. /// -/// Since 1.3, replaces the legacy single-requester public fields and `Copy` -/// contract. Accessors describe the observation instant, not a live view. -/// Changing/dropping a snapshot cannot modify the actor. The historical first -/// requester is deliberately not privileged. +/// Cloneable but not `Copy`. Accessors describe the observation instant, +/// not a live view. Changing or dropping a snapshot cannot modify the actor; +/// no requester in the collection has privileged ownership. /// /// ```compile_fail /// use rns_transport::actor::TransportActor; diff --git a/crates/rns-transport/src/path_recovery.rs b/crates/rns-transport/src/path_recovery.rs index 39f2354..9ebf816 100644 --- a/crates/rns-transport/src/path_recovery.rs +++ b/crates/rns-transport/src/path_recovery.rs @@ -1,4 +1,4 @@ -//! Bounded recovery of a locally originated Link's route. +//! Bounded recovery of routes used by local Links and tracked packet attempts. //! //! The transport records the route actually used at dispatch. Recovery may //! invalidate that unchanged route, never a replacement learned meanwhile. @@ -13,8 +13,12 @@ pub(crate) const RECOVERY_QUEUE_CAPACITY: usize = 64; #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub struct PathRecoveryOutcome { + /// A matching observed local route was selected for expiry. pub path_dropped: bool, + /// An unexpired route remains after the comparison; no reachability check. pub has_path: bool, + /// New or existing discovery work was found in a local queue/admission + /// lane. This is not proof that a request will be transmitted. pub request_scheduled: bool, } @@ -53,8 +57,10 @@ pub(crate) enum FailedRouteAttempt { /// Cloneable, transport-generation-owned admission handle. Obtain it before /// running the actor with [`crate::actor::TransportActor::path_recovery_handle`]. -/// This additive control lane does not change the existing exhaustive mailbox -/// enums or the semantics of explicit interface-suppression APIs. +/// Recovery does not suppress interfaces. Route comparisons require observations +/// younger than one hour by wall-clock age. Observations share a 1024-attempt +/// limit, so older attempts can be evicted before that age. +/// Unknown observations may request discovery but cannot invalidate a route. #[derive(Debug, Clone)] pub struct PathRecoveryHandle { pub(crate) tx: mpsc::Sender, @@ -94,9 +100,11 @@ impl PathRecoveryHandle { } /// Invalidate only the unchanged local route used by a tracked packet, - /// without scheduling discovery. Unknown, consumed, cancelled or replaced - /// attempts cannot invalidate a route. The returned `path_dropped` flag is - /// evidence of this local comparison, not permission or an atomic guarantee + /// without scheduling discovery. Unknown, expired, consumed or route-mismatched + /// attempts cannot invalidate a route. A request whose receiver is dropped + /// before execution is skipped without consuming its observation. The + /// returned `path_dropped` flag is evidence of this local comparison, + /// not permission or an atomic guarantee /// for another process' route table. /// /// Shared-client coordinators can use this before an authenticated owner diff --git a/crates/rns-transport/src/path_table.rs b/crates/rns-transport/src/path_table.rs index e051675..dd34172 100644 --- a/crates/rns-transport/src/path_table.rs +++ b/crates/rns-transport/src/path_table.rs @@ -8,22 +8,24 @@ use crate::constants::{ use crate::messages::InterfaceId; use rns_wire::types::DestHash; -/// One known path to a destination. +/// Stored route metadata for a destination. Fields are caller-writable; this +/// record alone does not establish a live interface or reachable peer. #[derive(Debug, Clone)] pub struct PathEntry { - /// Learn time (Unix seconds). + /// Learn or last-touch time (Unix seconds). pub timestamp: f64, /// Next-hop transport id; `None` for a directly-connected neighbour. pub next_hop: Option<[u8; 16]>, pub hops: u8, - /// Expiry (Unix seconds), derived from interface mode at insert time. + /// Expiry (Unix seconds). `new` derives it from the supplied interface mode. pub expires: f64, - /// Recent announce-random blobs, capped at `MAX_RANDOM_BLOBS` to bound - /// anti-replay memory on long-lived paths. + /// Recent announce-random blobs. Normal `add_random_blob` use from an empty + /// deque retains at most `MAX_RANDOM_BLOBS`; direct field mutation can + /// exceed that size. The helper does not authenticate or deduplicate blobs. pub random_blobs: VecDeque<[u8; 10]>, pub interface_id: InterfaceId, - /// Hash of the cached announce packet — used to satisfy CacheRequest - /// without holding the full packet bytes. + /// Hash used to locate a cached announce packet. The record does not own + /// its bytes, and a corresponding cache file may be unavailable. pub packet_hash: Option<[u8; 32]>, } @@ -63,9 +65,10 @@ impl PathEntry { now_f64() > self.expires } - /// Mark an actively used route as live. Reticulum's Python path cull is - /// timestamp based; Rust stores an explicit expiry, so both clocks must - /// move together when traffic proves the route is still useful. + /// Set the timestamp to now and preserve a positive prior lifetime + /// (`expires - timestamp`), or use the seven-day default otherwise. + /// This can renew an expired entry and performs no network liveness check; + /// the caller decides whether activity justifies renewal. pub fn touch(&mut self) { let now = now_f64(); let lifetime = if self.expires > self.timestamp { @@ -77,17 +80,18 @@ impl PathEntry { self.expires = now + lifetime; } - /// Most recent blobs to persist — older entries can be regenerated from - /// the wire on replay, so we cap the snapshot at `PERSIST_RANDOM_BLOBS` - /// to keep the on-disk table small. + /// Return at most the last `PERSIST_RANDOM_BLOBS` entries, preserving their + /// deque order, for a bounded persistence snapshot. Older blobs are omitted. pub fn blobs_for_persist(&self) -> Vec<[u8; 10]> { let start = self.random_blobs.len().saturating_sub(PERSIST_RANDOM_BLOBS); self.random_blobs.iter().skip(start).copied().collect() } } -/// Destination-hash → path mapping plus a parallel liveness state map so we -/// can probe unresponsive paths without rewriting the entries. +/// Destination-keyed routes and separately stored path-state labels. Ordinary +/// lookup/iteration includes expired entries; `get_live`/`iter_live` checks +/// expiry only, not interface health or reachability. State labels are supplied +/// by callers and can exist without a route. This table does not probe peers. #[derive(Clone)] pub struct PathTable { entries: HashMap, @@ -102,17 +106,9 @@ impl PathTable { } } - /// Insert or replace a path entry. The parallel liveness state is - /// cleared so a fresh/replacement entry never inherits a stale - /// `Responsive`/`Unresponsive` reading from its predecessor. `get_state` - /// reads a missing entry as `Unknown`, so clearing is equivalent to - /// writing `Unknown` but avoids holding an entry we'd only overwrite. - /// - /// Python Reticulum 1.1.8 (`8c082b2`) fixes the same bug by clearing state - /// at the inbound insert sites. The Rust transport has additional insert - /// sites (announce install, PathResponse install, tunnel path restore, disk - /// load), so the invariant is enforced here: state is never older than the - /// entry it describes. + /// Insert or replace a route without validating its fields, and remove the + /// old state label so `get_state` returns `Unknown`. Mutation through + /// `get_mut` does not perform this reset. pub fn insert(&mut self, dest_hash: impl Into, entry: PathEntry) { let hash: DestHash = dest_hash.into(); self.states.remove(&hash); @@ -136,7 +132,8 @@ impl PathTable { } /// A path exists and has not yet expired. Callers should prefer this - /// over `get().is_some()` so stale entries are not treated as routable. + /// over `get().is_some()` to exclude expired entries. This does not confirm + /// that the recorded interface or remote destination is currently reachable. pub fn has_path(&self, dest_hash: &[u8; 16]) -> bool { self.get_live(dest_hash).is_some() } @@ -150,23 +147,25 @@ impl PathTable { self.entries.remove(dest_hash) } - /// Drop every path whose interface id matches — used when an interface - /// goes down so we don't keep routing through a dead transport. + /// Remove every route whose interface ID matches. Associated state labels + /// remain until separately removed, replaced or cleaned by a full cull. pub fn drop_all_via(&mut self, interface_id: InterfaceId) -> usize { let before = self.entries.len(); self.entries.retain(|_, e| e.interface_id != interface_id); before - self.entries.len() } + /// Remove routes through this next hop, leaving their state labels intact. pub fn drop_all_via_next_hop(&mut self, next_hop: &[u8; 16]) -> usize { let before = self.entries.len(); self.entries.retain(|_, e| e.next_hop != Some(*next_hop)); before - self.entries.len() } - /// Force-expire a path and cull immediately. Useful when the caller - /// already knows the path is bad (e.g. a link proof failed) and - /// shouldn't wait for the periodic cull cycle. + /// Set a present route's expiry to zero, then run a full expired-route cull + /// across the table. Return whether the target entry existed before the + /// operation. The cull uses the current wall clock and can remove other + /// expired entries too. pub fn expire(&mut self, dest_hash: &[u8; 16]) -> bool { if let Some(entry) = self.entries.get_mut(dest_hash) { entry.expires = 0.0; @@ -188,8 +187,8 @@ impl PathTable { .unwrap_or(PathState::Unknown) } - /// Full cull pass. Prefer `cull_expired_batch` on the hot path to bound - /// per-tick work. + /// Scan all routes, remove expired entries and remove every state label + /// without a remaining route. Return the number of routes removed. pub fn cull_expired(&mut self) -> usize { let before = self.entries.len(); self.entries.retain(|_, entry| !entry.is_expired()); @@ -198,8 +197,9 @@ impl PathTable { before - self.entries.len() } - /// Batched cull — removes at most `limit` expired entries so the actor - /// cannot stall on a very large path table. + /// Remove at most `limit` expired routes and their state labels. The limit + /// bounds removals, not scanning time: finding those entries can examine + /// the entire table. Unrelated orphan state labels are not cleaned here. pub fn cull_expired_batch(&mut self, limit: usize) -> usize { let to_remove: Vec = self .entries diff --git a/crates/rns-transport/src/persistence.rs b/crates/rns-transport/src/persistence.rs index 23c073b..b0109b3 100644 --- a/crates/rns-transport/src/persistence.rs +++ b/crates/rns-transport/src/persistence.rs @@ -1,6 +1,14 @@ -//! Atomic msgpack persistence for transport tables. `atomic_write` is -//! write-to-tmp + fsync + rename (via the shared rns-identity helper) so a -//! crash or power loss leaves either the old or the new file, never a torn one. +//! Local snapshots and Python-compatible cache formats for transport state. +//! +//! Table and hashlist writers use [`rns_identity::persistence::atomic_write`]: +//! a same-directory temporary file, file sync, readback checks and replacement. +//! Parent-directory sync is best-effort on Unix; this is not an unconditional +//! power-loss guarantee or a transaction across files. The per-announce cache +//! writer has a separate, unsynced temporary-file path. +//! +//! Loaders decode local storage, not authenticated network input. Most read the +//! whole file and have no size limit; decoded metadata still needs validation +//! before use. Loading a route does not establish that its peer is reachable. use std::collections::{HashMap, HashSet}; use std::io::{BufReader, Read}; @@ -13,6 +21,9 @@ use crate::constants::PERSIST_RANDOM_BLOBS; use crate::hashlist::PacketHashlist; use crate::path_table::PathTable; +/// Rust path-snapshot fields. Byte-vector lengths and timestamp validity are not +/// checked by deserialization; callers must validate and rebind the interface +/// before installing a route. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PersistedPathEntry { pub destination_hash: Vec, @@ -22,17 +33,16 @@ pub struct PersistedPathEntry { pub expires: f64, pub random_blobs: Vec>, pub interface_id: u64, - /// Stable identifier for the interface that learned this path. The load - /// path uses it to remap the volatile `interface_id` (re-allocated from - /// zero on every actor boot) once the matching interface registers. + /// Saved interface name for rebinding to a current interface. A stored + /// `interface_id` alone is not a stable identity across actor instances. #[serde(default)] pub interface_name: Option, - /// Python's `destination_table` stores the full hash of `str(interface)`. - /// Keep it in the Rust sidecar too so sidecar/canonical loads can share - /// the same rebinding path. + /// Full SHA-256 of the saved interface name, as produced by + /// [`interface_hash_from_name`]. This is a lookup key, not authentication. #[serde(default)] pub interface_hash: Option>, - /// Full hash of the cached announce packet backing this path. + /// Optional full hash used to locate the cached announce packet. + /// Deserializing this byte vector does not validate its length or contents. #[serde(default)] pub packet_hash: Option>, } @@ -54,6 +64,9 @@ pub struct PersistedHashlist { pub version: u32, } +/// Save a version-4 Rust path snapshot. Paths without a supplied interface name +/// are skipped, and at most the last 32 random blobs per path are retained. +/// Expired paths are not filtered here; cull the table first when needed. pub fn save_path_table( table: &PathTable, interface_names: &HashMap, @@ -97,8 +110,11 @@ pub fn save_path_table( atomic_write(path, &persisted) } -/// Loads a path-table snapshot. Entries without `interface_name` (v1/v2) -/// are dropped at the actor boundary since `interface_id` is volatile. +/// Decode a Rust path snapshot with a supported version (1 through 4). +/// +/// This returns stored entries without checking byte-vector lengths, expiry, +/// announce signatures or interface availability. Older entries may lack an +/// interface name; the caller must decide whether they can be rebound safely. pub fn load_path_table(path: &Path) -> Result, PersistenceError> { let data = std::fs::read(path).map_err(PersistenceError::Io)?; let persisted: PersistedPathTable = @@ -152,10 +168,15 @@ pub struct PythonTunnelPath { pub packet_hash: [u8; 32], } +/// Hash the exact UTF-8 interface name with full SHA-256. No normalization or +/// identity authentication is performed. pub fn interface_hash_from_name(name: &str) -> [u8; 32] { rns_crypto::sha::full_hash(name.as_bytes()) } +/// Save the Python-compatible eight-field destination rows. Entries without a +/// supplied interface name or cached announce hash are skipped; expired entries +/// are retained. Each row includes at most the last 32 random blobs. pub fn save_python_destination_table( table: &PathTable, interface_names: &HashMap, @@ -193,6 +214,13 @@ pub fn save_python_destination_table( atomic_write_bytes(path, &serialized) } +/// Decode Python-compatible destination rows from a local file. +/// +/// The outer value must be an array. Non-array rows are skipped, but an array +/// row shorter than eight fields fails the load. Invalid fixed-length hashes or +/// hop counts skip that row; unsupported time encodings become zero, and invalid +/// random blobs are discarded. Valid blob lists are not length-capped here. +/// No announce signature, expiry or current-path check is performed. pub fn load_python_destination_table( path: &Path, ) -> Result, PersistenceError> { @@ -257,12 +285,13 @@ pub fn load_python_destination_table( Ok(out) } -/// Write one announce's raw bytes into the Python-compatible per-packet -/// announce cache, skipping when the file already exists (cache files are -/// content-addressed by packet hash, and SINGLE announces retransmit -/// byte-identical). Plain tmp+rename without fsync — matches Python -/// `Transport.cache`'s plain write; the cache is best-effort and rebuilt -/// from live traffic, and this runs on the actor for every fresh announce. +/// Write raw packet bytes and an optional interface reference under the +/// supplied packet hash in the Python-compatible announce cache. +/// +/// An existing path is left untouched without validating its contents. This +/// helper does not compute the packet hash or verify the announce. It uses a +/// fixed sibling `.tmp` file and rename without fsync; serialize writers for +/// the same key. The existence check is not an exclusive create operation. pub fn write_python_cached_announce_if_absent( announce_cache_dir: &Path, packet_hash: &[u8; 32], @@ -289,6 +318,11 @@ pub fn write_python_cached_announce_if_absent( std::fs::rename(&tmp, &path).map_err(PersistenceError::Io) } +/// Read the cached packet for a supplied hash, returning `None` if absent. +/// +/// The cache value must contain binary packet bytes; an invalid optional +/// interface-reference value becomes `None`. The filename hash, packet header, +/// signature and age are not checked. Validate the returned packet before use. pub fn load_python_cached_announce( announce_cache_dir: &Path, packet_hash: &[u8; 32], @@ -327,6 +361,9 @@ pub fn load_python_cached_announce( })) } +/// Save Python-compatible tunnel rows, retaining expired tunnels and paths. +/// Nested paths without a cached announce hash are omitted; each saved path +/// keeps at most the last 32 random blobs. An unknown interface has no hash. pub fn save_python_tunnel_table( table: &crate::tunnel::TunnelTable, interface_names: &HashMap, @@ -382,6 +419,10 @@ pub fn save_python_tunnel_table( atomic_write_bytes(path, &serialized) } +/// Decode a local Python-compatible tunnel table. Malformed tunnel or path +/// rows are skipped; unsupported time encodings become zero and invalid random +/// blobs are discarded. Hash lengths are checked, but signatures, timestamp +/// finiteness, expiry and current reachability are not. Blob lists are not capped. pub fn load_python_tunnel_table(path: &Path) -> Result, PersistenceError> { let data = std::fs::read(path).map_err(PersistenceError::Io)?; let value = rmpv::decode::read_value(&mut std::io::Cursor::new(data)) @@ -494,28 +535,29 @@ fn value_u8(value: &Value) -> Option { /// Result of streaming a canonical `packet_hashlist.raw` file. /// -/// A trailing fragment is recoverable: complete 32-byte hashes are returned -/// and the caller can report the ignored byte count. Duplicates are removed -/// while reading so a corrupt or manually concatenated file cannot inflate -/// the in-memory set. +/// Complete 32-byte hashes are returned in first-seen order, with duplicates +/// removed. A partial final record is ignored and reported separately. There +/// is no cap on the number of unique hashes loaded. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RawHashlistLoad { pub hashes: Vec<[u8; 32]>, + /// Number of complete records that repeated an earlier hash. pub duplicate_count: usize, + /// Bytes ignored after the last complete 32-byte record (0 through 31). pub partial_tail_bytes: usize, } -/// Atomically write the current packet-hash generation in Reticulum 1.4's -/// canonical raw format: an unframed concatenation of 32-byte hashes. +/// Write only the current packet-hash generation as an unframed +/// concatenation of 32-byte hashes. The previous generation is omitted. pub fn save_hashlist_raw(hashlist: &PacketHashlist, path: &Path) -> Result<(), PersistenceError> { let hashes = hashlist.current_hashes(); save_raw_hashes(&hashes, path) } -/// Persist a packet hashlist through the stable pre-1.4 facade. +/// Select a hashlist format by the exact, case-sensitive `raw` extension. /// -/// A `.raw` path uses the current canonical format; other paths retain the -/// legacy msgpack writer so existing save/load callers continue to round-trip. +/// Raw output saves only the current generation; every other extension uses +/// [`save_hashlist_legacy`] and saves both generations. pub fn save_hashlist(hashlist: &PacketHashlist, path: &Path) -> Result<(), PersistenceError> { if path.extension().is_some_and(|extension| extension == "raw") { save_hashlist_raw(hashlist, path) @@ -524,10 +566,8 @@ pub fn save_hashlist(hashlist: &PacketHashlist, path: &Path) -> Result<(), Persi } } -/// Write both in-memory generations using the legacy msgpack list shape. -/// -/// Runtime persistence never calls this; it exists only for compatibility -/// tooling and one-way migration support. +/// Write both in-memory generations as a legacy MessagePack array of binary +/// hashes. The file does not preserve the boundary between generations. pub fn save_hashlist_legacy( hashlist: &PacketHashlist, path: &Path, @@ -543,9 +583,9 @@ pub fn save_hashlist_legacy( atomic_write_bytes(path, &serialized) } -/// Atomically write an explicit hash snapshot. Used by legacy migration so -/// the canonical file is materialised without deleting or rewriting the -/// source file. +/// Replace `path` with the supplied hashes concatenated as raw 32-byte records. +/// Input order and duplicates are preserved. The full output is allocated in +/// memory before writing through the shared atomic-file helper. pub fn save_raw_hashes(hashes: &[[u8; 32]], path: &Path) -> Result<(), PersistenceError> { let mut serialized = Vec::with_capacity(hashes.len().saturating_mul(32)); for hash in hashes { @@ -554,11 +594,11 @@ pub fn save_raw_hashes(hashes: &[[u8; 32]], path: &Path) -> Result<(), Persisten atomic_write_bytes(path, &serialized) } -/// Stream a canonical raw hashlist with fixed-size buffering. +/// Load raw 32-byte hash records through a 64 KiB reader buffer. /// -/// This intentionally does not read the whole file into one byte vector. -/// The retained memory is the deduplicated set itself plus a bounded reader -/// buffer. A short final record is ignored and surfaced in the result. +/// Unique hashes are retained in both an output vector and a deduplication +/// set while reading, so total memory grows with the unique-record count. +/// A partial final record is ignored and reported in [`RawHashlistLoad`]. pub fn load_hashlist_raw(path: &Path) -> Result { const READ_BUFFER_SIZE: usize = 64 * 1024; @@ -598,6 +638,10 @@ pub fn load_hashlist_raw(path: &Path) -> Result Result, PersistenceError> { let data = std::fs::read(path).map_err(PersistenceError::Io)?; let raw_hashes = match rmp_serde::from_slice::>>(&data) { @@ -623,10 +667,11 @@ pub fn load_hashlist_legacy(path: &Path) -> Result, PersistenceErr Ok(hashes) } -/// Load a packet hashlist through the stable pre-1.4 facade. +/// Select a hashlist reader by the exact, case-sensitive `raw` extension. /// -/// A `.raw` path uses the current canonical format; other paths retain the -/// legacy msgpack reader so existing migration tools keep working. +/// Raw loads return only hashes, discarding duplicate and partial-tail +/// diagnostics. Call [`load_hashlist_raw`] directly when those counts matter. +/// Every other extension uses [`load_hashlist_legacy`]. pub fn load_hashlist(path: &Path) -> Result, PersistenceError> { if path.extension().is_some_and(|extension| extension == "raw") { Ok(load_hashlist_raw(path)?.hashes) @@ -671,6 +716,9 @@ impl PersistedBlackholeTable { pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2]; } +/// Save all entries as a version-2 Rust blackhole snapshot, including expired +/// entries. Publisher/source identity is not stored in this format; use +/// [`save_python_blackhole_files`] when source grouping must be preserved. pub fn save_blackhole_table( table: &crate::blackhole::BlackholeTable, path: &Path, @@ -694,6 +742,9 @@ pub fn save_blackhole_table( atomic_write(path, &persisted) } +/// Decode a version-1 or version-2 Rust blackhole snapshot. Stored hash lengths, +/// timestamps and expiry are not validated. This format has no publisher/source +/// identity field; loading it cannot recover that provenance. pub fn load_blackhole_table(path: &Path) -> Result, PersistenceError> { let data = std::fs::read(path).map_err(PersistenceError::Io)?; let persisted: PersistedBlackholeTable = @@ -719,6 +770,11 @@ pub struct PythonBlackholeEntry { pub reason_label: Option, } +/// Write a `local` file and one file per remote source represented in the table. +/// +/// Each file is replaced separately; this is not a multi-file transaction. +/// Obsolete source files are left in place, so the directory is not necessarily +/// an exact snapshot of this table after saving. Expired entries are included. pub fn save_python_blackhole_files( table: &crate::blackhole::BlackholeTable, local_identity_hash: [u8; 16], @@ -753,6 +809,19 @@ pub fn save_python_blackhole_files( Ok(()) } +/// Load local blackholes and enabled remote-source files from a directory. +/// +/// A missing directory gives an empty result; other directory-open errors fail. +/// Unreadable files, non-map records and invalid identity keys are skipped. +/// A map with a valid 16-byte identity can still omit `until`: missing, Nil or +/// nonnumeric values become a permanent entry (`ttl=None`). A missing or +/// nonstring reason becomes Manual; string reasons are also retained as labels. +/// Source identity comes from the filename (or `local_identity_hash` for +/// `local`), not an authenticated signature or stored `source`. Trust the directory. +/// +/// Expired entries are omitted. Returned creation times are `now`, and finite +/// lifetimes become the remaining duration. Remote entries precede local entries; +/// ordering between remote files is unspecified. pub fn load_python_blackhole_dir( blackhole_dir: &Path, local_identity_hash: [u8; 16], @@ -879,16 +948,17 @@ pub struct PersistedAnnounceEntry { pub timestamp: f64, pub public_key: Option>, pub ratchet: Option>, - /// Disk announce-cache key (`cache/announces/`). Raw announce bytes - /// are not persisted inline since v6 — CacheRequest replays read the - /// byte-identical packet from the per-announce cache file. + /// Optional disk-cache key (`cache/announces/`). Version 6 stores + /// metadata separately from raw packets; this value alone does not prove + /// that a valid packet is present in the cache. #[serde(default)] pub packet_hash: Option>, - /// Pinned via `RetainDestination`; the maintenance sweep skips the - /// entry regardless of age while this is `true`. + /// Stored retention preference. Loading this record does not itself + /// install the entry or run the actor's retention policy. pub retained: bool, - /// `SHA-256(app_name)[:10]` of the announced aspect. Lets cache consumers - /// retro-filter without re-parsing the announce. + /// Stored announce name hash from the destination's expanded hash name, + /// which can include aspects and a generated-identity suffix. It should + /// contain 10 bytes; deserialization does not validate its length or derivation. pub name_hash: Vec, #[serde(default)] pub is_path_response: bool, @@ -896,8 +966,8 @@ pub struct PersistedAnnounceEntry { pub last_used: Option, } -/// Exact v5 on-disk entry shape (raw announce bytes inline), kept for -/// one-shot migration to the disk-backed v6 cache. +/// Version-5 on-disk entry shape with raw announce bytes inline, accepted by +/// [`load_announce_cache_legacy_v5`] for migration to separate packet files. #[derive(Debug, Clone, Deserialize)] pub struct LegacyPersistedAnnounceEntryV5 { pub destination_hash: Vec, @@ -928,6 +998,8 @@ impl PersistedAnnounceCache { pub const LEGACY_RAW_VERSION: u32 = 5; } +/// Save version-6 announce metadata without raw packet bytes. Entries are +/// copied as supplied, without filtering expiry or validating their hashes. pub fn save_announce_cache<'a, I>(announces: I, path: &Path) -> Result<(), PersistenceError> where I: IntoIterator, @@ -957,6 +1029,9 @@ where atomic_write(path, &persisted) } +/// Decode version-6 announce metadata. Other versions are rejected; this does +/// not fall back to the legacy reader or validate field lengths, signatures, +/// expiry or the referenced packet files. pub fn load_announce_cache(path: &Path) -> Result, PersistenceError> { let data = std::fs::read(path).map_err(PersistenceError::Io)?; let persisted: PersistedAnnounceCache = @@ -972,8 +1047,9 @@ pub fn load_announce_cache(path: &Path) -> Result, P Ok(persisted.entries) } -/// Decode a v5 announce cache (raw bytes inline). Used only as the fallback -/// path when `load_announce_cache` rejects the file. +/// Decode a version-5 announce cache with inline raw bytes. This reader rejects +/// other versions and does not validate the embedded packets. Call +/// [`migrate_legacy_announce_entries`] explicitly to create separate cache files. pub fn load_announce_cache_legacy_v5( path: &Path, ) -> Result, PersistenceError> { @@ -989,10 +1065,15 @@ pub fn load_announce_cache_legacy_v5( Ok(persisted.entries) } -/// One-shot v5 → v6 migration: write each entry's raw announce into the -/// per-packet disk cache, derive `packet_hash`/`is_path_response` from the -/// raw bytes, and return the slim v6 shape. Entries whose raw bytes fail to -/// parse keep `packet_hash = None` (replay treats that as a cache miss). +/// Convert version-5 entries to version-6 metadata and attempt to cache their +/// raw packet bytes. This does not save the returned metadata or remove the +/// legacy file. +/// +/// A parseable packet header supplies the hash inputs and path-response flag; +/// the packet type and announce signature are not validated. Empty or malformed +/// bytes, or a failed cache write, leave `packet_hash = None`. Cache-write +/// errors are not returned, and an existing cache file is not checked. All +/// other stored metadata is retained, with `last_used` unset. pub fn migrate_legacy_announce_entries( legacy: Vec, announce_cache_dir: &Path, @@ -1041,11 +1122,11 @@ pub struct PersistedTunnelEntry { pub interface_id: u64, pub expires: f64, pub paths: Vec, - /// Interface the tunnel was bound to when saved. Tunnels load unbound, - /// so this and `interface_hash` are informational. + /// Interface name recorded at save time. The loader returns this field + /// without binding the tunnel to a current interface. #[serde(default)] pub interface_name: Option, - /// Python-compatible hash of `interface_name`. + /// Full SHA-256 of the saved UTF-8 interface name, when available. #[serde(default)] pub interface_hash: Option>, } @@ -1075,6 +1156,9 @@ impl PersistedTunnelTable { pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2, 3]; } +/// Save all tunnels and their paths as a version-3 Rust snapshot. Expired entries +/// are retained, and at most the last 32 random blobs per path are saved. +/// Interface names and hashes are included only when available. pub fn save_tunnel_table( table: &crate::tunnel::TunnelTable, interface_names: &HashMap, @@ -1128,6 +1212,9 @@ pub fn save_tunnel_table( atomic_write(path, &persisted) } +/// Decode a supported Rust tunnel snapshot (versions 1 through 3). This returns +/// stored fields without checking hash lengths, expiry, announce signatures or +/// interface availability, and does not install or bind any tunnel. pub fn load_tunnel_table(path: &Path) -> Result, PersistenceError> { let data = std::fs::read(path).map_err(PersistenceError::Io)?; let persisted: PersistedTunnelTable = @@ -1155,14 +1242,18 @@ pub enum PersistenceError { VersionMismatch { expected: u32, found: u32 }, } -/// Reference-counted prune of `storage/cache/announces` — Python -/// `Transport.clean_announce_cache` parity (Transport.py: keep only files -/// whose hex name is a packet hash referenced by an active path or tunnel -/// path; non-hex names are removed). Files younger than `grace` are always -/// kept: the keep-set is snapshotted on the actor while announces keep -/// arriving, so a fresh cache file can precede its path-table entry. -/// Returns (removed, total_seen). Missing dir and per-entry IO errors are -/// tolerated — the sweep is idempotent and re-runs on the next pass. +/// Remove old regular files from `storage/cache/announces` unless their hex +/// filename decodes to a hash in `keep`. +/// +/// The caller supplies the complete keep-set; this function does not inspect +/// transport tables. Non-hex names are eligible too. Files younger than +/// `grace`, with unknown modification time, or dated after the sweep starts are kept. +/// +/// Returns `(successfully_removed, maximum_files_seen_in_one_pass)`. Passes +/// repeat until one removes nothing. Directory and per-entry I/O errors are +/// tolerated, so a zero removal count does not establish an empty or fully +/// checked cache. Concurrent writers are not part of a transaction with this +/// sweep; use a dedicated, trusted cache directory. pub fn sweep_announce_cache( storage_dir: &Path, keep: &std::collections::HashSet<[u8; 32]>, diff --git a/crates/rns-transport/src/rate_limit.rs b/crates/rns-transport/src/rate_limit.rs index e6bf924..9087069 100644 --- a/crates/rns-transport/src/rate_limit.rs +++ b/crates/rns-transport/src/rate_limit.rs @@ -6,25 +6,32 @@ use rns_wire::types::DestHash; /// Announces-per-second above which a destination is counted as violating. pub const RATE_VIOLATION_THRESHOLD: f64 = 1.0; -/// Violations tolerated before a penalty kicks in. +/// Violation count at which `RateTable::record` first applies a penalty. pub const RATE_VIOLATIONS_BEFORE_PENALTY: u32 = 3; /// Base penalty in seconds; doubles with each additional violation. pub const RATE_PENALTY_BASE: f64 = 60.0; -/// Penalty cap (1 hour) so a persistent offender never stays blocked forever. +/// Maximum duration of each `RateTable::record` penalty (one hour). Later +/// violations can start another penalty. pub const RATE_PENALTY_MAX: f64 = 3600.0; #[derive(Debug, Clone)] pub struct RateEntry { pub timestamps: Vec, - /// Announces per second across the window. + /// Rate last computed by `record` across its timestamp window. It does + /// not decay with elapsed time; `check_interface_rate` does not update it. pub rate: f64, - /// Most recent announce (Unix seconds). + /// Last accepted accounting timestamp (Unix seconds). Calls rejected + /// during a penalty do not advance it. pub last: f64, pub violations: u32, - /// `0.0` means no active penalty; otherwise the Unix-seconds deadline. + /// Unix-seconds penalty deadline; zero is the initial value. An expired + /// nonzero deadline can remain stored. pub blocked_until: f64, } +/// Destination-keyed announce accounting using wall-clock time. Both rate +/// methods mutate the same entry even when interface-specific settings are +/// supplied. There is no automatic expiry or entry-count cap; use `cull`. pub struct RateTable { entries: HashMap, } @@ -36,9 +43,11 @@ impl RateTable { } } - /// Record an announce and return the current rate. A destination under - /// active penalty gets `f64::MAX` so callers can treat "over the limit" - /// and "blocked" as a single numeric comparison. + /// Record an announce and return the stored rate, computed over at most + /// 16 timestamps when their span is positive. During an active penalty, + /// return `f64::MAX` without updating timestamps. Violations accumulate; + /// this method does not decay their count. Crossing the threshold starts + /// a penalty but still returns the computed rate for that call. pub fn record(&mut self, dest_hash: impl Into) -> f64 { let dest_hash = dest_hash.into(); let now = crate::now_f64(); @@ -119,6 +128,8 @@ impl RateTable { self.entries.is_empty() } + /// Remove entries whose stored `last` is at or before the Unix-seconds + /// cutoff, even if a penalty is still active. pub fn cull(&mut self, cutoff: f64) { self.entries.retain(|_, e| e.last > cutoff); } @@ -127,15 +138,19 @@ impl RateTable { self.entries.iter() } - /// Per-interface announce rate limit. + /// Apply interface-supplied announce interval settings to this destination. /// /// Uses the interface-level triplet `(rate_target, rate_grace, rate_penalty)`: /// any interval shorter than `rate_target` is a violation, violations - /// decay when the interval is long enough, and exceeding the grace count - /// parks the destination for `rate_target + rate_penalty` seconds. + /// decay by one when the interval is long enough, and exceeding the grace + /// count sets a deadline at the previous `last + rate_target + rate_penalty`. + /// Both durations are seconds. This call is suppressed when grace is + /// exceeded, even if that calculated deadline has already passed. /// /// Returns `true` when rebroadcast should be suppressed. Path-table - /// storage is unaffected — only the outbound announce is held back. + /// storage is unaffected by this helper; the actor uses the result to + /// suppress rebroadcast. There is one entry per destination, not per + /// interface, and this method shares state with [`Self::record`]. pub fn check_interface_rate( &mut self, dest_hash: impl Into, diff --git a/crates/rns-transport/src/reverse_table.rs b/crates/rns-transport/src/reverse_table.rs index adc6ecc..c54837b 100644 --- a/crates/rns-transport/src/reverse_table.rs +++ b/crates/rns-transport/src/reverse_table.rs @@ -5,19 +5,22 @@ use crate::messages::InterfaceId; use rns_wire::types::TruncatedHash; /// Record of an in-flight packet so the matching proof can be routed back -/// along the same path. Entries expire after `REVERSE_TIMEOUT` — long enough -/// to tolerate slow links, short enough that stale routes don't accumulate. +/// along the recorded path. Explicit culling removes entries at least +/// `REVERSE_TIMEOUT` seconds old; lookup alone does not enforce that lifetime. #[derive(Debug, Clone)] pub struct ReverseEntry { pub timestamp: f64, pub receiving_interface: InterfaceId, pub remaining_hops: u8, /// Interface we forwarded the packet on, when known. Proofs that come - /// back on a different interface are rejected — the mismatch means - /// either a routing change or a spoof attempt. + /// back on a different interface are not forwarded by the actor. This + /// routing check is separate from cryptographic proof validation. pub outbound_interface: Option, } +/// Packet-hash keyed reverse routes. Insertions replace matching entries; +/// lookup includes expired records until explicit culling. The table itself +/// neither validates proofs nor limits the number of entries. pub struct ReverseTable { entries: HashMap, } @@ -77,7 +80,8 @@ impl ReverseTable { before - self.entries.len() } - /// Batched cull — bounds per-tick work on large tables. + /// Remove at most `limit` expired entries. This bounds removals, not the + /// scan: the whole table may be examined to find them. pub fn cull_expired_batch(&mut self, limit: usize) -> usize { let now = crate::now_f64(); let cutoff = now - REVERSE_TIMEOUT as f64; @@ -96,8 +100,8 @@ impl ReverseTable { count } - /// Drop entries whose receiving or outbound interface has gone away — - /// those proofs could never be routed back regardless. + /// Remove entries whose receiving interface or specified outbound + /// interface is absent from the caller-supplied active set. pub fn cull_dead_interfaces( &mut self, active_interfaces: &std::collections::HashSet, diff --git a/crates/rns-transport/src/traffic.rs b/crates/rns-transport/src/traffic.rs index e6fe7d1..4e8e03a 100644 --- a/crates/rns-transport/src/traffic.rs +++ b/crates/rns-transport/src/traffic.rs @@ -2,6 +2,8 @@ use std::collections::HashMap; use crate::messages::InterfaceId; +/// Accumulated byte counts and the most recently sampled byte deltas for one +/// interface. The speed fields assume a one-second sampling interval. #[derive(Debug, Clone, Default)] pub struct InterfaceTraffic { pub rx_bytes: u64, @@ -10,11 +12,15 @@ pub struct InterfaceTraffic { /// without keeping a ring buffer of samples. pub rx_bytes_prev: u64, pub tx_bytes_prev: u64, - /// Bytes per second, over the last `update_speeds` interval. + /// Received-byte delta from the last `update_speeds` call. This represents + /// bytes per second only when calls are one second apart. pub rx_speed: f64, + /// Transmitted-byte delta, with the same sampling assumption as `rx_speed`. pub tx_speed: f64, } +/// Per-interface counters updated explicitly by the caller. Records remain +/// until this counter is dropped; this type does not measure elapsed time. pub struct TrafficCounter { interfaces: HashMap, } @@ -36,8 +42,10 @@ impl TrafficCounter { entry.tx_bytes += bytes; } - /// Compute per-second speeds from the delta since the last call. Intended - /// to run on a 1 Hz tick so the delta equals bytes-per-second directly. + /// Store the byte-count deltas since the last call and advance the samples. + /// No division by elapsed time is performed. Call once per second if the + /// speed fields are to represent bytes per second; delayed or background + /// ticks represent a longer interval instead. pub fn update_speeds(&mut self) { for entry in self.interfaces.values_mut() { entry.rx_speed = (entry.rx_bytes - entry.rx_bytes_prev) as f64; diff --git a/crates/rns-transport/src/tunnel.rs b/crates/rns-transport/src/tunnel.rs index 3596df1..ab9c543 100644 --- a/crates/rns-transport/src/tunnel.rs +++ b/crates/rns-transport/src/tunnel.rs @@ -2,13 +2,13 @@ use std::collections::HashMap; use crate::messages::InterfaceId; -/// One virtual-overlay tunnel plus the per-destination paths riding it. -/// Tunnels let transports stitch together routes that cross a network -/// boundary the underlying interface cannot reach directly. +/// Retained routes for one transport tunnel. A valid synthesis packet can +/// rebind this path collection to an interface when connectivity returns. +/// Tunnel bookkeeping adds no separate payload encryption. #[derive(Debug, Clone)] pub struct TunnelEntry { pub tunnel_id: [u8; 32], - /// Interface the latest synthesis arrived on; `None` while unbound. + /// Current interface binding; `None` while unbound. pub interface_id: Option, pub tunnel_paths: HashMap<[u8; 16], TunnelPath>, pub expires: f64, @@ -24,6 +24,9 @@ pub struct TunnelPath { pub packet_hash: Option<[u8; 32]>, } +/// Tunnel records and cached interface-to-tunnel associations. Lookup does not +/// check expiry. Removing, expiring or rebinding an entry does not clear old +/// interface associations; `void_interface` explicitly forgets one binding. #[derive(Clone)] pub struct TunnelTable { entries: HashMap<[u8; 32], TunnelEntry>, @@ -40,7 +43,9 @@ impl TunnelTable { } } - /// A bound entry also becomes its interface's tunnel. + /// Insert or replace a record and associate its interface when supplied. + /// Previous interface associations are not removed, and fields are not + /// validated by this method. pub fn insert(&mut self, entry: TunnelEntry) { if let Some(interface_id) = entry.interface_id { self.by_interface.insert(interface_id, entry.tunnel_id); @@ -76,15 +81,16 @@ impl TunnelTable { self.entries.iter_mut() } - /// The tunnel that announces arriving on `interface_id` join - /// (Transport.py:2467-2476). + /// Resolve the cached association for this interface. It can return None + /// for a removed record, or a record now bound to another interface; + /// neither current binding nor expiry is checked here. pub fn get_mut_by_interface(&mut self, interface_id: InterfaceId) -> Option<&mut TunnelEntry> { let tunnel_id = self.by_interface.get(&interface_id)?; self.entries.get_mut(tunnel_id) } /// Forget `interface_id`: it names no tunnel, and the tunnels bound to it - /// become unbound but keep their paths (Transport.py:1031-1033). Returns + /// become unbound but keep their paths. Returns /// how many tunnels were unbound. pub fn void_interface(&mut self, interface_id: InterfaceId) -> usize { self.by_interface.remove(&interface_id); @@ -104,6 +110,9 @@ impl TunnelTable { .flat_map(|entry| entry.tunnel_paths.iter()) } + /// Remove records whose expiry is at/before now or more than twice the + /// eight-hour tunnel timeout ahead. This does not cull individual cached + /// paths or remove interface associations. pub fn cull_expired(&mut self) -> usize { let now = crate::now_f64(); @@ -112,7 +121,9 @@ impl TunnelTable { before - self.entries.len() } - /// Batched cull — bounds per-tick work on large tables. + /// Apply the same expiry test as `cull_expired`, removing at most `limit` + /// records. The limit does not bound scanning time, and interface + /// associations remain unchanged. pub fn cull_expired_batch(&mut self, limit: usize) -> usize { let now = crate::now_f64(); @@ -142,14 +153,15 @@ fn is_stale(entry: &TunnelEntry, now: f64) -> bool { entry.expires <= now || entry.expires > now + 2.0 * crate::constants::TUNNEL_TIMEOUT as f64 } -/// Payload of a tunnel-synthesis announce. Total wire size = 176 bytes. +/// The 176-byte tunnel-synthesis payload, excluding the Reticulum packet header. #[derive(Debug, Clone)] pub struct TunnelSynthesisData { /// Transport identity key: `X25519(32) || Ed25519(32)`. pub public_key: [u8; 64], /// SHA-256 of the interface identifier string. pub interface_hash: [u8; 32], - /// Randomness that makes each announce unique for replay protection. + /// Random bytes included in the signed payload. This type does not track + /// or reject replayed synthesis packets. pub random_hash: [u8; 16], /// Ed25519 signature over `public_key || interface_hash || random_hash`. pub signature: [u8; 64], @@ -166,7 +178,8 @@ impl TunnelSynthesisData { data } - /// Python accepts exactly 176 bytes (Transport.py:2790-2791). + /// Parse exactly 176 bytes without verifying the signature. Call + /// [`Self::is_signed`] before treating the payload as signed. pub fn unpack(data: &[u8]) -> Option { if data.len() != 176 { return None; @@ -197,8 +210,8 @@ impl TunnelSynthesisData { sha256(&tunnel_id_data) } - /// The signature verifies under the Ed25519 half of `public_key` - /// (Transport.py:2799-2805). + /// Verify the signature under the Ed25519 half of the embedded public key. + /// This does not check an external trust policy, replay state or freshness. pub fn is_signed(&self) -> bool { let Ok(signer) = rns_identity::identity::Identity::from_public_key(&self.public_key) else { return false; @@ -211,12 +224,11 @@ impl TunnelSynthesisData { } } -/// Install or refresh a tunnel from a validated tunnel-synthesis announce, -/// making it the receiving interface's tunnel and expiring it -/// `TUNNEL_TIMEOUT` later (Transport.py:2819-2834). -/// A reappearing tunnel keeps its existing path set — only the interface -/// binding and expiry move forward, so in-flight routes aren't lost when the -/// underlying link flaps. +/// Insert or refresh a tunnel's interface binding and eight-hour expiry, +/// retaining an existing path set. The caller must validate the synthesis +/// packet first; this helper accepts IDs without cryptographic checks. It +/// does not restore routes into the path table or remove old interface +/// associations when rebinding. pub fn handle_tunnel( tunnel_table: &mut TunnelTable, tunnel_id: [u8; 32], @@ -240,9 +252,10 @@ pub fn handle_tunnel( } /// Build a tunnel-synthesis packet addressed to the well-known tunnel -/// synthesize PLAIN destination. The returned bytes are ready to send on the -/// interface that should host the tunnel; the receiver validates the -/// signature and installs the tunnel via `handle_tunnel`. +/// synthesize PLAIN destination, with fresh random bytes and a signature. +/// Return `None` if the identity cannot sign. The result is a complete inner +/// Reticulum packet; interface-specific IFAC and framing remain separate. +/// The receiving transport validates the signature before installing the tunnel. pub fn build_tunnel_synthesis_packet( identity: &rns_identity::identity::Identity, interface_hash: [u8; 32], diff --git a/crates/rns-wire/src/constants.rs b/crates/rns-wire/src/constants.rs index 9a1c6da..c0fbc35 100644 --- a/crates/rns-wire/src/constants.rs +++ b/crates/rns-wire/src/constants.rs @@ -1,6 +1,9 @@ //! Shared protocol constants (MTU, hash sizes, header bounds). -/// Maximum Transmission Unit — hard protocol limit. +/// Base packet MTU in bytes, enforced by [`crate::packet::Packet::new`]. +/// +/// Raw parsing does not impose this limit. Link signalling can represent +/// larger offers; acceptance and forwarding limits belong to endpoint policy. pub const MTU: usize = 500; /// Truncated hash length in bits (128 bits = 16 bytes). diff --git a/crates/rns-wire/src/context.rs b/crates/rns-wire/src/context.rs index 3472bf6..d2c43d1 100644 --- a/crates/rns-wire/src/context.rs +++ b/crates/rns-wire/src/context.rs @@ -87,10 +87,11 @@ impl PacketContext { } } - /// Whether packets with this context are transmitted in plaintext. + /// Whether this context bypasses per-packet payload encryption. /// - /// Resource, ResourcePrf, Keepalive, and CacheRequest bypass `Packet.pack()` - /// encryption so they can be relayed by nodes without the link key. + /// This is the context classification used by the packet-encryption layer, + /// not a guarantee that the payload is readable. For example, a Resource + /// can be encrypted as a whole before its parts are put into packets. pub fn is_plaintext_context(self) -> bool { matches!( self, diff --git a/crates/rns-wire/src/flags.rs b/crates/rns-wire/src/flags.rs index 3bb92a3..d066eb3 100644 --- a/crates/rns-wire/src/flags.rs +++ b/crates/rns-wire/src/flags.rs @@ -54,13 +54,15 @@ pub struct PacketFlags { impl PacketFlags { /// Pack flags into a single byte. /// - /// Bit layout (from Python Packet.py:168-174): - /// Bit 7: unused/reserved (always 0) - /// Bit 6: header_type - /// Bit 5: context_flag - /// Bit 4: transport_type - /// Bits 3-2: destination_type - /// Bits 1-0: packet_type + /// Bit 7 is left clear here; the interface IFAC layer owns that bit. + /// + /// ```text + /// Bit 6: header_type + /// Bit 5: context_flag + /// Bit 4: transport_type + /// Bits 3-2: destination_type + /// Bits 1-0: packet_type + /// ``` pub fn pack(&self) -> u8 { let ht = (self.header_type as u8) << 6; let cf = (self.context_flag as u8) << 5; @@ -72,12 +74,16 @@ impl PacketFlags { /// Unpack flags from a single byte. /// - /// Follows Python's unpack masks (Packet.py:246-250): - /// header_type = (flags & 0b01000000) >> 6 - /// context_flag = (flags & 0b00100000) >> 5 - /// transport_type = (flags & 0b00010000) >> 4 - /// destination_type = (flags & 0b00001100) >> 2 - /// packet_type = (flags & 0b00000011) + /// Every byte maps to `Some`; bit 7 is ignored. This does not validate or + /// remove an IFAC tag. Decode IFAC framing before parsing a packet header. + /// + /// ```text + /// header_type = (flags & 0b01000000) >> 6 + /// context_flag = (flags & 0b00100000) >> 5 + /// transport_type = (flags & 0b00010000) >> 4 + /// destination_type = (flags & 0b00001100) >> 2 + /// packet_type = (flags & 0b00000011) + /// ``` pub fn unpack(byte: u8) -> Option { let header_type = match (byte & 0b0100_0000) >> 6 { 0 => HeaderType::Header1, diff --git a/crates/rns-wire/src/hash.rs b/crates/rns-wire/src/hash.rs index 2e8d6be..a926552 100644 --- a/crates/rns-wire/src/hash.rs +++ b/crates/rns-wire/src/hash.rs @@ -1,5 +1,6 @@ -//! Packet hashing — the bytes that contribute to a packet's identity hash -//! (excludes hop counter and routing-only fields so it's stable across hops). +//! Packet hashes exclude the hop counter and routing-only fields, so forwarding +//! does not change them. These helpers do not validate packet shape: pass a +//! parsed, nonempty packet and its matching header type. use alloc::vec::Vec; use rns_crypto::sha::truncated_hash; @@ -9,9 +10,12 @@ use crate::flags::HeaderType; /// Extract the portion of a raw packet that contributes to its hash. /// -/// Per Packet.py:345-361 the hop counter, routing-only flag bits, and -/// (for Header2) the transport id are excluded so a packet's hash is stable -/// across forwarding. +/// The hop counter, routing-only flag bits, and (for Header2) the transport +/// ID are excluded so a packet's hash is stable across forwarding. +/// +/// # Panics +/// +/// Panics if `raw` is empty. Short nonempty inputs are hashed without validation. pub fn get_hashable_part(raw: &[u8], header_type: HeaderType) -> Vec { let mut hashable = Vec::new(); @@ -41,6 +45,10 @@ pub fn get_hashable_part(raw: &[u8], header_type: HeaderType) -> Vec { /// /// Equivalent to `sha256(get_hashable_part(raw, header_type))` but streams /// directly into the hasher to avoid an intermediate allocation. +/// +/// # Panics +/// +/// Panics if `raw` is empty. See the module-level input requirements. pub fn packet_hash(raw: &[u8], header_type: HeaderType) -> [u8; 32] { use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); @@ -56,6 +64,10 @@ pub fn packet_hash(raw: &[u8], header_type: HeaderType) -> [u8; 32] { } /// [`packet_hash`] truncated to the first 16 bytes. +/// +/// # Panics +/// +/// Panics if `raw` is empty. See the module-level input requirements. pub fn truncated_packet_hash(raw: &[u8], header_type: HeaderType) -> [u8; 16] { let full = packet_hash(raw, header_type); let mut out = [0u8; 16]; @@ -64,6 +76,10 @@ pub fn truncated_packet_hash(raw: &[u8], header_type: HeaderType) -> [u8; 16] { } /// Return both full and truncated packet hashes from a single SHA-256 pass. +/// +/// # Panics +/// +/// Panics if `raw` is empty. See the module-level input requirements. pub fn packet_hash_pair(raw: &[u8], header_type: HeaderType) -> ([u8; 32], [u8; 16]) { let full = packet_hash(raw, header_type); let mut trunc = [0u8; 16]; @@ -73,9 +89,17 @@ pub fn packet_hash_pair(raw: &[u8], header_type: HeaderType) -> ([u8; 32], [u8; /// Derive the link id of a link-request packet. /// -/// Mirrors Python `Link.link_id_from_lr_packet`: take the hashable part, -/// clip the payload to the 64-byte ECPUBSIZE (X25519 || Ed25519 public keys) -/// so trailing padding doesn't change the id, then truncate SHA-256 to 16 bytes. +/// Hashes the lower flags nibble, destination hash, context, and the first +/// 64 payload bytes (X25519 || Ed25519 public keys), then truncates SHA-256 to +/// 16 bytes. A trailing signalling field does not change the ID. +/// +/// This helper does not validate request length or cipher policy. Use +/// [`crate::link_signalling::parse_request_signalling`] to check the payload +/// shape and signalling domain before admitting a request. +/// +/// # Panics +/// +/// Panics if `raw` is empty. See the module-level input requirements. pub fn link_id_from_raw(raw: &[u8], header_type: HeaderType) -> [u8; 16] { const ECPUBSIZE: usize = 64; let mut hashable = get_hashable_part(raw, header_type); diff --git a/crates/rns-wire/src/header.rs b/crates/rns-wire/src/header.rs index 452885b..1e1dc73 100644 --- a/crates/rns-wire/src/header.rs +++ b/crates/rns-wire/src/header.rs @@ -15,7 +15,8 @@ pub enum HeaderError { TooShort(usize), } -/// Parsed packet header. `transport_id` is `Some` exactly for Header2 packets. +/// Packet header. Parsing sets `transport_id` to `Some` exactly for Header2. +/// Callers constructing or changing fields must preserve that relationship. #[allow(missing_docs)] #[derive(Debug, Clone, PartialEq, Eq)] pub struct PacketHeader { @@ -28,6 +29,9 @@ pub struct PacketHeader { impl PacketHeader { /// Serialize the header to wire bytes. + /// + /// Writes a transport ID whenever it is `Some`, without checking the + /// header-type flag. The caller must supply consistent fields. pub fn pack(&self) -> Vec { let mut out = Vec::with_capacity(HEADER_MAXSIZE); out.push(self.flags.pack()); @@ -43,7 +47,8 @@ impl PacketHeader { /// Parse a header from the start of `raw`. /// /// Returns `(header, data_offset)` where `data_offset` is the first byte - /// of the payload. + /// of the payload. This checks header length, not MTU, authentication, or + /// payload semantics. The input must already have IFAC framing removed. pub fn unpack(raw: &[u8]) -> Result<(Self, usize), HeaderError> { if raw.len() < HEADER_MINSIZE { return Err(HeaderError::TooShort(raw.len())); diff --git a/crates/rns-wire/src/lib.rs b/crates/rns-wire/src/lib.rs index d99c5a6..2926c10 100644 --- a/crates/rns-wire/src/lib.rs +++ b/crates/rns-wire/src/lib.rs @@ -1,8 +1,10 @@ //! Reticulum wire format: packets, headers, flags, receipts, proofs. //! -//! Source of truth for packet bit-packing — must match the Python reference -//! ([`Packet.py`](https://github.com/markqvist/Reticulum/blob/master/RNS/Packet.py)) -//! exactly. `no_std + alloc` when `std` is off; `receipt` is `std`-only. +//! Defines Reticulum packet encodings and the checked Link signalling parser. +//! These low-level types do not authenticate packets or apply endpoint policy. +//! +//! Disabling `std` makes this crate use `no_std + alloc` and omits `receipt`; +//! it does not disable default features in the dependency graph. #![cfg_attr(not(feature = "std"), no_std)] #![warn(missing_docs)] extern crate alloc; diff --git a/crates/rns-wire/src/packet.rs b/crates/rns-wire/src/packet.rs index dce4785..45a88aa 100644 --- a/crates/rns-wire/src/packet.rs +++ b/crates/rns-wire/src/packet.rs @@ -23,7 +23,12 @@ pub enum PacketError { /// /// `raw` is the on-wire representation; the payload is the trailing slice /// `raw[data_offset..]`, exposed via [`Packet::data`]. `packet_hash` and -/// `truncated_hash` are cached at construction (see [`crate::hash`]). +/// `truncated_hash` are cached at construction (see [`crate::hash`]). The bytes +/// here exclude interface framing such as an IFAC tag. +/// +/// Public fields can be changed without updating the other representations. +/// Reconstruct the packet after changing its header or payload; +/// [`Packet::increment_hops`] is the supported hash-preserving mutation. #[allow(missing_docs)] #[derive(Debug, Clone)] pub struct Packet { @@ -35,13 +40,20 @@ pub struct Packet { } impl Packet { - /// Payload bytes — the slice of `raw` after the packed header. + /// Payload bytes — the slice of `raw` after the original packed header. + /// + /// # Panics + /// + /// Panics if the public `raw` buffer has been shortened below that offset. #[inline] pub fn data(&self) -> &[u8] { &self.raw[self.data_offset..] } /// Build a packet from a header and payload, precomputing its hashes. + /// + /// Rejects packets above [`MTU`]. The header must have consistent fields + /// (see [`PacketHeader::pack`]); payload encryption is the caller's job. pub fn new(header: PacketHeader, data: Vec) -> Result { let mut raw = header.pack(); let data_offset = raw.len(); @@ -65,13 +77,18 @@ impl Packet { /// Parse a packet from borrowed wire bytes. Allocates one `Vec` to /// own the buffer; callers that already own the buffer should use - /// [`Packet::from_raw_owned`] instead. + /// [`Packet::from_raw_owned`] instead. Like that method, this checks the + /// header shape but imposes no MTU or authentication policy. pub fn from_raw(raw: &[u8]) -> Result { Self::from_raw_owned(raw.to_vec()) } /// Parse a packet from owned wire bytes. Saves one allocation versus /// [`Packet::from_raw`] when the caller already owns the buffer. + /// + /// Validates the minimum header length, but does not enforce [`MTU`], + /// authenticate data, or decrypt payloads. The caller must remove IFAC + /// framing and apply the applicable packet-size policy first. pub fn from_raw_owned(raw: Vec) -> Result { if raw.len() < 19 { return Err(PacketError::TooShort); diff --git a/crates/rns-wire/src/proof.rs b/crates/rns-wire/src/proof.rs index 5c6c4cd..5cd7453 100644 --- a/crates/rns-wire/src/proof.rs +++ b/crates/rns-wire/src/proof.rs @@ -3,7 +3,10 @@ use crate::constants::{EXPL_LENGTH, IMPL_LENGTH}; use alloc::vec::Vec; -/// Body of a PROOF packet. +/// Body of a packet-delivery proof. +/// +/// These forms are distinct from a Link handshake proof. Parsing the body +/// does not verify its signature or identify the signer. #[allow(missing_docs)] #[derive(Debug, Clone, PartialEq, Eq)] pub enum ProofData { diff --git a/crates/rns-wire/src/receipt.rs b/crates/rns-wire/src/receipt.rs index b6b145c..c9cf8a0 100644 --- a/crates/rns-wire/src/receipt.rs +++ b/crates/rns-wire/src/receipt.rs @@ -25,17 +25,21 @@ pub enum ReceiptStatus { Receiving = 0x06, } -/// Tracks a sent packet until it is delivered, times out, or is culled. +/// State and callbacks for a sent packet. +/// +/// The owner drives proof validation and timeout checks; this type starts no +/// timer. Direct state-changing methods do not reject repeated or out-of-order +/// transitions. Keep lifecycle and destination-key validation in the owner. #[allow(missing_docs)] pub struct PacketReceipt { pub hash: [u8; 32], pub truncated_hash: [u8; 16], - /// Destination this packet was sent to. Proofs are only accepted from the - /// identity bound to this destination. + /// Destination this packet was sent to. This metadata does not itself + /// authenticate a proof or establish that a stored key belongs to the hash. pub destination_hash: Option<[u8; 16]>, /// Full Reticulum public key (`X25519 || Ed25519`) captured for the - /// destination. Keeping the exact identity used for the send prevents an - /// unrelated signature from concluding the receipt. + /// destination. [`Self::validate_proof_from_destination`] verifies with + /// this key; the owner must first validate its binding to the destination. pub destination_public_key: Option<[u8; 64]>, pub status: ReceiptStatus, pub sent_at: Instant, @@ -44,7 +48,8 @@ pub struct PacketReceipt { pub callbacks: ReceiptCallbacks, } -/// Optional callbacks invoked when a receipt transitions out of `Sent`. +/// Optional callbacks consumed by delivery or failure methods. +/// Culling does not invoke either callback. #[allow(missing_docs)] #[derive(Default)] pub struct ReceiptCallbacks { @@ -52,7 +57,8 @@ pub struct ReceiptCallbacks { pub timeout: Option, } -/// Callback invoked once when a packet receipt reaches a terminal state. +/// Callback consumed at most once per registration. +/// Delivery and timeout callbacks are independent; the owner controls transitions. pub type ReceiptCallback = Box; impl PacketReceipt { @@ -75,6 +81,8 @@ impl PacketReceipt { /// /// The public key may be supplied later when the destination hash is /// already known but its validated announce has not yet been recalled. + /// This records the first hash and the first supplied key for that hash; + /// it does not verify their cryptographic relationship. pub fn set_destination_identity( &mut self, destination_hash: [u8; 16], @@ -115,7 +123,8 @@ impl PacketReceipt { self.concluded_at = Some(Instant::now()); } - /// Measured round-trip time, if this receipt has concluded. + /// Elapsed time from creation to conclusion, for any concluded status. + /// Only a proof-backed delivery makes this a delivery round-trip measure. pub fn get_rtt(&self) -> Option { self.concluded_at.map(|t| t.duration_since(self.sent_at)) } @@ -140,8 +149,11 @@ impl PacketReceipt { /// Validate a PROOF body and mark delivered on match. /// Explicit (96): embedded hash must equal receipt hash. Implicit (64): - /// signature over the receipt hash. `verify` is Ed25519 verify with the - /// expected identity key. + /// signature over the receipt hash. The callback receives + /// `(signature, packet_hash)` in that order; it must perform Ed25519 + /// verification with the expected identity key. This method does + /// not consult the stored destination hash or public key and does not + /// require the current status to be `Sent`. pub fn validate_proof(&mut self, proof: &[u8], verify: F) -> bool where F: FnOnce(&[u8], &[u8]) -> bool, @@ -172,8 +184,9 @@ impl PacketReceipt { } /// Validate a PROOF body against the destination identity captured for - /// this receipt. A receipt without a known identity cannot be concluded by - /// a proof. + /// this receipt. Returns false if no public key is stored or verification + /// fails. It relies on the owner having validated that key's destination + /// binding; it does not rederive or compare the stored destination hash. pub fn validate_proof_from_destination(&mut self, proof: &[u8]) -> bool { let Some(public_key) = self.destination_public_key else { return false; diff --git a/crates/rns-wire/src/types.rs b/crates/rns-wire/src/types.rs index 9f2d318..2302bf6 100644 --- a/crates/rns-wire/src/types.rs +++ b/crates/rns-wire/src/types.rs @@ -1,5 +1,6 @@ //! Semantic newtypes for fixed-length hashes and identifiers — distinct types //! prevent silently mixing values with different meanings at call sites. +//! Construction checks length only, not derivation, authenticity, or existence. use core::fmt; @@ -121,12 +122,15 @@ macro_rules! hash_newtype { } hash_newtype! { - /// Destination hash: `SHA-256(name_hash || identity_hash)[..16]`. + /// Destination hash. Identity-bound destinations use + /// `SHA-256(name_hash || identity_hash)[..16]`; Plain destinations use + /// `SHA-256(name_hash)[..16]`. pub struct DestHash([u8; 16]); } hash_newtype! { - /// Identifier for an active or pending link, derived from the link-request keys. + /// Link identifier derived from the hashable Link request header and keys. + /// See [`crate::hash::link_id_from_raw`]. pub struct LinkId([u8; 16]); } @@ -151,7 +155,9 @@ hash_newtype! { } hash_newtype! { - /// SHA-256 of an LXMF message, used for tracking and receipts. + /// LXMF protocol message ID, used for tracking and receipts. Obtain it + /// from the LXMF message API: its hashable bytes exclude the signature, + /// so hashing the complete wire image does not produce this ID. pub struct MessageHash([u8; 32]); } diff --git a/scripts/ci/check_release_archives.py b/scripts/ci/check_release_archives.py index d646d84..f5fd6b3 100644 --- a/scripts/ci/check_release_archives.py +++ b/scripts/ci/check_release_archives.py @@ -70,9 +70,14 @@ def verify(directory: Path, tag: str) -> None: def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("--tag", required=True) - parser.add_argument("--directory", type=Path, required=True) + parser = argparse.ArgumentParser( + description="Check the three release archives, then write SHA256SUMS." + ) + parser.add_argument("--tag", required=True, help="release version in vX.Y.Z form, as used in archive names") + parser.add_argument( + "--directory", type=Path, required=True, + help="directory containing only the three platform archives; SHA256SUMS is written here after validation", + ) args = parser.parse_args() verify(args.directory, args.tag) diff --git a/scripts/ci/check_source_release_contract.py b/scripts/ci/check_source_release_contract.py index a731835..be73bbb 100644 --- a/scripts/ci/check_source_release_contract.py +++ b/scripts/ci/check_source_release_contract.py @@ -169,10 +169,10 @@ def check_candidate_tag(tag: str, version: str) -> None: def main() -> None: - parser = argparse.ArgumentParser() + parser = argparse.ArgumentParser(description=__doc__) tags = parser.add_mutually_exclusive_group() - tags.add_argument("--release-tag") - tags.add_argument("--candidate-tag") + tags.add_argument("--release-tag", help="also verify the existing annotated vX.Y.Z tag matches the workspace version and HEAD") + tags.add_argument("--candidate-tag", help="also verify vX.Y.Z matches the workspace version and has no local tag yet") args = parser.parse_args() version = check_packages(metadata()) diff --git a/tools/check-api-baseline.py b/tools/check-api-baseline.py index 935a409..c513877 100644 --- a/tools/check-api-baseline.py +++ b/tools/check-api-baseline.py @@ -273,10 +273,15 @@ def render_snapshot( def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("--metadata-only", action="store_true") + parser = argparse.ArgumentParser( + description="Compare current public APIs with the stored snapshots, or refresh them after review." + ) + parser.add_argument( + "--metadata-only", action="store_true", + help="validate metadata, package inventory and stored snapshot hashes without generating API output; incompatible with --update", + ) parser.add_argument("--update", action="store_true", - help="refresh snapshots from the working tree to commit alongside source changes") + help="regenerate snapshots and update their counts/hashes in api/stability.json; review the diff before committing") parser.add_argument("--snapshot-source-commit", help="optional HEAD guard for --update; includes uncommitted source changes") args = parser.parse_args() diff --git a/tools/check-api-manifest.py b/tools/check-api-manifest.py index 481d461..62cbc3c 100644 --- a/tools/check-api-manifest.py +++ b/tools/check-api-manifest.py @@ -122,12 +122,14 @@ def render_contract() -> str: def main() -> None: - parser = argparse.ArgumentParser() + parser = argparse.ArgumentParser( + description="Compare current library Cargo metadata with api/snapshots/manifest-contract.json." + ) parser.add_argument( "--print", action="store_true", dest="print_contract", - help="print the current canonical contract for reviewed application", + help="print current Cargo contract JSON instead of comparing it with the saved snapshot", ) args = parser.parse_args() rendered = render_contract()