docs: refresh guides and reference help

This commit is contained in:
DeFiDude committed 2026-11-02 11:13:50 -07:00
1 parent 5b38cae702
commit dc50ce5390
169 files changed
+4288 -2395

No files matched your search

+5 -2
View File
@@ -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
+57 -38
View File
@@ -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 <file> <destination_hash>
rncp-rs -l [-b SECONDS] [-s DEST_DIR] [-a <allowed_hash>]...
rncp-rs -l -F [-j <jail_dir>] [-a <allowed_hash>|-n]...
rncp-rs -f <destination_hash> <remote_path> [-s DEST_DIR]
rnodeconf-rs [-i] [-N|-T] [-b|-B|-p] [-w MODE] [-D N] [-t N] [-R N] [--freq HZ]
[--bw HZ] [--txp DBM] [--sf SF] [--cr CR] [-x|-X]
[--eeprom-backup|--eeprom-dump] [--trust-key HASH] [--version] [PORT]
rnodeconf-rs [-i] [--config] [--eeprom-backup|--eeprom-dump] [--version] [PORT]
rnodeconf-rs -T --freq HZ --bw HZ --txp DBM --sf SF --cr CR PORT
rnodeconf-rs -N PORT
rnsh-rs -l [-i FILE] [-s NAME] [-b PERIOD] [-a HASH]... [-n] [-A|-C] [-- CMD...]
rnsh-rs [-i FILE] [-s NAME] [-N] [-m] [-w SECONDS] <destination_hash> [-- CMD...]
```
@@ -142,14 +151,21 @@ rnsh-rs [-i FILE] [-s NAME] [-N] [-m] [-w SECONDS] <destination_hash> [-- CM
Add the release `bin/` directory or `target/release` to `PATH` if
you want to call them without a path prefix.
`rncp-rs` follows the established listener authentication model: without `-n`,
incoming senders must match `-a <hash>` or an `allowed_identities` file.
`rncp-rs -F` can serve fetch requests to authenticated clients; use
`-j <jail>` to bound file access unless unrestricted fetch paths are
intentional.
`rncp-rs` has a listener authorization limitation in both the current source
and standalone 1.3.0: `-a <hash>` and `allowed_identities` are checked when a
peer identifies, but identification is not required before receiving a pushed
file. Do not rely on the allowlist to exclude unidentified senders.
`rnodeconf-rs` in the current build only covers safe inspection/device setting paths, EEPROM
dump/backup, and trusted-key storage.
Without `-n`, fetch requests require an identified peer on the allowlist.
`rncp-rs -F` enables fetch service and leaves push reception enabled. Use
`-j <jail>` to constrain fetched paths to a directory under trusted local
control; it is not an operating-system sandbox.
`rnodeconf-rs` in 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 <public_identity_data> -w peer.pub
rnid-rs -M <private_identity_data> -X -w restored_identity
rnid-rs -m "PUBLIC_IDENTITY_DATA" -w peer.pub
rnid-rs -M "PRIVATE_IDENTITY_DATA" -X -w restored_identity
# Sign and validate. New signatures are Reticulum 1.4.2-compatible .rsg envelopes.
rnid-rs -i ~/.rsReticulum/identities/mgmt -s message.txt
rnid-rs -V message.txt.rsg
rnid-rs -i <signer_hash> -N -V message.txt.rsg
rnid-rs -i "SIGNER_IDENTITY_HASH" -N -V message.txt.rsg
# Encrypt to a public identity, decrypt with the matching private identity.
rnid-rs -i mgmt.pub -e message.txt
@@ -199,13 +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.
+5 -1
View File
@@ -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
+8 -4
View File
@@ -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.
+9 -6
View File
@@ -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.
+7 -3
View File
@@ -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<Vec<u8>, 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<Vec<u8>, AesCbcError> {
if iv.len() != AES_BLOCK_SIZE {
return Err(AesCbcError::InvalidIvLength(iv.len()));
+3 -1
View File
@@ -14,7 +14,9 @@ pub enum Ed25519Error {
/// Public key bytes were not a valid Ed25519 point.
#[error("invalid public key bytes")]
InvalidPublicKey,
/// Signature bytes could not be decoded as an Ed25519 signature.
/// Retained signature-decoding error variant. The current `verify` method
/// accepts a fixed 64-byte signature and returns `VerificationFailed` on
/// verification failure.
#[error("invalid signature bytes")]
InvalidSignature,
}
+4 -2
View File
@@ -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<Zeroizing<[u8; 64]>, HkdfError> {
let mut okm = Zeroizing::new([0u8; 64]);
+8 -3
View File
@@ -1,6 +1,11 @@
//! Cryptographic primitives for Reticulum. Constants, derivation inputs, and
//! wire-visible byte layouts match the Python reference (`RNS/Cryptography/`)
//! exactly — downstream interop depends on it. `no_std + alloc` when `std` is off.
//! Cryptographic primitives used by Reticulum identities, Links and Tokens.
//! This crate exposes low-level ciphers, hashes, key derivation and key types;
//! callers supply the protocol-specific salts, authentication and key lifecycle.
//!
//! Disabling this crate's `std` feature selects `no_std + alloc` for its code.
//! Workspace dependencies retain their own default features, and random/key
//! generation still requires an operating-system entropy source. This setting
//! alone does not make the crate a bare-metal cryptographic backend.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
extern crate alloc;
+4 -2
View File
@@ -8,7 +8,8 @@ const BLOCK_SIZE: usize = 16;
/// Errors surfaced by [`unpad`].
#[derive(Debug, Error)]
pub enum Pkcs7Error {
/// Trailing byte is zero or greater than the 16-byte block size.
/// Trailing byte is zero, greater than the 16-byte block size, or greater
/// than the input length.
#[error("invalid padding: padding byte value {0} exceeds block size {BLOCK_SIZE}")]
InvalidPaddingValue(u8),
/// The declared padding length doesn't match the trailing bytes.
@@ -33,7 +34,8 @@ pub fn pad(data: &[u8]) -> Vec<u8> {
/// Strip PKCS7 padding for a 16-byte block size.
///
/// All padding bytes are validated; a mismatch returns an error.
/// All padding bytes are validated; a mismatch returns an error. This helper
/// checks the trailing padding only, not the input's total block alignment.
pub fn unpad(data: &[u8]) -> Result<&[u8], Pkcs7Error> {
if data.is_empty() {
return Err(Pkcs7Error::EmptyInput);
+12 -8
View File
@@ -1,4 +1,5 @@
//! RNS encryption token: AES-256-CBC + HMAC-SHA256 over an IV-prefixed ciphertext.
//! RNS encryption token: AES-CBC + HMAC-SHA256 over an IV-prefixed ciphertext.
//! A 64-byte key selects AES-256; a legacy 32-byte key selects AES-128.
use alloc::vec::Vec;
use thiserror::Error;
@@ -15,9 +16,9 @@ pub const TOKEN_OVERHEAD: usize = 48;
pub const AES128_BLOCKSIZE: usize = 16;
/// AES block size used by current AES-256 tokens.
pub const AES256_BLOCKSIZE: usize = 16;
/// AES-256 token key size: 32-byte signing key + 32-byte encryption key.
/// AES-256 token key size: 32-byte HMAC key + 32-byte encryption key.
pub const KEY_LENGTH: usize = 64;
/// Legacy AES-128 token key size: 16-byte signing key + 16-byte encryption key.
/// Legacy AES-128 token key size: 16-byte HMAC key + 16-byte encryption key.
pub const LEGACY_KEY_LENGTH: usize = 32;
/// Python `Identity.DERIVED_KEY_LENGTH_LEGACY`.
pub const DERIVED_KEY_LENGTH_LEGACY: usize = LEGACY_KEY_LENGTH;
@@ -28,13 +29,15 @@ pub enum TokenError {
/// Key must be 32 or 64 bytes.
#[error("invalid key length: expected 32 or 64, got {0}")]
InvalidKeyLength(usize),
/// Token is shorter than [`TOKEN_OVERHEAD`] so cannot contain IV + HMAC.
/// Retained short-token error variant. The current `decrypt` method maps
/// every token shorter than 64 bytes to `AuthenticationFailed`.
#[error("token too short for decryption")]
TooShort,
/// HMAC tag did not validate.
/// Token length, authentication, block alignment, decryption or padding failed.
#[error("authentication failed")]
AuthenticationFailed,
/// Underlying AES-CBC decrypt returned an error.
/// Retained decryption error variant. The current `decrypt` method maps
/// underlying cipher failures to `AuthenticationFailed`.
#[error("decryption failed")]
DecryptionFailed,
/// Underlying AES-CBC encrypt returned an error.
@@ -80,8 +83,9 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
Ok(token)
}
/// Token decrypt. All failure modes collapse to `AuthenticationFailed`
/// (padding-oracle defence). HMAC comparison is constant-time.
/// Authenticate and decrypt a Token. An invalid key length returns
/// `InvalidKeyLength`; malformed-token, authentication, cipher and padding
/// failures return `AuthenticationFailed`. HMAC comparison is constant-time.
///
/// The plaintext is returned in the buffer it was decrypted into, and a failed
/// decryption wipes that buffer. Callers wrap a secret plaintext in
+7 -4
View File
@@ -4,7 +4,8 @@ use rand_core::OsRng;
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::Zeroize;
/// X25519 private key (32 bytes, clamped scalar).
/// X25519 private key material (32 bytes). Scalar clamping occurs during
/// public-key derivation and Diffie-Hellman, not when these bytes are stored.
///
/// Key material is zeroized on drop.
pub struct X25519PrivateKey {
@@ -38,14 +39,14 @@ impl X25519PrivateKey {
}
}
/// Construct from a 32-byte scalar.
/// Store 32 bytes of private key material without changing their encoding.
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self {
secret: StaticSecret::from(*bytes),
}
}
/// Return the 32-byte scalar.
/// Return the stored 32-byte private key material.
pub fn to_bytes(&self) -> [u8; 32] {
self.secret.to_bytes()
}
@@ -58,13 +59,15 @@ impl X25519PrivateKey {
}
/// Compute the shared secret with `peer` via X25519 Diffie-Hellman.
/// This primitive does not reject an all-zero result; a protocol requiring
/// a contributory-behavior check must validate the returned secret.
pub fn exchange(&self, peer: &X25519PublicKey) -> [u8; 32] {
self.secret.diffie_hellman(&peer.key).to_bytes()
}
}
impl X25519PublicKey {
/// Parse a 32-byte u-coordinate.
/// Store a 32-byte u-coordinate without rejecting low-order public inputs.
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self {
key: PublicKey::from(*bytes),
+13 -7
View File
@@ -35,7 +35,9 @@ pub enum AnnounceError {
InvalidWireTime(u64),
}
/// Parsed announce data.
/// Parsed announce fields; parsing alone does not authenticate them.
/// Call [`Self::validate`] or [`Self::validate_with_known_key`] before learning
/// a destination. Replay, age and ingress policy belong to the caller.
#[derive(Debug, Clone)]
pub struct AnnounceData {
pub public_key: [u8; 64],
@@ -49,8 +51,9 @@ pub struct AnnounceData {
impl AnnounceData {
/// Create and sign an announce for a destination.
///
/// The `random_hash` is `random(5) || timestamp_be(5)` so receivers can
/// detect replays without a shared clock.
/// The `random_hash` is `random(5) || timestamp_be(5)`, using current Unix
/// seconds. This supplies randomness and ordering information; replay
/// rejection requires receiver state and is not performed by this type.
pub fn create(
identity: &Identity,
app_name: &str,
@@ -64,8 +67,9 @@ impl AnnounceData {
Self::create_at(identity, app_name, app_data, ratchet_pub, ts)
}
/// Create and sign an announce with an explicit persisted 40-bit ordering
/// value. Rotation and expiry clocks must be managed separately.
/// Create and sign an announce with an explicit 40-bit ordering value.
/// The caller manages persistence before transmission, and manages rotation
/// and expiry clocks separately. No state is persisted by this method.
pub fn create_at(
identity: &Identity,
app_name: &str,
@@ -149,7 +153,8 @@ impl AnnounceData {
/// Parse an announce from packet payload bytes.
///
/// `has_ratchet` must match the packet header's context flag; the ratchet
/// field is not self-delimiting.
/// field is not self-delimiting. This checks minimum length only; use the
/// validation methods before trusting a parsed announce.
pub fn unpack(data: &[u8], has_ratchet: bool) -> Result<Self, AnnounceError> {
let min_size = if has_ratchet {
MIN_ANNOUNCE_SIZE + RATCHET_SIZE
@@ -261,7 +266,8 @@ impl AnnounceData {
}
/// Validate destination-hash binding and first-seen public-key continuity
/// after [`Self::verify_signature`] has succeeded.
/// after [`Self::verify_signature`] has succeeded. Pass the identity
/// returned by that call; this method does not repeat signature validation.
pub fn validate_destination_binding(
&self,
packet_dest_hash: &[u8; 16],
+6 -3
View File
@@ -64,14 +64,15 @@ impl RatchetControlState {
}
}
/// Rotation is due only when a persisted age exists and the wall clock has
/// Rotation is due only when an age anchor exists and the wall clock has
/// advanced by the full interval. Clock rollback never looks elapsed.
pub fn rotation_due(&self, wall_now: u64, interval_secs: u64) -> bool {
self.last_rotation_wall
.is_some_and(|last| wall_now >= last && wall_now.saturating_sub(last) >= interval_secs)
}
/// Return a cloned candidate recording a successful rotation.
/// Return a cloned candidate recording the supplied rotation time.
/// The caller performs the rotation and persists the candidate.
pub fn with_rotation_at(&self, wall_now: u64) -> Self {
let mut candidate = self.clone();
candidate.last_rotation_wall = Some(wall_now);
@@ -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)
}
+44 -20
View File
@@ -9,7 +9,9 @@ use zeroize::Zeroizing;
use crate::identity::{DecryptionResult, Identity};
use crate::name_hash::name_hash;
/// Callback invoked on incoming data packets: `fn(plaintext, raw_packet)`.
/// Callback invoked on incoming DATA: `fn(plaintext, raw_packet)`.
/// [`Destination::receive`] supplies only the payload as its second argument;
/// use [`Destination::receive_packet`] when the callback needs the full packet.
pub type PacketCallback = Box<dyn Fn(&[u8], &[u8]) + Send + Sync>;
/// Callback invoked when a new link is established: `fn(link_id)`.
pub type LinkEstablishedCallback = Box<dyn Fn([u8; 16]) + Send + Sync>;
@@ -191,12 +193,13 @@ pub struct Destination {
pub hash: [u8; 16],
pub name_hash: [u8; 10],
pub app_name: String,
/// Human-readable full destination name, including the identity hash.
/// Human-readable full destination name, including an identity hash when applicable.
pub name: String,
/// Identity hash bound into this destination address, when applicable.
pub identity_hash: Option<[u8; 16]>,
pub proof_strategy: ProofStrategy,
/// If set, incoming data is signature-checked but not decrypted.
/// Compatibility flag stored by the setter. The current receive methods
/// do not consult it; setting it does not enable signature-only validation.
pub only_validate_signature: bool,
group_key: Option<Zeroizing<Vec<u8>>>,
@@ -218,12 +221,15 @@ pub struct Destination {
default_app_data: Option<DefaultAppData>,
pub ratchets_enabled: bool,
/// When set, non-ratchet ciphertexts are rejected.
/// For SINGLE decryption, reject ciphertext not authenticated by a supplied
/// retained ratchet key. Does not change Plain or GROUP decryption.
pub ratchets_enforced: bool,
/// OUT: remote peer's most recent ratchet public key, used for forward-secret encryption.
/// Remote ratchet public key selected by [`Self::pack_packet`] unless
/// explicitly overridden. The caller validates its announce and expiry.
pub remote_ratchet_pub: Option<[u8; 32]>,
/// IN: our current ratchet public key, advertised in announces.
/// Local ratchet public key returned by [`Self::get_ratchet_for_announce`].
/// Announce builders use their explicit ratchet argument.
pub local_ratchet_pub: Option<[u8; 32]>,
path_responses: HashMap<Vec<u8>, PathResponseCache>,
@@ -285,7 +291,10 @@ impl Destination {
///
/// For SINGLE/GROUP inbound destinations, a new identity is generated
/// automatically when `identity` is `None`; retrieve it via
/// [`Destination::auto_identity`].
/// [`Destination::auto_identity`]. In that case the generated identity hash
/// is also appended to `app_name` before computing the name hash. Supply
/// an identity explicitly when addressing a fixed application/aspect name.
/// This constructor neither registers with a runtime nor creates a GROUP key.
///
/// See [`Destination::compute_hash`] for the hash derivation.
pub fn new(
@@ -437,7 +446,8 @@ impl Destination {
self.proof_strategy = strategy;
}
/// Set the pre-shared key used for GROUP encryption.
/// Store a pre-shared key without checking its length or destination type.
/// Prefer [`Self::load_group_key`] for validated GROUP key installation.
pub fn set_group_key(&mut self, key: Vec<u8>) {
self.group_key = Some(Zeroizing::new(key));
}
@@ -493,7 +503,8 @@ impl Destination {
/// Produce a proof over `packet_hash` for this (SINGLE) destination.
///
/// `implicit_proof = true` emits the 64-byte signature alone; otherwise
/// the output is `packet_hash || signature`.
/// the output is `packet_hash || signature`. Pass a 32-byte packet hash;
/// its length is not checked here.
pub fn prove(
&self,
packet_hash: &[u8],
@@ -524,8 +535,8 @@ impl Destination {
///
/// Announce and LinkRequest packets are plaintext. Resource payload,
/// Resource proof, keepalive, cache-request, and LRPROOF contexts are also
/// already protected or intentionally plaintext and therefore bypass
/// destination encryption. Other SINGLE/GROUP packets are encrypted here.
/// exempt from destination encryption. The caller must provide any
/// protection those payloads require. Other SINGLE/GROUP packets are encrypted here.
///
/// Ordinary Link packets remain owned by `LinkSession`; LRPROOF is the
/// sole Link context accepted by this stateless builder.
@@ -625,7 +636,9 @@ impl Destination {
/// Encrypt data for this destination.
///
/// For SINGLE destinations a `remote_ratchet_pub` replaces the identity's
/// X25519 key in the ECDH exchange, giving forward secrecy.
/// X25519 key in ECDH. See [`Identity::encrypt`] for its key-compromise
/// boundaries. This method uses only the ratchet argument, not the stored
/// `remote_ratchet_pub` field; [`Self::pack_packet`] selects that fallback.
pub fn encrypt(
&self,
plaintext: &[u8],
@@ -659,7 +672,8 @@ impl Destination {
self.decrypt_with_ratchets(ciphertext, identity, None)
}
/// Decrypt data, trying each ratchet private key before the identity key.
/// Decrypt data. For SINGLE, try supplied ratchet keys only when ratchets
/// are enabled, then the identity key unless ratchets are enforced.
pub fn decrypt_with_ratchets(
&self,
ciphertext: &[u8],
@@ -710,12 +724,14 @@ impl Destination {
}
}
/// Record the remote peer's ratchet public key, learnt from an announce.
/// Record the remote peer's ratchet public key after the caller validates
/// its announce. This setter performs no authentication or expiry check.
pub fn set_remote_ratchet(&mut self, pub_key: [u8; 32]) {
self.remote_ratchet_pub = Some(pub_key);
}
/// Set our outbound ratchet public key from the ratchet ring.
/// Set the local public key that peers can use for ratcheted encryption to us.
/// The caller retains the corresponding private key in its ratchet ring.
pub fn set_local_ratchet(&mut self, pub_key: [u8; 32]) {
self.local_ratchet_pub = Some(pub_key);
}
@@ -737,7 +753,8 @@ impl Destination {
self.link_established_callback = Some(callback);
}
/// Callback invoked under `ProveApp` strategy; returning `true` emits a proof.
/// Callback queried by [`Self::should_prove`] under `ProveApp`. Returning
/// true asks the runtime to emit a proof; the callback does not send one.
pub fn set_proof_requested_callback(&mut self, callback: ProofRequestedCallback) {
self.proof_requested_callback = Some(callback);
}
@@ -807,9 +824,9 @@ impl Destination {
/// Decrypt and dispatch an incoming packet.
///
/// LINKREQUEST (`0x02`) bypasses decryption and is handled by
/// [`Destination::incoming_link_request`]; DATA (`0x00`) packets
/// additionally fire the packet callback.
/// LINKREQUEST (`0x02`) is returned unchanged; the caller must handle Link
/// admission separately. DATA (`0x00`) also invokes the packet callback,
/// passing `data` as its raw-packet argument because no full packet was supplied.
pub fn receive(
&self,
packet_type: u8,
@@ -891,7 +908,9 @@ impl Destination {
self.accept_link_requests
}
/// Enable ratchet forward secrecy. If `enforce`, non-ratchet inbound ciphertext is rejected.
/// Enable use of supplied ratchet keys for SINGLE decryption. If `enforce`,
/// reject ciphertext that no supplied ratchet key can authenticate.
/// This only changes flags; the caller generates, persists and advertises keys.
pub fn enable_ratchets(&mut self, enforce: bool) {
self.ratchets_enabled = true;
self.ratchets_enforced = enforce;
@@ -949,6 +968,11 @@ impl Destination {
}
/// Build announce data with independent wire-ordering and cache clocks.
///
/// Requires an inbound SINGLE destination. The caller must supply its matching
/// signing identity; this builder does not check that binding. A cached tag
/// returns its prior body even if the supplied app data or ratchet changed.
/// Use the explicit ratchet argument; stored ratchet fields are not selected here.
pub fn create_announce_at(
&mut self,
identity: &Identity,
+33 -10
View File
@@ -24,7 +24,7 @@ pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
pub const HASH_LENGTH_BITS: usize = 128;
/// Ratchet identifier size, in bytes.
pub const RATCHET_ID_LENGTH: usize = 10;
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
/// HKDF-derived token key length: 32-byte HMAC key || 32-byte AES key.
pub const DERIVED_KEY_LENGTH: usize = 64;
/// Per-message overhead of `Identity::encrypt` before PKCS7 padding:
@@ -57,7 +57,8 @@ pub trait LocalKeyBackend: Send + Sync {
/// X25519 ECDH shared secret with `peer_pub`, or `None` if unavailable.
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]>;
/// Drop any cached authentication so the next operation must re-authenticate
/// (e.g. a hardware token re-locks its PIN). No-op for software backends.
/// (e.g. a hardware token re-locks its PIN). The default is a no-op;
/// backends with cached authentication must implement their own reset.
fn lock(&self) {}
}
@@ -67,6 +68,10 @@ pub trait LocalKeyBackend: Send + Sync {
/// - Private (64 B): `X25519_prv(32) || Ed25519_seed(32)`
/// - Public (64 B): `X25519_pub(32) || Ed25519_pub(32)`
/// - Hash (16 B): `SHA-256(public_64)[:16]`
///
/// Public-only identities can verify and encrypt. Hardware-backed identities
/// delegate private operations without exposing a software private key. Keep
/// the public `hash` unchanged: encryption derivation uses it as the HKDF salt.
pub struct Identity {
prv: Option<X25519PrivateKey>,
sig_prv: Option<Ed25519PrivateKey>,
@@ -120,6 +125,7 @@ impl Identity {
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
pub const HASH_LENGTH_BITS: usize = HASH_LENGTH_BITS;
/// Generate a software identity with fresh X25519 and Ed25519 keys.
pub fn new() -> Self {
let prv = X25519PrivateKey::generate();
let sig_prv = Ed25519PrivateKey::generate();
@@ -137,6 +143,8 @@ impl Identity {
}
}
/// Load exactly 64 bytes: an X25519 private key followed by an Ed25519 seed.
/// The caller remains responsible for protecting and wiping its input.
pub fn from_private_key(key: &[u8]) -> Result<Self, IdentityError> {
if key.len() != 64 {
return Err(IdentityError::InvalidPrivateKeyLength(key.len()));
@@ -163,6 +171,8 @@ impl Identity {
}
/// Construct a verify/encrypt-only identity from its 64-byte public key.
/// Checks the length and Ed25519 key encoding; it does not establish who
/// owns the key or reject low-order X25519 input.
pub fn from_public_key(key: &[u8]) -> Result<Self, IdentityError> {
if key.len() != 64 {
return Err(IdentityError::InvalidPublicKeyLength(key.len()));
@@ -188,7 +198,9 @@ impl Identity {
/// Construct an identity whose private operations are served by `backend`
/// (e.g. a hardware token). Public-key-only in memory; `sign` and `decrypt`
/// delegate to the backend. Wire-identical to a software identity.
/// delegate to the backend for base-key operations. The caller must ensure
/// the backend owns the matching private keys and implements the trait
/// contract; construction does not perform a signing or ECDH challenge.
pub fn from_backend(
public_key: &[u8],
backend: Arc<dyn LocalKeyBackend>,
@@ -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<Zeroizing<[u8; 64]>> {
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<Ed25519PrivateKey> {
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],
+6 -2
View File
@@ -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..])
}
@@ -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,
+4 -2
View File
@@ -206,8 +206,10 @@ impl<'de, const MAX: usize> serde::de::Visitor<'de> for SecretBytesVisitor<MAX>
/// 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()
@@ -139,7 +139,7 @@ fn target_path(path: &Path) -> io::Result<PathBuf> {
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<Option<StorageRisk>> {
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,
+49 -20
View File
@@ -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<LoadedRatchetRing> {
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<Path>, identity: &Identity) -> std::io::Result<Self> {
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<K: Eq + std::hash::Hash>(
}
/// Per-destination cache of remote ratchet public keys, with optional disk backing.
/// Callers validate announces before insertion. Disk writes are best-effort;
/// errors are logged while the in-memory entry is still updated.
pub struct ReceivedRatchetStore {
entries: HashMap<[u8; 16], ReceivedRatchet>,
storage_dir: Option<PathBuf>,
@@ -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())
}
+23 -17
View File
@@ -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<f32>,
/// Long-term airtime cap, percent (0.0..=100.0). `None` = unlimited.
/// Long-term airtime cap, percent (0.0..=100.0). `None` sends no command
/// and leaves the device's corresponding setting unchanged.
pub lt_alock: Option<f32>,
/// Station-ID beacon: seconds between IDs, sent only after data TX.
pub id_interval: Option<u64>,
@@ -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<bool, String> {
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<AtomicBool>
}
}
/// Invalidate the exact active physical generation from Android's USB detach
/// broadcast. Unknown and stale device paths are harmless no-ops.
/// Mark the currently registered connection for `device_name` as detached
/// and wake reconnect loops. Unknown paths are ignored. Selection uses the
/// path alone; callers must supply the current detach notification.
pub fn notify_android_usb_device_detached(device_name: &str) {
if let Some(attached) = android_usb_presence_registry()
.lock()
@@ -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<Vec<u8>>,
frame: Vec<u8>,
+20 -16
View File
@@ -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<Vec<NetworkInterfaceInfo>, String> {
use std::collections::BTreeMap;
+7 -4
View File
@@ -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..])
+16 -10
View File
@@ -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<String>,
/// Reject an IP after more than `fast_flapping_grace` short connections.
/// Reject a tracked IP after more than `fast_flapping_grace` short connections.
/// The process-wide tracking table is bounded; a new IP is not tracked when
/// that table is full.
pub block_fast_flapping: bool,
/// Connections shorter than this duration count as fast flaps.
pub fast_flapping_threshold: Duration,
@@ -104,7 +109,8 @@ pub struct BackboneClientConfig {
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
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<TunnelIdentity>,
}
+13 -13
View File
@@ -1,9 +1,6 @@
//! Apple CBCentralManager scan driver.
//!
//! Exists to pass `CBCentralManagerScanOptionAllowDuplicatesKey = YES` to
//! `scanForPeripheralsWithServices:options:` — btleplug does not expose
//! that key, and without it CoreBluetooth reports each peripheral at most
//! once per scan session.
//! Apple CBCentralManager scan driver. Requests repeated advertisement
//! callbacks with `CBCentralManagerScanOptionAllowDuplicatesKey = YES` and
//! reuses its native manager between scan cycles.
#![cfg(any(target_os = "ios", target_os = "macos"))]
@@ -77,8 +74,10 @@ fn manager_slot() -> &'static Mutex<SendPtr> {
MANAGER_PTR.get_or_init(|| Mutex::new(SendPtr(std::ptr::null_mut())))
}
/// Start a CBCentralManager scan with `AllowDuplicatesKey = YES`. Empty
/// `services` scans for all advertisements.
/// Request a CBCentralManager scan with `AllowDuplicatesKey = YES`. Empty
/// `services` removes the service filter. On first startup, manager creation
/// and the wait for PoweredOn continue on a worker thread after this function
/// returns; `Ok` is not confirmation that scanning has started.
pub async fn start_scan(
services: Vec<Uuid>,
) -> Result<mpsc::UnboundedReceiver<DiscoveryEvent>, String> {
@@ -228,8 +227,9 @@ pub async fn stop_scan() -> Result<(), String> {
Ok(())
}
/// Full teardown — interface shutdown only. Per-cycle stops use
/// [`stop_scan`] to keep the manager alive (macOS alloc-cycle bug).
/// Detach the delegate, release this module's explicit manager retain, and
/// clear its manager slot during interface shutdown. Per-cycle stops use
/// [`stop_scan`] and retain the manager for reuse.
pub async fn teardown_central() -> Result<(), String> {
let _ = stop_scan().await;
@@ -275,9 +275,9 @@ pub fn current_state() -> CentralState {
lifecycle().current()
}
/// Persistent `CBCentralManager` pointer. Apple central peripheral caches
/// are per-manager, not per-process — `ble_central_apple_connect` must
/// drive `connectPeripheral:` against the same manager that scanned.
/// Borrow the current `CBCentralManager` pointer without retaining it.
/// Connection setup uses the manager that performed discovery. Callers must
/// coordinate teardown; this accessor does not extend the pointer's lifetime.
pub fn central_manager_ptr() -> Option<*mut AnyObject> {
let lock = MANAGER_PTR.get()?;
let g = lock.lock().ok()?;
@@ -1,9 +1,7 @@
//! Apple central-role connect lifecycle. Sister to
//! [`ble_central_apple`](crate::ble_central_apple) (which owns scanning).
//!
//! Apple-specific because btleplug's CoreBluetooth backend allocates its
//! own manager, and two managers in the same process don't share peripheral
//! caches on macOS, so `adapter.peripherals()` returns empty every cycle.
//! Apple central-role connection lifecycle, using the manager and discovered
//! peripherals owned by [`ble_central_apple`](crate::ble_central_apple).
//! Scanning and connection setup share that manager rather than creating a
//! separate btleplug adapter.
#![cfg(any(target_os = "ios", target_os = "macos"))]
@@ -23,13 +21,12 @@ use crate::ble_peer::{
RATSPEAK_SERVICE_UUID, RATSPEAK_TX_UUID,
};
/// `connectPeripheral:` does not self-time-out; iOS RPA rotation leaves
/// ghost identifiers in `Connecting` state forever. 5s recycles ghosts
/// before they block the scan-loop pipeline.
/// Deadline for the connect callback. On timeout, partial connection state
/// is cancelled and released.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Generous safety net for service / characteristic / notify discovery
/// (CoreBluetooth normally responds in ~200 ms).
/// Per-step deadline for service discovery, characteristic discovery, and
/// notification subscription callbacks.
pub const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(10);
const DISCOVERED_TTL: Duration = Duration::from_secs(60);
@@ -65,9 +62,8 @@ static LAST_DISCONNECT_REASON: OnceLock<Mutex<HashMap<String, DisconnectReason>>
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DisconnectReason {
/// `CBErrorPeripheralConnectionTimeout` — almost always an iPhone /
/// Pixel RPA rotating out from under our open link. The peer
/// re-advertises within ~1s.
/// Classification used for `CBErrorPeripheralConnectionTimeout`. The label
/// does not establish address rotation as the cause or guarantee rediscovery.
Rotation,
OtherError,
}
@@ -122,9 +118,9 @@ pub fn take_last_disconnect_reason(address: &str) -> Option<DisconnectReason> {
.and_then(|mut g| g.remove(address))
}
/// Drop frees the retained ObjC objects. Disconnect goes via
/// [`disconnect_peer`] (`cancelPeripheralConnection:`); the delegate
/// callback removes the map entry, dropping the last `Arc`.
/// Owns retained Objective-C connection objects until the final `Arc` is
/// dropped. [`disconnect_peer`] removes the registered peer and requests
/// `cancelPeripheralConnection:`; other owners can outlive that request.
pub struct ConnectedPeer {
pub address: String,
pub protocol: PeerProtocol,
@@ -519,15 +515,19 @@ pub fn disconnect_all() {
}
}
/// Adopt a CBPeripheral handed back via `centralManager:willRestoreState:`.
/// Apple guarantees `peripheral.services` is populated and prior TX-char
/// subscriptions are preserved — only the delegate needs rebinding. On
/// success ownership of the +1 retain passes to `ConnectedPeer::drop`; on
/// Err the retain is released.
/// Adopt a restored peripheral using its cached service and characteristic
/// objects. This function rebinds the delegate; it does not rediscover services
/// or resubscribe to notifications.
///
/// For a nonempty address and non-null pointer, the supplied +1 retain is
/// consumed: success transfers it to the connection owner or releases it if
/// already registered, and service/characteristic failures release it. Invalid
/// arguments return early without releasing the pointer.
///
/// # Safety
/// `peripheral` must be a retained, non-null `CBPeripheral *` whose state
/// is `Connected (= 2)`.
/// `peripheral` must be a valid, retained `CBPeripheral *` in Connected state.
/// The caller must ensure its cached services and notification subscriptions
/// are usable; this function does not establish those conditions.
pub unsafe fn adopt_restored_peer(
address: String,
peripheral: *mut AnyObject,
@@ -633,8 +633,8 @@ pub unsafe fn adopt_restored_peer(
Ok(())
}
/// CB keeps connections alive thanks to `bluetooth-central`
/// UIBackgroundMode + restore-identifier; this just logs inventory.
/// Log connected-peer and pending-write counts when the app resigns active.
/// This hook does not change connection state or guarantee background delivery.
pub fn on_app_will_resign_active() {
let connected = connected_peers().lock().map(|g| g.len()).unwrap_or(0);
let pending = connected_peers()
@@ -654,8 +654,8 @@ pub fn on_app_will_resign_active() {
);
}
/// Prune discovered pointers older than the discovery TTL — after a long
/// background those are RPA-rotated ghosts.
/// Prune discovered pointers older than the discovery TTL and log the
/// remaining discovery and connection counts.
pub fn on_app_did_become_active() {
prune_discovered();
let discovered_remaining = match discovered().lock() {
@@ -1,5 +1,6 @@
//! BLE central (scan) lifecycle. `PlatformUnavailable` rewinds active states
//! to `StartingWaitingPlatform` so scanning resumes after a Bluetooth toggle.
//! BLE central scan lifecycle. `PlatformUnavailable` rewinds starting or
//! scanning states to `StartingWaitingPlatform`. A later `PlatformReady` can
//! resume scanning; stopping states are not rewound.
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Instant;
@@ -12,7 +13,8 @@ pub enum AdvertisedProtocol {
Columba,
}
/// `identifier` is platform-stable (Apple UUIDString, bluer D-Bus path, Android MAC).
/// `identifier` is a platform-provided scan identifier, such as an Apple UUID
/// or Bluetooth address. It is not a persistent authenticated peer identity.
#[derive(Debug, Clone)]
pub struct DiscoveryEvent {
pub identifier: String,
@@ -48,7 +50,7 @@ pub enum CentralState {
StoppingScan,
/// Cleanly torn down. Distinct from `Idle` for telemetry.
Stopped,
/// Bluetooth unsupported / permission denied; requires explicit `Reset`.
/// A fatal platform error was reported; requires explicit `Reset`.
Failed,
}
@@ -75,8 +77,8 @@ pub enum CentralEvent {
StartRequested,
/// Platform ready: adapter calls `scanForPeripheralsWithServices` here.
PlatformReady,
/// Active states rewind to `StartingWaitingPlatform` so recovery
/// resumes scanning.
/// Starting and scanning states rewind to `StartingWaitingPlatform`.
/// Stopping states reject this event.
PlatformUnavailable {
reason: String,
},
+40 -45
View File
@@ -1,18 +1,18 @@
//! BLE Peer-to-Peer mesh interface. Each device acts as both Central
//! (scanner/GATT client) and Peripheral (advertiser/GATT server)
//! simultaneously.
//! BLE peer interface with a central (scanner/GATT client) role and an
//! optional peripheral (advertiser/GATT server) role. Peripheral startup
//! failure leaves the central role running.
//!
//! ## Dual-service GATT
//!
//! ### Ratspeak (primary)
//! - Service: `a1b2c3d4-e5f6-4a5b-8c9d-0e1f2a3b4c5d`
//! - RX: `…4c5e` (WRITE, WRITE_NO_RESPONSE)
//! - TX: `…4c5f` (READ, NOTIFY)
//! - RX: `…4c5e` (peer writes here)
//! - TX: `…4c5f` (peer subscribes to notifications)
//!
//! ### Columba (cross-app compat)
//! - Service: `37145b00-442d-4a94-917f-8f42c5da28e3`
//! - RX: `…28e5` (WRITE, WRITE_NO_RESPONSE)
//! - TX: `…28e4` (READ, NOTIFY, INDICATE)
//! - RX: `…28e5` (peer writes here)
//! - TX: `…28e4` (peer subscribes to notifications)
//!
//! Peer identity binds only from directly-originated, signature-verified LXMF
//! delivery announces. There is no ID characteristic: a statically readable
@@ -26,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<Str
}
}
/// All-zero is the sentinel ("no identity yet") and must never reach
/// advertising.
/// Return whether the input contains exactly 16 bytes and is not all zero.
pub fn is_valid_identity_hash(bytes: &[u8]) -> bool {
bytes.len() == 16 && bytes.iter().any(|b| *b != 0)
}
@@ -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<std::sync::Mutex<HashMap<u64, (std::collections::HashSet<String>, 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<Vec<BlePeer>, 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,
+13 -27
View File
@@ -1,23 +1,11 @@
//! BLE peripheral lifecycle state machine. Platform adapters (Apple
//! `CBPeripheralManager`, Linux `bluer`, Android `BluetoothGattServer`,
//! Windows `GattServiceProvider`) drive it via [`PeripheralLifecycle::apply`].
//! BLE peripheral lifecycle state machine. Adapters report platform events
//! through [`PeripheralLifecycle::apply`] and perform side effects after the
//! transition returns.
//!
//! Two invariants this encodes that are easy to violate by hand:
//!
//! 1. **Teardown waits for platform confirmation.** iOS has no
//! `peripheralManagerDidStopAdvertising:` callback; the only reliable
//! "stopped" signal is polling `CBPeripheralManager.isAdvertising` until
//! `NO`. Calling `removeAllServices` while still advertising leaves
//! CoreBluetooth in a dirty state that breaks subsequent enables.
//!
//! 2. **Mid-session platform transitions rewind.** A `Resetting` →
//! `PoweredOff` → `PoweredOn` cycle (user toggling Bluetooth, OS stack
//! crash recovery) must drop back to `StartingWaitingPlatform` so the
//! next `PlatformReady` re-registers.
//!
//! Invalid transitions return an error; adapters log and continue rather
//! than panic — BLE backends occasionally deliver out-of-order or redundant
//! callbacks.
//! Teardown waits for advertising to stop before service removal. Starting
//! and advertising states rewind to `StartingWaitingPlatform` after
//! `PlatformUnavailable`; stopping states are not rewound. Invalid transitions
//! return an error rather than changing state.
use std::sync::{Mutex, MutexGuard, PoisonError};
@@ -45,7 +33,8 @@ pub enum PeripheralState {
}
impl PeripheralState {
/// True when the peripheral holds platform resources needing release on teardown.
/// True in starting, advertising, or stopping states. This classifies
/// lifecycle state; it does not inspect platform resource ownership.
pub fn is_active(self) -> bool {
!matches!(self, Self::Idle | Self::Stopped | Self::Failed)
}
@@ -72,19 +61,16 @@ pub enum LifecycleEvent {
StartRequested,
/// Platform ready for service registration + advertising.
PlatformReady,
/// Platform blocked (BT off, permission denied, adapter resetting).
/// Rewinds active states to `StartingWaitingPlatform` to preserve user
/// intent across recovery.
/// The platform became unavailable. Starting and advertising states rewind
/// to `StartingWaitingPlatform`; stopping states reject this event.
PlatformUnavailable {
reason: String,
},
ServicesAdded,
AdvertiseStarted,
StopRequested,
/// `stopAdvertising` completed. On iOS this comes from polling
/// `isAdvertising` since no delegate callback exists. Skipping this and
/// going straight to `removeAllServices` was the root cause of the
/// "disable doesn't fully tear down" bug.
/// `stopAdvertising` completed. The Apple adapter reports this after
/// checking `isAdvertising`; service removal follows this transition.
AdvertiseStopped,
ServicesRemoved,
FatalError {
+41 -60
View File
@@ -39,8 +39,9 @@ type BleCentralEventStream = std::pin::Pin<Box<dyn futures::Stream<Item = Centra
#[cfg(target_os = "android")]
static BTLEPLUG_INITIALIZED: AtomicBool = AtomicBool::new(false);
/// Set from `JNI_OnLoad` after `btleplug::platform::init()` succeeds.
/// Without it, btleplug has no JVM reference and every call panics.
/// Record successful `btleplug::platform::init()` during Android JNI setup.
/// This flag does not initialise btleplug itself; callers must complete that
/// initialisation before setting it.
#[cfg(target_os = "android")]
pub fn mark_btleplug_initialized() {
BTLEPLUG_INITIALIZED.store(true, Ordering::SeqCst);
@@ -1126,7 +1127,8 @@ pub struct LinuxPairingPrompt {
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct LinuxPairingFinished {
pub attempt_id: u64,
/// "ok", "cancelled", "timed_out", or a short BlueZ error string.
/// `"ok"` on success; otherwise the formatted interface error. Error strings
/// are descriptive text, not stable status codes.
pub status: String,
}
@@ -1202,16 +1204,10 @@ pub fn linux_submit_passkey(passkey: u32) -> 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<i16>,
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<bool, String> {
}
}
/// 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<Vec<BleDevice>, 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,
+5 -3
View File
@@ -1,5 +1,6 @@
//! HDLC-like framing shared by TCP, Serial, I2P, Local, Pipe, Backbone.
//! Wire: `[FLAG][escaped_payload][FLAG]`. Encode ESC before FLAG; decode FLAG before ESC.
//! HDLC-like framing shared by TCP, Serial, I2P, Local, Pipe, and Backbone.
//! Wire: `[FLAG][escaped_payload][FLAG]`. Payload FLAG and ESC bytes are
//! prefixed with ESC and XORed with [`ESC_MASK`].
/// HDLC frame delimiter.
pub const FLAG: u8 = 0x7E;
@@ -17,7 +18,8 @@ const MAX_FRAME_SIZE: usize = 524288;
/// with headroom; larger frames grow the Vec normally.
const DEFRAME_BUF_CAPACITY: usize = 2048;
/// Append the escape-encoded form of `data` to `out`. No allocation if `out` has capacity.
/// Append the escape-encoded form of `data` to `out`. No allocation is needed
/// when `out` has enough spare capacity for the escaped output.
pub fn escape_into(data: &[u8], out: &mut Vec<u8>) {
let mut i = 0;
while i < data.len() {
+13 -8
View File
@@ -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<String>,
/// 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<std::path::PathBuf>,
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<usize>,
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<TunnelIdentity>,
}
@@ -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,
+1 -1
View File
@@ -1,4 +1,4 @@
//! KISS TNC framing — used by KISS, AX.25-KISS, RNode, RNodeMulti, TCP/I2P.
//! KISS TNC framing for KISS, AX.25-KISS, RNode, RNodeMulti, and optionally TCP.
//! Wire: `[FEND][CMD][escaped_payload][FEND]`.
pub const FEND: u8 = 0xC0;
+9 -3
View File
@@ -29,8 +29,14 @@ pub struct KissInterfaceConfig {
pub txtail: Option<u8>,
/// Honour CMD_READY from TNC.
pub flow_control: bool,
/// Station-ID beacon: seconds between IDs, counted from the first data
/// TX after the previous beacon (Python `id_interval`/`id_callsign`).
/// Station-ID delay in seconds, armed by data transmission. Both this field
/// and `id_callsign` must be set to enable automatic beacons.
///
/// In this implementation, callsigns shorter than 15 bytes are padded for
/// transmission but compared with the unpadded value when resetting the timer.
/// After becoming due, such a beacon can repeat on each one-second idle poll,
/// subject to flow control and successful writes. Set either option to `None`
/// to disable automatic beaconing.
pub id_interval: Option<u64>,
pub id_callsign: Option<Vec<u8>>,
}
@@ -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<u8> {
let mut frame = id_callsign.to_vec();
while frame.len() < 15 {
+4 -4
View File
@@ -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;
+9 -5
View File
@@ -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,
}
+6 -2
View File
@@ -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,
}
+34 -27
View File
@@ -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<Self> {
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<f32>,
/// Long-term airtime cap, percent (0.0..100.0). `None` = unlimited.
/// Long-term airtime cap, percent (0.0..=100.0). `None` sends no command
/// and leaves the device's corresponding setting unchanged.
pub lt_alock: Option<f32>,
/// Station-ID beacon: seconds between IDs, 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<u8> {
let settings = RNodeRadioSettings::from(config);
let airtime = build_airtime_sequence(config);
+3 -1
View File
@@ -1,4 +1,6 @@
//! Extended-KISS admin codec shared by RNode runtime and `rnodeconf`.
//! Extended-KISS administrative frame codecs and command builders used by
//! `rnodeconf`. These helpers construct or decode bytes; they perform no
//! transport I/O or device authorization.
use std::net::Ipv4Addr;
+18 -20
View File
@@ -1,10 +1,11 @@
//! Privacy-bounded, read-only RNode capability parsing.
//! Read-only RNode capability parsing without retaining device identity bytes.
//!
//! RNode EEPROM identity information contains serial, manufacturing, checksum,
//! signature, and other device-specific bytes. This module validates the
//! immutable identity prefix in place, then returns only copyable product/model
//! codes and reviewed radio limits. It never retains the source image or
//! exposes identity, signature, configuration, or raw EEPROM fields.
//! This module checks the EEPROM information lock and MD5 identity-prefix
//! checksum, then returns product/model codes and limits from a static code
//! table. It ignores device signatures: checksum validation is not device
//! authentication. The value retains no source image, identity, signature,
//! configuration, or raw EEPROM fields. Code-table limits are not a hardware
//! measurement or permission to transmit.
use md5::{Digest, Md5};
@@ -203,10 +204,10 @@ pub enum RNodeRadioAdmissionError {
/// Bounded classification of a full-length RNode EEPROM image.
///
/// `Provisioned` carries validated capabilities from a locked, checksummed
/// identity. `Unprovisioned` means the info lock at `0x9b` is absent: the
/// device carries no attested identity, so product, model, and checksum bytes
/// are deliberately never read.
/// `Provisioned` carries capabilities from a locked, checksummed identity
/// prefix. `Unprovisioned` means the info lock at `0x9b` is absent, so product,
/// model, and checksum bytes are not consulted. Neither state authenticates a
/// device signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RNodeEepromImage {
@@ -216,13 +217,11 @@ pub enum RNodeEepromImage {
/// Classify an EEPROM image, admitting unprovisioned devices as a typed state.
///
/// The image must still span the identity-information lock at `0x9b`. An
/// unlocked image classifies as [`RNodeEepromImage::Unprovisioned`] without
/// consulting the checksum or identity bytes — an unattested model byte must
/// never impose or relax model-specific limits. A locked image validates the
/// MD5 checksum over the exact stored bytes `0x00..0x0b` (model aliases are
/// deliberately not normalised first); bytes after the identity prefix,
/// including the signature region, are ignored.
/// The image must span the information lock at `0x9b`. An unlocked image is
/// [`RNodeEepromImage::Unprovisioned`] without reading product, model, or
/// checksum bytes. A locked image must match the MD5 checksum over stored
/// bytes `0x00..0x0b`; model aliases are not normalised first. Signature bytes
/// are ignored, so this check does not authenticate the device.
pub fn classify_rnode_eeprom_image(
eeprom: &[u8],
) -> Result<RNodeEepromImage, RNodeCapabilityParseError> {
@@ -324,9 +323,8 @@ pub fn admit_rnode_radio_settings(
/// Admit radio settings for a device that presented no locked EEPROM identity.
///
/// Only generic RNode validation applies: with no attested model there are no
/// model-specific limits to consult, matching the treatment of unknown and
/// quarantined model codes.
/// Only generic RNode validation applies. No model-specific profile is
/// inferred, as with unknown and quarantined model codes.
pub fn admit_unprovisioned_rnode_radio_settings(
settings: RNodeRadioSettings,
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
+3 -3
View File
@@ -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<u8> {
let mut out = Vec::with_capacity(80);
+18 -18
View File
@@ -1,16 +1,14 @@
//! Deterministic state reduction for the generic, single-radio RNode protocol.
//!
//! This module deliberately does not drive an interface. It gives serial, TCP,
//! USB, and BLE implementations one strict grammar and one order-independent
//! readiness decision to adopt in a later integration step. Callers pass
//! already-deframed extended-KISS command payloads to
//! [`RNodeProtocolState::apply_frame`].
//! Serial, TCP, USB, and BLE drivers pass already-deframed extended-KISS
//! payloads to [`RNodeProtocolState::apply_frame`]. The reducer performs no
//! I/O. Readiness uses the latest accepted evidence in a stable blocker order;
//! effective-setting mode also requires a transmit-power echo after radio-on.
//!
//! The reducer is intentionally limited to generic single-radio readiness and
//! flow-control evidence. It must not be used for `RNodeMultiInterface`: multi
//! virtual-port command bytes overlap generic commands (notably `0x90`). It
//! also does not retain opaque errors, EEPROM contents, hashes, Wi-Fi
//! credentials, signatures, or other administration data.
//! This grammar is not suitable for `RNodeMultiInterface`: its virtual-port
//! command bytes overlap generic commands, notably `0x90`. The reducer retains
//! no opaque errors, EEPROM contents, hashes, Wi-Fi credentials, signatures,
//! or other administration data.
use crate::rnode;
@@ -41,7 +39,8 @@ impl RNodeFirmwareVersion {
}
}
/// Radio settings whose exact echoes establish that configuration completed.
/// Radio settings used to check configuration echoes. Frequency allows
/// [`FREQUENCY_TOLERANCE_HZ`]; the other settings require exact matches.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RNodeProtocolTarget {
pub frequency: u32,
@@ -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 {
+2 -2
View File
@@ -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;
+12 -8
View File
@@ -1,9 +1,10 @@
//! Shared TCP socket tuning for [`crate::tcp`], [`crate::backbone`],
//! [`crate::i2p`], and [`crate::rnode`] (TCP transport).
//! `set_keepalive`: portable SO_KEEPALIVE. `set_keepalive_tuned`: adds Linux
//! TCP_KEEPIDLE/INTVL/CNT + TCP_USER_TIMEOUT. All helpers are generic over
//! the raw-fd/raw-socket borrow, so they accept tokio and std streams alike.
//! `iface_addr_for`: kernel iface name → IpAddr for Backbone `device =` key.
//!
//! The helpers accept Tokio and standard-library streams through their raw
//! socket handles. Keepalive settings are applied where the platform supports
//! them; TCP_USER_TIMEOUT is set on Linux, Android, and Fuchsia. Tuning is
//! best effort. Interface-address helpers resolve local device names.
use std::net::IpAddr;
use std::time::Duration;
@@ -53,7 +54,8 @@ pub fn set_keepalive<S: RawStream>(stream: &S) -> std::io::Result<()> {
with_socket2(stream, |sock| sock.set_keepalive(true))
}
/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort.
/// Request keepalive idle time, interval, and retry count where supported,
/// plus TCP_USER_TIMEOUT on Linux, Android, and Fuchsia. Best effort.
pub fn set_keepalive_tuned<S: RawStream>(
stream: &S,
idle: Duration,
@@ -66,7 +68,8 @@ pub fn set_keepalive_tuned<S: RawStream>(
});
}
/// Raise TCP send/recv buffers; best-effort.
/// Request TCP send and receive buffer sizes. The kernel may adjust them;
/// errors are ignored.
pub fn set_socket_buffers<S: RawStream>(stream: &S, size: usize) {
with_socket2(stream, |sock| {
let _ = sock.set_recv_buffer_size(size);
@@ -124,8 +127,9 @@ pub fn iface_broadcast_for(name: &str) -> Option<std::net::Ipv4Addr> {
})
}
/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back
/// to wildcard bind.
/// Resolve an interface name to `IpAddr`, preferring the requested address
/// family and falling back to the other family. Returns `None` if enumeration
/// fails or no address matches; the caller decides whether to fall back.
pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option<IpAddr> {
let ifaces = match if_addrs::get_if_addrs() {
Ok(v) => v,
+4 -3
View File
@@ -66,10 +66,11 @@ pub struct TcpClientConfig {
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
/// Override HW MTU for link MTU discovery (Python `fixed_mtu`, >= 500).
/// Override the MTU used for link MTU discovery. Accepted values are
/// 500 through 262,144 bytes, inclusive.
pub fixed_mtu: Option<u32>,
/// 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<TunnelIdentity>,
}
+7 -8
View File
@@ -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<AtomicBool>,
pub rxb: Option<Arc<AtomicU64>>,
pub txb: Option<Arc<AtomicU64>>,
/// Optional live aggregate inspection source carried into the transport
/// actor. This field intentionally makes pre-freeze struct literals update
/// explicitly so new interface drivers choose whether they expose stats.
/// Optional live aggregate inspection source carried into the transport actor.
pub inspection: Option<rns_transport::messages::InterfaceInspectionSource>,
pub tx: mpsc::Sender<Bytes>,
pub read_task: tokio::task::JoinHandle<()>,
@@ -58,8 +56,8 @@ pub(crate) async fn handoff_accepted_interface(
pub struct TunnelIdentity(pub Arc<rns_identity::identity::Identity>);
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<Bytes> {
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<u32> {
if bitrate >= 1_000_000_000 {
Some(524_288)
+5 -4
View File
@@ -1,12 +1,13 @@
//! Weave switching fabric — protocol primitives only.
//! Weave switching-fabric codecs and constants.
//!
//! Wire format (WDCL inside HDLC):
//! ```text
//! [HDLC_FLAG] [escaped WDCL] [HDLC_FLAG]
//! WDCL = [ADDR u32][TYPE u8][PAYLOAD…] ADDR 0xFFFFFFFF = broadcast
//! WDCL = [ADDR:4 bytes][TYPE:1 byte][PAYLOAD...]
//! ADDR 0xFFFFFFFF = broadcast
//! ```
//! Discovery: Ed25519 challenge-response over WDCL_T_DISCOVER / WDCL_T_CONNECT.
//! Runtime spawn (serial I/O, peer mgmt) not yet wired up.
//! This module provides frame and log codecs plus configuration types. It
//! has no serial runtime, discovery handshake, or signature-verification path.
use crate::traits::InterfaceMode;
+12 -12
View File
@@ -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)
}
+7 -5
View File
@@ -42,7 +42,7 @@ pub const TRAFFIC_TIMEOUT_FLOOR_MS: u64 = 5;
pub const MODE_AES128_CBC: u8 = 0x00;
/// Default: AES-256-CBC.
pub const MODE_AES256_CBC: u8 = 0x01;
/// Reserved for future AES-256-GCM support.
/// Reserved AES-256-GCM identifier; not accepted by current Link endpoints.
pub const MODE_AES256_GCM: u8 = 0x02;
pub const MODE_OTP_RESERVED: u8 = 0x03;
pub const MODE_PQ_RESERVED_1: u8 = 0x04;
@@ -50,7 +50,8 @@ pub const MODE_PQ_RESERVED_2: u8 = 0x05;
pub const MODE_PQ_RESERVED_3: u8 = 0x06;
pub const MODE_PQ_RESERVED_4: u8 = 0x07;
/// Encryption modes accepted by this implementation; others are advertised-but-refused.
/// Encryption modes accepted by [`crate::link::Link`] endpoints. Other mode
/// identifiers are representable on the wire but rejected by those endpoints.
pub const ENABLED_MODES: &[u8] = &[MODE_AES256_CBC];
pub const DEFAULT_MODE: u8 = MODE_AES256_CBC;
@@ -67,13 +68,14 @@ pub const ACCEPT_ALL: u8 = 0x02;
/// Low 21 bits of the 24-bit MTU signalling value carry the MTU.
pub const MTU_BYTEMASK: u32 = 0x001F_FFFF;
/// Bits 21-23 of the MTU signalling value carry the encryption mode.
/// Mask for mode bits 5–7 of the first signalling byte. In the full 24-bit
/// big-endian signalling value, those are bits 21–23 (mask `0xE00000`).
pub const MODE_BYTEMASK: u32 = 0x00E0;
/// Derived key length for AES-256-CBC: 32 bytes cipher key || 32 bytes HMAC key.
/// Derived key length for AES-256-CBC: 32-byte HMAC key || 32-byte cipher key.
pub const AES256_DERIVED_KEY_LENGTH: usize = 64;
/// Derived key length for AES-128-CBC: 16 bytes cipher key || 16 bytes HMAC key.
/// Derived key length for AES-128-CBC: 16-byte HMAC key || 16-byte cipher key.
pub const AES128_DERIVED_KEY_LENGTH: usize = 32;
/// Seconds of slack granted to a response beyond its nominal transfer time.
+3 -2
View File
@@ -18,8 +18,9 @@ pub fn link_encrypt(keys: &LinkKeys, plaintext: &[u8]) -> Result<Vec<u8>, LinkCr
/// Decrypt a ciphertext frame with the link's session keys.
///
/// Errors are deliberately opaque — padding and HMAC failures are indistinguishable
/// to callers so timing side channels cannot leak which check failed.
/// All token errors map to `DecryptionFailed`, so the error value does not
/// distinguish padding, HMAC, or key-length failure. This error mapping alone
/// is not a guarantee of identical execution time for every invalid input.
pub fn link_decrypt(keys: &LinkKeys, ciphertext: &[u8]) -> Result<Vec<u8>, LinkCryptoError> {
let mut combined_key = Zeroizing::new(Vec::with_capacity(
keys.signing_key.len() + keys.encryption_key.len(),
+28 -7
View File
@@ -49,7 +49,8 @@ impl EphemeralKeys {
/// Link request payload (Message 1: initiator -> destination).
///
/// Wire format: `X25519_pub(32) || Ed25519_pub(32) || signalling(3)` — 67 bytes.
/// Modern wire format: `X25519_pub(32) || Ed25519_pub(32) || signalling(3)`
/// (67 bytes). Parsing also accepts the 64-byte legacy form without signalling.
#[derive(Debug, Clone)]
pub struct LinkRequestData {
pub peer_x25519_pub: [u8; 32],
@@ -69,8 +70,9 @@ impl LinkRequestData {
/// Parse a link request payload.
///
/// Python accepts exactly the legacy 64-byte key payload or the modern
/// 67-byte key payload with signalling. Other lengths are dropped.
/// Accepts exactly the legacy 64-byte key payload or modern 67-byte
/// payload, and validates the signalled MTU domain. It does not authenticate
/// the keys or enforce the endpoint's enabled cipher modes.
pub fn unpack(data: &[u8]) -> Result<Self, HandshakeError> {
if data.len() < ECPUBSIZE {
return Err(HandshakeError::TooShort);
@@ -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<Self, HandshakeError> {
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],
+5 -2
View File
@@ -4,7 +4,9 @@ use crate::constants::*;
/// Keepalive timing state for a single link.
///
/// Only the initiator side schedules keepalives; the responder simply echoes them.
/// Only the initiator schedules requests. The responder can suppress a reply
/// when it has sent other traffic within the keepalive interval. The owner
/// records activity and sends any required frames.
#[derive(Debug, Clone)]
pub struct KeepaliveState {
pub keepalive_interval: Duration,
@@ -46,7 +48,8 @@ impl KeepaliveState {
/// Rescale the keepalive interval after a new RTT measurement.
///
/// Interval scales linearly with RTT up to `KEEPALIVE_MAX_RTT`, then saturates.
/// Interval scales linearly with RTT, clamped to `KEEPALIVE_MIN` through
/// `KEEPALIVE_MAX`; it reaches the upper limit at `KEEPALIVE_MAX_RTT`.
/// Jitter is re-rolled so the ±10% spread is relative to the new interval.
pub fn update_from_rtt(&mut self, rtt: Duration) {
let rtt_secs = rtt.as_secs_f64();
+7 -2
View File
@@ -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<u8>,
/// AES encryption key.
pub encryption_key: Vec<u8>,
@@ -20,6 +21,10 @@ impl LinkKeys {
/// Runs `HKDF-SHA256(ECDH(my_prv, peer_pub), salt = link_id)` and splits the
/// output into `signing_key || encryption_key`. Intermediate shared secrets
/// are zeroized as soon as HKDF consumes them.
///
/// This primitive accepts AES-128-CBC and AES-256-CBC; endpoint admission
/// is narrower (see [`crate::constants::ENABLED_MODES`]). It does not
/// authenticate the peer or reject an all-zero X25519 shared secret.
pub fn derive(
my_prv: &X25519PrivateKey,
peer_pub: &X25519PublicKey,
+4 -2
View File
@@ -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;
+62 -23
View File
@@ -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<Duration> {
/// An encrypted bidirectional tunnel between two peers.
///
/// The state machine is driven by `tick()` calls from the owning actor/runtime;
/// there is no internal watchdog thread.
/// there is no internal watchdog thread. It uses `std::time::Instant` for
/// state deadlines. The owner handles transport, peer-key trust, callback
/// dispatch and packet-size admission. Keep public role, ID, mode and budget
/// fields consistent with construction; changing them does not renegotiate a Link.
pub struct Link {
/// Truncated SHA-256 of the request's hashable part.
pub link_id: [u8; 16],
@@ -224,24 +229,29 @@ pub struct Link {
pub rssi: Option<f64>,
/// Signal-to-noise ratio in dB.
pub snr: Option<f64>,
/// Link quality indicator in `[0.0, 1.0]`.
/// Caller/interface-supplied quality value. Stored without normalization
/// or clamping; its scale depends on the source interface.
pub q: Option<f64>,
track_phy_stats: bool,
pub has_channel: bool,
pub packet_callback: Option<PacketCallback>,
/// Called when a resource transfer begins; returns `true` to accept.
/// Stored acceptance callback for an owner that dispatches it. Link itself
/// does not invoke this callback; [`Self::should_accept_resource`] returns
/// the configured strategy without calling it.
pub resource_callback: Option<ResourceCallback>,
pub remote_identified_callback: Option<RemoteIdentifiedCallback>,
/// Fires when the link transitions to `Active`.
/// Stored activation callback. The owner dispatches it; state transitions
/// in this type do not invoke Link lifecycle callbacks themselves.
pub link_established_callback: Option<LinkCallback>,
pub link_closed_callback: Option<LinkCallback>,
}
/// Callback for decrypted link-packet payloads.
pub type PacketCallback = Box<dyn Fn(&[u8]) + Send + Sync>;
/// Callback for accepting or rejecting an incoming resource transfer.
/// Owner-dispatched Resource acceptance callback. Its boolean input is supplied
/// by that owner; `true` as the return value means acceptance.
pub type ResourceCallback = Box<dyn Fn(bool) -> bool + Send + Sync>;
/// Callback fired after the remote peer identifies on the link.
pub type RemoteIdentifiedCallback = Box<dyn Fn(&Link, &[u8; 64]) + Send + Sync>;
@@ -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<Vec<u8>, 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<ParsedRequestData, LinkCryptoError> {
// 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<u8>), 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<f64>, Option<f64>, Option<f64>) {
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<LinkKeys> {
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))
+12 -7
View File
@@ -13,8 +13,9 @@ pub enum RequestState {
Receiving,
Delivered,
Failed,
/// Response payload has arrived; kept distinct from [`Delivered`] so callers
/// can distinguish "ack with data" from "ack only".
/// Response payload arrived through [`RequestReceipt::receive_response`].
/// [`Delivered`] can represent either an ack-only transition or a response
/// recorded through [`RequestReceipt::deliver`].
///
/// [`Delivered`]: RequestState::Delivered
ResponseReceived,
@@ -28,12 +29,13 @@ pub struct RequestCallbacks {
pub progress: Option<ProgressCallback>,
}
/// Callback invoked once when a request receives a response or terminal failure.
/// Callback consumed at most once per registration on a response or failure.
pub type RequestCallback = Box<dyn FnOnce(&RequestReceipt) + Send>;
/// Progress callback for resource-backed request responses.
pub type ProgressCallback = Box<dyn Fn(f32) + Send + Sync>;
/// Tracks the lifecycle of an outbound request over a link.
/// Tracks an outbound request. The owner drives timeout and delivery methods;
/// this type does not start a timer or observe a Resource transfer itself.
pub struct RequestReceipt {
pub request_id: [u8; 32],
pub link_id: [u8; 16],
@@ -42,7 +44,8 @@ pub struct RequestReceipt {
pub timeout: Duration,
pub response: Option<Vec<u8>>,
pub rtt: Option<Duration>,
/// Transfer progress in [0.0, 1.0]; only meaningful for resource responses.
/// Caller-supplied transfer progress, conventionally in `[0.0, 1.0]` for
/// Resource responses. Neither this public field nor its setter clamps values.
pub progress: f32,
pub callbacks: RequestCallbacks,
}
@@ -125,7 +128,8 @@ impl RequestReceipt {
}
}
/// Transition to `Delivered` without a response payload (ack-only).
/// Transition from `Sent` to `Delivered` without a response payload (ack-only).
/// Other states are unchanged; this does not invoke a response callback.
pub fn mark_delivered(&mut self) {
if self.state == RequestState::Sent {
self.state = RequestState::Delivered;
@@ -158,7 +162,8 @@ impl RequestReceipt {
}
}
/// True once the request has reached a terminal state (delivered, failed, or response received).
/// Whether the request is no longer pending for timeout processing.
/// A `Delivered` receipt can still transition through [`Self::receive_response`].
pub fn concluded(&self) -> bool {
matches!(
self.state,
+22 -16
View File
@@ -6,12 +6,13 @@ use crate::stream_data::{STREAM_ID_MAX, StreamDataMessage};
/// Upper bound on a single chunk before the writer splits (16 KiB).
pub const MAX_CHUNK_LEN: usize = 16384;
/// Number of progressively smaller segments the writer will try when
/// compressing a chunk before giving up and sending it uncompressed.
/// Exclusive upper bound for compression-prefix trials. The writer tries
/// chunk/1, chunk/2 and chunk/3 before falling back to raw bytes.
pub const COMPRESSION_TRIES: usize = 4;
/// Accumulates inbound [`StreamDataMessage`] payloads into a byte queue and
/// tracks explicit EOF.
/// Accumulates decoded [`StreamDataMessage`] payloads and tracks explicit EOF.
/// The owner must provide ordered messages, bound queued data, and stop feeding
/// after EOF; this queue has no size limit and accepts later data.
pub struct StreamReader {
stream_id: u16,
buffer: VecDeque<u8>,
@@ -27,8 +28,8 @@ impl StreamReader {
}
}
/// Append `msg` to the buffer. Returns `false` (and ignores the payload)
/// if the message belongs to a different stream.
/// Append an already-decoded `msg`; this method does not decompress its data.
/// Returns `false` and ignores the payload for a different stream ID.
pub fn feed(&mut self, msg: &StreamDataMessage) -> bool {
if msg.stream_id != self.stream_id {
return false;
@@ -47,9 +48,9 @@ impl StreamReader {
/// Pop up to `size` bytes off the front of the buffer.
///
/// Returns `None` when the buffer is empty and EOF has not yet arrived,
/// and `Some(Vec::new())` once it has — letting callers distinguish "wait"
/// from "end of stream".
/// For a positive `size`, `None` means the empty stream is still open, and
/// `Some(Vec::new())` means EOF with no buffered data. A zero-size read can
/// also return an empty vector while data remains; it is not an EOF test.
pub fn read(&mut self, size: usize) -> Option<Vec<u8>> {
if self.buffer.is_empty() {
if self.eof {
@@ -89,8 +90,10 @@ impl StreamReader {
}
}
/// Chunks outbound bytes into [`StreamDataMessage`]s sized for the underlying
/// channel, opportunistically compressing each chunk with bzip2.
/// Chunks outbound bytes into [`StreamDataMessage`]s with optional bzip2
/// compression. `max_data_len` must be positive and excludes the two-byte
/// stream header and six-byte Channel envelope. Zero is not checked and makes
/// a nonempty write fail to advance. Stream IDs are masked to 14 bits.
pub struct StreamWriter {
stream_id: u16,
max_data_len: usize,
@@ -106,9 +109,10 @@ impl StreamWriter {
}
}
/// Slice `data` into channel-sized frames. Each frame is sent compressed
/// if bzip2 would fit a larger source segment into `max_data_len` than the
/// uncompressed alternative; otherwise the chunk is sent raw.
/// Slice `data` into frames within the configured payload budget. A prefix
/// is compressed when bzip2 makes it smaller and its encoded size is
/// strictly below `max_data_len`; otherwise the writer takes raw bytes.
/// Returned frames still need packing, Channel admission and transmission.
pub fn write(&mut self, data: &[u8]) -> Result<Vec<StreamDataMessage>, BufferError> {
if self.closed {
return Err(BufferError::WriterClosed);
@@ -200,8 +204,10 @@ pub enum BufferError {
WriterClosed,
}
/// Bidirectional convenience wrapper that pairs a [`StreamWriter`] and
/// [`StreamReader`] on the same stream ID.
/// Pairs a [`StreamWriter`] and [`StreamReader`] on the same stream.
/// `max_data_len` must satisfy the writer's positive-budget requirement.
/// Use an ID in `0..=STREAM_ID_MAX`: the reader/writer mask higher bits,
/// while this wrapper's `stream_id()` returns the original argument.
pub struct ChannelBuffer {
writer: StreamWriter,
reader: StreamReader,
+54 -35
View File
@@ -17,7 +17,7 @@ pub const WINDOW_MAX_MEDIUM: usize = 12;
pub const WINDOW_MAX_FAST: usize = 48;
/// Upper ceiling on `window_max` across all tiers; also sizes pre-allocated guard regions.
pub const WINDOW_MAX: usize = WINDOW_MAX_FAST;
/// Consecutive rounds at a tier's RTT before `window_max` is promoted to that tier.
/// RTT sample threshold used to promote the window ceiling; see [`ChannelWindow::grow`].
pub const FAST_RATE_THRESHOLD: usize = 10;
/// RTT at or below which a link is considered "fast" (seconds).
pub const RTT_FAST: f64 = 0.18;
@@ -25,7 +25,8 @@ pub const RTT_FAST: f64 = 0.18;
pub const RTT_MEDIUM: f64 = 0.75;
/// RTT above which a fresh window starts at a single slot.
pub const RTT_SLOW: f64 = 1.45;
/// Minimum gap `shrink()` will leave between `window_max` and `window_min`.
/// Gap threshold below which `shrink()` stops lowering the window ceiling.
/// This does not establish a minimum gap for freshly constructed windows.
pub const WINDOW_FLEXIBILITY: usize = 4;
pub const SEQ_MAX: u16 = 0xFFFF;
@@ -34,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<dyn Fn(u16, &[u8]) -> bool + Send>;
/// Opaque token for removing one registered message handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HandlerId(u64);
/// Sequenced, reliable message pipe over a Reticulum link.
/// Sequenced message state machine for a Reticulum Link.
///
/// The channel is passive: the owning runtime calls `send`/`receive`/
/// `timeout`/`delivered` to step the state machine. When one or more message
/// types are registered, inbound envelopes carrying an unregistered type are
/// rejected rather than silently dropped.
/// The owner drives `send`, `receive`, `timeout` and `delivered`, supplies
/// authenticated delivery proofs, and sends the returned bytes. Register
/// every inbound message type before receiving it; an empty registry accepts
/// no types. The Channel itself provides neither encryption nor a scheduler.
pub struct Channel {
next_tx_sequence: u16,
next_rx_sequence: u16,
@@ -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<u16>,
/// 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<Vec<u8>, 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<Vec<u8>, ChannelError> {
self.prepare_send_tracked(msg).map(|prepared| prepared.data)
}
+4 -3
View File
@@ -14,10 +14,11 @@ pub fn bz2_compress(data: &[u8]) -> Result<Vec<u8>, CompressionError> {
.map_err(|_| CompressionError::CompressFailed)
}
/// Decompress bzip2 `data`, failing once the output would exceed `max_size`.
/// Decompress bzip2 `data`, checking `max_size` after each 8192-byte read.
///
/// Decoding in chunks lets us stop early on a decompression bomb rather than
/// allocating the full expanded buffer.
/// Decoding stops when accumulated output exceeds the limit, at most one read
/// chunk beyond it. This is an output-length check, not a strict bound on peak
/// allocation or decoder working memory.
pub fn bz2_decompress(data: &[u8], max_size: usize) -> Result<Vec<u8>, CompressionError> {
let mut decoder = bzip2::read::BzDecoder::new(data);
let mut output = Vec::new();
+10 -3
View File
@@ -1,6 +1,13 @@
//! Higher-level protocol layers over Links: resource transfer, channels,
//! buffers, and stream I/O. Python reference: `RNS/Resource.py`,
//! `RNS/Channel.py`, `RNS/Buffer.py`.
//! Resource transfer, Channels and byte streams over Reticulum Links.
//!
//! The state machines are passive: their owner supplies packet I/O, Link keys,
//! proof routing and timeout polling. Use [`resource::OutboundTransfer`] and
//! [`resource::InboundTransfer`] for request-driven Resource transfer,
//! [`channel::LinkChannel`] for sequenced messages, and [`buffer::ChannelBuffer`]
//! for byte-stream framing on a Channel. Codec helpers do not establish Links
//! or authorize application actions.
//!
//! Python reference formats: `RNS/Resource.py`, `RNS/Channel.py`, `RNS/Buffer.py`.
pub mod buffer;
pub mod channel;
+155 -113
View File
@@ -5,8 +5,8 @@ use rns_crypto::sha::full_hash;
use crate::compression;
/// Lifecycle state of a resource transfer. `Rejected` is tagged 0x09 — not
/// 0x00 — so it is wire-distinguishable from `None`.
/// Lifecycle state of a Resource transfer. `Rejected` has discriminant
/// `0x09`, distinct from `None` (`0x00`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ResourceState {
@@ -36,13 +36,15 @@ pub const RATE_FAST: usize = 6250;
pub const RATE_VERY_SLOW: usize = 250;
pub const WINDOW_FLEXIBILITY: usize = 4;
pub const MAPHASH_LEN: usize = 4;
/// Only the low 4 bytes of the resource's random tag ship on the wire (in the
/// advertisement's `r` field) and feed the map-hash calculation.
/// Size of the random tag generated by this implementation and included in
/// its advertisement and part/resource hash inputs.
pub const RANDOM_HASH_SIZE: usize = 4;
pub const SDU: usize = rns_wire::constants::MDU;
/// Largest payload that fits a single-segment resource (1 MiB - 1).
/// Maximum uncompressed content per segment (1 MiB - 1), including any
/// three-byte metadata prefix and metadata bytes.
pub const MAX_EFFICIENT_SIZE: usize = 1_048_575;
/// Largest metadata block that a 3-byte length prefix can encode.
/// Metadata length representable by the three-byte prefix. Constructors also
/// require metadata and its prefix to fit the first segment's smaller budget.
pub const METADATA_MAX_SIZE: usize = 16_777_215;
pub const MAX_RETRIES: usize = 16;
pub const MAX_ADV_RETRIES: usize = 4;
@@ -146,8 +148,9 @@ pub fn compute_expected_proof(data: &[u8], resource_hash: &[u8; 32]) -> [u8; 32]
full_hash(&input)
}
/// Decode a sender-to-receiver hashmap update:
/// `resource_hash(32) || msgpack([segment_index, hashmap_bytes])`.
/// Decode `resource_hash(32) || msgpack([segment_index, hashmap_bytes])`.
/// This parser does not reject trailing bytes or validate the resource binding,
/// segment range or four-byte entry alignment; the transfer owner must do so.
pub fn parse_hashmap_update(data: &[u8]) -> Result<([u8; 32], usize, Vec<u8>), ResourceError> {
if data.len() < 32 {
return Err(ResourceError::Corrupt);
@@ -188,13 +191,9 @@ impl WindowState {
}
}
/// Grow the window once a whole batch has arrived. Must be called before
/// the next request batch is dispatched so the new slots are visible to
/// the batch-size calculation.
///
/// Also slides `window_min` up when the window has outgrown its
/// flexibility band, and promotes the ceiling for sustained fast or
/// very-slow links.
/// Grow the window after a received batch, before calculating the next
/// request size. The minimum follows a growing window; sustained fast rounds
/// promote its ceiling, while sustained very-slow rounds lower and clamp it.
pub fn grow(&mut self, rate: usize) {
if self.window < self.window_max {
self.window += 1;
@@ -228,9 +227,9 @@ impl WindowState {
}
}
/// Shrink the window after a timeout. Both the instantaneous `window`
/// and the ceiling `window_max` contract, and the flexibility band
/// between them is kept within `WINDOW_FLEXIBILITY - 1`.
/// Shrink the window and ceiling toward their minimum after a timeout.
/// If the ceiling remains more than `WINDOW_FLEXIBILITY - 1` above the
/// window, lower it once more; one call need not close a larger gap.
pub fn shrink(&mut self) {
if self.window > self.window_min {
self.window -= 1;
@@ -273,17 +272,18 @@ pub struct OutboundResource {
pub window: WindowState,
pub retries: usize,
pub sdu: usize,
/// Optional payload metadata. When set it is prepended to the resource
/// data as `length(3 BE) || metadata` before compression.
/// Framed metadata: `length(3 BE) || metadata`, already including the prefix.
/// Prepended to the payload before compression by the constructors.
pub metadata: Option<Vec<u8>>,
/// Size of the packed metadata block (length prefix included).
pub metadata_size: usize,
}
impl OutboundResource {
/// Build a single-segment outbound resource. Payloads above
/// `MAX_EFFICIENT_SIZE` must use `MultiSegmentOutbound`. `encrypt_fn` is
/// applied to the assembled blob after compression, before chunking.
/// Build a single segment. Data plus framed metadata must fit
/// `MAX_EFFICIENT_SIZE`; use [`MultiSegmentOutbound`] or
/// [`LazyMultiSegmentOutbound`] for larger payloads. `encrypt_fn`, when
/// supplied, runs on the whole compressed blob before part slicing.
pub fn new(
data: Vec<u8>,
auto_compress: bool,
@@ -296,13 +296,13 @@ impl OutboundResource {
// `with_options_inner` for the retry loop.
const MAX_COLLISION_RETRIES: usize = 5;
/// Extended constructor with optional metadata and a custom SDU.
/// Construct with optional metadata and a custom part SDU.
///
/// `metadata` is framed as `length(3 BE) || bytes` and prepended to the
/// data before compression/encryption, matching the Python layout.
///
/// `link_sdu` lets callers override the default SDU when the link has
/// negotiated a non-standard MTU.
/// Metadata is prepended as `length(3 BE) || bytes` before compression and
/// counts toward the segment content limit. `link_sdu` must be nonzero and
/// changes part slicing only; control-packet admission still uses the base
/// Reticulum MTU. Supplying an encryption hook sets the encrypted flag, so
/// the hook must return encrypted bytes rather than silently falling back.
pub fn with_options(
data: Vec<u8>,
auto_compress: bool,
@@ -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<usize> {
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<u8> {
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<u8>,
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<u8>,
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<u8>,
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<Option<InboundResource>>,
pub assembled_segments: Vec<Option<Vec<u8>>>,
pub data_size: usize,
/// First non-None metadata observed across the segment stream. Rust's
/// `MultiSegmentOutbound` attaches no per-segment metadata, but Python
/// peers may.
/// First metadata supplied through `set_metadata`. Outbound constructors
/// can attach metadata to the first segment; the owner must carry it here
/// after assembling that segment.
pub metadata: Option<Vec<u8>>,
}
impl MultiSegmentInbound {
/// Allocate slots for `total_segments` segments; seed with the
/// `original_hash` advertised by the sender for the full payload.
/// Allocate slots and retain the sender's `original_hash`. Before calling,
/// validate a nonzero count no greater than `MAX_SEGMENTS` and the transfer
/// limits. This constructor does not check them and allocates directly from
/// `total_segments`.
pub fn new(total_segments: usize, original_hash: [u8; 32]) -> Self {
Self {
original_hash,
@@ -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<OutboundResource>,
@@ -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<u8>,
@@ -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<u8>,
@@ -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<Vec<u8>> {
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<u8>) -> 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<Vec<u8>, ResourceError> {
let decrypt_fn: Option<Box<ResourceDecryptor<'_>>> =
if let Some(ref keys) = self.session_keys {
@@ -1368,7 +1396,8 @@ pub enum TransferAction {
/// `(part_index, part_data)`.
SendPart(usize, Vec<u8>),
SendProof(Vec<u8>),
/// Hashmap update frame from receiver to sender.
/// Sender-to-receiver hashmap update: resource hash followed by
/// MessagePack `[segment_index, hashmap_bytes]`.
SendHmu(Vec<u8>),
/// Receiver-to-sender request for specific parts. Payload layout:
/// `exhausted_flag || optional last_map_hash || resource_hash || requested_part_hashes...`.
@@ -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<u8>,
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<u8> {
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(
+23 -10
View File
@@ -1,9 +1,13 @@
use crate::resource::{MAPHASH_LEN, ResourceFlags};
/// Advertisement overhead in bytes (non-hashmap data).
/// Nominal non-hashmap overhead used by the hashmap-capacity estimator.
/// Actual MessagePack size depends on field values; use exact control admission
/// before transmission.
pub const OVERHEAD: usize = 134;
/// Maximum map-hash entries that fit alongside the advertisement overhead in one MDU.
/// Estimate map-hash capacity as `(mdu - OVERHEAD) / MAPHASH_LEN`. This does
/// not check the actual advertisement encoding or encrypted packet length; use
/// [`crate::resource_control::check_advertisement`] for admission.
pub fn hashmap_max_len(mdu: usize) -> usize {
if mdu > OVERHEAD {
(mdu - OVERHEAD) / MAPHASH_LEN
@@ -48,8 +52,9 @@ pub struct ResourceAdvertisement {
}
impl ResourceAdvertisement {
/// Build an advertisement with no metadata prefix. Equivalent to
/// [`Self::with_metadata_size`] with `metadata_size = 0`.
/// Build an advertisement with a local metadata-size annotation of zero.
/// Equivalent to [`Self::with_metadata_size`] with `metadata_size = 0`; it
/// does not clear the caller-supplied `has_metadata` flag.
// Mirrors the Resource ADV wire fields; grouping these into a builder
// would hide the packet layout this constructor exists to preserve.
#[allow(clippy::too_many_arguments)]
@@ -76,9 +81,10 @@ impl ResourceAdvertisement {
)
}
/// Build an advertisement, truncating `map_hashes` to what actually fits in
/// the MDU. Callers are expected to send the remaining hashes in a
/// subsequent hashmap-update packet.
/// Build an advertisement, truncating `map_hashes` using the nominal MDU
/// estimate. Send remaining hashes in subsequent hashmap updates. Before
/// sending, call [`crate::resource_control::check_advertisement`] to verify
/// the actual encoded packet size.
// Same Resource ADV field set as `new`, plus the local metadata prefix
// size needed to split payload from metadata after receive.
#[allow(clippy::too_many_arguments)]
@@ -117,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<Self, String> {
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::<MAPHASH_LEN>()
+4 -1
View File
@@ -20,7 +20,10 @@ pub fn encrypted_len(plaintext_len: usize) -> Result<usize, ResourceError> {
.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,
+8 -2
View File
@@ -1,6 +1,12 @@
//! rnsh channel message codecs.
//! rnsh Channel message codecs.
//!
//! Python reference: `RNS/Utilities/rnsh/protocol.py`.
//! Use `MessageBase` to pack/unpack a message or `RnshMessage::decode` to
//! dispatch by type, and register `MESSAGE_TYPES` with the Channel. These
//! codecs do not execute commands or authorize a remote shell.
//!
//! Stream messages use IDs 0/1/2 for stdin/stdout/stderr and the Buffer
//! compression format. Decoding expands compressed data while retaining its
//! flag; clear the flag or recompress before repacking that message.
use std::io::Cursor;
+8 -4
View File
@@ -10,10 +10,14 @@ pub const OVERHEAD: usize = 8;
/// Stream frame for the Buffer protocol.
///
/// Wire layout (2-byte big-endian header followed by payload):
/// - bit 15: EOF flag
/// - bit 14: compressed flag (payload is bz2)
/// - bits 13..0: stream ID (0..=16_383)
/// Wire layout (two-byte big-endian header followed by payload):
/// - bit 15: EOF
/// - bit 14: bzip2-compressed payload
/// - bits 13..0: stream ID (`0..=16_383`)
///
/// `MessageBase::unpack` decompresses into `data` but retains the received
/// `compressed` flag. `pack` only serializes the fields; before repacking a
/// decoded compressed frame, clear the flag or recompress its data.
#[derive(Debug, Clone)]
pub struct StreamDataMessage {
pub stream_id: u16,
+33 -15
View File
@@ -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: <https://docs.yubico.com/yesdk/users-manual/application-piv/commands.html>
//! 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<u8>` values: wipe them
//! after use. Large-message builders do not enforce card/APDU length limits.
//!
//! Reference: <https://docs.yubico.com/yesdk/users-manual/application-piv/commands.html>
use crate::error::RatkeyError;
@@ -171,7 +179,9 @@ pub fn select_piv() -> Vec<u8> {
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<u8> {
use zeroize::Zeroize;
let mut pin_data = [0xFFu8; 8];
@@ -198,7 +208,9 @@ pub fn change_pin(old_pin: &str, new_pin: &str) -> Vec<u8> {
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<u8> {
use zeroize::Zeroize;
let mut data = [0xFFu8; 16];
@@ -213,9 +225,11 @@ pub fn reset_retry(puk: &str, new_pin: &str) -> Vec<u8> {
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<u8> {
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<u8> {
let challenge = tlv(TAG_AUTH_CHALLENGE, message);
// Empty response tag = request sig output.
@@ -328,12 +344,14 @@ pub fn get_metadata(slot: u8) -> Vec<u8> {
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<u8> {
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<u8> {
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 {
+31 -39
View File
@@ -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"
}
+19 -10
View File
@@ -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<Sender<Cmd>>,
}
@@ -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<Identity, RatkeyError> {
let ed_pub = hwid.ed25519_pub_bytes()?;
let x_pub = hwid.x25519_pub_bytes()?;
+7 -3
View File
@@ -7,9 +7,11 @@ pub struct DeviceInfo {
pub reader_name: String,
pub serial: Option<u32>,
pub firmware: Option<String>,
/// 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") {
+8 -4
View File
@@ -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")]
+23 -10
View File
@@ -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<dyn IdentityBackend>,
@@ -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()
}
+19 -8
View File
@@ -1,5 +1,11 @@
//! `.hwid` TOML: public metadata for a hardware identity. No private key material ever.
//! Location: `<reticulum-config-dir>/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 `<identities_dir>/<hash_hex>/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<String, RatkeyError> {
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}"))
+14 -7
View File
@@ -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;
+6 -4
View File
@@ -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,
}
+7 -2
View File
@@ -1,4 +1,7 @@
//! PIN cache: `Zeroizing<String>` wiped on drop or expiry.
//! Host-side PIN cache backed by `Zeroizing<String>`. 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,
+28 -11
View File
@@ -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<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
@@ -179,8 +192,9 @@ pub fn import_recoverable_identity<T: PivTransport>(
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<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
@@ -200,8 +214,10 @@ pub fn provision_hardware_only<T: PivTransport>(
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<T: PivTransport>(
session: &mut PivSession<T>,
config: &ProvisionConfig,
@@ -275,8 +291,9 @@ fn finalize_provision<T: PivTransport>(
})
}
/// 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<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
+12 -8
View File
@@ -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],
+47 -18
View File
@@ -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<T: PivTransport> PivSession<T> {
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<T: PivTransport> PivSession<T> {
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<T: PivTransport> PivSession<T> {
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<T: PivTransport> PivSession<T> {
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<T: PivTransport> PivSession<T> {
}
}
/// 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<T: PivTransport> PivSession<T> {
}
}
/// 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<T: PivTransport> PivSession<T> {
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<T: PivTransport> PivSession<T> {
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<T: PivTransport> PivSession<T> {
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<T: PivTransport> PivSession<T> {
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<Vec<u8>, RatkeyError> {
let resp = self.transport.transmit(&apdu::attest_key(slot))?;
Ok(apdu::check_response(&resp)?.to_vec())
@@ -250,18 +279,18 @@ impl<T: PivTransport> PivSession<T> {
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)?;
+9 -5
View File
@@ -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<Vec<u8>, 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,
}
+71 -16
View File
@@ -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 <destination-hash> "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 <directory>` 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).
+1 -1
View File
@@ -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));
}
}
}
+7 -4
View File
@@ -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,
+8 -5
View File
@@ -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<Self, ConfigError> {
let content = std::fs::read_to_string(path)?;
let mut config = Self::parse(&content)?;
+9 -3
View File
@@ -49,8 +49,12 @@ fn integer(section: &ConfigSection, key: &'static str) -> Result<Option<usize>,
.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<Option<usize>, 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<IfacUnitChange> {
config
.subsections("interfaces")
+4 -3
View File
@@ -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,
+13 -13
View File
@@ -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<TransportMessage>,
destination_hash: [u8; 16],
+30 -16
View File
@@ -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<Vec<u8>>,
/// Per-advertisement acceptance policy consulted when
/// Per-advertisement acceptance policy for ordinary Resources, consulted when
/// `resource_strategy` is `AcceptApp`.
pub resource_accept: Option<ResourceAcceptPolicy>,
/// 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<ResourceAcceptCallback>);
@@ -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<dyn Fn([u8; 16], [u8; 16]) -> 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<u8>,
}
/// Event receivers owned by one registered destination. All are bounded by
/// `event_capacity` except `link_packets`: inbound link data is proved to the
/// peer on receipt, so its local delivery is lossless and must be drained.
/// 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<DestinationPacket>,
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<TransportMessage>,
identity: Identity,
@@ -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<oneshot::Sender<Resolution>>,
@@ -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<LinkPacketReceiptOutcome> {
self.resolve(Decision::Close)
}
+75 -40
View File
@@ -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<u64>,
pub id_callsign: Option<String>,
}
@@ -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<u16>,
pub usb_product_id: Option<u16>,
pub usb_serial_number: Option<String>,
@@ -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<f32>,
/// Long-term airtime cap, percent (0.0..=100.0). `None` = unlimited.
/// Long-term airtime cap, percent (0.0..=100.0). `None` sends no
/// command for this setting; it does not explicitly clear a prior limit.
pub lt_alock: Option<f32>,
/// Station-ID beacon: seconds between IDs, sent only after data TX.
pub id_interval: Option<u64>,
@@ -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<f32>,
/// Long-term airtime cap, percent (0.0..=100.0). `None` = unlimited.
/// Long-term airtime cap, percent (0.0..=100.0). `None` sends no
/// command for this setting; it does not explicitly clear a prior limit.
pub lt_alock: Option<f32>,
/// Station-ID beacon: seconds between IDs, sent only after data TX.
pub id_interval: Option<u64>,
@@ -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<RNodeSubInterfaceConfig>,
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<u64>,
pub id_callsign: Option<String>,
}
@@ -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<String>,
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<usize>,
/// 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<u64>,
/// 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<f64>,
pub announce_rate_target: Option<u64>,
pub announce_rate_grace: Option<u32>,
pub announce_rate_penalty: Option<u64>,
pub ifac_network_name: Option<String>,
/// Wiped when dropped.
/// This owned copy is wiped on drop. The input `ConfigSection` retains its
/// separate ordinary `String` copy.
pub ifac_passphrase: Option<zeroize::Zeroizing<String>>,
/// Effective IFAC tag length in bytes, already decoded from file units.
pub ifac_size: Option<usize>,
/// 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<f64> {
}
}
/// 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(_)
+4 -2
View File
@@ -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};
+10 -11
View File
@@ -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);
+12 -5
View File
@@ -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],
+229 -96
View File
@@ -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<oneshot::Sender<Result<(), DestinationControlError>>>,
@@ -348,7 +357,8 @@ pub enum LinkManagerCommand {
app_data: Option<Vec<u8>>,
result_tx: Option<oneshot::Sender<Result<(), DestinationControlError>>>,
},
/// 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<rns_transport::messages::InterfaceId>,
pub tag: Option<Vec<u8>>,
/// 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<u8>,
/// 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<Vec<u8>>,
}
/// 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<LinkEndpointDispatchCancellation>,
},
/// 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<u8>),
ReplyWithResource {
ack: Vec<u8>,
data: Vec<u8>,
/// 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<Vec<u8>>,
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<rns_transport::link_endpoint_dispatch::LinkEndpointDispatchHandle>,
endpoint_dispatch_tokens:
@@ -639,7 +665,7 @@ pub struct LinkManager {
resource_accept_handler: Option<ResourceAcceptHandler>,
/// Fires when a link reaches the active state.
link_established_tx: Option<mpsc::Sender<[u8; 16]>>,
/// Fires on LinkIdentify before a resource ADV can race it.
/// Best-effort notification on the first verified LinkIdentify.
link_identified_tx: Option<mpsc::Sender<([u8; 16], [u8; 16])>>,
/// 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<TransportMessage>,
event_rx: mpsc::Receiver<DestinationEvent>,
@@ -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<TransportMessage>,
event_rx: mpsc::Receiver<DestinationEvent>,
@@ -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<std::path::Path>,
@@ -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<Mutex<HashMap<[u8; 16], [u8; 16]>>> {
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<LinkManagerCommand>) {
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<F>(&mut self, handler: F)
where
F: Fn([u8; 16], [u8; 16], Vec<u8>) -> Option<Vec<u8>> + 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<F>(&mut self, handler: F)
where
F: Fn([u8; 16], [u8; 16], Vec<u8>) -> 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<F>(
&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<F>(
&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<F>(&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<LinkResponse>) {
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<F>(&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<F>(&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<InboundLinkPacket>,
@@ -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<LinkPacketProof>) {
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<LinkResourceProof>) {
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<DestinationDeliveryProof>,
@@ -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<LinkManagerAccountingEvent>,
@@ -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<LinkChannelMessage>) {
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<Vec<u8>>) {
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<TransportMessage>,
dest_hash: [u8; 16],
+102 -19
View File
@@ -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<u8>,
@@ -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<bool, LinkSessionChannelError> {
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<LinkPhyStats> {
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<u8>,
@@ -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<S>(
&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<LinkSessionEvent>,
@@ -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<TransportMessage>,
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<TransportMessage>,
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<TransportMessage>,
destination_hash: [u8; 16],
+7 -5
View File
@@ -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),
+22 -8
View File
@@ -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<String>,
pub destination_hash: [u8; 16],
}
/// Signs every inbound DATA with a PROOF (Python `PROVE_ALL`). Callers must
/// persist `identity` (canonical `<storage_dir>/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 `<storage_dir>/probe_identity`) to retain its destination hash
/// across restarts.
pub async fn spawn_probe_responder(
transport_tx: mpsc::Sender<TransportMessage>,
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<TransportMessage>,
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<Duration, ProbeError> {
let duration = Duration::try_from_secs_f64(seconds).map_err(|_| ProbeError::InvalidTimeout)?;
std::time::Instant::now()
+12 -12
View File
@@ -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<TransportMessage>,
identity: &Identity,
+9 -1
View File
@@ -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<T> ResourceSource for T where T: Read + Seek + Send {}
+252 -142
View File
@@ -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<TransportMessage>,
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<AtomicBool>,
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<Identity>,
pub network_identity: Option<Arc<Identity>>,
/// 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<bool, AnnounceSubscriptionError> {
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<Duration>,
/// Restrict dispatch to one interface.
pub attached_interface: Option<rns_transport::messages::InterfaceId>,
@@ -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<SendResult, SendError> {
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<Duration, ReceiptError> {
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<Duration>,
/// 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<Option<Arc<dyn DiscoveryStamper + Send + Sync>>>,
store: Mutex<Option<Arc<DiscoveryStore>>>,
@@ -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<String>,
@@ -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<String>,
@@ -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<TransportQueryResponse> {
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<u8>,
@@ -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<InterfaceStats, ControlError> {
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<TransportQueryResponse> {
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<dyn DiscoveryStamper + Send + Sync>,
@@ -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<DiscoveredInterface> {
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<Vec<u8>>,
pub rpc_key: Option<Vec<u8>>,
/// 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<u64>,
pub default_ar_target: Option<u64>,
pub default_ar_penalty: Option<u64>,
@@ -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<PathBuf>,
/// 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<PathBuf>,
}
@@ -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<Self, ConfigError> {
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<PathBuf>,
@@ -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<String>,
pub passphrase: Option<String>,
@@ -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<f32>,
/// 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<f32>,
/// 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<f32>,
/// 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<f32>,
/// 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()
}
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more