Compare commits

...
57 Commits
Author SHA1 Message Date
DeFiDude 4cbb7d8b59 ble: smooth rnode pairing startup 2026-05-23 20:46:48 -06:00
DeFiDude 84bfd4871d rnode: detach serial transports on teardown 2026-05-23 17:43:24 -06:00
DeFiDude 4df2e6581f rnode: send detach sequence on BLE stop 2026-05-23 17:27:17 -06:00
DeFiDude 8328393a5f rnode: send radio off on BLE teardown 2026-05-23 16:46:41 -06:00
DeFiDude b45f6b10de tests: cover shared instance startup smoke 2026-05-23 15:33:19 -06:00
DeFiDude 55d2d34488 transport: load persisted state before actor startup 2026-05-23 15:19:34 -06:00
DeFiDude 73b250f36e Revert "ble-peer: add low-power advertising option"
This reverts commit f21f526b0a.
2026-05-23 02:38:05 -06:00
DeFiDude 1d4c1d6d7f Revert "ble-peer: restore balanced advertising default"
This reverts commit d30626a098.
2026-05-23 02:38:05 -06:00
DeFiDude d30626a098 ble-peer: restore balanced advertising default 2026-05-23 02:28:12 -06:00
DeFiDude f21f526b0a ble-peer: add low-power advertising option 2026-05-23 02:11:21 -06:00
DeFiDude 52cd1a0939 ble-peer: fix direct link request framing 2026-05-23 01:04:12 -06:00
DeFiDude d9af1beece runtime: satisfy ingress override clippy 2026-05-22 14:25:07 -06:00
DeFiDude 8b80ca88fd Merge remote-tracking branch 'origin/main' 2026-05-22 14:03:27 -06:00
DeFiDude a2c2a256d4 transport: harden shared instance client state 2026-05-22 13:57:45 -06:00
dude.eth 112dfc1d2c Update README.md
oops
2026-05-21 13:01:32 -06:00
dude.eth f9a8f89ffd Update README.md
Change target to 1.2.5 after the 1.2.4 -> 1.2.5 changes
2026-05-21 13:01:05 -06:00
DeFiDude 46449b21d3 runtime: normalize announce cap percent 2026-05-20 16:59:07 -06:00
DeFiDude 08848509b6 transport: add cache clear queries 2026-05-20 14:33:15 -06:00
DeFiDude 6a4e3af78a transport: mark path response announce entries 2026-05-20 12:02:57 -06:00
DeFiDude ffe641b3af transport: ignore stale paths for live routing 2026-05-20 10:27:47 -06:00
DeFiDude 0013707496 resource: track outbound send progress 2026-05-19 23:59:38 -06:00
DeFiDude ade40c8283 interface: satisfy rnode tcp clippy 2026-05-19 22:34:25 -06:00
DeFiDude 20bee8bafd interface: split RNode TCP feature gate 2026-05-19 19:59:55 -06:00
DeFiDude f1042c0bb4 ci: use Node 24 action versions 2026-05-18 02:31:16 -06:00
DeFiDude 9d45c9a61f transport: suppress failed direct path interfaces 2026-05-17 22:24:14 -06:00
dude.eth a6c384f856 Merge pull request #2 from strijar/fix/ble
Fixed dependency on BLE
2026-05-17 15:48:38 -06:00
DeFiDude 84b0f0175a Update README.md 2026-05-17 15:38:54 -06:00
dude.eth 8e7d588faf Merge pull request #4 from strijar/fix/udevlib
Unnecessary dependency on udevlib has been removed
2026-05-17 15:35:55 -06:00
DeFiDude 83c63b463e interface: tune RNode TCP sockets 2026-05-17 15:23:12 -06:00
DeFiDude 8ac7f9a625 interface: clean up RNode TCP error wrapping 2026-05-17 15:11:42 -06:00
DeFiDude c7f048bac5 interface: reconnect RNode streams after disconnect 2026-05-17 15:02:06 -06:00
DeFiDude 7579873409 interface: harden RNode TCP endpoint parsing 2026-05-17 14:41:25 -06:00
DeFiDude a8df6d0b36 interface: note RNode TCP feature-gate cleanup 2026-05-17 14:20:41 -06:00
DeFiDude eb2972510c interface: bound RNode TCP connect attempts 2026-05-17 14:11:51 -06:00
DeFiDude 6d1b43bfc4 interface: treat RNode TCP EOF as disconnect 2026-05-17 14:10:51 -06:00
Belousov Oleg bebb9a8fca RNode cosmetic fixes 2026-05-17 14:09:02 -06:00
Belousov Oleg 497502596a RNode via TCP 2026-05-17 14:09:02 -06:00
DeFiDude 491664d24c interface: silence Android BLE build warnings 2026-05-15 20:37:13 -06:00
DeFiDude 3e85c74917 transport: satisfy strict ci lints 2026-05-15 19:32:47 -06:00
DeFiDude 68a83f83dc transport: finish upstream path reliability gaps 2026-05-15 15:45:27 -06:00
DeFiDude 1ad1a12388 transport: align path routing with upstream 2026-05-15 15:02:34 -06:00
DeFiDude 3758ae8bac transport: normalize inbound hop accounting 2026-05-15 14:34:33 -06:00
DeFiDude 15ae922535 runtime: choose packet or resource for link payloads 2026-05-15 03:25:02 -06:00
DeFiDude 5d0b6641cd runtime: add link app send commands 2026-05-15 03:22:52 -06:00
Belousov Oleg d651a4bcea Unnecessary dependency on udevlib has been removed 2026-05-15 09:29:42 +03:00
Belousov Oleg 51def9d622 Fixed dependency on BLE 2026-05-15 08:58:43 +03:00
DeFiDude 017b747eeb ci: avoid caching cargo shims 2026-05-14 23:34:50 -06:00
DeFiDude 863d723531 link: make keepalive jitter test platform-safe 2026-05-14 23:28:42 -06:00
DeFiDude 673a9715d5 tools: align utilities with Reticulum 1.2.5 2026-05-14 13:31:25 -06:00
DeFiDude 81672542ce runtime: group BLE RNode spawn args 2026-05-13 23:22:12 -06:00
DeFiDude c744831517 transport: satisfy strict clippy checks 2026-05-12 05:05:37 -06:00
DeFiDude 4cab54659c transport: implement Reticulum 1.2.5 routing controls 2026-05-11 20:15:21 -06:00
DeFiDude 4ddbf01a2a transport: expose announce aspect hashes 2026-05-11 16:05:05 -06:00
DeFiDude fe665b2216 release: prepare v0.9.3 2026-05-10 01:06:50 -06:00
DeFiDude e83fa8e208 interface: keep AutoInterface link-local addrs 2026-05-09 22:39:38 -06:00
DeFiDude bc232d65da release: prepare AutoInterface prerelease 2026-05-09 20:49:23 -06:00
DeFiDude 365bd02e75 interface: scope AutoInterface peers 2026-05-09 19:48:31 -06:00
61 changed files with 8634 additions and 1049 deletions

No files matched your search

+4 -2
View File
@@ -19,9 +19,11 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
cache-bin: false
- name: Install system deps (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
@@ -36,7 +38,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
+7 -5
View File
@@ -39,11 +39,13 @@ jobs:
env:
ARCHIVE_NAME: rsReticulum-${{ github.event.inputs.tag_name || github.ref_name }}-${{ matrix.artifact_suffix }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
ref: ${{ env.RELEASE_TAG }}
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
cache-bin: false
- name: Install system deps (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
@@ -70,7 +72,7 @@ jobs:
if: runner.os == 'Windows'
shell: pwsh
run: Compress-Archive -Path "dist/${env:PACKAGE_ROOT}" -DestinationPath "${env:ARCHIVE_NAME}.zip" -Force
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v7
with:
name: ${{ env.ARCHIVE_NAME }}
path: |
@@ -85,15 +87,15 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/download-artifact@v4
- uses: actions/download-artifact@v7
with:
path: release-assets
merge-multiple: true
- name: Generate checksums
working-directory: release-assets
run: sha256sum * > SHA256SUMS
- uses: softprops/action-gh-release@v2
- uses: softprops/action-gh-release@v3
with:
tag_name: ${{ env.RELEASE_TAG }}
prerelease: true
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}
files: release-assets/*
Generated
+10 -31
View File
@@ -1026,26 +1026,6 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "libudev"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78b324152da65df7bb95acfcaab55e3097ceaab02fb19b228a9eb74d55f135e0"
dependencies = [
"libc",
"libudev-sys",
]
[[package]]
name = "libudev-sys"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324"
dependencies = [
"libc",
"pkg-config",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -1481,7 +1461,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"aes",
"cbc",
@@ -1502,7 +1482,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"hex",
"proptest",
@@ -1519,7 +1499,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"bluer",
"btleplug",
@@ -1549,7 +1529,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"hex",
"proptest",
@@ -1565,7 +1545,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"bzip2",
"hex",
@@ -1582,7 +1562,7 @@ dependencies = [
[[package]]
name = "rns-ratkey"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"hex",
"pcsc",
@@ -1598,7 +1578,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"bytes",
"hex",
@@ -1623,7 +1603,7 @@ dependencies = [
[[package]]
name = "rns-tools"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"base64",
"bytes",
@@ -1650,7 +1630,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"bytes",
"hex",
@@ -1670,7 +1650,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "0.9.2"
version = "0.9.3"
dependencies = [
"proptest",
"rns-crypto",
@@ -1824,7 +1804,6 @@ dependencies = [
"core-foundation",
"core-foundation-sys",
"io-kit-sys",
"libudev",
"mach2",
"nix 0.26.4",
"scopeguard",
+5 -6
View File
@@ -14,7 +14,7 @@ members = [
]
[workspace.package]
version = "0.9.2"
version = "0.9.3"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.85"
@@ -49,13 +49,12 @@ tokio = { version = "1", features = ["full"] }
bzip2 = "0.5"
# Serial
serialport = "4"
# BLE
btleplug = "0.11"
serialport = { version = "4", default-features = false }
# Networking
if-addrs = "0.13"
# AutoInterface requires fe80::/10 discovery addresses. if-addrs filters them
# unless this feature is enabled, which leaves Linux/Windows with no adopted NICs.
if-addrs = { version = "0.13", features = ["link-local"] }
socket2 = { version = "0.5", features = ["all"] }
# CLI
+4 -4
View File
@@ -7,7 +7,7 @@
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.85+](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org)
[![Reticulum 1.2.4](https://img.shields.io/badge/target-Reticulum%201.2.4-success.svg)](https://reticulum.network/)
[![Reticulum 1.2.5](https://img.shields.io/badge/target-Reticulum%201.2.5-success.svg)](https://reticulum.network/)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[Reticulum Manual](https://reticulum.network/manual/) |
@@ -61,19 +61,19 @@ Debian, Ubuntu, and Raspberry Pi OS:
```bash
sudo apt update
sudo apt install -y build-essential pkg-config libudev-dev
sudo apt install -y build-essential pkg-config
```
Fedora:
```bash
sudo dnf install gcc make pkgconf-pkg-config systemd-devel
sudo dnf install gcc make pkgconf-pkg-config
```
Arch:
```bash
sudo pacman -S --needed base-devel pkgconf systemd
sudo pacman -S --needed base-devel pkgconf
```
##### Build the tools:
+25 -1
View File
@@ -198,6 +198,19 @@ impl AnnounceData {
packet_dest_hash: &[u8; 16],
known_public_key: Option<&[u8; 64]>,
) -> Result<Identity, AnnounceError> {
let identity = self.verify_signature(packet_dest_hash)?;
self.validate_destination_binding(packet_dest_hash, &identity, known_public_key)?;
Ok(identity)
}
/// Verify the announce signature without checking destination-hash
/// binding or first-seen key continuity.
///
/// Reticulum transport performs this lightweight precheck before announce
/// ingress limiting, then runs full binding validation before learning the
/// path. Keeping this as a distinct step lets transport match that order
/// without duplicating announce wire-format logic.
pub fn verify_signature(&self, packet_dest_hash: &[u8; 16]) -> Result<Identity, AnnounceError> {
let identity = Identity::from_public_key(&self.public_key)
.map_err(|_| AnnounceError::InvalidPublicKey)?;
@@ -224,6 +237,17 @@ impl AnnounceData {
return Err(AnnounceError::SignatureInvalid);
}
Ok(identity)
}
/// Validate destination-hash binding and first-seen public-key continuity
/// after [`verify_signature`] has succeeded.
pub fn validate_destination_binding(
&self,
packet_dest_hash: &[u8; 16],
identity: &Identity,
known_public_key: Option<&[u8; 64]>,
) -> Result<(), AnnounceError> {
// Destination hash = SHA-256(name_hash || identity_hash) truncated to 16 bytes.
let expected_hash = {
let mut material = Vec::with_capacity(26);
@@ -256,7 +280,7 @@ impl AnnounceData {
}
}
Ok(identity)
Ok(())
}
}
+4 -3
View File
@@ -8,7 +8,8 @@ license.workspace = true
[features]
default = []
serial = ["dep:serialport"]
ble = ["dep:btleplug", "dep:futures", "dep:uuid"]
rnode-tcp = []
ble = ["dep:btleplug", "dep:futures", "dep:uuid", "dep:bluer"]
ble_peer = ["ble"]
# See rns-transport's mobile-throttle. When enabled, auto-interface beacons
# and reverse-peering probes slow down in the background; BLE peer scan
@@ -26,7 +27,7 @@ tracing = { workspace = true }
socket2 = { workspace = true }
if-addrs = { workspace = true }
serialport = { workspace = true, optional = true }
btleplug = { workspace = true, optional = true }
btleplug = { version = "0.11", optional = true }
futures = { version = "0.3", optional = true }
uuid = { version = "1", optional = true }
rand = { workspace = true }
@@ -56,7 +57,7 @@ jni = "0.19"
# Linux-only target dep so non-Linux builds don't pull in BlueZ. The
# linux_peripheral module is gated by both `ble` feature and target_os.
[target.'cfg(target_os = "linux")'.dependencies]
bluer = { version = "0.17", features = ["bluetoothd"] }
bluer = { version = "0.17", features = ["bluetoothd"], optional = true }
# Windows BLE Peripheral via WinRT GattServiceProvider (MSIX-packaged apps).
# Windows-only target dep so cross-platform builds don't pull in WinRT
+81 -10
View File
@@ -1,7 +1,8 @@
//! USB serial RNode over Android USB-C OTG via JNI to `UsbManager`. 115200 8N1.
use std::sync::Arc;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use bytes::Bytes;
use tokio::sync::mpsc;
@@ -27,6 +28,60 @@ pub const KNOWN_VIDS: &[(u16, &str)] = &[
(0x1915, "Nordic Semiconductor NRF52840"),
];
type AndroidUsbRNodeStopRegistry = Mutex<HashMap<InterfaceId, mpsc::Sender<()>>>;
fn android_usb_rnode_stop_registry() -> &'static AndroidUsbRNodeStopRegistry {
static REGISTRY: OnceLock<AndroidUsbRNodeStopRegistry> = OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}
struct AndroidUsbRNodeStopRegistryGuard {
id: InterfaceId,
}
impl Drop for AndroidUsbRNodeStopRegistryGuard {
fn drop(&mut self) {
android_usb_rnode_stop_registry()
.lock()
.expect("android_usb_rnode_stop_registry mutex poisoned")
.remove(&self.id);
}
}
fn register_android_usb_rnode_stop(
id: InterfaceId,
stop_tx: mpsc::Sender<()>,
) -> AndroidUsbRNodeStopRegistryGuard {
android_usb_rnode_stop_registry()
.lock()
.expect("android_usb_rnode_stop_registry mutex poisoned")
.insert(id, stop_tx);
AndroidUsbRNodeStopRegistryGuard { id }
}
/// Ask an Android USB RNode interface to send upstream's detach sequence before
/// runtime teardown aborts the task. Idempotent; unknown ids are ignored.
pub fn stop_android_usb_rnode_interface(id: InterfaceId) {
let stop_tx = android_usb_rnode_stop_registry()
.lock()
.expect("android_usb_rnode_stop_registry mutex poisoned")
.get(&id)
.cloned();
let Some(stop_tx) = stop_tx else {
tracing::debug!(id, "Android USB RNode stop requested for unknown interface");
return;
};
match stop_tx.try_send(()) {
Ok(()) => tracing::info!(id, "Android USB RNode stop signal sent"),
Err(mpsc::error::TrySendError::Full(_)) => {
tracing::debug!(id, "Android USB RNode stop signal already pending")
}
Err(mpsc::error::TrySendError::Closed(_)) => {
tracing::debug!(id, "Android USB RNode stop signal receiver already closed")
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UsbSerialDevice {
pub device_name: String,
@@ -68,7 +123,6 @@ impl AndroidUsbConfig {
use jni::JavaVM;
use jni::objects::{GlobalRef, JObject, JValue};
use std::sync::OnceLock;
static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
static APP_CONTEXT: OnceLock<GlobalRef> = OnceLock::new();
@@ -453,7 +507,7 @@ async fn open_usb_serial(
let cw = connected.clone();
let vm = match JAVA_VM.get() {
Some(v) => v.clone(),
Some(v) => v,
None => return Err("JavaVM not initialized for USB write loop".into()),
};
let cr_w = conn_ref.clone();
@@ -487,7 +541,7 @@ async fn open_usb_serial(
let cr = connected.clone();
let vm2 = match JAVA_VM.get() {
Some(v) => v.clone(),
Some(v) => v,
None => return Err("JavaVM not initialized for USB read loop".into()),
};
tokio::task::spawn_blocking(move || {
@@ -572,17 +626,32 @@ pub async fn spawn_android_usb_rnode_interface(
let shared_rxb = Arc::new(AtomicU64::new(0));
let (tx, mut app_rx) = mpsc::channel::<Bytes>(64);
let (stop_tx, mut stop_rx) = mpsc::channel::<()>(1);
let stop_guard = register_android_usb_rnode_stop(id, stop_tx);
let txb = shared_txb.clone();
let wtx = raw_write_tx.clone();
let write_name = name.clone();
tokio::spawn(async move {
while let Some(payload) = app_rx.recv().await {
let frame = kiss::frame(&payload);
txb.fetch_add(frame.len() as u64, Ordering::Relaxed);
if wtx.send(frame).await.is_err() {
tracing::warn!(name = %write_name, "USB write channel closed");
break;
loop {
tokio::select! {
Some(payload) = app_rx.recv() => {
let frame = kiss::frame(&payload);
txb.fetch_add(frame.len() as u64, Ordering::Relaxed);
if wtx.send(frame).await.is_err() {
tracing::warn!(name = %write_name, "USB write channel closed");
break;
}
}
Some(_) = stop_rx.recv() => {
if wtx.send(rnode::build_detach_sequence()).await.is_err() {
tracing::warn!(name = %write_name, "USB detach sequence could not be queued");
} else {
tracing::info!(name = %write_name, "USB detach sequence queued");
}
break;
}
else => break,
}
}
});
@@ -593,6 +662,7 @@ pub async fn spawn_android_usb_rnode_interface(
let rxb = shared_rxb.clone();
let online = connected.clone();
let read_task = tokio::spawn(async move {
let _stop_guard = stop_guard;
let mut deframer = kiss::KissDeframer::new();
let mut last_rssi: Option<f32> = None;
let mut last_snr: Option<f32> = None;
@@ -625,6 +695,7 @@ pub async fn spawn_android_usb_rnode_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode: config.mode,
direction: InterfaceDirection {
+410 -66
View File
@@ -237,14 +237,38 @@ impl Default for AutoInterfaceConfig {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct PeerKey {
ip: Ipv6Addr,
scope_id: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PeerScopeSource {
Received,
LocalCandidate,
UnscopedNonLinkLocal,
}
#[derive(Debug, Clone)]
struct PeerScopeCandidate {
ifname: String,
scope_id: u32,
source: PeerScopeSource,
}
#[derive(Debug, Clone)]
struct Peer {
ip: Ipv6Addr,
ifname: String,
scope_id: u32,
scope_source: PeerScopeSource,
addr: SocketAddrV6,
last_seen: Instant,
last_reverse: Instant,
}
type PeerTable = Arc<Mutex<HashMap<Ipv6Addr, Peer>>>;
type PeerTable = Arc<Mutex<HashMap<PeerKey, Peer>>>;
#[derive(Debug, Clone)]
struct DeduplicateEntry {
@@ -334,6 +358,111 @@ fn normalize_link_local_addr(addr: Ipv6Addr) -> Ipv6Addr {
)
}
fn is_link_local_v6(addr: Ipv6Addr) -> bool {
(addr.segments()[0] & 0xffc0) == 0xfe80
}
fn peer_scope_candidates(
peer_ip: Ipv6Addr,
received_scope: u32,
link_locals: &[(String, Ipv6Addr, u32)],
) -> Vec<PeerScopeCandidate> {
// Python Reticulum associates AutoInterface peers with the receiving
// ifname and sends to fe80::peer%ifindex. Some platforms report scope 0
// from a wildcard-bound socket, so expand link-local peers to scoped local
// candidates instead of storing an unusable fe80::peer%0 address.
if received_scope != 0 {
let ifname = link_locals
.iter()
.find(|(_, _, scope_id)| *scope_id == received_scope)
.map(|(name, _, _)| name.clone())
.unwrap_or_else(|| format!("ifindex:{received_scope}"));
return vec![PeerScopeCandidate {
ifname,
scope_id: received_scope,
source: PeerScopeSource::Received,
}];
}
if !is_link_local_v6(peer_ip) {
return vec![PeerScopeCandidate {
ifname: String::new(),
scope_id: 0,
source: PeerScopeSource::UnscopedNonLinkLocal,
}];
}
let mut candidates = Vec::new();
for (ifname, _, scope_id) in link_locals {
if *scope_id == 0
|| candidates
.iter()
.any(|c: &PeerScopeCandidate| c.scope_id == *scope_id)
{
continue;
}
candidates.push(PeerScopeCandidate {
ifname: ifname.clone(),
scope_id: *scope_id,
source: PeerScopeSource::LocalCandidate,
});
}
candidates
}
fn upsert_peer_candidates(
table: &mut HashMap<PeerKey, Peer>,
peer_ip: Ipv6Addr,
data_port: u16,
received_scope: u32,
link_locals: &[(String, Ipv6Addr, u32)],
now: Instant,
source: &'static str,
) -> usize {
let candidates = peer_scope_candidates(peer_ip, received_scope, link_locals);
if candidates.is_empty() {
tracing::warn!(
peer = %peer_ip,
received_scope,
local_candidates = link_locals.len(),
source,
"auto: discovered link-local peer but no usable scope candidates are available"
);
return 0;
}
let mut inserted = 0usize;
for candidate in candidates {
let key = PeerKey {
ip: peer_ip,
scope_id: candidate.scope_id,
};
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, candidate.scope_id);
table
.entry(key)
.and_modify(|p| {
p.ifname = candidate.ifname.clone();
p.scope_id = candidate.scope_id;
p.scope_source = candidate.source;
p.addr = data_addr;
p.last_seen = now;
})
.or_insert_with(|| {
inserted += 1;
Peer {
ip: peer_ip,
ifname: candidate.ifname,
scope_id: candidate.scope_id,
scope_source: candidate.source,
addr: data_addr,
last_seen: now,
last_reverse: now,
}
});
}
inserted
}
/// Derive `ff_T_S_:0:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX` from address-type nibble,
/// scope nibble, and bytes 2..14 of `SHA-256(group_id)`.
pub fn derive_multicast_address(
@@ -779,9 +908,19 @@ fn get_link_local_addrs_android(
}
fn iface_scope_id(iface: &if_addrs::Interface) -> u32 {
iface
.index
.unwrap_or_else(|| iface_name_to_scope_id(&iface.name))
if let Some(index) = iface.index {
return index;
}
#[cfg(windows)]
{
let adapter_index = iface_name_to_scope_id(&iface.adapter_name);
if adapter_index != 0 {
return adapter_index;
}
}
iface_name_to_scope_id(&iface.name)
}
/// Convert interface name to scope ID via POSIX/Windows `if_nametoindex`.
@@ -841,6 +980,11 @@ fn bind_one(port: u16) -> std::io::Result<UdpSocket> {
UdpSocket::from_std(sock.into())
}
fn set_multicast_if_v6(sock: &UdpSocket, scope_id: u32) -> std::io::Result<()> {
let sock_ref = socket2::SockRef::from(sock);
sock_ref.set_multicast_if_v6(scope_id)
}
/// Diagnostic: probe alternate ports to localize bind failures.
#[cfg(target_os = "android")]
fn probe_alternate_ports(base: u16) {
@@ -927,6 +1071,15 @@ pub async fn spawn_auto_interface(
tracing::info!(name = %config.name, port = config.discovery_port, "auto discovery socket bound");
for (iface_name, _ll_addr, scope_id) in &initial_link_locals {
if let Err(e) = set_multicast_if_v6(disc_sock.as_ref(), *scope_id) {
tracing::warn!(
iface = %iface_name,
scope_id,
error = %e,
raw_os_error = ?e.raw_os_error(),
"failed to set IPv6 multicast outbound interface"
);
}
if let Err(e) = disc_sock.join_multicast_v6(&mcast_group, *scope_id) {
// EPERM/EACCES on Apple is the canonical signal that the
// multicast networking entitlement isn't provisioned (e.g. iOS
@@ -1001,16 +1154,38 @@ pub async fn spawn_auto_interface(
for (_name, ll_addr, scope_id) in &snapshot {
let beacon = make_beacon(&group_id, ll_addr);
let dest = SocketAddrV6::new(mcast_group, disc_port, 0, *scope_id);
if let Err(e) = set_multicast_if_v6(disc_sock_send.as_ref(), *scope_id) {
tracing::warn!(
iface = %_name,
ll = %ll_addr,
scope_id,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: failed to select multicast outbound interface"
);
}
let res = disc_sock_send.send_to(&beacon, dest).await;
tracing::debug!(
iface = %_name,
ll = %ll_addr,
scope_id,
dst = %dest,
hash = %hex32(&beacon),
sent = res.is_ok(),
"auto-instr beacon TX"
);
match res {
Ok(n) => tracing::debug!(
iface = %_name,
ll = %ll_addr,
scope_id,
dst = %dest,
hash = %hex32(&beacon),
sent_bytes = n,
"auto-instr beacon TX"
),
Err(e) => tracing::warn!(
iface = %_name,
ll = %ll_addr,
scope_id,
dst = %dest,
hash = %hex32(&beacon),
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: beacon TX failed"
),
}
}
}
});
@@ -1037,8 +1212,8 @@ pub async fn spawn_auto_interface(
if let SocketAddr::V6(src_v6) = src {
let peer_ip = *src_v6.ip();
// Match source LL against ours — non-empty means self-echo.
let snapshot = { disc_link_locals.lock().await.clone() };
let self_iface = {
let snapshot = disc_link_locals.lock().await;
snapshot
.iter()
.find(|(_, ll, _)| *ll == peer_ip)
@@ -1068,19 +1243,25 @@ pub async fn spawn_auto_interface(
if !match_ok {
continue;
}
let scope = src_v6.scope_id();
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope);
let received_scope = src_v6.scope_id();
let now = Instant::now();
let mut table = peers_disc.lock().await;
table
.entry(peer_ip)
.and_modify(|p| p.last_seen = now)
.or_insert(Peer {
addr: data_addr,
last_seen: now,
last_reverse: now,
});
tracing::debug!(peer = %peer_ip, "auto: peer discovered/refreshed");
let inserted = upsert_peer_candidates(
&mut table,
peer_ip,
data_port,
received_scope,
&snapshot,
now,
"multicast",
);
tracing::debug!(
peer = %peer_ip,
received_scope,
inserted,
peer_records = table.len(),
"auto: peer discovered/refreshed"
);
} else {
tracing::debug!(src = %src, "auto-instr mcast RX non-v6 source");
}
@@ -1099,16 +1280,19 @@ pub async fn spawn_auto_interface(
let unicast_group_id = config.group_id.clone();
let unicast_link_locals = link_locals.clone();
let unicast_disc_port = config.discovery_port + 1;
if let Ok(unicast_sock) = UdpSocket::bind(SocketAddrV6::new(
Ipv6Addr::UNSPECIFIED,
unicast_disc_port,
0,
0,
))
.await
{
let unicast_sock = Arc::new(unicast_sock);
let unicast_sock = match bind_reusable_udp_v6(unicast_disc_port) {
Ok(sock) => Some(Arc::new(sock)),
Err(e) => {
tracing::debug!(
port = unicast_disc_port,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: could not bind unicast discovery port"
);
None
}
};
if let Some(unicast_sock) = unicast_sock {
let urecv_sock = unicast_sock.clone();
let urecv_peers = peers_unicast.clone();
let urecv_online = online_u.clone();
@@ -1127,29 +1311,33 @@ pub async fn spawn_auto_interface(
}
if let SocketAddr::V6(src_v6) = src {
let peer_ip = *src_v6.ip();
let is_self = {
let snapshot = urecv_link_locals.lock().await;
snapshot.iter().any(|(_, ll, _)| *ll == peer_ip)
};
let snapshot = { urecv_link_locals.lock().await.clone() };
let is_self = { snapshot.iter().any(|(_, ll, _)| *ll == peer_ip) };
if is_self {
continue;
}
if !verify_beacon(&buf[..n], &urecv_group_id, &peer_ip) {
continue;
}
let scope = src_v6.scope_id();
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope);
let received_scope = src_v6.scope_id();
let now = Instant::now();
let mut table = urecv_peers.lock().await;
table
.entry(peer_ip)
.and_modify(|p| p.last_seen = now)
.or_insert(Peer {
addr: data_addr,
last_seen: now,
last_reverse: now,
});
tracing::debug!(peer = %peer_ip, "auto: unicast peer discovered");
let inserted = upsert_peer_candidates(
&mut table,
peer_ip,
data_port,
received_scope,
&snapshot,
now,
"unicast",
);
tracing::debug!(
peer = %peer_ip,
received_scope,
inserted,
peer_records = table.len(),
"auto: unicast peer discovered"
);
}
}
Err(e) => {
@@ -1194,26 +1382,42 @@ pub async fn spawn_auto_interface(
let snapshot = { rev_link_locals.lock().await.clone() };
let now = Instant::now();
let mut table = rev_peers.lock().await;
for (_ip, peer) in table.iter_mut() {
for (_key, peer) in table.iter_mut() {
if now.duration_since(peer.last_reverse).as_secs_f64()
>= REVERSE_PEERING_INTERVAL
{
for (_name, ll_addr, scope_id) in &snapshot {
let mut targets: Vec<_> = snapshot
.iter()
.filter(|(_, _, scope_id)| {
peer.scope_id == 0 || *scope_id == peer.scope_id
})
.collect();
if targets.is_empty() {
targets = snapshot.iter().collect();
}
for (_name, ll_addr, scope_id) in targets {
let beacon = make_beacon(&rev_group_id, ll_addr);
let dest =
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
let _ = unicast_sock.send_to(&beacon, dest).await;
if let Err(e) = unicast_sock.send_to(&beacon, dest).await {
tracing::debug!(
peer = %peer.ip,
peer_ifname = %peer.ifname,
peer_scope_id = peer.scope_id,
local_iface = %_name,
local_scope_id = scope_id,
dst = %dest,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: reverse peering TX failed"
);
}
}
peer.last_reverse = now;
}
}
}
});
} else {
tracing::debug!(
"auto: could not bind unicast discovery port {}",
unicast_disc_port
);
}
// Periodic jobs: NIC re-enum, peer aging, carrier detection (every PEER_JOB_INTERVAL).
@@ -1273,6 +1477,17 @@ pub async fn spawn_auto_interface(
);
}
for (ifname, addr, scope_id) in &added {
if let Err(e) = set_multicast_if_v6(jobs_disc_sock.as_ref(), *scope_id) {
tracing::warn!(
iface = %jobs_iface_name,
nic = %ifname,
addr = %addr,
scope_id,
error = %e,
raw_os_error = ?e.raw_os_error(),
"AutoInterface failed to set multicast interface for new NIC"
);
}
match jobs_disc_sock.join_multicast_v6(&jobs_mcast, *scope_id) {
Ok(()) => tracing::info!(
iface = %jobs_iface_name,
@@ -1360,18 +1575,46 @@ pub async fn spawn_auto_interface(
let prefix = hex_prefix(&data, 16);
let table = peers_write.lock().await;
let peer_count = table.len();
for (_ip, peer) in table.iter() {
let res = data_sock_w.send_to(&data, peer.addr).await;
if peer_count == 0 {
tracing::debug!(
dst = %peer.addr,
len,
prefix = %prefix,
peer_count,
sent = res.is_ok(),
"auto-instr data TX"
"auto-instr data TX skipped: no discovered peers"
);
if res.is_ok() {
task_txb.fetch_add(len as u64, Ordering::Relaxed);
}
for (_key, peer) in table.iter() {
let res = data_sock_w.send_to(&data, peer.addr).await;
match res {
Ok(n) => {
tracing::debug!(
peer = %peer.ip,
ifname = %peer.ifname,
scope_id = peer.scope_id,
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
sent_bytes = n,
prefix = %prefix,
peer_count,
"auto-instr data TX"
);
task_txb.fetch_add(len as u64, Ordering::Relaxed);
}
Err(e) => {
tracing::warn!(
peer = %peer.ip,
ifname = %peer.ifname,
scope_id = peer.scope_id,
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
prefix = %prefix,
peer_count,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: data TX failed"
);
}
}
}
}
@@ -1427,6 +1670,7 @@ pub async fn spawn_auto_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -1559,6 +1803,83 @@ mod tests {
assert!(!verify_beacon(&beacon[..16], "reticulum", &addr));
}
#[test]
fn peer_scope_candidates_preserves_received_scope() {
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let locals = vec![
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
];
let candidates = peer_scope_candidates(peer, 22, &locals);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].ifname, "eth0");
assert_eq!(candidates[0].scope_id, 22);
assert_eq!(candidates[0].source, PeerScopeSource::Received);
}
#[test]
fn peer_scope_candidates_expands_zero_scope_for_link_local() {
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let locals = vec![
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
("duplicate".to_string(), Ipv6Addr::LOCALHOST, 22),
];
let candidates = peer_scope_candidates(peer, 0, &locals);
assert_eq!(candidates.len(), 2);
assert_eq!(candidates[0].ifname, "en0");
assert_eq!(candidates[0].scope_id, 11);
assert_eq!(candidates[0].source, PeerScopeSource::LocalCandidate);
assert_eq!(candidates[1].ifname, "eth0");
assert_eq!(candidates[1].scope_id, 22);
}
#[test]
fn upsert_peer_candidates_keys_same_ip_by_scope() {
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let locals = vec![
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
];
let mut table = HashMap::new();
let inserted = upsert_peer_candidates(
&mut table,
peer,
DATA_PORT,
0,
&locals,
Instant::now(),
"test",
);
assert_eq!(inserted, 2);
assert_eq!(table.len(), 2);
assert!(table.contains_key(&PeerKey {
ip: peer,
scope_id: 11,
}));
assert!(table.contains_key(&PeerKey {
ip: peer,
scope_id: 22,
}));
assert_eq!(
table
.get(&PeerKey {
ip: peer,
scope_id: 11,
})
.unwrap()
.addr
.scope_id(),
11
);
}
#[test]
fn test_scope_id_prefers_enumerated_interface_index() {
let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
@@ -1566,6 +1887,29 @@ mod tests {
assert_eq!(iface_scope_id(&iface), 1234);
}
#[cfg(target_os = "linux")]
#[test]
fn if_addrs_link_local_feature_is_enabled() {
let proc_addrs = std::fs::read_to_string("/proc/net/if_inet6").unwrap_or_default();
let host_has_link_local = proc_addrs.lines().any(|line| {
line.split_whitespace()
.nth(3)
.is_some_and(|scope| scope.eq_ignore_ascii_case("20"))
});
if !host_has_link_local {
return;
}
let addrs = if_addrs::get_if_addrs().expect("list network interfaces");
assert!(
addrs.iter().any(|iface| {
matches!(&iface.addr, if_addrs::IfAddr::V6(addr) if addr.is_link_local())
}),
"Linux has link-local IPv6 addresses in /proc/net/if_inet6, but if-addrs returned none; \
keep the workspace if-addrs dependency feature `link-local` enabled"
);
}
fn test_interface(name: &str, ip: Ipv6Addr, index: Option<u32>) -> if_addrs::Interface {
let addr = if_addrs::IfAddr::V6(if_addrs::Ifv6Addr {
ip,
+1
View File
@@ -411,6 +411,7 @@ pub async fn spawn_ax25kiss_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+3
View File
@@ -291,6 +291,7 @@ pub async fn spawn_backbone_server(
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(id),
name: client_name,
mode,
direction: InterfaceDirection {
@@ -323,6 +324,7 @@ pub async fn spawn_backbone_server(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -490,6 +492,7 @@ pub async fn spawn_backbone_client(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+317 -91
View File
@@ -18,9 +18,11 @@
//!
//! ## Fragmentation
//!
//! Packets larger than (MTU - 3) use a 5-byte header
//! `[type:1][seq:2-BE][total:2-BE]`. Types: LONE / START / CONTINUE / END.
//! Reassembly timeout 30s.
//! Packets larger than (MTU - 3), and small packets whose first byte would
//! collide with START / CONTINUE / END frame tags, use a 5-byte header
//! `[type:1][seq:2-BE][total:2-BE]`. Reassembly timeout 30s. Small ambiguous
//! 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.
@@ -262,7 +264,7 @@ async fn scan_sleep(
pub const TARGET_MTU: u16 = 517;
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FragmentType {
Lone = 0x00,
Start = 0x01,
@@ -270,6 +272,18 @@ pub enum FragmentType {
End = 0x03,
}
impl FragmentType {
fn from_byte(byte: u8) -> Option<Self> {
match byte {
0x00 => Some(Self::Lone),
0x01 => Some(Self::Start),
0x02 => Some(Self::Continue),
0x03 => Some(Self::End),
_ => None,
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BlePeer {
/// 16-byte hex Reticulum identity hash.
@@ -431,20 +445,92 @@ impl BlePeerConfig {
}
}
const FRAGMENT_HEADER_LEN: usize = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FragmentHeader {
kind: FragmentType,
seq: u16,
total: u16,
}
type FragmentReassembly = HashMap<u16, (Vec<Option<Vec<u8>>>, Instant)>;
fn raw_packet_needs_fragment_envelope(data: &[u8]) -> bool {
matches!(
data.first().copied(),
Some(x)
if x == FragmentType::Start as u8
|| x == FragmentType::Continue as u8
|| x == FragmentType::End as u8
)
}
fn make_fragment(kind: FragmentType, seq: u16, total: u16, payload: &[u8]) -> Vec<u8> {
let mut frag = Vec::with_capacity(FRAGMENT_HEADER_LEN + payload.len());
frag.push(kind as u8);
frag.extend_from_slice(&seq.to_be_bytes());
frag.extend_from_slice(&total.to_be_bytes());
frag.extend_from_slice(payload);
frag
}
fn parse_fragment_header(data: &[u8]) -> Option<FragmentHeader> {
if data.len() < FRAGMENT_HEADER_LEN {
return None;
}
let kind = FragmentType::from_byte(data[0])?;
if kind == FragmentType::Lone {
// Reticulum DATA packets commonly start with 0x00. This transport no
// longer emits explicit LONE frames, so preserve 0x00 as legacy raw
// packet data and only parse START/CONTINUE/END envelopes.
return None;
}
let seq = u16::from_be_bytes([data[1], data[2]]);
let total = u16::from_be_bytes([data[3], data[4]]);
if total == 0 || seq >= total {
return None;
}
let valid = match kind {
FragmentType::Lone => false,
FragmentType::Start => seq == 0 && total >= 2,
FragmentType::Continue => total >= 3 && seq > 0 && seq < total - 1,
FragmentType::End => total >= 2 && seq == total - 1,
};
valid.then_some(FragmentHeader { kind, seq, total })
}
pub fn fragment_packet(data: &[u8], mtu: usize) -> Vec<Vec<u8>> {
let payload_mtu = mtu.saturating_sub(5); // 5-byte header
if payload_mtu == 0 || data.len() <= mtu.saturating_sub(3) {
let payload_mtu = mtu.saturating_sub(FRAGMENT_HEADER_LEN);
if payload_mtu == 0 {
return vec![data.to_vec()];
}
// Raw packets beginning with 0x01/0x02/0x03 collide with START/CONTINUE/END
// frame tags. Direct LXMF LinkRequests are Header1 packets whose first byte
// is 0x02, so they must be enveloped even when they fit in a single ATT
// write. Use a two-frame START/END sequence instead of a LONE frame so
// peers with the older reassembler can still decode the packet.
if data.len() <= mtu.saturating_sub(3) && !raw_packet_needs_fragment_envelope(data) {
return vec![data.to_vec()];
}
let chunks: Vec<&[u8]> = data.chunks(payload_mtu).collect();
if chunks.len() == 1 {
return vec![
make_fragment(FragmentType::Start, 0, 2, chunks[0]),
make_fragment(FragmentType::End, 1, 2, &[]),
];
}
let total = chunks.len() as u16;
let mut fragments = Vec::with_capacity(chunks.len());
for (i, chunk) in chunks.iter().enumerate() {
let ftype = if chunks.len() == 1 {
FragmentType::Lone
} else if i == 0 {
let ftype = if i == 0 {
FragmentType::Start
} else if i == chunks.len() - 1 {
FragmentType::End
@@ -453,12 +539,7 @@ pub fn fragment_packet(data: &[u8], mtu: usize) -> Vec<Vec<u8>> {
};
let seq = i as u16;
let mut frag = Vec::with_capacity(5 + chunk.len());
frag.push(ftype as u8);
frag.extend_from_slice(&seq.to_be_bytes());
frag.extend_from_slice(&total.to_be_bytes());
frag.extend_from_slice(chunk);
fragments.push(frag);
fragments.push(make_fragment(ftype, seq, total, chunk));
}
fragments
@@ -469,16 +550,79 @@ pub fn reassemble_fragments(fragments: &[Vec<u8>]) -> Option<Vec<u8>> {
return None;
}
let mut result = Vec::new();
let mut total: Option<u16> = None;
let mut parts: Vec<Option<&[u8]>> = Vec::new();
for frag in fragments {
if frag.len() < 5 {
let header = parse_fragment_header(frag)?;
if total.is_some_and(|expected| expected != header.total) {
return None;
}
result.extend_from_slice(&frag[5..]);
if total.is_none() {
total = Some(header.total);
parts.resize(header.total as usize, None);
}
let slot = parts.get_mut(header.seq as usize)?;
if slot.is_some() {
return None;
}
*slot = Some(&frag[FRAGMENT_HEADER_LEN..]);
}
let mut result = Vec::new();
for part in parts {
result.extend_from_slice(part?);
}
Some(result)
}
fn consume_ble_frame(data: Vec<u8>, reassembly: &mut FragmentReassembly) -> Option<Vec<u8>> {
let Some(header) = parse_fragment_header(&data) else {
return Some(data);
};
if header.kind != FragmentType::Start && !reassembly.contains_key(&header.total) {
// CONTINUE/END cannot begin a real fragment set on an ordered BLE
// characteristic. Treat it as a legacy raw Reticulum packet instead;
// this lets updated receivers accept old raw Header1 LinkRequest
// packets that begin with 0x02 when no matching START was observed.
return Some(data);
}
if header.kind == FragmentType::Start {
reassembly.insert(
header.total,
(vec![None; header.total as usize], Instant::now()),
);
}
let entry = reassembly
.entry(header.total)
.or_insert_with(|| (vec![None; header.total as usize], Instant::now()));
if entry.0.len() != header.total as usize {
entry.0 = vec![None; header.total as usize];
entry.1 = Instant::now();
}
entry.0[header.seq as usize] = Some(data[FRAGMENT_HEADER_LEN..].to_vec());
if header.kind != FragmentType::End {
return None;
}
if entry.0.iter().any(|part| part.is_none()) {
return None;
}
let (parts, _) = reassembly.remove(&header.total)?;
let mut result = Vec::new();
for part in parts {
result.extend_from_slice(&part?);
}
Some(result)
}
fn prune_reassembly(reassembly: &mut FragmentReassembly) {
reassembly.retain(|_, (_, started)| started.elapsed() < FRAGMENT_TIMEOUT);
}
/// 60s positive-ID cache for the btleplug scan path. WinRT's advertisement
/// parse is empirically eventually-consistent: the same iOS RPA can yield
/// services_count=1 in one 3s scan window and 0 in the next, even when iOS
@@ -2862,7 +3006,7 @@ mod android_peripheral {
if raw.is_null() {
return String::new();
}
let jstr: jni::objects::JString = unsafe { jni::objects::JObject::from(raw) }.into();
let jstr: jni::objects::JString = jni::objects::JObject::from(raw).into();
env.get_string(jstr)
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default()
@@ -2942,6 +3086,7 @@ mod android_peripheral {
/// characteristic, optionally excluding `exclude_address` (used by the
/// anti-loop filter to skip echoing a packet back to the peer it arrived
/// from). Returns the number of subscribers we attempted to notify.
#[allow(dead_code)]
pub fn broadcast_notify_tx(char_uuid: Uuid, data: &[u8], exclude_address: Option<&str>) -> i32 {
with_env(|env| {
let server_cls = find_app_class(env, "org.ratspeak.android.RatspeakBleServer")
@@ -4121,7 +4266,10 @@ mod windows_peripheral {
/// own `CBCentralManager` and two managers in one process don't share
/// peripheral caches on macOS); Android drives the same primitives via JNI
/// in `RatspeakBlePeerClient.kt`.
#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))]
#[cfg(all(
feature = "ble",
not(any(target_os = "android", target_os = "ios", target_os = "macos"))
))]
struct MeshPeerConnection {
peripheral: btleplug::platform::Peripheral,
rx_char: btleplug::api::Characteristic,
@@ -4141,7 +4289,10 @@ struct MeshPeerConnection {
///
/// Linux + Windows only — see [`MeshPeerConnection`] header for why Apple
/// uses a parallel native path.
#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))]
#[cfg(all(
feature = "ble",
not(any(target_os = "android", target_os = "ios", target_os = "macos"))
))]
async fn connect_mesh_peer(
adapter: &btleplug::platform::Adapter,
peer: &BlePeer,
@@ -4289,7 +4440,10 @@ async fn connect_mesh_peer(
/// to transport. Linux + Windows only — Apple's notify delegate pushes
/// directly into `apple_peripheral::INBOUND_TX` so the global per-peer
/// reassembler handles inbound without a per-connection task.
#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))]
#[cfg(all(
feature = "ble",
not(any(target_os = "android", target_os = "ios", target_os = "macos"))
))]
struct PeerReadLoopCtx {
interface_id: InterfaceId,
transport_tx: mpsc::Sender<TransportMessage>,
@@ -4301,7 +4455,10 @@ struct PeerReadLoopCtx {
anti_loop: AntiLoopMap,
}
#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))]
#[cfg(all(
feature = "ble",
not(any(target_os = "android", target_os = "ios", target_os = "macos"))
))]
async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
let PeerReadLoopCtx {
interface_id,
@@ -4326,8 +4483,8 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
}
};
// Fragment reassembly buffer: maps (total_count) → accumulated fragments
let mut reassembly: HashMap<u16, (Vec<Vec<u8>>, Instant)> = HashMap::new();
// Fragment reassembly buffer: maps total_count to per-sequence payload slots.
let mut reassembly: FragmentReassembly = HashMap::new();
let mut missed_keepalives: u32 = 0;
loop {
@@ -4396,33 +4553,7 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
continue;
}
// Check if this is a fragmented packet (has 5-byte header)
let first_byte = data[0];
let complete_packet = if first_byte == FragmentType::Lone as u8
|| (first_byte > FragmentType::End as u8)
{
// LONE or no header — complete packet
Some(data)
} else if data.len() >= 5 {
let total = u16::from_be_bytes([data[3], data[4]]);
let entry = reassembly
.entry(total)
.or_insert_with(|| (Vec::new(), Instant::now()));
entry.0.push(data);
if first_byte == FragmentType::End as u8 {
// All fragments received — reassemble. Invariant: the
// entry was just inserted via `or_insert_with` above.
let (frags, _) = reassembly
.remove(&total)
.expect("reassembly entry must exist: inserted above");
reassemble_fragments(&frags)
} else {
None
}
} else {
Some(data) // Short data without valid header — treat as complete
};
let complete_packet = consume_ble_frame(data, &mut reassembly);
// Forward complete packet to transport
if let Some(raw) = complete_packet {
@@ -4445,7 +4576,7 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
}
// Clean up timed-out reassembly buffers
reassembly.retain(|_, (_, started)| started.elapsed() < FRAGMENT_TIMEOUT);
prune_reassembly(&mut reassembly);
}
Some(_) => {} // Notification from other characteristic — ignore
None => {
@@ -4473,7 +4604,10 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
/// characteristic via btleplug. Linux + Windows only — Apple's outbound
/// path lives inline in the spawn body and calls
/// `ble_central_apple_connect::write_peer` per fragment.
#[cfg(all(feature = "ble", not(any(target_os = "ios", target_os = "macos"))))]
#[cfg(all(
feature = "ble",
not(any(target_os = "android", target_os = "ios", target_os = "macos"))
))]
async fn peer_write_loop(
peripheral: btleplug::platform::Peripheral,
rx_char: btleplug::api::Characteristic,
@@ -4640,7 +4774,7 @@ pub async fn spawn_ble_peer_interface(
// (BluetoothDevice MAC on Android; CBCentral.identifier UUID
// string on Apple). Two peers writing fragments concurrently
// can no longer corrupt each other's reassembly buffers.
type PeerReassembly = HashMap<u16, (Vec<Vec<u8>>, Instant)>;
type PeerReassembly = FragmentReassembly;
let mut reassembly: HashMap<String, PeerReassembly> = HashMap::new();
// Identity is learned from the first signed Reticulum announce.
// Emit once per peer address so callers can dedupe
@@ -4662,29 +4796,8 @@ pub async fn spawn_ble_peer_interface(
if data.is_empty() || (data.len() == 1 && data[0] == 0x00) {
continue; // Empty or keepalive
}
let first = data[0];
let per_peer = reassembly.entry(peer.clone()).or_default();
let complete =
if first == FragmentType::Lone as u8 || first > FragmentType::End as u8 {
Some(data)
} else if data.len() >= 5 {
let total = u16::from_be_bytes([data[3], data[4]]);
let entry = per_peer
.entry(total)
.or_insert_with(|| (Vec::new(), Instant::now()));
entry.0.push(data);
if first == FragmentType::End as u8 {
// Invariant: `or_insert_with` just inserted `total`.
let (frags, _) = per_peer
.remove(&total)
.expect("per-peer reassembly entry must exist: inserted above");
reassemble_fragments(&frags)
} else {
None
}
} else {
Some(data)
};
let complete = consume_ble_frame(data, per_peer);
if let Some(raw) = complete {
rxb.fetch_add(raw.len() as u64, Ordering::Relaxed);
@@ -4746,7 +4859,7 @@ pub async fn spawn_ble_peer_interface(
// Drop expired reassembly buffers (per peer, then per fragment-set).
for buf in reassembly.values_mut() {
buf.retain(|_, (_, t)| t.elapsed() < FRAGMENT_TIMEOUT);
prune_reassembly(buf);
}
reassembly.retain(|_, m| !m.is_empty());
}
@@ -5201,7 +5314,6 @@ pub async fn spawn_ble_peer_interface(
tokio::spawn(async move {
let mut connected_addrs: HashMap<String, Arc<AtomicBool>> = HashMap::new();
let mut scan_interval = SCAN_ACTIVE_INTERVAL;
loop {
if !running_flag().load(Ordering::SeqCst) {
tracing::info!("Apple BLE mesh Central scan loop: shutdown signal, exiting");
@@ -5479,7 +5591,6 @@ pub async fn spawn_ble_peer_interface(
// new peer powers on, long enough to catch low-duty-cycle adverts.
const SCAN_TIMEOUT_MS: i64 = 3000;
let mut connected_addrs: HashMap<String, Arc<AtomicBool>> = HashMap::new();
let mut scan_interval = SCAN_ACTIVE_INTERVAL;
loop {
if !running_flag().load(Ordering::SeqCst) {
@@ -5518,12 +5629,12 @@ pub async fn spawn_ble_peer_interface(
.await
.unwrap_or_default();
scan_interval = if !scan_results.is_empty() || has_wanted_reconnects(&recently_disc)
{
SCAN_ACTIVE_INTERVAL
} else {
SCAN_IDLE_INTERVAL
};
let scan_interval =
if !scan_results.is_empty() || has_wanted_reconnects(&recently_disc) {
SCAN_ACTIVE_INTERVAL
} else {
SCAN_IDLE_INTERVAL
};
for (addr, rssi, protocol) in &scan_results {
if connected_addrs.contains_key(addr) {
@@ -5702,6 +5813,7 @@ pub async fn spawn_ble_peer_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode: config.mode,
direction: InterfaceDirection {
@@ -5732,12 +5844,56 @@ mod tests {
#[test]
fn test_fragmentation_lone() {
let data = vec![1, 2, 3, 4, 5];
let data = vec![0x04, 2, 3, 4, 5];
let frags = fragment_packet(&data, 100);
assert_eq!(frags.len(), 1);
assert_eq!(frags[0], data);
}
#[test]
fn test_fragmentation_envelopes_ambiguous_small_packets() {
for first in [
FragmentType::Start as u8,
FragmentType::Continue as u8,
FragmentType::End as u8,
] {
let mut data = vec![first];
data.extend(1u8..80u8);
let frags = fragment_packet(&data, 100);
assert_eq!(frags.len(), 2);
assert_eq!(frags[0][0], FragmentType::Start as u8);
assert_eq!(frags[1][0], FragmentType::End as u8);
assert_eq!(reassemble_fragments(&frags).unwrap(), data);
}
}
#[test]
fn test_direct_link_request_header_is_not_sent_raw() {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::LinkRequest,
},
hops: 0,
transport_id: None,
destination_hash: [0xAA; 16],
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(&[0x55; 64]);
assert_eq!(raw[0], FragmentType::Continue as u8);
let frags = fragment_packet(&raw, 500);
assert_eq!(frags.len(), 2);
assert_eq!(frags[0][0], FragmentType::Start as u8);
assert_eq!(frags[1][0], FragmentType::End as u8);
assert_eq!(reassemble_fragments(&frags).unwrap(), raw);
}
#[test]
fn test_fragmentation_multi() {
let data = vec![0u8; 200];
@@ -5804,7 +5960,7 @@ mod tests {
#[test]
fn test_fragmentation_mtu_too_small() {
// MTU <= 5 means payload_mtu = 0, should produce LONE frame
// MTU <= 5 means payload_mtu = 0, so we cannot add an envelope.
let data = vec![1, 2, 3];
let frags = fragment_packet(&data, 5);
assert_eq!(frags.len(), 1);
@@ -5864,12 +6020,82 @@ mod tests {
#[test]
fn test_reassemble_header_only() {
// Fragment with only a 5-byte header (no payload)
let frag = vec![FragmentType::Start as u8, 0, 0, 0, 1];
let result = reassemble_fragments(&[frag]);
// A two-frame empty payload is valid; START(total=1) is not.
let start = vec![FragmentType::Start as u8, 0, 0, 0, 2];
let end = vec![FragmentType::End as u8, 0, 1, 0, 2];
let result = reassemble_fragments(&[start, end]);
assert_eq!(result, Some(vec![]));
}
#[test]
fn test_reassemble_rejects_invalid_start_total() {
let frag = vec![FragmentType::Start as u8, 0, 0, 0, 1];
assert!(reassemble_fragments(&[frag]).is_none());
}
#[test]
fn test_consume_ble_frame_preserves_legacy_raw_data_zero() {
let raw = vec![0x00, 0x00, 0x00, 0x00, 0x01, 0xAA, 0xBB];
let mut reassembly = FragmentReassembly::new();
assert_eq!(consume_ble_frame(raw.clone(), &mut reassembly), Some(raw));
assert!(reassembly.is_empty());
}
#[test]
fn test_consume_ble_frame_preserves_legacy_raw_link_request_without_start() {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::LinkRequest,
},
hops: 0,
transport_id: None,
destination_hash: [0xAA; 16],
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(&[0x55; 64]);
assert_eq!(raw[0], FragmentType::Continue as u8);
let mut reassembly = FragmentReassembly::new();
assert_eq!(consume_ble_frame(raw.clone(), &mut reassembly), Some(raw));
assert!(reassembly.is_empty());
}
#[test]
fn test_consume_ble_frame_decodes_enveloped_link_request() {
let raw = {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::LinkRequest,
},
hops: 0,
transport_id: None,
destination_hash: [0x11; 16],
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(&[0x22; 64]);
raw
};
let frags = fragment_packet(&raw, 500);
let mut reassembly = FragmentReassembly::new();
assert_eq!(consume_ble_frame(frags[0].clone(), &mut reassembly), None);
assert_eq!(
consume_ble_frame(frags[1].clone(), &mut reassembly),
Some(raw)
);
assert!(reassembly.is_empty());
}
// ── Service UUIDs ──
#[test]
+147 -57
View File
@@ -46,9 +46,12 @@ const RECONNECT_WAIT_MAX: u64 = 120;
/// `None` retries forever; teardown goes via `stop_ble_rnode_interface`.
const MAX_RECONNECT_TRIES: Option<usize> = None;
const SCAN_TIMEOUT: u64 = 3;
const CONNECT_TIMEOUT: u64 = 5;
/// Bounds disable-while-offline teardown latency to ~1s.
const RUNNING_POLL: Duration = Duration::from_secs(1);
#[cfg(target_os = "linux")]
const RNODE_POST_BOND_SETTLE: Duration = Duration::from_millis(2600);
const RNODE_NATIVE_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(6);
const RNODE_NATIVE_HANDSHAKE_PROBE: Duration = Duration::from_millis(650);
/// `stop_ble_rnode_interface` flips false; the read_task removes the entry
/// on its way out.
@@ -117,38 +120,77 @@ async fn wait_or_shutdown(total: Duration, flag: &AtomicBool) -> bool {
!flag.load(Ordering::SeqCst)
}
/// RNode can pack multiple frames in one read, so use the raw deframer for
/// full-command extended KISS framing.
async fn wait_for_rnode_handshake(
fn is_rnode_handshake_frame(cmd: u8, frame: &[u8]) -> bool {
(cmd == rnode::CMD_DETECT && frame.first().copied() == Some(rnode::DETECT_RESP))
|| (cmd == rnode::CMD_FW_VERSION && !frame.is_empty())
}
fn is_pairing_transition_error(error: &InterfaceError) -> bool {
matches!(
error,
InterfaceError::SendFailed(message) if message.starts_with("BLE pairing in progress:")
)
}
/// Android's native bridge can come up immediately after SMP completes, while
/// rsCardputer's RNode BLE stack is still settling. Probe detect a few times
/// inside one connection attempt so a single dropped early frame does not cost
/// a full reconnect backoff.
async fn probe_native_rnode_handshake(
tcp_read: &mut tokio::net::tcp::OwnedReadHalf,
tcp_write: &mut tokio::net::tcp::OwnedWriteHalf,
timeout: Duration,
probe_interval: Duration,
running_task: &AtomicBool,
) -> bool {
use tokio::io::AsyncReadExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let detect_seq = rnode::build_detect_sequence();
let mut deframer = kiss::RawKissDeframer::new();
let mut buf = [0u8; 1024];
let deadline = std::time::Instant::now() + timeout;
let mut next_probe = std::time::Instant::now();
while std::time::Instant::now() < deadline {
if !running_task.load(Ordering::SeqCst) {
return false;
}
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
let read = tokio::time::timeout(remaining.min(RUNNING_POLL), tcp_read.read(&mut buf)).await;
let now = std::time::Instant::now();
if now >= next_probe {
if let Err(e) = tcp_write.write_all(&detect_seq).await {
tracing::warn!(error = %e, "BLE RNode native detect probe write failed");
return false;
}
let _ = tcp_write.flush().await;
next_probe = std::time::Instant::now() + probe_interval;
}
let now = std::time::Instant::now();
let read_budget = next_probe
.min(deadline)
.saturating_duration_since(now)
.min(RUNNING_POLL);
if read_budget.is_zero() {
tokio::task::yield_now().await;
continue;
}
let read = tokio::time::timeout(read_budget, tcp_read.read(&mut buf)).await;
let n = match read {
Ok(Ok(0)) => return false,
Ok(Ok(n)) => n,
Ok(Err(_)) => return false,
Err(_) => continue,
};
for (cmd, frame) in deframer.feed(&buf[..n]) {
if cmd == rnode::CMD_DETECT && frame.first().copied() == Some(rnode::DETECT_RESP) {
return true;
}
if cmd == rnode::CMD_FW_VERSION && !frame.is_empty() {
if is_rnode_handshake_frame(cmd, &frame) {
return true;
}
}
}
false
}
@@ -584,6 +626,11 @@ struct BleRNodeConnection {
write_mtu: usize,
}
enum NativeBridgeWrite {
Packet(Bytes),
Raw(Vec<u8>),
}
async fn connect_rnode(
adapter: &Adapter,
ble_uri: &str,
@@ -592,6 +639,18 @@ async fn connect_rnode(
let peripheral = resolve_ble_target(adapter, ble_uri).await?;
ble_diag(format!("[ble] resolved peripheral id={}", peripheral.id()));
#[cfg(target_os = "linux")]
{
// BlueZ needs explicit pairing before we open a btleplug GATT
// connection. If this creates a fresh bond, RNode intentionally
// disconnects shortly afterwards; wait through that before connect().
let bluer_addr = parse_linux_ble_address(&peripheral.address().to_string())?;
if linux_trigger_pairing(bluer_addr).await? {
ble_diag("[pair][linux] fresh bond complete — waiting for RNode post-pair disconnect");
tokio::time::sleep(RNODE_POST_BOND_SETTLE).await;
}
}
let mut last_err = String::new();
for attempt in 1..=3 {
match peripheral.connect().await {
@@ -657,18 +716,10 @@ async fn connect_rnode(
// SMP must run BEFORE subscribe on desktop / Apple platforms — reading
// the encrypted TX char kicks off SMP and drops L2CAP, which kills any
// pending subscribe. iOS/macOS share CoreBluetooth; Windows uses WinRT
// GATT (auto-prompt on encrypted-char reads). Same trigger shape works
// for all three. Linux uses bluer's explicit `Device::pair()` instead —
// BlueZ does not auto-prompt SMP from an encrypted-char read.
// GATT (auto-prompt on encrypted-char reads). Linux used explicit BlueZ
// pairing before `connect()`, above.
#[cfg(any(target_os = "ios", target_os = "macos", target_os = "windows"))]
desktop_trigger_pairing(&peripheral, &tx_char).await?;
#[cfg(target_os = "linux")]
{
// peripheral.address() returns a BDAddr → MAC string; the helper
// also accepts BlueZ D-Bus paths for callers that pass `id()`.
let bluer_addr = parse_linux_ble_address(&peripheral.address().to_string())?;
linux_trigger_pairing(bluer_addr).await?;
}
ble_diag("[ble] subscribe TX start");
peripheral.subscribe(&tx_char).await.map_err(|e| {
@@ -896,7 +947,7 @@ fn parse_linux_ble_address(addr: &str) -> Result<bluer::Address, InterfaceError>
/// daemon stops retrying SMP instead of re-invoking `request_passkey`
/// every ~60s.
#[cfg(target_os = "linux")]
async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), InterfaceError> {
async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<bool, InterfaceError> {
let overall_start = std::time::Instant::now();
// Reuse the cached session so the second-and-subsequent attempts skip
@@ -927,7 +978,7 @@ async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), Interfa
"[pair][linux] already bonded with {bluer_addr} (is_paired check {:.2}s)",
t_paired.elapsed().as_secs_f32()
));
return Ok(());
return Ok(false);
}
ble_diag(format!(
"[pair][linux] is_paired=false in {:.2}s",
@@ -1049,7 +1100,7 @@ async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), Interfa
}
}
let _ = linux_pairing_finished_sender().send(LinuxPairingFinished { attempt_id, status });
outcome
outcome.map(|()| true)
}
/// WithoutResponse is fire-and-forget at the ATT layer; the radio still
@@ -1069,6 +1120,14 @@ pub(crate) async fn ble_write(
Ok(())
}
async fn ble_send_radio_off(conn: &BleRNodeConnection) {
let seq = rnode::build_detach_sequence();
match ble_write(&conn.peripheral, &conn.rx_char, &seq, conn.write_mtu).await {
Ok(()) => ble_diag("[ble] detach sent before disconnect"),
Err(e) => ble_diag(format!("[ble] detach before disconnect failed: {e}")),
}
}
/// Auto-reconnect across drops; resolve_ble_target re-runs every retry so
/// iOS RPA rotation heals automatically.
pub async fn spawn_ble_rnode_interface(
@@ -1154,9 +1213,11 @@ pub async fn spawn_ble_rnode_interface(
let conn = match connect_rnode(&adapter, &ble_uri).await {
Ok(c) => c,
Err(e) => {
let pairing_transition = is_pairing_transition_error(&e);
let retry_wait = if pairing_transition { 1 } else { backoff };
tracing::warn!(name = %log_name, error = %e, "BLE RNode connect failed");
ble_diag(format!(
"[ble] connect_rnode err: {e} — retrying in {backoff}s (attempt {})",
"[ble] connect_rnode err: {e} — retrying in {retry_wait}s (attempt {})",
tries + 1
));
if reconnect_try_exhausted(&mut tries) {
@@ -1164,10 +1225,14 @@ pub async fn spawn_ble_rnode_interface(
ble_diag("[ble] max reconnect tries reached — giving up");
return;
}
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
if wait_or_shutdown(Duration::from_secs(retry_wait), &running_task).await {
return;
}
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
if pairing_transition {
backoff = RECONNECT_WAIT;
} else {
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
}
continue;
}
};
@@ -1286,16 +1351,21 @@ pub async fn spawn_ble_rnode_interface(
let mut transport_closed = false;
'read: loop {
if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) {
if !online_handle.load(Ordering::SeqCst) {
break 'read;
}
if !running_task.load(Ordering::SeqCst) {
ble_send_radio_off(&conn).await;
break 'read;
}
let notification = tokio::select! {
n = notification_stream.next() => n,
_ = tokio::time::sleep(Duration::from_secs(CONNECT_TIMEOUT)) => {
_ = tokio::time::sleep(RUNNING_POLL) => {
// Polling slice — bounds disable-while-connected
// teardown latency.
if !running_task.load(Ordering::SeqCst) {
ble_send_radio_off(&conn).await;
break 'read;
}
if conn.peripheral.is_connected().await.unwrap_or(false) {
@@ -1368,6 +1438,7 @@ pub async fn spawn_ble_rnode_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -1471,22 +1542,17 @@ pub async fn spawn_ble_rnode_interface_native(
let (mut tcp_read, mut tcp_write) = stream.into_split();
let detect_seq = rnode::build_detect_sequence();
if let Err(e) = tcp_write.write_all(&detect_seq).await {
tracing::warn!(error = %e, "BLE RNode native detect write failed");
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
return;
}
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
continue;
}
// Without gating on DETECT_RESP + firmware version we'd flag
// "online" while the radio is asleep or the BLE-NUS bridge
// dropped a frame.
let detected =
wait_for_rnode_handshake(&mut tcp_read, Duration::from_secs(5), &running_task)
.await;
let detected = probe_native_rnode_handshake(
&mut tcp_read,
&mut tcp_write,
RNODE_NATIVE_HANDSHAKE_TIMEOUT,
RNODE_NATIVE_HANDSHAKE_PROBE,
&running_task,
)
.await;
if !detected {
tracing::warn!(
name = %log_name,
@@ -1524,26 +1590,38 @@ pub async fn spawn_ble_rnode_interface_native(
let ready = Arc::new(AtomicBool::new(true));
let (conn_tx, mut conn_rx) = mpsc::channel::<Bytes>(256);
let (conn_tx, mut conn_rx) = mpsc::channel::<NativeBridgeWrite>(256);
let conn_tx_for_stop = conn_tx.clone();
let online_w = online_handle.clone();
let ready_w = ready.clone();
let txb_w = task_txb.clone();
let write_handle = tokio::spawn(async move {
while let Some(data) = conn_rx.recv().await {
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
if flow_control {
while !ready_w.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
while let Some(msg) = conn_rx.recv().await {
match msg {
NativeBridgeWrite::Packet(data) => {
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
if flow_control {
while !ready_w.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
}
}
}
let framed = kiss::frame(&data);
if let Err(e) = tcp_write.write_all(&framed).await {
tracing::warn!(error = %e, "BLE RNode native write error");
online_w.store(false, Ordering::SeqCst);
return;
}
}
}
let framed = kiss::frame(&data);
if let Err(e) = tcp_write.write_all(&framed).await {
tracing::warn!(error = %e, "BLE RNode native write error");
online_w.store(false, Ordering::SeqCst);
return;
NativeBridgeWrite::Raw(data) => {
if let Err(e) = tcp_write.write_all(&data).await {
tracing::warn!(error = %e, "BLE RNode native raw write error");
}
let _ = tcp_write.flush().await;
return;
}
}
}
});
@@ -1554,7 +1632,7 @@ pub async fn spawn_ble_rnode_interface_native(
let fwd_handle = tokio::spawn(async move {
let mut guard = rx_ref.lock().await;
while let Some(data) = guard.recv().await {
if conn_tx.send(data).await.is_err() {
if conn_tx.send(NativeBridgeWrite::Packet(data)).await.is_err() {
break;
}
}
@@ -1567,7 +1645,14 @@ pub async fn spawn_ble_rnode_interface_native(
let mut transport_closed = false;
'read: loop {
if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) {
if !online_handle.load(Ordering::SeqCst) {
break 'read;
}
if !running_task.load(Ordering::SeqCst) {
let _ = conn_tx_for_stop
.send(NativeBridgeWrite::Raw(rnode::build_detach_sequence()))
.await;
tokio::time::sleep(Duration::from_millis(100)).await;
break 'read;
}
@@ -1589,6 +1674,10 @@ pub async fn spawn_ble_rnode_interface_native(
// Idle LoRa silence is normal — only break if
// shutdown flag cleared.
if !running_task.load(Ordering::SeqCst) {
let _ = conn_tx_for_stop
.send(NativeBridgeWrite::Raw(rnode::build_detach_sequence()))
.await;
tokio::time::sleep(Duration::from_millis(100)).await;
break 'read;
}
continue;
@@ -1648,6 +1737,7 @@ pub async fn spawn_ble_rnode_interface_native(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+3
View File
@@ -545,6 +545,7 @@ pub async fn spawn_i2p_client(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -738,6 +739,7 @@ pub async fn spawn_i2p_server(
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: config.mode,
direction: InterfaceDirection {
@@ -774,6 +776,7 @@ pub async fn spawn_i2p_server(
Ok(InterfaceHandle {
id: 0,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+1
View File
@@ -233,6 +233,7 @@ pub async fn spawn_kiss_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+6
View File
@@ -265,6 +265,7 @@ mod platform {
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -300,6 +301,7 @@ mod platform {
Ok(InterfaceHandle {
id: 0,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -345,6 +347,7 @@ mod platform {
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -431,6 +434,7 @@ mod platform {
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -466,6 +470,7 @@ mod platform {
Ok(InterfaceHandle {
id: 0,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -512,6 +517,7 @@ mod platform {
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
+1
View File
@@ -189,6 +189,7 @@ pub async fn spawn_pipe_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
File diff suppressed because it is too large. Load diff
+1
View File
@@ -423,6 +423,7 @@ pub async fn spawn_rnode_multi_interface(
handles.push(InterfaceHandle {
id: ids[i],
parent_id: None,
name: sub_name,
mode: sub_cfg.mode,
direction: InterfaceDirection {
+1
View File
@@ -171,6 +171,7 @@ pub async fn spawn_serial_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+97
View File
@@ -29,6 +29,25 @@ pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
Ok(())
}
/// Enable portable `SO_KEEPALIVE` on a blocking std TCP stream.
#[cfg(unix)]
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
sock.set_keepalive(true)?;
Ok(())
}
#[cfg(windows)]
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
sock.set_keepalive(true)?;
Ok(())
}
/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort.
#[cfg(unix)]
pub fn set_keepalive_tuned(
@@ -58,6 +77,35 @@ pub fn set_keepalive_tuned(
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
/// Tuned keepalive for blocking std TCP streams. Best-effort.
#[cfg(unix)]
pub fn set_keepalive_tuned_std(
stream: &std::net::TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
#[cfg(windows)]
pub fn set_keepalive_tuned_std(
stream: &std::net::TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
fn apply_tuned_keepalive(
sock: &socket2::Socket,
idle: Duration,
@@ -107,6 +155,25 @@ pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
let _ = sock.set_send_buffer_size(size);
}
/// Raise TCP send/recv buffers on a blocking std TCP stream; best-effort.
#[cfg(unix)]
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
#[cfg(windows)]
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back
/// to wildcard bind.
pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option<IpAddr> {
@@ -177,6 +244,36 @@ mod tests {
set_socket_buffers(&client, 131_072);
}
#[test]
fn std_keepalive_and_buffers_apply_without_panic() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let accept = std::thread::spawn(move || listener.accept().unwrap().0);
let client = std::net::TcpStream::connect(addr).unwrap();
let server = accept.join().unwrap();
set_keepalive_std(&server).expect("server set_keepalive_std");
set_keepalive_std(&client).expect("client set_keepalive_std");
set_keepalive_tuned_std(
&server,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_keepalive_tuned_std(
&client,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_socket_buffers_std(&server, 131_072);
set_socket_buffers_std(&client, 131_072);
}
#[test]
fn iface_addr_for_loopback_resolves() {
// Loopback name varies by OS; iterate candidates.
+5
View File
@@ -391,6 +391,7 @@ pub async fn spawn_tcp_client(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -419,6 +420,7 @@ pub async fn spawn_tcp_client(
async fn spawn_tcp_accepted(
stream: TcpStream,
id: InterfaceId,
parent_id: InterfaceId,
name: String,
transport_tx: mpsc::Sender<TransportMessage>,
kiss_framing: bool,
@@ -459,6 +461,7 @@ async fn spawn_tcp_accepted(
let bitrate: u64 = 10_000_000;
InterfaceHandle {
id,
parent_id: Some(parent_id),
name,
mode,
direction: InterfaceDirection {
@@ -510,6 +513,7 @@ pub async fn spawn_tcp_server(
let handle = spawn_tcp_accepted(
stream,
client_id,
id,
client_name,
transport_tx.clone(),
kiss_framing,
@@ -533,6 +537,7 @@ pub async fn spawn_tcp_server(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+45 -12
View File
@@ -9,6 +9,9 @@ pub type InterfaceId = u64;
/// Handle returned by every `spawn_*`: write channel, status flag, and read task.
pub struct InterfaceHandle {
pub id: InterfaceId,
/// Parent interface for dynamically spawned children such as accepted TCP,
/// Backbone or I2P peers.
pub parent_id: Option<InterfaceId>,
pub name: String,
pub mode: InterfaceMode,
pub direction: InterfaceDirection,
@@ -154,21 +157,39 @@ pub fn optimise_mtu(bitrate: u64) -> Option<u32> {
pub const NAME_HASH_LENGTH: usize = 10;
// Ingress control constants — must match Reticulum reference.
pub const IA_FREQ_SAMPLES: usize = 128;
pub const OA_FREQ_SAMPLES: usize = 128;
pub const IA_FREQ_SAMPLES: usize = 48;
pub const OA_FREQ_SAMPLES: usize = 48;
pub const IP_FREQ_SAMPLES: usize = 48;
pub const OP_FREQ_SAMPLES: usize = 48;
pub const AR_MINFREQ_HZ: f64 = 0.1;
pub const PR_MINFREQ_HZ: f64 = 0.1;
pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ;
pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ;
pub const MAX_HELD_ANNOUNCES: usize = 256;
/// Duration a new interface stays in "new" state (seconds).
pub const IC_NEW_TIME: f64 = 7200.0;
/// Burst threshold for new interfaces (announces/sec).
pub const IC_BURST_FREQ_NEW: f64 = 6.0;
pub const IC_BURST_FREQ_NEW: f64 = 3.0;
/// Burst threshold for established interfaces (announces/sec).
pub const IC_BURST_FREQ: f64 = 35.0;
pub const IC_BURST_FREQ: f64 = 10.0;
/// Burst threshold for new interfaces (path requests/sec).
pub const IC_PR_BURST_FREQ_NEW: f64 = 3.0;
/// Burst threshold for established interfaces (path requests/sec).
pub const IC_PR_BURST_FREQ: f64 = 8.0;
/// Burst detection window duration (seconds).
pub const IC_BURST_HOLD: f64 = 60.0;
pub const IC_BURST_HOLD: f64 = 15.0;
/// Penalty duration after a detected burst (seconds).
pub const IC_BURST_PENALTY: f64 = 15.0;
/// Interval between released held announces (seconds).
pub const IC_HELD_RELEASE_INTERVAL: f64 = 2.0;
pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0;
/// Minimum samples required before incoming frequency is considered defined.
pub const IC_DEQUE_MIN_SAMPLE: usize = 2;
/// Minimum samples required for burst clearing / PR egress limiting.
pub const IC_BURST_MIN_SAMPLES: usize = 6;
/// Optional outgoing path-request limiter threshold (requests/sec).
pub const EC_PR_FREQ: f64 = 5.0;
/// Whether outgoing path-request limiting is active by default.
pub const EGRESS_CONTROL: bool = false;
#[derive(Debug, thiserror::Error)]
pub enum InterfaceError {
@@ -239,13 +260,25 @@ mod tests {
#[test]
fn test_ingress_control_constants() {
assert_eq!(IA_FREQ_SAMPLES, 128);
assert_eq!(OA_FREQ_SAMPLES, 128);
assert_eq!(IC_BURST_FREQ, 35.0);
assert_eq!(IC_BURST_FREQ_NEW, 6.0);
assert_eq!(IC_BURST_HOLD, 60.0);
assert_eq!(IA_FREQ_SAMPLES, 48);
assert_eq!(OA_FREQ_SAMPLES, 48);
assert_eq!(IP_FREQ_SAMPLES, 48);
assert_eq!(OP_FREQ_SAMPLES, 48);
assert_eq!(AR_MINFREQ_HZ, 0.1);
assert_eq!(PR_MINFREQ_HZ, 0.1);
assert_eq!(AR_FREQ_DECAY, 10.0);
assert_eq!(PR_FREQ_DECAY, 10.0);
assert_eq!(IC_BURST_FREQ, 10.0);
assert_eq!(IC_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_PR_BURST_FREQ, 8.0);
assert_eq!(IC_PR_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_BURST_HOLD, 15.0);
assert_eq!(IC_BURST_PENALTY, 15.0);
assert_eq!(IC_NEW_TIME, 7200.0);
assert_eq!(IC_HELD_RELEASE_INTERVAL, 2.0);
assert_eq!(IC_HELD_RELEASE_INTERVAL, 5.0);
assert_eq!(IC_DEQUE_MIN_SAMPLE, 2);
assert_eq!(IC_BURST_MIN_SAMPLES, 6);
assert_eq!(EC_PR_FREQ, 5.0);
const { assert!(!EGRESS_CONTROL) };
}
}
+1
View File
@@ -145,6 +145,7 @@ pub async fn spawn_udp_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+21 -6
View File
@@ -149,6 +149,17 @@ mod tests {
use super::*;
use std::thread;
fn instant_before_now(elapsed: Duration) -> Instant {
if let Some(instant) = Instant::now().checked_sub(elapsed) {
instant
} else {
thread::sleep(elapsed);
Instant::now()
.checked_sub(elapsed)
.expect("elapsed duration should be representable after waiting")
}
}
#[test]
fn test_rtt_scaling() {
let mut ks = KeepaliveState::new(true);
@@ -225,11 +236,13 @@ mod tests {
#[test]
fn test_jitter_desynchronizes_keepalives() {
let links: Vec<KeepaliveState> = (0..20)
.map(|_| {
.map(|i| {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(500));
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
ks.jitter_offset = Duration::from_millis(500);
ks.jitter_negative = i % 2 == 0;
// Push last_inbound just past the interval boundary.
ks.last_inbound = Instant::now() - ks.keepalive_interval;
ks.last_inbound = instant_before_now(ks.keepalive_interval);
ks
})
.collect();
@@ -237,10 +250,12 @@ mod tests {
let firing: usize = links.iter().filter(|ks| ks.should_send_keepalive()).count();
let links_past: Vec<KeepaliveState> = (0..20)
.map(|_| {
.map(|i| {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(500));
ks.last_inbound = Instant::now() - ks.keepalive_interval * 2;
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
ks.jitter_offset = Duration::from_millis(500);
ks.jitter_negative = i % 2 == 0;
ks.last_inbound = instant_before_now(Duration::from_secs(6));
ks
})
.collect();
+63 -3
View File
@@ -1253,6 +1253,7 @@ pub struct OutboundTransfer {
/// Scopes the search range when servicing RESOURCE_REQ lookups.
pub receiver_min_consecutive_height: usize,
pub sent_parts: usize,
sent_part_indices: HashSet<usize>,
req_hashlist: HashSet<[u8; 32]>,
}
@@ -1301,6 +1302,7 @@ impl OutboundTransfer {
window_max_sent: 0,
receiver_min_consecutive_height: 0,
sent_parts: 0,
sent_part_indices: HashSet::new(),
req_hashlist: HashSet::new(),
}
}
@@ -1351,6 +1353,9 @@ impl OutboundTransfer {
if let Some(part_data) = part_data {
self.last_part_sent = Some(Instant::now());
self.resource.state = ResourceState::Transferring;
if self.sent_part_indices.insert(part_idx) {
self.sent_parts += 1;
}
if self.window_cursor >= window_end {
// Last part in the window is now in flight; stop
@@ -1548,6 +1553,9 @@ impl OutboundTransfer {
{
if let Some(part_data) = self.resource.get_part(i) {
actions.push(TransferAction::SendPart(i, part_data.to_vec()));
if self.sent_part_indices.insert(i) {
self.sent_parts += 1;
}
sent_count += 1;
}
}
@@ -1736,13 +1744,16 @@ impl OutboundTransfer {
buf
}
/// Fraction of parts confirmed, in `0.0..=1.0`.
/// Fraction of unique parts transmitted, in `0.0..=1.0`.
///
/// Upstream Reticulum reports initiator-side progress from `sent_parts`,
/// while receiver HMUs/proofs still decide completion. This keeps UI
/// progress useful on large resources before a full segment proof arrives.
pub fn progress(&self) -> f64 {
let confirmed = self.confirmed_parts.iter().filter(|&&c| c).count();
if self.resource.num_parts() == 0 {
return 1.0;
}
confirmed as f64 / self.resource.num_parts() as f64
self.sent_parts.min(self.resource.num_parts()) as f64 / self.resource.num_parts() as f64
}
}
@@ -2821,6 +2832,55 @@ mod tests {
assert_eq!(transfer.progress(), 0.0);
}
#[test]
fn test_transfer_progress_tracks_unique_sent_parts() {
let data = vec![0x55; SDU * 2 + 100];
let mut sender =
OutboundTransfer::new(data.clone(), false, Duration::from_millis(50)).unwrap();
assert!(sender.resource.num_parts() > 1);
assert!(matches!(
sender.tick(),
TransferAction::SendAdvertisement(_)
));
let first_progress = match sender.tick() {
TransferAction::SendPart(_, _) => sender.progress(),
other => panic!("expected first part, got {other:?}"),
};
assert!(first_progress > 0.0);
assert!(first_progress < 1.0);
let mut receiver = InboundTransfer::from_advertisement(
sender.resource.num_parts(),
sender.resource.total_size,
data.len(),
sender.resource.random_hash,
sender.resource.resource_hash,
ResourceFlags {
compressed: false,
..Default::default()
},
sender.resource.map_hashes.clone(),
Duration::from_millis(50),
)
.unwrap();
let TransferAction::SendRequest(request) = receiver.request_next() else {
panic!("expected receiver request");
};
let first_count = sender.sent_parts;
let _ = sender.handle_request(&request);
let after_request = sender.sent_parts;
let _ = sender.handle_request(&request);
assert!(after_request >= first_count);
assert_eq!(
sender.sent_parts, after_request,
"duplicate requests must not inflate visible send progress"
);
}
#[test]
fn test_full_transfer_roundtrip() {
// Simulate a complete transfer: sender → receiver
+1
View File
@@ -8,6 +8,7 @@ license.workspace = true
[features]
default = []
serial = ["rns-interface/serial"]
rnode-tcp = ["rns-interface/rnode-tcp"]
ble = ["rns-interface/ble"]
[dependencies]
+6 -3
View File
@@ -12,9 +12,12 @@ pub const RESOURCE_CACHE: u64 = 86400;
pub const MAX_QUEUED_ANNOUNCES: usize = 16384;
pub const QUEUED_ANNOUNCE_LIFE: u64 = 86400;
/// Percentage matching Python `Reticulum.ANNOUNCE_CAP = 2`; transport actor
/// divides by 100 before applying to bitrate math.
pub const ANNOUNCE_CAP: f64 = 2.0;
/// Announce bandwidth cap as a fraction of interface bitrate (2%).
///
/// Python exposes/configures this as `2` percent, then stores `0.02` on live
/// interfaces. Runtime registration must hand the transport actor the stored
/// fraction, because queue spacing is calculated as `tx_time / announce_cap`.
pub const ANNOUNCE_CAP: f64 = 0.02;
pub const MINIMUM_BITRATE: u64 = 5;
pub const IFAC_MIN_SIZE: usize = 1;
+91 -14
View File
@@ -30,7 +30,7 @@ pub enum InterfaceConfig {
#[cfg(feature = "serial")]
KissSerial(KissSerialConfig),
Auto(AutoInterfaceConfig),
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
RNode(RNodeInterfaceConfig),
Local(LocalInterfaceConfig),
I2P(I2PInterfaceConfig),
@@ -79,7 +79,7 @@ pub struct AutoInterfaceConfig {
pub mode: InterfaceMode,
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[derive(Debug, Clone)]
pub struct RNodeInterfaceConfig {
pub name: String,
@@ -254,7 +254,12 @@ pub fn synthesize_interface(
"KISSInterface" => synthesize_kiss_serial(name, section, mode),
"AutoInterface" => synthesize_auto(name, section, mode),
"RNodeInterface" => {
let port = section.get("port").unwrap_or("");
let port = section
.get("port")
.ok_or_else(|| InterfaceFactoryError::MissingField {
name: name.to_string(),
field: "port".to_string(),
})?;
if port.starts_with("ble://") {
#[cfg(feature = "ble")]
{
@@ -274,14 +279,23 @@ pub fn synthesize_interface(
"RNodeInterface '{name}' is an Android USB-OTG entry — skipped at startup; re-add from the UI after plugging the device in"
)));
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
{
synthesize_rnode(name, section, mode)
let is_tcp = port
.get(.."tcp://".len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("tcp://"));
if is_tcp || cfg!(feature = "serial") {
synthesize_rnode(name, section, mode)
} else {
Err(InterfaceFactoryError::Disabled(format!(
"RNodeInterface '{name}' requires 'serial' feature for non-TCP ports"
)))
}
}
#[cfg(not(feature = "serial"))]
#[cfg(not(any(feature = "serial", feature = "rnode-tcp")))]
{
Err(InterfaceFactoryError::Disabled(format!(
"RNodeInterface '{name}' requires 'serial' feature for serial ports"
"RNodeInterface '{name}' requires 'serial' or 'rnode-tcp' feature"
)))
}
}
@@ -524,7 +538,7 @@ fn synthesize_auto(
}))
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
fn synthesize_rnode(
name: &str,
section: &ConfigSection,
@@ -1003,6 +1017,8 @@ impl InterfacePostInit {
enabled: if ingress_control { None } else { Some(false) },
burst_freq_new: section.get_float("ic_burst_freq_new"),
burst_freq: section.get_float("ic_burst_freq"),
pr_burst_freq_new: section.get_float("ic_pr_burst_freq_new"),
pr_burst_freq: section.get_float("ic_pr_burst_freq"),
new_time: section.get_float("ic_new_time"),
burst_hold: section.get_float("ic_burst_hold"),
burst_penalty: section.get_float("ic_burst_penalty"),
@@ -1010,11 +1026,15 @@ impl InterfacePostInit {
.get_uint("ic_max_held_announces")
.map(|v| v as usize),
held_release_interval: section.get_float("ic_held_release_interval"),
ec_pr_freq: section.get_float("ec_pr_freq"),
egress_control: section.get_bool("egress_control"),
};
Self {
outgoing: section.get_bool("outgoing").unwrap_or(true),
bitrate: section.get_uint("bitrate"),
announce_cap: section.get_float("announce_cap"),
announce_cap: section
.get_float("announce_cap")
.and_then(normalize_announce_cap_percent),
announce_rate_target,
announce_rate_grace: section
.get_uint("announce_rate_grace")
@@ -1044,6 +1064,14 @@ impl InterfacePostInit {
}
}
fn normalize_announce_cap_percent(value: f64) -> Option<f64> {
if value > 0.0 && value <= 100.0 {
Some(value / 100.0)
} else {
None
}
}
/// Python `DEFAULT_IFAC_SIZE`: network interfaces 16 bytes, serial/packet-radio 8.
pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize {
match config {
@@ -1056,9 +1084,10 @@ pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize {
#[cfg(feature = "serial")]
InterfaceConfig::Serial(_)
| InterfaceConfig::KissSerial(_)
| InterfaceConfig::RNode(_)
| InterfaceConfig::RNodeMulti(_)
| InterfaceConfig::AX25KISS(_) => 8,
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
InterfaceConfig::RNode(_) => 8,
InterfaceConfig::Local(_) | InterfaceConfig::Pipe(_) => 8,
#[cfg(feature = "ble")]
InterfaceConfig::BleRNode(_) => 8,
@@ -1451,7 +1480,26 @@ mod tests {
}
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[test]
fn test_synthesize_rnode_tcp() {
let mut section = ConfigSection::new();
section.set("type", "RNodeInterface");
section.set("port", "tcp://rnode.local");
section.set("frequency", "915000000");
let config = synthesize_interface("rnode_tcp", &section).unwrap();
match config {
InterfaceConfig::RNode(c) => {
assert_eq!(c.name, "rnode_tcp");
assert_eq!(c.port, "tcp://rnode.local");
assert_eq!(c.frequency, 915000000);
}
_ => panic!("expected RNode"),
}
}
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[test]
fn test_synthesize_rnode_missing_port() {
let mut section = ConfigSection::new();
@@ -1466,12 +1514,12 @@ mod tests {
}
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[test]
fn test_synthesize_rnode_missing_frequency() {
let mut section = ConfigSection::new();
section.set("type", "RNodeInterface");
section.set("port", "/dev/ttyACM0");
section.set("port", "tcp://rnode.local");
match synthesize_interface("rnode_no_freq", &section) {
Err(InterfaceFactoryError::MissingField { field, .. }) => {
@@ -1572,6 +1620,10 @@ mod tests {
section.set("ifac_size", "16");
section.set("ingress_control", "false");
section.set("announce_cap", "5.0");
section.set("ic_pr_burst_freq_new", "4.5");
section.set("ic_pr_burst_freq", "9.5");
section.set("ec_pr_freq", "6.5");
section.set("egress_control", "Yes");
let pi = InterfacePostInit::from_section(&section);
assert!(!pi.outgoing);
@@ -1580,7 +1632,32 @@ mod tests {
assert_eq!(pi.ifac_passphrase.as_deref(), Some("secret"));
assert_eq!(pi.ifac_size, Some(16));
assert!(!pi.ingress_control);
assert!((pi.announce_cap.unwrap() - 5.0).abs() < f64::EPSILON);
assert!((pi.announce_cap.unwrap() - 0.05).abs() < f64::EPSILON);
assert_eq!(pi.ingress_overrides.enabled, Some(false));
assert_eq!(pi.ingress_overrides.pr_burst_freq_new, Some(4.5));
assert_eq!(pi.ingress_overrides.pr_burst_freq, Some(9.5));
assert_eq!(pi.ingress_overrides.ec_pr_freq, Some(6.5));
assert_eq!(pi.ingress_overrides.egress_control, Some(true));
}
#[test]
fn announce_cap_config_uses_python_percent_shape() {
let mut section = ConfigSection::new();
section.set("announce_cap", "2");
let pi = InterfacePostInit::from_section(&section);
assert_eq!(pi.announce_cap, Some(0.02));
section.set("announce_cap", "100");
let pi = InterfacePostInit::from_section(&section);
assert_eq!(pi.announce_cap, Some(1.0));
section.set("announce_cap", "0");
let pi = InterfacePostInit::from_section(&section);
assert_eq!(pi.announce_cap, None);
section.set("announce_cap", "101");
let pi = InterfacePostInit::from_section(&section);
assert_eq!(pi.announce_cap, None);
}
#[test]
+375
View File
@@ -64,6 +64,36 @@ pub struct ChannelSendReceipt {
pub packet_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub struct LinkPacketSendReceipt {
pub link_id: [u8; 16],
pub packet_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub struct LinkResourceSendReceipt {
pub link_id: [u8; 16],
pub resource_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub struct LinkPacketProof {
pub link_id: [u8; 16],
pub packet_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub struct LinkResourceProof {
pub link_id: [u8; 16],
pub resource_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub enum LinkPayloadSendReceipt {
Packet(LinkPacketSendReceipt),
Resource(LinkResourceSendReceipt),
}
#[derive(Debug, thiserror::Error)]
pub enum ChannelSendError {
#[error("link not found")]
@@ -78,12 +108,43 @@ pub enum ChannelSendError {
TransportUnavailable,
}
#[derive(Debug, thiserror::Error)]
pub enum LinkSendError {
#[error("link not found")]
LinkNotFound,
#[error("link is not active")]
LinkNotActive,
#[error("link session keys are unavailable")]
NoSessionKeys,
#[error("transport channel is full or closed")]
TransportUnavailable,
#[error("resource transfer could not be started")]
ResourceStartFailed,
}
pub enum LinkManagerCommand {
SendChannelMessage {
link_id: [u8; 16],
message: Box<dyn MessageBase>,
result_tx: Option<oneshot::Sender<Result<ChannelSendReceipt, ChannelSendError>>>,
},
SendLinkPacket {
link_id: [u8; 16],
payload: Vec<u8>,
result_tx: Option<oneshot::Sender<Result<LinkPacketSendReceipt, LinkSendError>>>,
},
SendLinkResource {
link_id: [u8; 16],
payload: Vec<u8>,
auto_compress: bool,
result_tx: Option<oneshot::Sender<Result<LinkResourceSendReceipt, LinkSendError>>>,
},
SendLinkPayload {
link_id: [u8; 16],
payload: Vec<u8>,
auto_compress: bool,
result_tx: Option<oneshot::Sender<Result<LinkPayloadSendReceipt, LinkSendError>>>,
},
CloseLink {
link_id: [u8; 16],
reason: CloseReason,
@@ -162,6 +223,10 @@ pub struct LinkManager {
link_identity_gate: Option<LinkIdentityGate>,
/// Decrypted link-packet stream (LXMF DIRECT).
link_packet_tx: Option<mpsc::Sender<(Vec<u8>, [u8; 16])>>,
/// Valid proof for an application link packet sent through this manager.
link_packet_proof_tx: Option<mpsc::Sender<LinkPacketProof>>,
/// Valid proof for an application resource sent through this manager.
outbound_resource_proof_tx: Option<mpsc::Sender<LinkResourceProof>>,
/// Decrypted channel envelopes as `(link_id, msg_type, payload)`.
channel_message_tx: Option<mpsc::Sender<LinkChannelMessage>>,
/// Fires when an active link is closed or torn down.
@@ -199,6 +264,8 @@ impl LinkManager {
link_identified_tx: None,
link_identity_gate: None,
link_packet_tx: None,
link_packet_proof_tx: None,
outbound_resource_proof_tx: None,
channel_message_tx: None,
link_closed_tx: None,
inbound_raw_tx: None,
@@ -245,6 +312,8 @@ impl LinkManager {
link_identified_tx: None,
link_identity_gate: None,
link_packet_tx: None,
link_packet_proof_tx: None,
outbound_resource_proof_tx: None,
channel_message_tx: None,
link_closed_tx: None,
inbound_raw_tx: None,
@@ -342,6 +411,41 @@ impl LinkManager {
}
true
}
LinkManagerCommand::SendLinkPacket {
link_id,
payload,
result_tx,
} => {
let result = self.send_link_packet(&link_id, &payload);
if let Some(tx) = result_tx {
let _ = tx.send(result);
}
true
}
LinkManagerCommand::SendLinkResource {
link_id,
payload,
auto_compress,
result_tx,
} => {
let result = self.send_link_resource(&link_id, payload, auto_compress);
if let Some(tx) = result_tx {
let _ = tx.send(result);
}
true
}
LinkManagerCommand::SendLinkPayload {
link_id,
payload,
auto_compress,
result_tx,
} => {
let result = self.send_link_payload(&link_id, payload, auto_compress);
if let Some(tx) = result_tx {
let _ = tx.send(result);
}
true
}
LinkManagerCommand::CloseLink {
link_id,
reason,
@@ -1418,6 +1522,8 @@ impl LinkManager {
.is_some_and(|transfer| transfer.handle_proof(data));
if complete {
active.outbound_resources.remove(&rh);
let mut started_next_segment = false;
let completed_resource_hash = queue_key.unwrap_or(rh);
if let Some(key) = queue_key {
let (next, empty) = if let Some(queue) =
active.outbound_split_queues.get_mut(&key)
@@ -1437,8 +1543,17 @@ impl LinkManager {
&link_id,
next,
);
started_next_segment = true;
}
}
if !started_next_segment
&& let Some(ref tx) = self.outbound_resource_proof_tx
{
let _ = tx.try_send(LinkResourceProof {
link_id,
resource_hash: completed_resource_hash,
});
}
}
}
}
@@ -1933,8 +2048,10 @@ impl LinkManager {
}
let rtt = active.link.rtt_secs();
let mut matched_channel_sequence = false;
if let Some(channel) = active.channel.as_mut() {
if let Some(sequence) = channel.delivered_by_packet_hash(&packet_hash, rtt) {
matched_channel_sequence = true;
active.link.keepalive.record_proof();
tracing::debug!(
link_id = hex::encode(link_id),
@@ -1944,6 +2061,12 @@ impl LinkManager {
);
}
}
if !matched_channel_sequence && let Some(ref tx) = self.link_packet_proof_tx {
let _ = tx.try_send(LinkPacketProof {
link_id,
packet_hash,
});
}
}
pub fn set_request_handler<F>(&mut self, handler: F)
@@ -2002,6 +2125,14 @@ impl LinkManager {
self.link_packet_tx = Some(tx);
}
pub fn set_link_packet_proof_channel(&mut self, tx: mpsc::Sender<LinkPacketProof>) {
self.link_packet_proof_tx = Some(tx);
}
pub fn set_outbound_resource_proof_channel(&mut self, tx: mpsc::Sender<LinkResourceProof>) {
self.outbound_resource_proof_tx = Some(tx);
}
pub fn set_channel_message_channel(&mut self, tx: mpsc::Sender<LinkChannelMessage>) {
self.channel_message_tx = Some(tx);
}
@@ -2092,6 +2223,111 @@ impl LinkManager {
})
}
pub fn send_link_packet(
&mut self,
link_id: &[u8; 16],
payload: &[u8],
) -> Result<LinkPacketSendReceipt, LinkSendError> {
let active = self
.active_links
.get(link_id)
.ok_or(LinkSendError::LinkNotFound)?;
if active.link.state != LinkState::Active {
return Err(LinkSendError::LinkNotActive);
}
let encrypted = active
.link
.encrypt(payload)
.map_err(|_| LinkSendError::NoSessionKeys)?;
let transport_tx = self.transport_tx.clone();
let permit = transport_tx
.try_reserve()
.map_err(|_| LinkSendError::TransportUnavailable)?;
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: *link_id,
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(&encrypted);
let packet_hash = rns_wire::hash::packet_hash(&raw, header.flags.header_type);
let active = self
.active_links
.get_mut(link_id)
.ok_or(LinkSendError::LinkNotFound)?;
active.link.record_tx(raw.len());
permit.send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: *link_id,
}));
Ok(LinkPacketSendReceipt {
link_id: *link_id,
packet_hash,
})
}
pub fn send_link_resource(
&mut self,
link_id: &[u8; 16],
payload: Vec<u8>,
auto_compress: bool,
) -> Result<LinkResourceSendReceipt, LinkSendError> {
let active = self
.active_links
.get(link_id)
.ok_or(LinkSendError::LinkNotFound)?;
if active.link.state != LinkState::Active {
return Err(LinkSendError::LinkNotActive);
}
if active.link.session_keys().is_none() {
return Err(LinkSendError::NoSessionKeys);
}
let resource_hash = self
.start_resource_transfer(link_id, payload, auto_compress)
.ok_or(LinkSendError::ResourceStartFailed)?;
Ok(LinkResourceSendReceipt {
link_id: *link_id,
resource_hash,
})
}
pub fn send_link_payload(
&mut self,
link_id: &[u8; 16],
payload: Vec<u8>,
auto_compress: bool,
) -> Result<LinkPayloadSendReceipt, LinkSendError> {
let active = self
.active_links
.get(link_id)
.ok_or(LinkSendError::LinkNotFound)?;
if active.link.state != LinkState::Active {
return Err(LinkSendError::LinkNotActive);
}
if payload.len() <= active.link.mdu {
self.send_link_packet(link_id, &payload)
.map(LinkPayloadSendReceipt::Packet)
} else {
self.send_link_resource(link_id, payload, auto_compress)
.map(LinkPayloadSendReceipt::Resource)
}
}
pub fn process_destination_packet(&self, raw: &[u8], identity: &Identity) -> Option<Vec<u8>> {
let dest = self.destination.as_ref()?;
let (header, data_offset) = rns_wire::header::PacketHeader::unpack(raw).ok()?;
@@ -3105,6 +3341,145 @@ mod tests {
assert!(lm.get_channel(&link_id).unwrap().is_ready_to_send());
}
#[test]
fn send_link_packet_emits_plain_link_data_and_proof_event() {
let (initiator_link, responder_link, _identity_key) = handshaken_link_pair_with_identity();
let link_id = responder_link.link_id;
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut lm = LinkManager::new(transport_tx, event_rx, [0xC1; 16], None);
let (proof_tx, mut proof_rx) = mpsc::channel(4);
lm.set_link_packet_proof_channel(proof_tx);
lm.active_links.insert(
link_id,
ActiveLink {
link: responder_link,
_interface_id: 1,
channel: None,
inbound_resources: HashMap::new(),
outbound_resources: HashMap::new(),
outbound_split_queues: HashMap::new(),
inbound_split_resources: HashMap::new(),
segment_routing: HashMap::new(),
},
);
let receipt = lm
.send_link_packet(&link_id, b"backchannel payload")
.expect("link packet queued");
let outbound = transport_rx.try_recv().expect("link packet outbound");
let TransportMessage::Outbound(request) = outbound else {
panic!("expected outbound link packet");
};
let (sent_header, sent_offset) =
rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(sent_header.context, rns_wire::context::PacketContext::None);
assert_eq!(sent_header.destination_hash, link_id);
assert_eq!(
receipt.packet_hash,
rns_wire::hash::packet_hash(&request.raw, sent_header.flags.header_type)
);
assert_eq!(
initiator_link.decrypt(&request.raw[sent_offset..]).unwrap(),
b"backchannel payload"
);
let proof_data = initiator_link
.prove_packet_with_link_key(&receipt.packet_hash)
.unwrap();
let proof_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Proof,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::None,
};
let mut proof_raw = proof_header.pack();
proof_raw.extend_from_slice(&proof_data);
lm.handle_inbound_packet(&proof_raw, 1);
let proof = proof_rx.try_recv().expect("link packet proof event");
assert_eq!(proof.link_id, link_id);
assert_eq!(proof.packet_hash, receipt.packet_hash);
}
#[test]
fn send_link_resource_emits_resource_proof_event() {
let (_initiator_link, responder_link, _identity_key) = handshaken_link_pair_with_identity();
let link_id = responder_link.link_id;
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut lm = LinkManager::new(transport_tx, event_rx, [0xC2; 16], None);
let (proof_tx, mut proof_rx) = mpsc::channel(4);
lm.set_outbound_resource_proof_channel(proof_tx);
lm.active_links.insert(
link_id,
ActiveLink {
link: responder_link,
_interface_id: 1,
channel: None,
inbound_resources: HashMap::new(),
outbound_resources: HashMap::new(),
outbound_split_queues: HashMap::new(),
inbound_split_resources: HashMap::new(),
segment_routing: HashMap::new(),
},
);
let receipt = lm
.send_link_resource(&link_id, b"resource payload".to_vec(), false)
.expect("resource started");
let outbound = transport_rx.try_recv().expect("resource ADV outbound");
let TransportMessage::Outbound(request) = outbound else {
panic!("expected outbound resource ADV");
};
let (adv_header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(
adv_header.context,
rns_wire::context::PacketContext::ResourceAdv
);
let proof_data = {
let active = lm.active_links.get(&link_id).unwrap();
let transfer = active
.outbound_resources
.get(&receipt.resource_hash)
.expect("outbound resource tracked");
let mut proof = Vec::new();
proof.extend_from_slice(&transfer.resource.resource_hash);
proof.extend_from_slice(&transfer.resource.expected_proof);
proof
};
let proof_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Proof,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::ResourcePrf,
};
let mut proof_raw = proof_header.pack();
proof_raw.extend_from_slice(&proof_data);
lm.handle_inbound_packet(&proof_raw, 1);
let proof = proof_rx.try_recv().expect("resource proof event");
assert_eq!(proof.link_id, link_id);
assert_eq!(proof.resource_hash, receipt.resource_hash);
}
#[test]
fn unmatched_valid_link_packet_proof_does_not_record_keepalive_proof() {
let (sender_link, receiver_link, _identity_key) = handshaken_link_pair_with_identity();
+4
View File
@@ -455,6 +455,8 @@ mod tests {
timestamp: 0.0,
public_key: Some([0x11; 64]),
ratchet: None,
name_hash: [0; 10],
is_path_response: false,
retained: false,
},
AnnounceRpcEntry {
@@ -464,6 +466,8 @@ mod tests {
timestamp: 0.0,
public_key: Some([0x22; 64]),
ratchet: None,
name_hash: [0; 10],
is_path_response: false,
retained: false,
},
];
+50 -1
View File
@@ -252,7 +252,13 @@ fn interface_stats_from_rpc(e: InterfaceStatRpcEntry) -> schema::InterfaceStats
txb: e.tx_bytes,
incoming_announce_frequency: e.incoming_announce_frequency,
outgoing_announce_frequency: e.outgoing_announce_frequency,
incoming_pr_frequency: e.incoming_pr_frequency,
outgoing_pr_frequency: e.outgoing_pr_frequency,
held_announces: e.held_announces,
burst_active: e.burst_active,
burst_activated: e.burst_activated,
pr_burst_active: e.pr_burst_active,
pr_burst_activated: e.pr_burst_activated,
status: e.online,
mode,
bitrate: Some(e.bitrate),
@@ -330,7 +336,13 @@ mod tests {
txb: 7,
incoming_announce_frequency: 0.0,
outgoing_announce_frequency: 0.0,
incoming_pr_frequency: 0.0,
outgoing_pr_frequency: 0.0,
held_announces: 0,
burst_active: false,
burst_activated: 0.0,
pr_burst_active: false,
pr_burst_activated: 0.0,
status: true,
mode: 0x01,
bitrate: Some(1_000_000),
@@ -465,11 +477,17 @@ mod tests {
held_announces: 1,
incoming_announce_frequency: 0.5,
outgoing_announce_frequency: 0.25,
incoming_pr_frequency: 3.0,
outgoing_pr_frequency: 1.5,
burst_active: true,
burst_activated: 1_700_000_001.0,
pr_burst_active: true,
pr_burst_activated: 1_700_000_002.0,
clients: None,
announce_rate_target: None,
announce_rate_grace: None,
announce_rate_penalty: None,
announce_cap: 2.0,
announce_cap: 0.02,
ifac_size: 0,
tx_drops: 0,
}];
@@ -484,6 +502,9 @@ mod tests {
hops: 2,
expires: 1_700_100_000.0,
interface: "MockIf".to_string(),
interface_id: 1,
interface_mode: rns_transport::constants::InterfaceMode::Full,
interface_role: rns_transport::messages::InterfaceRole::Normal,
}];
TransportQueryResponse::PathTable(entries)
}
@@ -562,6 +583,34 @@ mod tests {
Some(0x06),
"Gateway mode maps to Python MODE_GATEWAY=0x06"
);
let incoming_pr = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("incoming_pr_frequency"))
.unwrap()
.1
.as_f64();
assert_eq!(incoming_pr, Some(3.0));
let outgoing_pr = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("outgoing_pr_frequency"))
.unwrap()
.1
.as_f64();
assert_eq!(outgoing_pr, Some(1.5));
let burst_active = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("burst_active"))
.unwrap()
.1
.as_bool();
assert_eq!(burst_active, Some(true));
let pr_burst_active = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("pr_burst_active"))
.unwrap()
.1
.as_bool();
assert_eq!(pr_burst_active, Some(true));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -34,7 +34,13 @@ pub struct InterfaceStats {
pub txb: u64,
pub incoming_announce_frequency: f64,
pub outgoing_announce_frequency: f64,
pub incoming_pr_frequency: f64,
pub outgoing_pr_frequency: f64,
pub held_announces: u64,
pub burst_active: bool,
pub burst_activated: f64,
pub pr_burst_active: bool,
pub pr_burst_activated: f64,
/// Python field name (not `online`).
pub status: bool,
/// Matches Python `Interface.MODE_*` integers.
File diff suppressed because it is too large. Load diff
+142 -3
View File
@@ -65,6 +65,8 @@ pub enum RpcRequest {
DropAllVia {
transport_hash: Vec<u8>,
},
DropPathTable,
DropRecentAnnounces,
DropAnnounceQueues,
BlackholeIdentity {
identity_hash: Vec<u8>,
@@ -130,6 +132,18 @@ pub struct InterfaceStatEntry {
pub held_announces: u64,
pub incoming_announce_frequency: f64,
pub outgoing_announce_frequency: f64,
#[serde(default)]
pub incoming_pr_frequency: f64,
#[serde(default)]
pub outgoing_pr_frequency: f64,
#[serde(default)]
pub burst_active: bool,
#[serde(default)]
pub burst_activated: f64,
#[serde(default)]
pub pr_burst_active: bool,
#[serde(default)]
pub pr_burst_activated: f64,
pub clients: Option<u64>,
pub announce_rate_target: Option<f64>,
pub announce_rate_grace: Option<u32>,
@@ -255,6 +269,13 @@ fn request_to_py_value(req: &RpcRequest) -> PyValue {
("drop", PyValue::String("all_via".to_string())),
("destination_hash", PyValue::Bytes(transport_hash.clone())),
]),
RpcRequest::DropPathTable => {
py_dict(vec![("drop", PyValue::String("path_table".to_string()))])
}
RpcRequest::DropRecentAnnounces => py_dict(vec![(
"drop",
PyValue::String("recent_announces".to_string()),
)]),
RpcRequest::DropAnnounceQueues => py_dict(vec![(
"drop",
PyValue::String("announce_queues".to_string()),
@@ -350,6 +371,8 @@ fn py_value_to_request(value: &PyValue) -> Result<RpcRequest, RpcError> {
"all_via" => Ok(RpcRequest::DropAllVia {
transport_hash: dict_bytes(entries, "destination_hash")?,
}),
"path_table" => Ok(RpcRequest::DropPathTable),
"recent_announces" => Ok(RpcRequest::DropRecentAnnounces),
"announce_queues" => Ok(RpcRequest::DropAnnounceQueues),
other => Err(RpcError::Deserialize(format!(
"unknown Python RPC drop path: {other}"
@@ -454,6 +477,18 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
"outgoing_announce_frequency",
PyValue::Float(e.outgoing_announce_frequency),
),
(
"incoming_pr_frequency",
PyValue::Float(e.incoming_pr_frequency),
),
(
"outgoing_pr_frequency",
PyValue::Float(e.outgoing_pr_frequency),
),
("burst_active", PyValue::Bool(e.burst_active)),
("burst_activated", PyValue::Float(e.burst_activated)),
("pr_burst_active", PyValue::Bool(e.pr_burst_active)),
("pr_burst_activated", PyValue::Float(e.pr_burst_activated)),
(
"clients",
e.clients
@@ -581,9 +616,10 @@ fn py_value_to_response_for_request(
| RpcRequest::GetPacketRssi { .. }
| RpcRequest::GetPacketSnr { .. }
| RpcRequest::GetPacketQ { .. } => Ok(RpcResponse::FloatResult(py_optional_float(value)?)),
RpcRequest::GetLinkCount | RpcRequest::DropAllVia { .. } => {
Ok(RpcResponse::IntResult(py_required_int(value)?))
}
RpcRequest::GetLinkCount
| RpcRequest::DropAllVia { .. }
| RpcRequest::DropPathTable
| RpcRequest::DropRecentAnnounces => Ok(RpcResponse::IntResult(py_required_int(value)?)),
RpcRequest::GetBlackholedIdentities => {
Ok(RpcResponse::BlackholeList(parse_blackhole_list(value)?))
}
@@ -704,6 +740,24 @@ fn parse_interface_stats(value: &PyValue) -> Result<Vec<InterfaceStatEntry>, Rpc
outgoing_announce_frequency: dict_get(m, "outgoing_announce_frequency")
.and_then(py_f64)
.unwrap_or(0.0),
incoming_pr_frequency: dict_get(m, "incoming_pr_frequency")
.and_then(py_f64)
.unwrap_or(0.0),
outgoing_pr_frequency: dict_get(m, "outgoing_pr_frequency")
.and_then(py_f64)
.unwrap_or(0.0),
burst_active: dict_get(m, "burst_active")
.and_then(py_bool)
.unwrap_or(false),
burst_activated: dict_get(m, "burst_activated")
.and_then(py_f64)
.unwrap_or(0.0),
pr_burst_active: dict_get(m, "pr_burst_active")
.and_then(py_bool)
.unwrap_or(false),
pr_burst_activated: dict_get(m, "pr_burst_activated")
.and_then(py_f64)
.unwrap_or(0.0),
clients: match dict_get(m, "clients") {
Some(PyValue::None) | None => None,
Some(value) => py_u64(value),
@@ -1640,6 +1694,89 @@ mod tests {
}
}
fn interface_stat_entry() -> InterfaceStatEntry {
InterfaceStatEntry {
id: 7,
name: "TestIf".to_string(),
rx_bytes: 100,
tx_bytes: 200,
rx_rate: 10,
tx_rate: 20,
online: true,
bitrate: 115_200,
mtu: 500,
mode: "Gateway".to_string(),
role: "normal".to_string(),
announce_queue: Some(2),
held_announces: 3,
incoming_announce_frequency: 4.0,
outgoing_announce_frequency: 5.0,
incoming_pr_frequency: 6.0,
outgoing_pr_frequency: 7.0,
burst_active: true,
burst_activated: 1_700_000_001.0,
pr_burst_active: true,
pr_burst_activated: 1_700_000_002.0,
clients: Some(4),
announce_rate_target: Some(3600.0),
announce_rate_grace: Some(5),
announce_rate_penalty: Some(30.0),
announce_cap: 0.02,
ifac_size: 0,
tx_drops: 1,
}
}
#[test]
fn test_interface_stats_response_roundtrip_includes_125_fields() {
let resp = RpcResponse::InterfaceStats(vec![interface_stat_entry()]);
let encoded = encode_response(&resp).unwrap();
let decoded =
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap();
match decoded {
RpcResponse::InterfaceStats(entries) => {
assert_eq!(entries.len(), 1);
let entry = &entries[0];
assert_eq!(entry.incoming_pr_frequency, 6.0);
assert_eq!(entry.outgoing_pr_frequency, 7.0);
assert!(entry.burst_active);
assert_eq!(entry.burst_activated, 1_700_000_001.0);
assert!(entry.pr_burst_active);
assert_eq!(entry.pr_burst_activated, 1_700_000_002.0);
}
_ => panic!("wrong variant"),
}
}
#[test]
fn test_interface_stats_parser_defaults_missing_125_fields() {
let legacy = py_dict(vec![(
"interfaces",
PyValue::List(vec![py_dict(vec![
("name", PyValue::String("LegacyIf".to_string())),
("rxb", PyValue::Int(1)),
("txb", PyValue::Int(2)),
("status", PyValue::Bool(true)),
])]),
)]);
let encoded = encode_python_pickle(&legacy).unwrap();
let decoded =
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap();
match decoded {
RpcResponse::InterfaceStats(entries) => {
assert_eq!(entries.len(), 1);
let entry = &entries[0];
assert_eq!(entry.incoming_pr_frequency, 0.0);
assert_eq!(entry.outgoing_pr_frequency, 0.0);
assert!(!entry.burst_active);
assert_eq!(entry.burst_activated, 0.0);
assert!(!entry.pr_burst_active);
assert_eq!(entry.pr_burst_activated, 0.0);
}
_ => panic!("wrong variant"),
}
}
#[test]
fn test_python_blackhole_dict_response_shape() {
let identity_hash = vec![0x42; 16];
@@ -1703,6 +1840,8 @@ mod tests {
RpcRequest::DropPath {
destination_hash: vec![0; 16],
},
RpcRequest::DropPathTable,
RpcRequest::DropRecentAnnounces,
RpcRequest::DropAnnounceQueues,
RpcRequest::BlackholeIdentity {
identity_hash: vec![0; 16],
+40 -8
View File
@@ -222,17 +222,23 @@ async fn query_transport(
query: rns_transport::messages::TransportQuery,
) -> Option<rns_transport::messages::TransportQueryResponse> {
let (tx, rx) = tokio::sync::oneshot::channel();
if transport_tx
.send(TransportMessage::Rpc {
let budget = std::time::Duration::from_secs(5);
let started = std::time::Instant::now();
match tokio::time::timeout(
budget,
transport_tx.send(TransportMessage::Rpc {
query,
response_tx: tx,
})
.await
.is_err()
}),
)
.await
{
return None;
Ok(Ok(())) => {}
Ok(Err(_)) => return None,
Err(_) => return None,
}
tokio::time::timeout(std::time::Duration::from_secs(5), rx)
let remaining = budget.checked_sub(started.elapsed())?;
tokio::time::timeout(remaining, rx)
.await
.ok()
.and_then(|r| r.ok())
@@ -286,6 +292,12 @@ async fn process_rpc_request(
held_announces: e.held_announces,
incoming_announce_frequency: e.incoming_announce_frequency,
outgoing_announce_frequency: e.outgoing_announce_frequency,
incoming_pr_frequency: e.incoming_pr_frequency,
outgoing_pr_frequency: e.outgoing_pr_frequency,
burst_active: e.burst_active,
burst_activated: e.burst_activated,
pr_burst_active: e.pr_burst_active,
pr_burst_activated: e.pr_burst_activated,
clients: e.clients,
announce_rate_target: e.announce_rate_target,
announce_rate_grace: e.announce_rate_grace,
@@ -297,7 +309,9 @@ async fn process_rpc_request(
.collect();
RpcResponse::InterfaceStats(rpc_entries)
}
_ => RpcResponse::InterfaceStats(Vec::new()),
_ => RpcResponse::Error(
"transport actor did not answer interface stats query".to_string(),
),
}
}
RpcRequest::GetRateTable => {
@@ -367,6 +381,22 @@ async fn process_rpc_request(
}
RpcResponse::Ok
}
RpcRequest::DropPathTable => {
if let Some(TransportQueryResponse::IntResult(n)) =
query_transport(transport_tx, TransportQuery::DropPathTable).await
{
return RpcResponse::IntResult(n);
}
RpcResponse::IntResult(0)
}
RpcRequest::DropRecentAnnounces => {
if let Some(TransportQueryResponse::IntResult(n)) =
query_transport(transport_tx, TransportQuery::DropRecentAnnounces).await
{
return RpcResponse::IntResult(n);
}
RpcResponse::IntResult(0)
}
RpcRequest::DropAnnounceQueues => {
let _ = query_transport(transport_tx, TransportQuery::DropAnnounceQueues).await;
RpcResponse::Ok
@@ -847,6 +877,8 @@ listener.close()
RpcRequest::DropAllVia {
transport_hash: vec![0; 16],
},
RpcRequest::DropPathTable,
RpcRequest::DropRecentAnnounces,
RpcRequest::DropAnnounceQueues,
RpcRequest::BlackholeIdentity {
identity_hash: vec![0; 16],
+1 -1
View File
@@ -42,7 +42,7 @@ use rns_runtime::rncp::{
};
const DEFAULT_TIMEOUT_SECS: f64 = 15.0;
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
#[derive(Parser)]
#[command(
+73 -17
View File
@@ -1,6 +1,6 @@
//! rnid-rs - identity create/inspect/sign/verify/encrypt/decrypt.
//!
//! Python reference: `RNS/Utilities/rnid.py` from Reticulum 1.2.4.
//! Python reference: `RNS/Utilities/rnid.py` from Reticulum 1.2.5.
mod rsg;
@@ -26,7 +26,7 @@ use rns_transport::messages::{
#[cfg(feature = "hardware")]
mod hw_commands;
const RETICULUM_COMPAT_VERSION: &str = "1.2.4";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
const DEFAULT_ASPECTS: &str = "rns.id";
const PUB_EXT: &str = "pub";
const SIG_EXT: &str = "rsg";
@@ -159,6 +159,10 @@ struct Args {
#[arg(short = 'B', long)]
base32: bool,
/// Use hex-encoded input and output.
#[arg(long)]
hex: bool,
/// Print version and exit.
#[arg(long)]
version: bool,
@@ -271,8 +275,12 @@ async fn run(mut args: Args) -> ExitCode {
eprintln!("The -i, -g, -m and -M args are mutually exclusive");
return ExitCode::from(1);
}
if args.base64 && args.base32 {
eprintln!("The -b and -B args are mutually exclusive");
let encoding_count = [args.base64, args.base32, args.hex]
.into_iter()
.filter(|flag| *flag)
.count();
if encoding_count > 1 {
eprintln!("The -b, -B and --hex args are mutually exclusive");
return ExitCode::from(1);
}
@@ -858,19 +866,6 @@ fn sign_file(identity: &Identity, args: &Args) -> ExitCode {
return ExitCode::from(6);
}
};
let Some(output_path) = args
.write
.clone()
.or_else(|| Some(append_extension(input_path, SIG_EXT)))
else {
eprintln!("Signing requested, but no output specified");
return ExitCode::from(253);
};
if let Err(e) = ensure_output_allowed(&output_path, args.force) {
eprintln!("{e}");
return ExitCode::from(11);
}
let signature = if args.raw {
match rsg::create_raw_signature(identity, input) {
Ok(signature) => signature.to_vec(),
@@ -888,6 +883,37 @@ fn sign_file(identity: &Identity, args: &Args) -> ExitCode {
}
}
};
if !args.raw && (args.base64 || args.base32 || args.hex) {
let encoded = if args.base64 {
URL_SAFE.encode(&signature)
} else if args.base32 {
encode_base32(&signature)
} else {
hex::encode(&signature)
};
println!("\n{}\n", wrap_rsg(encoded.as_bytes()));
println!(
"Signed file {} with {}",
input_path.display(),
pretty_hash(&identity.hash)
);
return ExitCode::SUCCESS;
}
let Some(output_path) = args
.write
.clone()
.or_else(|| Some(append_extension(input_path, SIG_EXT)))
else {
eprintln!("Signing requested, but no output specified");
return ExitCode::from(253);
};
if let Err(e) = ensure_output_allowed(&output_path, args.force) {
eprintln!("{e}");
return ExitCode::from(11);
}
if let Err(e) = write_output(&output_path, &signature, args.stdout) {
eprintln!("{e}");
return ExitCode::from(253);
@@ -1301,6 +1327,36 @@ fn encode_key_text(bytes: &[u8], args: &Args) -> String {
}
}
fn wrap_rsg(rsg: &[u8]) -> String {
const HEADER: &[u8] = b"#### Start of rsg data ";
const FOOTER: &[u8] = b" End of rsg data ####";
const ROW_WIDTH: usize = 64;
let mut header = String::from_utf8_lossy(HEADER).into_owned();
while header.len() < ROW_WIDTH {
header.push('#');
}
let mut footer = String::new();
while footer.len() + FOOTER.len() < ROW_WIDTH {
footer.push('#');
}
footer.push_str(&String::from_utf8_lossy(FOOTER));
let mut wrapped = String::new();
wrapped.push_str(&header);
wrapped.push('\n');
for chunk in rsg.chunks(ROW_WIDTH) {
wrapped.push_str(&String::from_utf8_lossy(chunk));
for _ in chunk.len()..ROW_WIDTH {
wrapped.push('=');
}
wrapped.push('\n');
}
wrapped.push_str(&footer);
wrapped
}
fn encode_base32(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let mut out = String::new();
+1 -1
View File
@@ -291,7 +291,7 @@ mod tests {
use super::*;
fn message() -> &'static [u8] {
b"Reticulum 1.2.4 rsg test payload"
b"Reticulum 1.2.5 rsg test payload"
}
fn pack_value(value: Value) -> Vec<u8> {
+1 -1
View File
@@ -27,7 +27,7 @@ const REMOTE_TIMEOUT_SECS: u64 = 30;
const REMOTE_HOPS: u8 = 8;
const MGMT_APP: &str = "rnstransport.remote.management";
const BLACKHOLE_APP: &str = "rnstransport.info.blackhole";
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
#[derive(Parser)]
#[command(
+1 -1
View File
@@ -13,7 +13,7 @@ use rns_runtime::probe::{
const DEFAULT_PROBE_SIZE: usize = 16;
const DEFAULT_TIMEOUT_SECS: f64 = 12.0;
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
#[derive(Parser)]
#[command(
+1 -1
View File
@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
use clap::Parser;
use tracing_subscriber::fmt::MakeWriter;
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
const LOG_ROTATE_BYTES: u64 = 5 * 1024 * 1024;
const RNSD_EXAMPLE_CONFIG: &str = r#"# This is an example Reticulum config file.
+2 -2
View File
@@ -23,7 +23,7 @@ use rns_runtime::rnsh::{
};
use tokio::sync::mpsc;
const RNS_VERSION: &str = "1.2.2";
const RNS_VERSION: &str = "1.2.5";
const RNSH_PROTOCOL_VERSION: &str = "0.2.0";
const APP_NAME: &str = "rnsh";
const DEFAULT_SERVICE_NAME: &str = "default";
@@ -872,7 +872,7 @@ mod tests {
fn version_string_uses_rust_command_name() {
assert_eq!(
format!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"),
"rnsh-rs 1.2.2 (protocol 0.2.0)"
"rnsh-rs 1.2.5 (protocol 0.2.0)"
);
}
+261 -8
View File
@@ -27,7 +27,7 @@ const DEFAULT_TIMEOUT_SECS: u64 = 5;
const REMOTE_TIMEOUT_SECS: u64 = 30;
const REMOTE_HOPS: u8 = 8;
const MGMT_APP: &str = "rnstransport.remote.management";
const RETICULUM_COMPAT_VERSION: &str = "1.2.4";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
#[derive(Parser)]
#[command(
@@ -44,15 +44,23 @@ struct Args {
#[arg(short = 'A', long)]
announce_stats: bool,
/// Show path request frequency stats.
#[arg(short = 'P', long = "pr-stats")]
pr_stats: bool,
/// Show link table entry count.
#[arg(short, long)]
link_stats: bool,
/// Only show interfaces with active announce or path request bursts.
#[arg(short = 'B', long)]
burst: bool,
/// Display traffic totals.
#[arg(short, long)]
totals: bool,
/// Sort interfaces by rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held.
/// Sort interfaces by rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx or held.
#[arg(short, long)]
sort: Option<String>,
@@ -200,6 +208,10 @@ async fn run_local_once(args: &Args) -> ExitCode {
match local_rpc_request(&endpoint, &rpc_key, &RpcRequest::GetInterfaceStats, timeout).await
{
Ok(RpcResponse::InterfaceStats(v)) => v,
Ok(RpcResponse::Error(e)) => {
eprintln!("rnstatus-rs: {e}");
return ExitCode::from(1);
}
Ok(other) => {
eprintln!("rnstatus-rs: unexpected response: {other:?}");
return ExitCode::from(1);
@@ -323,6 +335,8 @@ enum SortKey {
Announces,
AnnounceRx,
AnnounceTx,
PathRequestRx,
PathRequestTx,
Held,
}
@@ -353,10 +367,12 @@ fn parse_sort_key(value: Option<&str>) -> Result<Option<SortKey>, String> {
"announces" | "announce" => SortKey::Announces,
"arx" => SortKey::AnnounceRx,
"atx" => SortKey::AnnounceTx,
"prx" => SortKey::PathRequestRx,
"ptx" => SortKey::PathRequestTx,
"held" => SortKey::Held,
_ => {
return Err(format!(
"--sort must be one of rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held; got {value}"
"--sort must be one of rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx or held; got {value}"
));
}
};
@@ -374,6 +390,8 @@ fn local_stat_sort_value(e: &rpc::InterfaceStatEntry, key: SortKey) -> f64 {
SortKey::Announces => e.incoming_announce_frequency + e.outgoing_announce_frequency,
SortKey::AnnounceRx => e.incoming_announce_frequency,
SortKey::AnnounceTx => e.outgoing_announce_frequency,
SortKey::PathRequestRx => e.incoming_pr_frequency,
SortKey::PathRequestTx => e.outgoing_pr_frequency,
SortKey::Held => e.held_announces as f64,
}
}
@@ -394,6 +412,24 @@ fn interface_matches_filter(name: &str, filter: Option<&str>) -> bool {
})
}
fn interface_matches_burst_filter(
name: &str,
burst_active: bool,
pr_burst_active: bool,
args: &Args,
) -> bool {
if !args.burst {
return interface_matches_filter(name, args.filter.as_deref());
}
burst_active
|| pr_burst_active
|| args.filter.as_deref().is_some_and(|filter| {
name.to_ascii_lowercase()
.contains(&filter.to_ascii_lowercase())
})
}
fn filtered_local_stats<'a>(
stats: &'a [rpc::InterfaceStatEntry],
args: &Args,
@@ -401,7 +437,14 @@ fn filtered_local_stats<'a>(
let mut entries: Vec<_> = stats
.iter()
.filter(|entry| args.all || visible_by_default(&entry.name))
.filter(|entry| interface_matches_filter(&entry.name, args.filter.as_deref()))
.filter(|entry| {
interface_matches_burst_filter(
&entry.name,
entry.burst_active,
entry.pr_burst_active,
args,
)
})
.collect();
if let Ok(Some(key)) = parse_sort_key(args.sort.as_deref()) {
entries.sort_by(|a, b| {
@@ -457,6 +500,7 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
}
if entry.incoming_announce_frequency > 0.0
|| entry.outgoing_announce_frequency > 0.0
|| entry.burst_active
{
print_announce_frequency(
entry.incoming_announce_frequency,
@@ -465,9 +509,18 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
entry.announce_rate_target,
entry.announce_rate_penalty,
entry.announce_rate_grace,
burst_status_text(entry.burst_active, entry.burst_activated),
);
}
}
if args.pr_stats {
print_path_request_frequency(
entry.incoming_pr_frequency,
entry.outgoing_pr_frequency,
entry.clients,
burst_status_text(entry.pr_burst_active, entry.pr_burst_activated),
);
}
println!(
" Traffic : {} rx / {} tx",
format::pretty_size(entry.rx_bytes),
@@ -514,7 +567,7 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
print!(",");
}
print!(
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
json_str(&e.name),
e.online,
json_str(&e.mode),
@@ -531,6 +584,12 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
e.held_announces,
e.incoming_announce_frequency,
e.outgoing_announce_frequency,
e.incoming_pr_frequency,
e.outgoing_pr_frequency,
e.burst_active,
e.burst_activated,
e.pr_burst_active,
e.pr_burst_activated,
opt_u64_json(e.clients),
opt_f64_json(e.announce_rate_target),
opt_u32_json(e.announce_rate_grace),
@@ -902,6 +961,12 @@ struct RemoteInterface {
held_announces: u64,
incoming_announce_frequency: f64,
outgoing_announce_frequency: f64,
incoming_pr_frequency: f64,
outgoing_pr_frequency: f64,
burst_active: bool,
burst_activated: f64,
pr_burst_active: bool,
pr_burst_activated: f64,
clients: Option<u64>,
announce_rate_target: Option<f64>,
announce_rate_grace: Option<u32>,
@@ -922,6 +987,8 @@ impl RemoteInterface {
}
SortKey::AnnounceRx => self.incoming_announce_frequency,
SortKey::AnnounceTx => self.outgoing_announce_frequency,
SortKey::PathRequestRx => self.incoming_pr_frequency,
SortKey::PathRequestTx => self.outgoing_pr_frequency,
SortKey::Held => self.held_announces as f64,
}
}
@@ -972,7 +1039,14 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
ifs.iter()
.filter_map(|iface| iface.as_map().map(|m| remote_interface_from_map(m)))
.filter(|iface| args.all || visible_by_default(&iface.name))
.filter(|iface| interface_matches_filter(&iface.name, args.filter.as_deref()))
.filter(|iface| {
interface_matches_burst_filter(
&iface.name,
iface.burst_active,
iface.pr_burst_active,
args,
)
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
@@ -994,7 +1068,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
print!(",");
}
print!(
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
json_str(&iface.name),
iface.online,
iface.mode,
@@ -1010,6 +1084,12 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
iface.held_announces,
iface.incoming_announce_frequency,
iface.outgoing_announce_frequency,
iface.incoming_pr_frequency,
iface.outgoing_pr_frequency,
iface.burst_active,
iface.burst_activated,
iface.pr_burst_active,
iface.pr_burst_activated,
opt_u64_json(iface.clients),
opt_f64_json(iface.announce_rate_target),
opt_u32_json(iface.announce_rate_grace),
@@ -1058,6 +1138,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
}
if iface.incoming_announce_frequency > 0.0
|| iface.outgoing_announce_frequency > 0.0
|| iface.burst_active
{
print_announce_frequency(
iface.incoming_announce_frequency,
@@ -1066,9 +1147,18 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
iface.announce_rate_target,
iface.announce_rate_penalty,
iface.announce_rate_grace,
burst_status_text(iface.burst_active, iface.burst_activated),
);
}
}
if args.pr_stats {
print_path_request_frequency(
iface.incoming_pr_frequency,
iface.outgoing_pr_frequency,
iface.clients,
burst_status_text(iface.pr_burst_active, iface.pr_burst_activated),
);
}
println!(
" Traffic : {} rx / {} tx",
format::pretty_size(iface.rxb),
@@ -1118,6 +1208,12 @@ fn remote_interface_from_map(m: &[(rmpv::Value, rmpv::Value)]) -> RemoteInterfac
.unwrap_or(0.0),
outgoing_announce_frequency: map_f64_or_u64(m, "outgoing_announce_frequency")
.unwrap_or(0.0),
incoming_pr_frequency: map_f64_or_u64(m, "incoming_pr_frequency").unwrap_or(0.0),
outgoing_pr_frequency: map_f64_or_u64(m, "outgoing_pr_frequency").unwrap_or(0.0),
burst_active: map_bool(m, "burst_active").unwrap_or(false),
burst_activated: map_f64_or_u64(m, "burst_activated").unwrap_or(0.0),
pr_burst_active: map_bool(m, "pr_burst_active").unwrap_or(false),
pr_burst_activated: map_f64_or_u64(m, "pr_burst_activated").unwrap_or(0.0),
clients: map_u64(m, "clients"),
announce_rate_target: map_f64_or_u64(m, "announce_rate_target"),
announce_rate_grace: map_u64(m, "announce_rate_grace")
@@ -1157,6 +1253,7 @@ fn print_announce_frequency(
target: Option<f64>,
penalty: Option<f64>,
grace: Option<u32>,
burst_text: String,
) {
let outgoing_text = format!("{}↑", format::pretty_frequency(outgoing));
let incoming_text = format!("{}↓", format::pretty_frequency(incoming));
@@ -1166,7 +1263,38 @@ fn print_announce_frequency(
.unwrap_or_default();
let limits = announce_rate_limits_text(target, penalty, grace);
println!(" Announces: {outgoing_text}{per_client}");
println!(" {incoming_text} {limits}");
println!(" {incoming_text} {limits}{burst_text}");
}
fn print_path_request_frequency(
incoming: f64,
outgoing: f64,
clients: Option<u64>,
burst_text: String,
) {
let outgoing_text = format!("{}↑", format::pretty_frequency(outgoing));
let incoming_text = format!("{}↓", format::pretty_frequency(incoming));
let per_client = clients
.filter(|clients| *clients > 0)
.map(|clients| format!(" {}/c", format::pretty_frequency(outgoing / clients as f64)))
.unwrap_or_default();
println!(" Path Rqs.: {outgoing_text}{per_client}");
println!(" {incoming_text} {burst_text}");
}
fn burst_status_text(active: bool, activated: f64) -> String {
if !active || activated <= 0.0 {
return String::new();
}
let age = (unix_now() - activated).max(0.0);
format!(" burst for {}", format::pretty_time(age))
}
fn unix_now() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
fn announce_rate_limits_text(
@@ -1246,6 +1374,131 @@ fn json_str(s: &str) -> String {
mod tests {
use super::*;
fn test_args() -> Args {
Args {
all: true,
announce_stats: false,
pr_stats: false,
link_stats: false,
burst: false,
totals: false,
sort: None,
reverse: false,
json: false,
config: None,
remote: None,
identity: None,
timeout: None,
discovered: false,
discovered_details: false,
monitor: false,
monitor_interval: 1.0,
version: false,
verbose: 0,
quiet: 0,
filter: None,
}
}
fn local_entry(
name: &str,
burst_active: bool,
pr_burst_active: bool,
) -> rpc::InterfaceStatEntry {
rpc::InterfaceStatEntry {
id: 1,
name: name.to_string(),
rx_bytes: 0,
tx_bytes: 0,
rx_rate: 0,
tx_rate: 0,
online: true,
bitrate: 1,
mtu: 500,
mode: "Full".to_string(),
role: "normal".to_string(),
announce_queue: None,
held_announces: 0,
incoming_announce_frequency: 0.0,
outgoing_announce_frequency: 0.0,
incoming_pr_frequency: 2.0,
outgoing_pr_frequency: 3.0,
burst_active,
burst_activated: if burst_active { 1_700_000_000.0 } else { 0.0 },
pr_burst_active,
pr_burst_activated: if pr_burst_active {
1_700_000_001.0
} else {
0.0
},
clients: None,
announce_rate_target: None,
announce_rate_grace: None,
announce_rate_penalty: None,
announce_cap: 0.0,
ifac_size: 0,
tx_drops: 0,
}
}
#[test]
fn sort_key_accepts_path_request_rates() {
assert_eq!(
parse_sort_key(Some("prx")).unwrap(),
Some(SortKey::PathRequestRx)
);
assert_eq!(
parse_sort_key(Some("ptx")).unwrap(),
Some(SortKey::PathRequestTx)
);
let entry = local_entry("SortIf", false, false);
assert_eq!(local_stat_sort_value(&entry, SortKey::PathRequestRx), 2.0);
assert_eq!(local_stat_sort_value(&entry, SortKey::PathRequestTx), 3.0);
}
#[test]
fn pr_and_burst_flags_parse() {
let args = Args::try_parse_from(["rnstatus-rs", "-P", "-B"]).unwrap();
assert!(args.pr_stats);
assert!(args.burst);
}
#[test]
fn burst_filter_includes_active_bursts_or_name_matches() {
let stats = vec![
local_entry("InactiveIf", false, false),
local_entry("AnnounceBurstIf", true, false),
local_entry("PrBurstIf", false, true),
local_entry("ManualMatchIf", false, false),
];
let mut args = test_args();
args.burst = true;
args.filter = Some("manual".to_string());
let names: Vec<_> = filtered_local_stats(&stats, &args)
.into_iter()
.map(|entry| entry.name.as_str())
.collect();
assert_eq!(names, vec!["AnnounceBurstIf", "PrBurstIf", "ManualMatchIf"]);
}
#[test]
fn remote_status_parser_defaults_missing_125_fields() {
let iface = remote_interface_from_map(&[
(rmpv::Value::from("name"), rmpv::Value::from("LegacyIf")),
(rmpv::Value::from("status"), rmpv::Value::from(true)),
]);
assert_eq!(iface.incoming_pr_frequency, 0.0);
assert_eq!(iface.outgoing_pr_frequency, 0.0);
assert!(!iface.burst_active);
assert_eq!(iface.burst_activated, 0.0);
assert!(!iface.pr_burst_active);
assert_eq!(iface.pr_burst_activated, 0.0);
}
#[test]
fn local_rpc_auth_failure_explains_config_mismatch_and_port_owner() {
let endpoint = SharedInstanceRpcEndpoint::Tcp(37429);
+6 -1
View File
@@ -135,7 +135,12 @@ fn rnid_flag_conflicts_are_rejected() {
let tmp = TempDir::new("rnid-flag-conflicts");
let output = rnid(&tmp, ["-b", "-B"]);
assert_failure(&output, Some(1), "-b and -B", "base64/base32 conflict");
assert_failure(
&output,
Some(1),
"-b, -B and --hex",
"base64/base32 conflict",
);
let generated = tmp.join("identity");
let output = rnid(
+307
View File
@@ -0,0 +1,307 @@
use std::ffi::OsStr;
use std::fs;
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(prefix: &str) -> Self {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_nanos();
let path = std::env::temp_dir().join(format!(
"rsreticulum-{prefix}-{}-{nonce}",
std::process::id()
));
fs::create_dir_all(&path).expect("create tempdir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
fn join(&self, path: impl AsRef<Path>) -> PathBuf {
self.path.join(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
struct ChildGuard {
child: Option<Child>,
}
impl ChildGuard {
fn spawn<I, S>(program: &str, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let child = Command::new(program)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn child process");
Self { child: Some(child) }
}
fn try_wait(&mut self) -> Option<std::process::ExitStatus> {
self.child
.as_mut()
.and_then(|child| child.try_wait().expect("poll child status"))
}
fn terminate_and_output(mut self) -> Output {
let mut child = self.child.take().expect("child already taken");
let _ = child.kill();
child.wait_with_output().expect("collect child output")
}
}
impl Drop for ChildGuard {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
fn free_tcp_port_pair() -> (u16, u16) {
let first = TcpListener::bind("127.0.0.1:0").expect("bind first free tcp port");
let second = TcpListener::bind("127.0.0.1:0").expect("bind second free tcp port");
let first_port = first.local_addr().expect("first local addr").port();
let second_port = second.local_addr().expect("second local addr").port();
(first_port, second_port)
}
fn write_stale_python_destination_table(storage_dir: &Path, entries: usize) {
fs::create_dir_all(storage_dir).expect("create storage dir");
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_secs_f64();
let mut table = rns_transport::path_table::PathTable::new();
for i in 0..entries {
let mut dest = [0u8; 16];
dest[..8].copy_from_slice(&(i as u64).to_be_bytes());
dest[8..].copy_from_slice(&(!i as u64).to_be_bytes());
let mut packet_hash = [0u8; 32];
packet_hash[..8].copy_from_slice(&(i as u64).to_be_bytes());
packet_hash[8..16].copy_from_slice(&(entries as u64).to_be_bytes());
packet_hash[16..24].copy_from_slice(&(0xA5A5_A5A5_A5A5_A5A5u64).to_be_bytes());
packet_hash[24..].copy_from_slice(&(!i as u64).to_be_bytes());
let mut entry = rns_transport::path_table::PathEntry::new(
None,
1,
7,
rns_transport::constants::InterfaceMode::Gateway,
);
entry.timestamp = now;
entry.expires = now + 3600.0;
entry.packet_hash = Some(packet_hash);
table.insert(dest, entry);
}
let mut names = std::collections::HashMap::new();
names.insert(7u64, "Border_TCP".to_string());
rns_transport::persistence::save_python_destination_table(
&table,
&names,
&storage_dir.join("destination_table"),
)
.expect("write Python destination_table");
}
fn output_text(output: &Output) -> (String, String) {
(
String::from_utf8_lossy(&output.stdout).into_owned(),
String::from_utf8_lossy(&output.stderr).into_owned(),
)
}
fn rnstatus_json(tmp: &TempDir, timeout_secs: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_rnstatus-rs"))
.arg("--config")
.arg(tmp.path())
.arg("--json")
.arg("--all")
.arg("--timeout")
.arg(timeout_secs)
.output()
.expect("run rnstatus-rs")
}
fn poll_rnstatus_until<F>(
daemon: &mut ChildGuard,
tmp: &TempDir,
deadline_after: Duration,
timeout_secs: &str,
predicate: F,
) -> Result<(), String>
where
F: Fn(&[serde_json::Value]) -> bool,
{
let deadline = Instant::now() + deadline_after;
let mut last_status = None;
let mut last_stdout = String::new();
let mut last_stderr = String::new();
while Instant::now() < deadline {
if let Some(status) = daemon.try_wait() {
return Err(format!(
"rnsd-rs exited before rnstatus-rs succeeded: {status}"
));
}
let output = rnstatus_json(tmp, timeout_secs);
last_status = output.status.code();
(last_stdout, last_stderr) = output_text(&output);
if output.status.success() {
let value: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("rnstatus-rs JSON output");
let interfaces = value
.get("interfaces")
.and_then(|v| v.as_array())
.expect("interfaces array");
if predicate(interfaces) {
return Ok(());
}
}
thread::sleep(Duration::from_millis(100));
}
Err(format!(
"rnstatus-rs did not report the expected interface before the deadline\n\
last rnstatus status: {last_status:?}\n\
--- last rnstatus stdout ---\n{last_stdout}\n\
--- last rnstatus stderr ---\n{last_stderr}"
))
}
fn panic_with_daemon_output(message: String, daemon: ChildGuard) -> ! {
let daemon_output = daemon.terminate_and_output();
let (daemon_stdout, daemon_stderr) = output_text(&daemon_output);
panic!(
"{message}\n\
--- daemon stdout ---\n{daemon_stdout}\n\
--- daemon stderr ---\n{daemon_stderr}"
);
}
#[test]
fn rnsd_rnstatus_cli_survives_stale_python_destination_table() {
let tmp = TempDir::new("rnsd-rnstatus-stale-python-table");
let (shared_port, control_port) = free_tcp_port_pair();
let rpc_key_hex = "5353535353535353535353535353535353535353535353535353535353535353";
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = {rpc_key_hex}\n\
enable_transport = Yes\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n"
);
fs::write(tmp.join("config"), config).expect("write config");
write_stale_python_destination_table(&tmp.join("storage"), 512);
let mut daemon = ChildGuard::spawn(
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), tmp.path().as_os_str()],
);
if let Err(message) = poll_rnstatus_until(
&mut daemon,
&tmp,
Duration::from_secs(5),
"1",
|interfaces| {
interfaces
.iter()
.any(|entry| entry.get("role").and_then(|v| v.as_str()) == Some("shared_server"))
},
) {
panic_with_daemon_output(message, daemon);
}
}
#[test]
#[ignore = "requires network access to a public Reticulum TCP peer"]
fn rnsd_rnstatus_cli_public_tcp_testnet_smoke() {
let tmp = TempDir::new("rnsd-rnstatus-public-tcp-testnet");
let (shared_port, control_port) = free_tcp_port_pair();
let host = std::env::var("RSRETICULUM_LIVE_TCP_HOST")
.unwrap_or_else(|_| "rns.ratspeak.org".to_string());
let port = std::env::var("RSRETICULUM_LIVE_TCP_PORT")
.ok()
.and_then(|value| value.parse::<u16>().ok())
.unwrap_or(4242);
let rpc_key_hex = "5353535353535353535353535353535353535353535353535353535353535353";
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = {rpc_key_hex}\n\
enable_transport = No\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n\
\n\
[[Public TCP]]\n\
type = TCPClientInterface\n\
enabled = Yes\n\
target_host = {host}\n\
target_port = {port}\n"
);
fs::write(tmp.join("config"), config).expect("write config");
let mut daemon = ChildGuard::spawn(
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), tmp.path().as_os_str()],
);
if let Err(message) = poll_rnstatus_until(
&mut daemon,
&tmp,
Duration::from_secs(10),
"2",
|interfaces| {
interfaces.iter().any(|entry| {
entry.get("name").and_then(|v| v.as_str()) == Some("Public TCP")
&& entry.get("online").and_then(|v| v.as_bool()) == Some(true)
})
},
) {
panic_with_daemon_output(
format!("{message}\nexpected Public TCP to come online for {host}:{port}"),
daemon,
);
}
}
+453 -189
View File
@@ -34,7 +34,7 @@ impl TransportActor {
packet.raw.clone()
};
let (parsed, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
let (mut parsed, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
Ok((header, offset)) => (header, offset),
Err(e) => {
tracing::warn!(
@@ -89,6 +89,8 @@ impl TransportActor {
}
}
parsed.hops = self.adjusted_inbound_hops(parsed.hops, packet.interface_id);
tracing::debug!(
pkt_type = ?parsed.flags.packet_type,
dest = %hex::encode(parsed.destination_hash),
@@ -133,13 +135,73 @@ impl TransportActor {
return;
}
// Per-interface ingress control. Record the announce and, if the
// interface is burst-limiting, hold it for later release by the
// maintenance tick rather than processing now.
//
// Bypass the hold when the announce answers an outstanding path
// request: the announce *is* the resolution, and delaying it there
// would stall the requester for no gain.
let (announce_data, validated_identity) = {
if data_offset >= raw.len() {
tracing::warn!(
dest = hex::encode(header.destination_hash),
"announce missing payload, dropping"
);
return;
}
let payload = &raw[data_offset..];
let has_ratchet = header.flags.context_flag;
tracing::debug!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
has_ratchet = has_ratchet,
header_type = ?header.flags.header_type,
"announce payload received"
);
match rns_identity::announce::AnnounceData::unpack(payload, has_ratchet) {
Ok(announce_data) => {
tracing::debug!(
dest = hex::encode(header.destination_hash),
app_data_len = announce_data.app_data.as_ref().map(|d| d.len()),
has_ratchet_key = announce_data.ratchet.is_some(),
"announce unpacked"
);
match announce_data.verify_signature(&header.destination_hash) {
Ok(validated_identity) => {
if self.blackhole_table.is_blackholed(&validated_identity.hash) {
trace!(
identity = hex::encode(validated_identity.hash),
dest = hex::encode(header.destination_hash),
"announce from blackholed identity, dropping"
);
return;
}
(announce_data, validated_identity)
}
Err(e) => {
tracing::warn!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
error = %e,
"announce validation failed, dropping"
);
return;
}
}
}
Err(e) => {
tracing::warn!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
has_ratchet = has_ratchet,
error = %e,
"announce unpack failed, dropping"
);
return;
}
}
};
// Python validates the announce signature before ingress accounting,
// and only holds still-unknown destinations. Known re-announces and
// path responses for paths we already know must continue refreshing
// route state during an ingress burst.
let announced_destination_known = self.path_table.get(&header.destination_hash).is_some();
let answers_path_request = self.path_requests.contains_key(&header.destination_hash)
|| self
.discovery_path_requests
@@ -147,6 +209,7 @@ impl TransportActor {
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.ingress.received_announce();
if !is_from_local_client
&& !announced_destination_known
&& !answers_path_request
&& entry.ingress.should_ingress_limit()
{
@@ -165,6 +228,36 @@ impl TransportActor {
}
}
let known_public_key = self
.recent_announces
.get(&header.destination_hash)
.and_then(|entry| entry.public_key);
if let Err(e) = announce_data.validate_destination_binding(
&header.destination_hash,
&validated_identity,
known_public_key.as_ref(),
) {
tracing::warn!(
dest = hex::encode(header.destination_hash),
error = %e,
"announce validation failed, dropping"
);
return;
}
tracing::debug!(
dest = hex::encode(header.destination_hash),
app_data_present = announce_data.app_data.is_some(),
"announce validated"
);
let announce_app_data = announce_data.app_data.clone();
let announce_public_key = Some(validated_identity.get_public_key());
let announce_ratchet = announce_data.ratchet;
let announce_name_hash = announce_data.name_hash;
let announce_identity_hash = Some(validated_identity.hash);
let announce_random_hash = announce_data.random_hash;
let mut rate_blocked = false;
// Per-interface rate limiting is opt-in and suppresses rebroadcast
@@ -206,95 +299,6 @@ impl TransportActor {
self.rate_table.record(header.destination_hash);
}
let (
announce_app_data,
announce_public_key,
announce_ratchet,
announce_name_hash,
announce_identity_hash,
announce_random_hash,
) = {
if data_offset >= raw.len() {
tracing::warn!(
dest = hex::encode(header.destination_hash),
"announce missing payload, dropping"
);
return;
}
let payload = &raw[data_offset..];
let has_ratchet = header.flags.context_flag;
tracing::debug!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
has_ratchet = has_ratchet,
header_type = ?header.flags.header_type,
"announce payload received"
);
match rns_identity::announce::AnnounceData::unpack(payload, has_ratchet) {
Ok(announce_data) => {
tracing::debug!(
dest = hex::encode(header.destination_hash),
app_data_len = announce_data.app_data.as_ref().map(|d| d.len()),
has_ratchet_key = announce_data.ratchet.is_some(),
"announce unpacked"
);
let known_public_key = self
.recent_announces
.get(&header.destination_hash)
.and_then(|entry| entry.public_key);
match announce_data.validate_with_known_key(
&header.destination_hash,
known_public_key.as_ref(),
) {
Ok(validated_identity) => {
if self.blackhole_table.is_blackholed(&validated_identity.hash) {
trace!(
identity = hex::encode(validated_identity.hash),
dest = hex::encode(header.destination_hash),
"announce from blackholed identity, dropping"
);
return;
}
tracing::debug!(
dest = hex::encode(header.destination_hash),
app_data_present = announce_data.app_data.is_some(),
"announce validated"
);
(
announce_data.app_data.clone(),
Some(validated_identity.get_public_key()),
announce_data.ratchet,
announce_data.name_hash,
Some(validated_identity.hash),
announce_data.random_hash,
)
}
Err(e) => {
tracing::warn!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
error = %e,
"announce validation failed, dropping"
);
return;
}
}
}
Err(e) => {
tracing::warn!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
has_ratchet = has_ratchet,
error = %e,
"announce unpack failed, dropping"
);
return;
}
}
};
let iface_mode = self
.interfaces
.get(&interface_id)
@@ -342,7 +346,11 @@ impl TransportActor {
.get(&header.destination_hash)
.map(|entry| entry.random_blobs.clone())
.unwrap_or_default();
let should_add = if let Some(existing) = self.path_table.get(&header.destination_hash) {
let suppressed =
self.is_path_interface_suppressed(header.destination_hash, interface_id, now_f64());
let should_add = if suppressed {
false
} else if let Some(existing) = self.path_table.get(&header.destination_hash) {
let random_seen = existing.has_random_blob(&announce_random_hash);
let path_timebase = path_timebase_from_random_blobs(existing.random_blobs.iter());
if header.hops <= existing.hops {
@@ -369,10 +377,12 @@ impl TransportActor {
&& header.hops < PATHFINDER_M
{
let now = now_f64();
let mut rebroadcast_raw = raw.to_vec();
if rebroadcast_raw.len() >= 2 {
rebroadcast_raw[1] = header.hops.saturating_add(1);
}
let rebroadcast_raw = self.transport_announce_from_raw(
raw,
header.destination_hash,
header.hops,
rns_wire::context::PacketContext::None,
);
let announce_entry = crate::announce::AnnounceEntry {
timestamp: now,
retransmit_timeout: if is_from_local_client {
@@ -380,7 +390,11 @@ impl TransportActor {
} else {
now + rand_window()
},
retries: 0,
retries: if is_from_local_client {
PATHFINDER_R
} else {
0
},
received_from: header.transport_id.unwrap_or(header.destination_hash),
hops: header.hops,
packet_raw: rebroadcast_raw,
@@ -411,8 +425,23 @@ impl TransportActor {
entry.random_blobs = random_blobs;
// Store the announce packet hash so a later CacheRequest for this
// destination can replay the exact announce bytes.
entry.packet_hash = Some(rns_wire::hash::packet_hash(raw, header.flags.header_type));
let announce_packet_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
entry.packet_hash = Some(announce_packet_hash);
let tunnel_path = crate::tunnel::TunnelPath {
timestamp: entry.timestamp,
next_hop: entry.next_hop,
hops: entry.hops,
expires: entry.expires,
random_blobs: entry.random_blobs.iter().copied().collect(),
packet_hash: entry.packet_hash,
};
self.path_table.insert(header.destination_hash, entry);
if let Some(tunnel) = self.tunnel_table.get_mut_by_interface(interface_id) {
tunnel
.tunnel_paths
.insert(header.destination_hash, tunnel_path);
tunnel.expires = now_f64() + TUNNEL_TIMEOUT as f64;
}
self.state_dirty = true;
// Wake any callers waiting on a path for this destination.
self.fire_path_waiters(&header.destination_hash);
@@ -441,8 +470,11 @@ impl TransportActor {
dest = hex::encode(header.destination_hash),
hops = header.hops,
announce_emitted,
interface_id,
suppressed,
"ignoring replayed or stale announce"
);
return;
}
// Diagnostics + identity cache. `retained` pins survive re-announce so
@@ -568,7 +600,7 @@ impl TransportActor {
let from_local_client = self.is_local_client_interface(interface_id);
let for_local_client = self
.path_table
.get(&header.destination_hash)
.get_live(&header.destination_hash)
.is_some_and(|path| self.is_local_client_interface(path.interface_id));
let path_request_dest = Self::path_request_dest_hash();
@@ -589,15 +621,6 @@ impl TransportActor {
}
}
// Reverse entries only exist to route proofs back through us, so a
// non-transport node has no reason to keep one unless it is acting for
// a local shared client.
if self.is_transport_enabled || from_local_client {
let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type);
self.reverse_table
.insert(pkt_hash, interface_id, header.hops);
}
if self.route_link_packet_via_link_table(raw, header, interface_id, "data") {
return;
}
@@ -669,28 +692,6 @@ impl TransportActor {
return;
}
if header.context == rns_wire::context::PacketContext::PathResponse {
let iface_mode = self
.interfaces
.get(&interface_id)
.map(|e| e.mode)
.unwrap_or(InterfaceMode::Gateway);
let entry = crate::path_table::PathEntry::new(
Some(header.destination_hash),
header.hops,
interface_id,
iface_mode,
);
self.path_table.insert(header.destination_hash, entry);
self.state_dirty = true;
self.fire_path_waiters(&header.destination_hash);
debug!(
dest = hex::encode(header.destination_hash),
"path learned from PathResponse"
);
return;
}
if header.context == rns_wire::context::PacketContext::CacheRequest {
self.handle_cache_request(raw, header, interface_id);
return;
@@ -717,20 +718,29 @@ impl TransportActor {
return;
}
if self.is_transport_enabled || from_local_client || for_local_client {
if let Some(path) = self.path_table.get(&header.destination_hash) {
let target_interface = path.interface_id;
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops.saturating_add(1);
}
self.send_to_interface(target_interface, &forwarded);
trace!(
dest = hex::encode(header.destination_hash),
via_interface = target_interface,
"data packet forwarded"
);
if let Some((target_interface, forwarded)) = self.transport_forward_candidate(
raw,
header,
interface_id,
from_local_client,
for_local_client,
) {
let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type);
self.reverse_table.insert_with_outbound(
pkt_hash,
interface_id,
header.hops,
Some(target_interface),
);
self.send_to_interface(target_interface, &forwarded);
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
path.touch();
}
trace!(
dest = hex::encode(header.destination_hash),
via_interface = target_interface,
"data packet forwarded"
);
}
}
@@ -743,16 +753,20 @@ impl TransportActor {
let from_local_client = self.is_local_client_interface(interface_id);
let for_local_client = self
.path_table
.get(&header.destination_hash)
.get_live(&header.destination_hash)
.is_some_and(|path| self.is_local_client_interface(path.interface_id));
if self.is_transport_enabled || from_local_client {
let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type);
self.reverse_table
.insert(pkt_hash, interface_id, header.hops);
}
let link_request_for_this_instance = header.transport_id.is_none()
|| header
.transport_id
.zip(self.transport_identity_hash)
.is_some_and(|(packet_transport_id, our_transport_id)| {
packet_transport_id == our_transport_id
});
if self.local_destinations.contains(&header.destination_hash) {
if self.local_destinations.contains(&header.destination_hash)
&& link_request_for_this_instance
{
if let Some(tx) = self.destination_channels.get(&header.destination_hash) {
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::LinkRequest {
raw: raw.clone(),
@@ -766,18 +780,22 @@ impl TransportActor {
return;
}
if let Some(path) = (self.is_transport_enabled || from_local_client || for_local_client)
.then(|| self.path_table.get(&header.destination_hash))
.flatten()
{
let target_interface = path.interface_id;
if let Some((target_interface, forwarded)) = self.transport_forward_candidate(
raw,
header,
interface_id,
from_local_client,
for_local_client,
) {
let Some(path) = self.path_table.get_live(&header.destination_hash) else {
return;
};
let remaining_hops = path.hops;
let next_hop = path.next_hop;
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops.saturating_add(1);
}
self.send_to_interface(target_interface, &forwarded);
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
path.touch();
}
// Cache the relay so the matching LRPROOF can be routed back to
// the initiator without a fresh path lookup. Proof timeout scales
@@ -824,6 +842,92 @@ impl TransportActor {
}
}
fn transport_forward_candidate(
&self,
raw: &[u8],
header: &rns_wire::header::PacketHeader,
interface_id: InterfaceId,
from_local_client: bool,
for_local_client: bool,
) -> Option<(InterfaceId, Vec<u8>)> {
let path = self.path_table.get_live(&header.destination_hash)?;
if path.interface_id == interface_id && !for_local_client {
return None;
}
let may_forward_for_shared_client = from_local_client || for_local_client;
let addressed_to_us = header
.transport_id
.zip(self.transport_identity_hash)
.is_some_and(|(packet_transport_id, our_transport_id)| {
packet_transport_id == our_transport_id
});
// Upstream Transport only relays in-transport packets when the Header2
// transport id names this instance. Shared-instance local-client edges
// are the exception: they are allowed to use the local path cache even
// when packets arrive without normal transport wrapping.
if may_forward_for_shared_client && header.transport_id.is_some() && !addressed_to_us {
return None;
}
if !may_forward_for_shared_client && (!self.is_transport_enabled || !addressed_to_us) {
return None;
}
let forwarded = self.rewrite_forwarded_transport_packet(raw, header, path)?;
Some((path.interface_id, forwarded))
}
fn rewrite_forwarded_transport_packet(
&self,
raw: &[u8],
header: &rns_wire::header::PacketHeader,
path: &crate::path_table::PathEntry,
) -> Option<Vec<u8>> {
let payload_offset = header.size();
if raw.len() < payload_offset {
return None;
}
if path.hops > 1 {
let next_hop = path.next_hop?;
let mut flags = header.flags;
flags.header_type = rns_wire::flags::HeaderType::Header2;
flags.transport_type = rns_wire::flags::TransportType::Transport;
let new_header = rns_wire::header::PacketHeader {
flags,
hops: header.hops,
transport_id: Some(next_hop),
destination_hash: header.destination_hash,
context: header.context,
};
let mut forwarded = new_header.pack();
forwarded.extend_from_slice(&raw[payload_offset..]);
Some(forwarded)
} else if path.hops == 1 {
let mut flags = header.flags;
flags.header_type = rns_wire::flags::HeaderType::Header1;
flags.transport_type = rns_wire::flags::TransportType::Broadcast;
let new_header = rns_wire::header::PacketHeader {
flags,
hops: header.hops,
transport_id: None,
destination_hash: header.destination_hash,
context: header.context,
};
let mut forwarded = new_header.pack();
forwarded.extend_from_slice(&raw[payload_offset..]);
Some(forwarded)
} else {
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops;
}
Some(forwarded)
}
}
fn process_proof(
&mut self,
raw: &bytes::Bytes,
@@ -843,7 +947,9 @@ impl TransportActor {
.get(&header.destination_hash)
.is_some_and(|entry| self.is_local_client_interface(entry.receiving_interface));
if let Some(receipt) = self.receipt_table.get_mut(&header.destination_hash) {
if header.context != rns_wire::context::PacketContext::Lrproof
&& let Some(receipt) = self.receipt_table.get_mut(&header.destination_hash)
{
let rtt = receipt
.get_rtt()
.or_else(|| Some(receipt.sent_at.elapsed()));
@@ -878,38 +984,49 @@ impl TransportActor {
// Link-request proofs route back via the link_table to the interface
// the original request arrived on.
//
// Hop-count note: proofs start at hops=0 at the destination. Python
// auto-increments hops on receipt; we do not, so the equivalence is
// `hops+1 == remaining_hops` here and we bump hops on forward so the
// next relay sees the expected value.
// Proofs start at hops=0 at the destination. We normalise inbound
// hops before dispatch, matching Python Transport's increment-on-
// receive rule, so the proof must equal the remaining hops recorded
// when the request was forwarded.
if header.context == rns_wire::context::PacketContext::Lrproof {
if self.is_transport_enabled || from_local_client || for_local_client_link {
if let Some(link_entry) = self.link_table.get(&header.destination_hash) {
let expected_hops = link_entry.remaining_hops;
let outbound_interface = link_entry.interface_id;
let target_interface = link_entry.receiving_interface;
let destination_hash = link_entry.destination_hash;
// Require that the proof arrived on the same interface we
// forwarded the request to; a mismatch is either a routing
// change or a spoof and must not be relayed.
let hops_match = if expected_hops == 0 {
header.hops == 0
} else {
header.hops.saturating_add(1) == expected_hops
};
let hops_match = header.hops == expected_hops;
if hops_match && _interface_id == outbound_interface {
if !self.validate_transit_lrproof(raw, header, link_entry) {
return;
}
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
if !self.packet_hashlist.insert(pkt_hash) {
trace!(
link_id = hex::encode(header.destination_hash),
"duplicate LRPROOF dropped after link-table claim"
);
return;
}
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops.saturating_add(1);
forwarded[1] = header.hops;
}
if let Some(entry) = self.link_table.get_mut(&header.destination_hash) {
entry.validated = true;
}
self.send_to_interface(target_interface, &forwarded);
if !self.is_shared_instance {
self.use_destination(&destination_hash);
}
debug!(
link_id = hex::encode(header.destination_hash),
via_interface = target_interface,
hops = header.hops + 1,
hops = header.hops,
"link proof (LRPROOF) routed via link table"
);
return;
@@ -918,7 +1035,7 @@ impl TransportActor {
link_id = hex::encode(header.destination_hash),
expected_hops,
actual_hops = header.hops,
"link proof hop mismatch, not transporting (expected hops+1 == remaining_hops)"
"link proof hop mismatch, not transporting"
);
} else {
warn!(
@@ -934,13 +1051,18 @@ impl TransportActor {
// Fall through to local-pending-link delivery when link_table
// didn't claim the proof.
if let Some(tx) = self.destination_channels.get(&header.destination_hash) {
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
raw: raw.clone(),
interface_id: _interface_id,
}) {
let delivered =
tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
raw: raw.clone(),
interface_id: _interface_id,
});
if let Err(e) = delivered {
self.channel_drops += 1;
warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e,
"failed to deliver LRPROOF to local pending link (channel full)");
} else {
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
self.packet_hashlist.insert(pkt_hash);
}
}
return;
@@ -966,7 +1088,11 @@ impl TransportActor {
);
} else {
let target_interface = reverse_entry.receiving_interface;
self.send_to_interface(target_interface, raw);
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops;
}
self.send_to_interface(target_interface, &forwarded);
trace!(
dest = hex::encode(header.destination_hash),
via_interface = target_interface,
@@ -976,7 +1102,11 @@ impl TransportActor {
}
} else {
let target_interface = reverse_entry.receiving_interface;
self.send_to_interface(target_interface, raw);
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops;
}
self.send_to_interface(target_interface, &forwarded);
trace!(
dest = hex::encode(header.destination_hash),
via_interface = target_interface,
@@ -1023,10 +1153,43 @@ impl TransportActor {
return false;
}
let target_interface = if interface_id == entry.receiving_interface {
entry.interface_id
let target_interface = if entry.interface_id == entry.receiving_interface {
if header.hops == entry.remaining_hops || header.hops == entry.taken_hops {
entry.interface_id
} else {
trace!(
link_id = hex::encode(header.destination_hash),
actual_hops = header.hops,
remaining_hops = entry.remaining_hops,
taken_hops = entry.taken_hops,
"link packet hop mismatch, not transporting"
);
return true;
}
} else if interface_id == entry.receiving_interface {
if header.hops == entry.taken_hops {
entry.interface_id
} else {
trace!(
link_id = hex::encode(header.destination_hash),
actual_hops = header.hops,
expected_hops = entry.taken_hops,
"link packet initiator-side hop mismatch, not transporting"
);
return true;
}
} else if interface_id == entry.interface_id {
entry.receiving_interface
if header.hops == entry.remaining_hops {
entry.receiving_interface
} else {
trace!(
link_id = hex::encode(header.destination_hash),
actual_hops = header.hops,
expected_hops = entry.remaining_hops,
"link packet destination-side hop mismatch, not transporting"
);
return true;
}
} else {
warn!(
link_id = hex::encode(header.destination_hash),
@@ -1040,7 +1203,26 @@ impl TransportActor {
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops.saturating_add(1);
forwarded[1] = header.hops;
}
let skip_hashlist = matches!(
header.context,
rns_wire::context::PacketContext::Keepalive
| rns_wire::context::PacketContext::Resource
| rns_wire::context::PacketContext::ResourceReq
| rns_wire::context::PacketContext::ResourcePrf
| rns_wire::context::PacketContext::CacheRequest
| rns_wire::context::PacketContext::Channel
);
if !skip_hashlist {
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
if !self.packet_hashlist.insert(pkt_hash) {
trace!(
link_id = hex::encode(header.destination_hash),
packet_kind, "duplicate link-table packet dropped after claim"
);
return true;
}
}
if let Some(entry) = self.link_table.get_mut(&header.destination_hash) {
entry.timestamp = now_f64();
@@ -1049,10 +1231,92 @@ impl TransportActor {
trace!(
link_id = hex::encode(header.destination_hash),
via_interface = target_interface,
hops = header.hops.saturating_add(1),
hops = header.hops,
packet_kind,
"link packet routed via link table"
);
true
}
fn validate_transit_lrproof(
&self,
raw: &[u8],
header: &rns_wire::header::PacketHeader,
link_entry: &crate::link_table::LinkEntry,
) -> bool {
let payload_offset = header.size();
if raw.len() < payload_offset {
warn!(
link_id = hex::encode(header.destination_hash),
raw_len = raw.len(),
"link proof missing payload, not transporting"
);
return false;
}
let proof_data = &raw[payload_offset..];
if proof_data.len() != 96 && proof_data.len() != 99 {
warn!(
link_id = hex::encode(header.destination_hash),
proof_len = proof_data.len(),
"malformed link request proof length, not transporting"
);
return false;
}
let mut signature = [0u8; 64];
signature.copy_from_slice(&proof_data[..64]);
let responder_x25519_pub = &proof_data[64..96];
let signalling = if proof_data.len() == 99 {
&proof_data[96..99]
} else {
&[]
};
let Some(destination_public_key) = self
.recent_announces
.get(&link_entry.destination_hash)
.and_then(|announce| announce.public_key)
else {
warn!(
link_id = hex::encode(header.destination_hash),
destination = hex::encode(link_entry.destination_hash),
"link request proof has no known destination identity, not transporting"
);
return false;
};
let mut destination_ed25519 = [0u8; 32];
destination_ed25519.copy_from_slice(&destination_public_key[32..64]);
let verify_key =
match rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&destination_ed25519) {
Ok(key) => key,
Err(err) => {
warn!(
link_id = hex::encode(header.destination_hash),
destination = hex::encode(link_entry.destination_hash),
error = %err,
"link request proof destination identity is invalid, not transporting"
);
return false;
}
};
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + signalling.len());
signed_data.extend_from_slice(&header.destination_hash);
signed_data.extend_from_slice(responder_x25519_pub);
signed_data.extend_from_slice(&destination_ed25519);
signed_data.extend_from_slice(signalling);
if verify_key.verify(&signed_data, &signature).is_ok() {
true
} else {
warn!(
link_id = hex::encode(header.destination_hash),
destination = hex::encode(link_entry.destination_hash),
"invalid link request proof signature, not transporting"
);
false
}
}
}
+210 -14
View File
@@ -30,6 +30,8 @@ impl TransportActor {
self.path_table.cull_expired_batch(100);
self.reverse_table.cull_expired_batch(100);
self.tunnel_table.cull_expired_batch(50);
self.cull_stale_tunnel_paths(now);
self.cull_path_interface_suppressions(now);
// Drop entries pointing to interfaces that have gone away —
// those routes could never be used anyway.
@@ -38,17 +40,22 @@ impl TransportActor {
self.reverse_table.cull_dead_interfaces(&active_interfaces);
self.link_table.cull_dead_interfaces(&active_interfaces);
// An unvalidated link whose proof window elapsed means the
// cached path is probably stale — expire it and re-resolve so
// the next attempt doesn't hammer a dead route.
let (_, expired_dests) = self.link_table.cull_stale(LINK_TIMEOUT);
for dest_hash in expired_dests {
self.path_table.expire(&dest_hash);
self.on_path_request(dest_hash);
debug!(
dest = hex::encode(dest_hash),
"unvalidated link expired -- path expired and re-discovery triggered"
);
// Failed link establishment can mean either a stale path or a
// topology change. Queue rediscovery so automated path requests
// are bounded and throttled like upstream Reticulum 1.2.5.
let (_, expired_links) = self.link_table.cull_stale(LINK_TIMEOUT);
let mut queued_dests = HashSet::new();
for expired_link in expired_links {
if let Some(request) = self.rediscovery_request_for_expired_link(expired_link, now)
{
if queued_dests.insert(request.destination_hash) {
self.queue_discovery_path_request(
request.destination_hash,
request.blocked_interface,
now,
);
}
}
}
// Cull may have removed path/tunnel entries — flag for save so
@@ -151,17 +158,170 @@ impl TransportActor {
self.expire_path_waiters(now);
// Drop pending path-request markers older than 30 s so a retried
// request isn't treated as "still in flight".
self.path_requests.retain(|_, last| now - *last < 30.0);
// Drop pending path-request markers after the upstream gate timeout.
self.path_requests
.retain(|_, last| now - *last < PATH_REQUEST_GATE_TIMEOUT);
self.discovery_path_requests
.retain(|_, request| now < request.timeout);
self.discovery_pr_tags
.retain(|_, last| now - *last < PATH_REQUEST_GATE_TIMEOUT);
self.process_pending_discovery_path_requests(now);
self.process_announce_queues(now);
}
pub(super) fn queue_discovery_path_request(
&mut self,
destination_hash: [u8; 16],
blocked_interface: Option<InterfaceId>,
now: f64,
) -> bool {
if self.pending_discovery_prs.len() >= MAX_QUEUED_DISCOVERY_PRS {
trace!(
dest = hex::encode(destination_hash),
"dropping queued discovery path request because queue is full"
);
return false;
}
let was_empty = self.pending_discovery_prs.is_empty();
self.pending_discovery_prs
.push_back(PendingDiscoveryPathRequest {
destination_hash,
blocked_interface,
});
if was_empty {
self.last_discovery_pr_tx = now;
}
true
}
pub(super) fn process_pending_discovery_path_requests(&mut self, now: f64) {
if self.pending_discovery_prs.is_empty() {
return;
}
if now - self.last_discovery_pr_tx < DISCOVERY_PR_TX_THROTTLE {
return;
}
let Some(request) = self.pending_discovery_prs.pop_front() else {
return;
};
self.last_discovery_pr_tx = now;
if let Some(blocked_interface) = request.blocked_interface {
let ids: Vec<InterfaceId> = self
.interfaces
.iter()
.filter_map(|(&id, entry)| {
if id == blocked_interface || !entry.direction.outbound {
None
} else {
Some(id)
}
})
.collect();
for id in ids {
self.send_path_request(request.destination_hash, id, None, false);
}
} else {
let mut request_tag = [0u8; 16];
{
use rand::RngCore;
rand::thread_rng().fill_bytes(&mut request_tag);
}
let ids: Vec<InterfaceId> = self
.interfaces
.iter()
.filter_map(|(&id, entry)| entry.direction.outbound.then_some(id))
.collect();
for id in ids {
self.send_path_request(request.destination_hash, id, Some(&request_tag), false);
}
}
}
#[cfg(test)]
pub(super) fn handle_expired_unvalidated_link(
&mut self,
expired_link: crate::link_table::ExpiredLink,
now: f64,
) {
if let Some(request) = self.rediscovery_request_for_expired_link(expired_link, now) {
self.queue_discovery_path_request(
request.destination_hash,
request.blocked_interface,
now,
);
}
}
fn rediscovery_request_for_expired_link(
&mut self,
expired_link: crate::link_table::ExpiredLink,
now: f64,
) -> Option<PendingDiscoveryPathRequest> {
let destination_hash = expired_link.destination_hash;
let last_path_request = self
.path_requests
.get(&destination_hash)
.copied()
.unwrap_or(0.0);
let path_request_throttle = now - last_path_request < PATH_REQUEST_MI;
let mut blocked_interface = None;
let mut should_request = false;
if !self.path_table.has_path(&destination_hash) {
should_request = true;
} else if !path_request_throttle {
if expired_link.taken_hops == 0 {
should_request = true;
} else if self.path_table.hops_to(&destination_hash) == Some(1)
|| expired_link.taken_hops == 1
{
should_request = true;
blocked_interface = Some(expired_link.receiving_interface);
self.mark_failed_link_path_unresponsive(&expired_link);
}
}
if !should_request {
return None;
}
if !self.is_transport_enabled {
self.path_table.expire(&destination_hash);
}
debug!(
dest = hex::encode(destination_hash),
blocked_interface, "unvalidated link expired -- queued re-discovery"
);
Some(PendingDiscoveryPathRequest {
destination_hash,
blocked_interface,
})
}
fn mark_failed_link_path_unresponsive(
&mut self,
expired_link: &crate::link_table::ExpiredLink,
) {
if !self.is_transport_enabled {
return;
}
let receiving_is_boundary = self
.interfaces
.get(&expired_link.receiving_interface)
.is_some_and(|entry| entry.mode == InterfaceMode::Boundary);
if !receiving_is_boundary {
self.path_table
.set_state(expired_link.destination_hash, PathState::Unresponsive);
}
}
/// Called on background → foreground. Resets every `last_*_check` so the
/// next `on_tick` runs all maintenance paths in one go.
pub(super) fn on_resume(&mut self) {
@@ -271,6 +431,42 @@ impl TransportActor {
}
}
pub(super) fn cull_stale_tunnel_paths(&mut self, now: f64) {
let mut removed = 0usize;
for (tunnel_id, tunnel) in self.tunnel_table.iter_mut() {
let stale: Vec<[u8; 16]> = tunnel
.tunnel_paths
.iter()
.filter_map(|(dest_hash, tunnel_path)| {
if now > tunnel_path.timestamp + TUNNEL_PATH_TIMEOUT as f64 {
return Some(*dest_hash);
}
let active = self.path_table.get_live(dest_hash)?;
let current_timebase =
path_timebase_from_random_blobs(active.random_blobs.iter());
let tunnel_timebase =
path_timebase_from_random_blobs(tunnel_path.random_blobs.iter());
(current_timebase > tunnel_timebase).then_some(*dest_hash)
})
.collect();
for dest_hash in stale {
tunnel.tunnel_paths.remove(&dest_hash);
removed += 1;
debug!(
dest = hex::encode(dest_hash),
tunnel = hex::encode(&tunnel_id[..16]),
"removed stale tunnel path"
);
}
}
if removed > 0 {
self.state_dirty = true;
}
}
/// Sweep `recent_announces`. Keep retained + pathed entries; reap the
/// rest past `DESTINATION_TIMEOUT` (7 days). No count cap.
pub(super) fn cleanup_known_destinations(&mut self, now: f64) {
File diff suppressed because it is too large. Load diff
+117 -79
View File
@@ -57,7 +57,7 @@ impl TransportActor {
self.broadcast_on_interfaces(&request.raw, None);
}
rns_wire::flags::DestinationType::Single | rns_wire::flags::DestinationType::Link => {
if let Some(path) = self.path_table.get(&request.destination_hash) {
if let Some(path) = self.path_table.get_live(&request.destination_hash) {
let target_interface = path.interface_id;
let path_hops = path.hops;
let path_next_hop = path.next_hop;
@@ -112,8 +112,8 @@ impl TransportActor {
// Touch the path so an actively-used route isn't culled
// for staleness while traffic is still flowing on it.
if let Some(path) = self.path_table.get_mut(&request.destination_hash) {
path.timestamp = now_f64();
if let Some(path) = self.path_table.get_live_mut(&request.destination_hash) {
path.touch();
}
} else {
let iface_names: Vec<&str> = self
@@ -128,7 +128,7 @@ impl TransportActor {
"outbound: no path, broadcasting"
);
self.broadcast_on_interfaces(&request.raw, None);
self.on_path_request(request.destination_hash);
self.on_automatic_path_request(request.destination_hash);
}
}
}
@@ -283,6 +283,10 @@ impl TransportActor {
return;
};
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.ingress.received_path_request();
}
let now = now_f64();
let mut unique_tag = Vec::with_capacity(32);
unique_tag.extend_from_slice(&requested_dest);
@@ -321,7 +325,7 @@ impl TransportActor {
}
if !is_from_local_client {
if let Some(path) = self.path_table.get(&requested_dest) {
if let Some(path) = self.path_table.get_live(&requested_dest) {
if self.is_local_client_interface(path.interface_id) {
self.pending_local_path_requests
.insert(requested_dest, interface_id);
@@ -333,7 +337,7 @@ impl TransportActor {
// shared instance's path cache even when the instance is not a transport
// node. Ordinary peers still require transport mode.
if let Some(path) = (self.is_transport_enabled || is_from_local_client)
.then(|| self.path_table.get(&requested_dest))
.then(|| self.path_table.get_live(&requested_dest))
.flatten()
{
let requestor_is_next_hop =
@@ -424,29 +428,39 @@ impl TransportActor {
);
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, false);
} else if self.is_transport_enabled && should_search_unknown {
let should_forward = match self.discovery_path_requests.entry(requested_dest) {
std::collections::hash_map::Entry::Occupied(_) => {
debug!(
dest = %hex::encode(requested_dest),
"not forwarding path request — discovery request is already waiting"
);
false
}
std::collections::hash_map::Entry::Vacant(entry) => {
debug!(
dest = %hex::encode(requested_dest),
"forwarding path request on other interfaces"
);
entry.insert(DiscoveryPathRequest {
requesting_interface: interface_id,
timeout: now + PATH_REQUEST_TIMEOUT,
});
true
}
};
if should_forward {
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, true);
if self.discovery_path_requests.contains_key(&requested_dest) {
debug!(
dest = %hex::encode(requested_dest),
"not forwarding path request — discovery request is already waiting"
);
return;
}
let ingress_limited = self
.interfaces
.get_mut(&interface_id)
.is_some_and(|iface| iface.ingress.should_ingress_limit_pr());
if ingress_limited {
debug!(
dest = %hex::encode(requested_dest),
interface_id,
"not forwarding recursive path request — ingress PR burst active"
);
return;
}
debug!(
dest = %hex::encode(requested_dest),
"forwarding path request on other interfaces"
);
self.discovery_path_requests.insert(
requested_dest,
DiscoveryPathRequest {
requesting_interface: interface_id,
timeout: now + PATH_REQUEST_TIMEOUT,
},
);
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, true);
} else if self.has_local_client_interfaces() {
debug!(
dest = %hex::encode(requested_dest),
@@ -501,16 +515,61 @@ impl TransportActor {
raw
}
fn send_path_request(
pub(super) fn send_path_request(
&mut self,
destination_hash: [u8; 16],
interface_id: InterfaceId,
tag: Option<&[u8]>,
_recursive: bool,
recursive: bool,
) {
let raw = self.build_path_request_packet(destination_hash, tag);
let now = now_f64();
{
let Some(entry) = self.interfaces.get_mut(&interface_id) else {
return;
};
if !entry.direction.outbound {
return;
}
if recursive {
if entry.ingress.should_egress_limit_pr() {
trace!(
dest = %hex::encode(destination_hash),
interface_id,
"skipping recursive path request — egress PR limit active"
);
return;
}
if !entry.announce_queue.is_empty() {
trace!(
dest = %hex::encode(destination_hash),
interface_id,
"skipping recursive path request — announce queue is not empty"
);
return;
}
if now < entry.announce_allowed_at {
trace!(
dest = %hex::encode(destination_hash),
interface_id,
"skipping recursive path request — announce cap window active"
);
return;
}
let bitrate = entry.bitrate.max(1) as f64;
let tx_time = (raw.len() as f64 * 8.0) / bitrate;
let wait_time = tx_time / entry.announce_cap.max(0.001);
entry.announce_allowed_at = now + wait_time;
}
}
self.send_to_interface(interface_id, &raw);
self.path_requests.insert(destination_hash, now_f64());
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.ingress.sent_path_request();
}
self.path_requests.insert(destination_hash, now);
}
fn forward_path_request(
@@ -537,60 +596,29 @@ impl TransportActor {
}
pub(super) fn on_path_request(&mut self, destination_hash: [u8; 16]) {
let now = now_f64();
if let Some(last) = self.path_requests.get(&destination_hash) {
if now - last < PATH_REQUEST_MI {
return;
}
}
self.path_requests.insert(destination_hash, now);
self.broadcast_path_request(destination_hash);
}
pub(super) fn on_automatic_path_request(&mut self, destination_hash: [u8; 16]) {
if self.path_table.has_path(&destination_hash) {
return;
}
if let Some(last) = self.path_requests.get(&destination_hash) {
if now_f64() - last < PATH_REQUEST_MI {
return;
}
}
self.broadcast_path_request(destination_hash);
}
// Python Transport.request_path sends a PLAIN packet to the
// rnstransport.path.request destination. The payload is the requested
// destination hash, optionally followed by the transport identity hash,
// and a random tag used for request deduplication.
fn broadcast_path_request(&mut self, destination_hash: [u8; 16]) {
let mut request_tag = [0u8; 16];
{
use rand::RngCore;
rand::thread_rng().fill_bytes(&mut request_tag);
}
let mut request_data = Vec::with_capacity(48);
request_data.extend_from_slice(&destination_hash);
if self.is_transport_enabled {
if let Some(identity_hash) = self.transport_identity_hash {
request_data.extend_from_slice(&identity_hash);
}
}
request_data.extend_from_slice(&request_tag);
let path_request_dest = rns_identity::destination::Destination::hash_from_name_and_identity(
"rnstransport.path.request",
None,
);
let flags = rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Plain,
packet_type: rns_wire::flags::PacketType::Data,
};
let path_request_header = rns_wire::header::PacketHeader {
flags,
hops: 0,
transport_id: None,
destination_hash: path_request_dest,
context: rns_wire::context::PacketContext::None,
};
let mut request_raw = path_request_header.pack();
request_raw.extend_from_slice(&request_data);
self.broadcast_on_interfaces(&request_raw, None);
self.forward_path_request(destination_hash, None, Some(&request_tag), false);
debug!(
dest = hex::encode(destination_hash),
@@ -622,10 +650,19 @@ impl TransportActor {
if let Some(existing) = self.path_table.get(dest_hash) {
let old_hops = existing.hops;
let old_expires = existing.expires;
// Only overwrite a live path if the tunnel copy is at least
// as short, or the live entry is already stale.
if tunnel_path.hops <= old_hops || now > old_expires {
should_add = true;
let current_timebase =
path_timebase_from_random_blobs(existing.random_blobs.iter());
let tunnel_timebase =
path_timebase_from_random_blobs(tunnel_path.random_blobs.iter());
if tunnel_timebase >= current_timebase {
should_add = true;
} else {
debug!(
dest = hex::encode(dest_hash),
"did not restore tunnel path: existing path is more recent"
);
}
} else {
debug!(
dest = hex::encode(dest_hash),
@@ -644,12 +681,12 @@ impl TransportActor {
if should_add {
let entry = crate::path_table::PathEntry {
timestamp: now,
next_hop: None,
next_hop: tunnel_path.next_hop,
hops: tunnel_path.hops,
expires: tunnel_path.expires,
random_blobs: tunnel_path.random_blobs.iter().copied().collect(),
interface_id,
packet_hash: None,
packet_hash: tunnel_path.packet_hash,
};
self.path_table.insert(*dest_hash, entry);
self.state_dirty = true;
@@ -675,6 +712,7 @@ impl TransportActor {
);
}
}
self.state_dirty = true;
}
}
}
+269 -18
View File
@@ -10,6 +10,81 @@ fn now() -> f64 {
.unwrap_or(0.0)
}
fn recent_announce_from_cached_packet(
dest_hash: [u8; 16],
hops: u8,
timestamp: f64,
raw_packet: Vec<u8>,
) -> RecentAnnounce {
let mut recent = RecentAnnounce {
dest_hash,
hops,
app_data: None,
timestamp,
public_key: None,
ratchet: None,
raw_packet,
retained: false,
name_hash: [0u8; 10],
};
if let Ok((header, offset)) = rns_wire::header::PacketHeader::unpack(&recent.raw_packet)
&& header.flags.packet_type == rns_wire::flags::PacketType::Announce
&& header.destination_hash == dest_hash
&& recent.raw_packet.len() >= offset
&& let Ok(announce) = rns_identity::announce::AnnounceData::unpack(
&recent.raw_packet[offset..],
header.flags.context_flag,
)
{
recent.app_data = announce.app_data;
recent.public_key = Some(announce.public_key);
recent.ratchet = announce.ratchet;
recent.name_hash = announce.name_hash;
}
recent
}
fn python_announce_cache_index(
announce_cache_dir: &std::path::Path,
) -> Option<std::collections::HashSet<String>> {
match std::fs::read_dir(announce_cache_dir) {
Ok(entries) => {
let mut names = std::collections::HashSet::new();
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str()
&& name.len() == 64
&& name.as_bytes().iter().all(u8::is_ascii_hexdigit)
{
names.insert(name.to_ascii_lowercase());
}
}
Some(names)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Some(std::collections::HashSet::new())
}
Err(_) => None,
}
}
fn load_indexed_python_cached_announce(
announce_cache_dir: &std::path::Path,
cache_index: Option<&std::collections::HashSet<String>>,
packet_hash: &[u8; 32],
) -> Result<Option<crate::persistence::PythonCachedAnnounce>, crate::persistence::PersistenceError>
{
if let Some(index) = cache_index {
let name = hex::encode(packet_hash);
if !index.contains(&name) {
return Ok(None);
}
}
crate::persistence::load_python_cached_announce(announce_cache_dir, packet_hash)
}
impl TransportActor {
/// Flush the small/critical routing-state files: path_table,
/// announce_cache, blackhole_table, tunnel_table. Hashlist is excluded —
@@ -20,6 +95,13 @@ impl TransportActor {
/// `state_dirty` and bumps `last_state_save` so the periodic trigger
/// doesn't double-fire.
pub(super) fn save_routing_state(&mut self) {
if self.shared_instance_client_mode {
trace!("skipping routing-state save in shared-instance client mode");
self.state_dirty = false;
self.last_state_save = now();
return;
}
if let Some(ref dir) = self.storage_dir {
let interface_names: std::collections::HashMap<u64, String> = self
.interfaces
@@ -84,8 +166,9 @@ impl TransportActor {
}
let announce_cache_dir = dir.join("cache").join("announces");
if let Err(e) = crate::persistence::save_python_announce_cache_for_paths(
if let Err(e) = crate::persistence::save_python_announce_cache_for_paths_and_tunnels(
&self.path_table,
Some(&self.tunnel_table),
self.recent_announces.values(),
&interface_names,
&announce_cache_dir,
@@ -104,6 +187,15 @@ impl TransportActor {
debug!("saved tunnel table ({} entries)", self.tunnel_table.len());
}
let python_tunnels_path = dir.join("tunnels");
if let Err(e) = crate::persistence::save_python_tunnel_table(
&self.tunnel_table,
&interface_names,
&python_tunnels_path,
) {
trace!("failed to save Python tunnels table: {}", e);
}
// Single-line summary for diagnosing periodic routing-state saves
// without surfacing normal flushes at default log levels.
debug!(
@@ -124,6 +216,9 @@ impl TransportActor {
pub(super) fn save_state(&mut self) {
// Routing state first so the order matches the periodic-save shape.
self.save_routing_state();
if self.shared_instance_client_mode {
return;
}
if let Some(ref dir) = self.storage_dir {
let hashlist_path = dir.join("packet_hashlist");
@@ -186,13 +281,15 @@ impl TransportActor {
let mut missing_cache = 0usize;
let mut pending = 0usize;
let announce_cache_dir = dir.join("cache").join("announces");
let announce_cache_index = python_announce_cache_index(&announce_cache_dir);
for pe in entries {
if pe.expires <= now_ts {
expired += 1;
continue;
}
let cached = match crate::persistence::load_python_cached_announce(
let cached = match load_indexed_python_cached_announce(
&announce_cache_dir,
announce_cache_index.as_ref(),
&pe.packet_hash,
) {
Ok(Some(cached)) => cached,
@@ -229,16 +326,13 @@ impl TransportActor {
});
self.recent_announces
.entry(pe.destination_hash)
.or_insert_with(|| RecentAnnounce {
dest_hash: pe.destination_hash,
hops: pe.hops,
app_data: None,
timestamp: pe.timestamp,
public_key: None,
ratchet: None,
raw_packet: cached.raw_packet,
retained: false,
name_hash: [0u8; 10],
.or_insert_with(|| {
recent_announce_from_cached_packet(
pe.destination_hash,
pe.hops,
pe.timestamp,
cached.raw_packet,
)
});
pending += 1;
}
@@ -323,9 +417,121 @@ impl TransportActor {
}
self.load_python_blackhole_if_ready();
// tunnel_table — defer remap.
// Python tunnels — canonical interop shape. Each path is only staged
// when its cached announce packet is present, mirroring upstream's
// dependency between tunnel paths and the announce cache.
let python_tunnels_path = dir.join("tunnels");
let loaded_python_tunnel_table = if python_tunnels_path.exists() {
match crate::persistence::load_python_tunnel_table(&python_tunnels_path) {
Ok(entries) => {
let total = entries.len();
let mut expired = 0usize;
let mut missing_cache = 0usize;
let mut legacy = 0usize;
let mut pending = 0usize;
let announce_cache_dir = dir.join("cache").join("announces");
let announce_cache_index = python_announce_cache_index(&announce_cache_dir);
for te in entries {
if te.expires <= now_ts {
expired += 1;
continue;
}
let mut paths = Vec::new();
let mut interface_name = None;
let mut interface_hash =
te.interface_hash.as_ref().map(|hash| hash.to_vec());
for tp in te.paths {
if tp.expires <= now_ts {
expired += 1;
continue;
}
if interface_hash.is_none() {
interface_hash =
tp.interface_hash.as_ref().map(|hash| hash.to_vec());
}
let cached = match load_indexed_python_cached_announce(
&announce_cache_dir,
announce_cache_index.as_ref(),
&tp.packet_hash,
) {
Ok(Some(cached)) => cached,
Ok(None) | Err(_) => {
missing_cache += 1;
continue;
}
};
if interface_name.is_none() {
interface_name = cached.interface_reference.clone();
}
let next_hop = if tp.received_from == tp.destination_hash {
None
} else {
Some(tp.received_from.to_vec())
};
paths.push(crate::persistence::PersistedTunnelPath {
destination_hash: tp.destination_hash.to_vec(),
next_hop,
hops: tp.hops,
expires: tp.expires,
timestamp: tp.timestamp,
random_blobs: tp
.random_blobs
.iter()
.map(|blob| blob.to_vec())
.collect(),
packet_hash: Some(tp.packet_hash.to_vec()),
});
self.recent_announces
.entry(tp.destination_hash)
.or_insert_with(|| {
recent_announce_from_cached_packet(
tp.destination_hash,
tp.hops,
tp.timestamp,
cached.raw_packet,
)
});
}
if paths.is_empty() {
continue;
}
if interface_name.is_none() && interface_hash.is_none() {
legacy += 1;
continue;
}
self.pending_tunnel_entries.push(
crate::persistence::PersistedTunnelEntry {
tunnel_id: te.tunnel_id.to_vec(),
interface_id: 0,
expires: te.expires,
paths,
interface_name,
interface_hash,
},
);
pending += 1;
}
debug!(
total,
pending, expired, missing_cache, legacy, "staged Python tunnel entries"
);
pending > 0
}
Err(e) => {
trace!("failed to load Python tunnels table: {}", e);
false
}
}
} else {
false
};
// tunnel_table — legacy Rust sidecar fallback, defer remap.
let tunnel_path = dir.join("tunnel_table.msgpack");
if tunnel_path.exists() {
if !loaded_python_tunnel_table && tunnel_path.exists() {
match crate::persistence::load_tunnel_table(&tunnel_path) {
Ok(entries) => {
let total = entries.len();
@@ -340,7 +546,7 @@ impl TransportActor {
expired += 1;
continue;
}
if te.interface_name.is_none() {
if te.interface_name.is_none() && te.interface_hash.is_none() {
legacy += 1;
continue;
}
@@ -364,10 +570,18 @@ impl TransportActor {
match crate::persistence::load_announce_cache(&announce_path) {
Ok(entries) => {
let count = entries.len();
let mut expired = 0usize;
for ae in entries {
if ae.destination_hash.len() == 16 {
let mut hash = [0u8; 16];
hash.copy_from_slice(&ae.destination_hash);
let stale_pathless = !ae.retained
&& !self.recent_announces.contains_key(&hash)
&& now_ts - ae.timestamp > DESTINATION_TIMEOUT as f64;
if stale_pathless {
expired += 1;
continue;
}
let public_key = ae.public_key.and_then(|k| {
if k.len() == 64 {
let mut arr = [0u8; 64];
@@ -408,7 +622,7 @@ impl TransportActor {
});
}
}
debug!("loaded {} announce cache entries from disk", count);
debug!(count, expired, "loaded announce cache entries from disk");
}
Err(e) => {
trace!("failed to load announce cache: {}", e);
@@ -535,7 +749,11 @@ impl TransportActor {
if !self.pending_tunnel_entries.is_empty() {
let mut promoted = 0usize;
self.pending_tunnel_entries.retain(|te| {
if te.interface_name.as_deref() != Some(name) {
let name_matches = te.interface_name.as_deref() == Some(name);
let hash_matches = te.interface_hash.as_deref().is_some_and(|hash| {
hash == crate::persistence::interface_hash_from_name(name).as_slice()
});
if !name_matches && !hash_matches {
return true;
}
if te.tunnel_id.len() != 32 {
@@ -548,13 +766,46 @@ impl TransportActor {
if tp.destination_hash.len() == 16 {
let mut dest = [0u8; 16];
dest.copy_from_slice(&tp.destination_hash);
let next_hop = tp.next_hop.as_ref().and_then(|next_hop| {
if next_hop.len() == 16 {
let mut arr = [0u8; 16];
arr.copy_from_slice(next_hop);
Some(arr)
} else {
None
}
});
let packet_hash = tp.packet_hash.as_ref().and_then(|packet_hash| {
if packet_hash.len() == 32 {
let mut arr = [0u8; 32];
arr.copy_from_slice(packet_hash);
Some(arr)
} else {
None
}
});
let random_blobs = tp
.random_blobs
.iter()
.filter_map(|blob| {
if blob.len() == 10 {
let mut arr = [0u8; 10];
arr.copy_from_slice(blob);
Some(arr)
} else {
None
}
})
.collect();
tunnel_paths.insert(
dest,
crate::tunnel::TunnelPath {
timestamp: tp.timestamp,
next_hop,
hops: tp.hops,
expires: tp.expires,
random_blobs: vec![],
random_blobs,
packet_hash,
},
);
}
+100 -15
View File
@@ -10,7 +10,7 @@ impl TransportActor {
TransportQuery::GetPathTable => {
let entries: Vec<PathTableRpcEntry> = self
.path_table
.iter()
.iter_live()
.map(|(hash, entry)| {
let iface_name = self
.interfaces
@@ -24,12 +24,24 @@ impl TransportActor {
hops: entry.hops,
expires: entry.expires,
interface: iface_name,
interface_id: entry.interface_id,
interface_mode: self
.interfaces
.get(&entry.interface_id)
.map(|e| e.mode)
.unwrap_or(crate::constants::InterfaceMode::Full),
interface_role: self
.interfaces
.get(&entry.interface_id)
.map(|e| e.role)
.unwrap_or_default(),
}
})
.collect();
TransportQueryResponse::PathTable(entries)
}
TransportQuery::GetInterfaceStats => {
let now = now_f64();
let stats: Vec<InterfaceStatRpcEntry> = self
.interfaces
.iter()
@@ -66,7 +78,23 @@ impl TransportActor {
incoming_announce_frequency: entry
.ingress
.incoming_announce_frequency(),
outgoing_announce_frequency: 0.0,
outgoing_announce_frequency: entry
.ingress
.outgoing_announce_frequency(),
incoming_pr_frequency: entry.ingress.incoming_pr_frequency(),
outgoing_pr_frequency: entry.ingress.outgoing_pr_frequency(),
burst_active: entry.ingress.is_burst_active(),
burst_activated: activation_epoch(
now,
entry.ingress.is_burst_active(),
entry.ingress.burst_activated(),
),
pr_burst_active: entry.ingress.is_pr_burst_active(),
pr_burst_activated: activation_epoch(
now,
entry.ingress.is_pr_burst_active(),
entry.ingress.pr_burst_activated(),
),
clients: None,
announce_rate_target: entry.announce_rate_target,
announce_rate_grace: entry.announce_rate_grace,
@@ -101,14 +129,24 @@ impl TransportActor {
let mut entries: Vec<AnnounceRpcEntry> = self
.recent_announces
.values()
.map(|a| AnnounceRpcEntry {
dest_hash: a.dest_hash,
hops: a.hops,
app_data: a.app_data.clone(),
timestamp: a.timestamp,
public_key: a.public_key,
ratchet: a.ratchet,
retained: a.retained,
.map(|a| {
let is_path_response =
rns_wire::header::PacketHeader::unpack(&a.raw_packet)
.ok()
.is_some_and(|(header, _)| {
header.context == rns_wire::context::PacketContext::PathResponse
});
AnnounceRpcEntry {
dest_hash: a.dest_hash,
hops: a.hops,
app_data: a.app_data.clone(),
timestamp: a.timestamp,
public_key: a.public_key,
ratchet: a.ratchet,
name_hash: a.name_hash,
is_path_response,
retained: a.retained,
}
})
.collect();
// HashMap iteration order is unspecified; sort newest-first
@@ -122,13 +160,13 @@ impl TransportActor {
TransportQueryResponse::Announces(entries)
}
TransportQuery::GetNextHop { dest } => {
let next_hop = self.path_table.get(&dest).and_then(|e| e.next_hop);
let next_hop = self.path_table.get_live(&dest).and_then(|e| e.next_hop);
TransportQueryResponse::HashResult(next_hop)
}
TransportQuery::GetNextHopIfName { dest } => {
let name = self
.path_table
.get(&dest)
.get_live(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id).map(|i| i.name.clone()));
TransportQueryResponse::StringResult(name)
}
@@ -157,12 +195,48 @@ impl TransportActor {
self.state_dirty = true;
TransportQueryResponse::Ok
}
TransportQuery::SuppressPathInterface {
dest,
interface_id,
duration,
} => TransportQueryResponse::BoolResult(self.suppress_path_interface(
dest,
interface_id,
duration,
)),
TransportQuery::SuppressCurrentPathInterface { dest, duration } => {
let interface_id = self
.path_table
.get_live(&dest)
.map(|entry| entry.interface_id);
TransportQueryResponse::BoolResult(interface_id.is_some_and(|interface_id| {
self.suppress_path_interface(dest, interface_id, duration)
}))
}
TransportQuery::DropAnnounceQueues => {
for entry in self.interfaces.values_mut() {
entry.announce_queue.clear();
}
TransportQueryResponse::Ok
}
TransportQuery::DropPathTable => {
let cleared = self.path_table.len();
self.path_table = crate::path_table::PathTable::new();
self.pending_path_entries.clear();
self.discovery_path_requests.clear();
self.pending_local_path_requests.clear();
self.pending_discovery_prs.clear();
self.state_dirty = true;
self.save_routing_state();
TransportQueryResponse::IntResult(cleared as i64)
}
TransportQuery::DropRecentAnnounces => {
let cleared = self.recent_announces.len();
self.recent_announces.clear();
self.state_dirty = true;
self.save_routing_state();
TransportQueryResponse::IntResult(cleared as i64)
}
TransportQuery::GetBlackholedIdentities => {
// Snapshot of identity hashes we have a current announce for —
// used to decorate each entry with `verified`.
@@ -386,19 +460,22 @@ impl TransportActor {
TransportQuery::GetNextHopBitrate { dest } => {
let bitrate = self
.path_table
.get(&dest)
.get_live(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id))
.map(|iface| iface.bitrate as f64);
TransportQueryResponse::FloatResult(bitrate)
}
TransportQuery::GetNextHopInterfaceId { dest } => {
let id = self.path_table.get(&dest).map(|e| e.interface_id as i64);
let id = self
.path_table
.get_live(&dest)
.map(|e| e.interface_id as i64);
TransportQueryResponse::IntResult(id.unwrap_or(-1))
}
TransportQuery::FirstHopTimeout { dest } => {
let timeout = self
.path_table
.get(&dest)
.get_live(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id))
.map(|iface| {
let per_byte_latency = 8.0 / iface.bitrate as f64;
@@ -521,3 +598,11 @@ impl TransportActor {
}
}
}
fn activation_epoch(now: f64, active: bool, activated: std::time::Instant) -> f64 {
if active {
now - activated.elapsed().as_secs_f64()
} else {
0.0
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ pub struct AnnounceEntry {
pub received_from: [u8; 16],
/// Hop count as observed on receipt.
pub hops: u8,
/// Outbound packet bytes with the hop count already incremented.
/// Outbound packet bytes with the Python-parity inbound-adjusted hop count.
pub packet_raw: Vec<u8>,
/// Count of duplicate rebroadcasts heard from neighbours — used to suppress flooding.
pub local_rebroadcasts: u32,
+2 -1
View File
@@ -2,7 +2,8 @@
//!
//! Mirrors Python `Transport.await_path(destination_hash, timeout=None)`
//! (RNS/Transport.py:2524). The helper sends an [`AwaitPath`] actor
//! message and races the oneshot reply against a caller-supplied timeout.
//! message and races the oneshot reply against a caller-supplied timeout. The
//! actor emits the upstream-compatible path request before parking the waiter.
//!
//! [`AwaitPath`]: crate::messages::TransportMessage::AwaitPath
+57 -15
View File
@@ -53,6 +53,12 @@ pub const PATH_REQUEST_TIMEOUT: f64 = 15.0;
/// Duplicate inbound path request tag retention (seconds).
pub const PATH_REQUEST_GATE_TIMEOUT: f64 = 120.0;
/// Maximum queued automatic discovery path requests after failed link setup.
pub const MAX_QUEUED_DISCOVERY_PRS: usize = 32;
/// Minimum spacing between queued discovery path-request transmissions.
pub const DISCOVERY_PR_TX_THROTTLE: f64 = 0.5;
/// Grace before path response (seconds).
pub const PATH_REQUEST_GRACE: f64 = 0.4;
@@ -116,41 +122,77 @@ pub const ANNOUNCE_CAP: f64 = 0.02;
pub const MAX_HELD_ANNOUNCES: usize = 256;
/// Held announce release interval (seconds).
/// Matches Python 1.2.4 `Interface.IC_HELD_RELEASE_INTERVAL = 2`.
pub const IC_HELD_RELEASE_INTERVAL: f64 = 2.0;
/// Matches Python 1.2.5 `Interface.IC_HELD_RELEASE_INTERVAL = 5`.
pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0;
/// Incoming announce frequency window samples.
/// Matches Python 1.2.4 `Interface.IA_FREQ_SAMPLES = 128`.
pub const IA_FREQ_SAMPLES: usize = 128;
/// Matches Python 1.2.5 `Interface.IA_FREQ_SAMPLES = 48`.
pub const IA_FREQ_SAMPLES: usize = 48;
/// Outgoing announce frequency window samples.
/// Matches Python 1.2.4 `Interface.OA_FREQ_SAMPLES = 128`.
pub const OA_FREQ_SAMPLES: usize = 128;
/// Matches Python 1.2.5 `Interface.OA_FREQ_SAMPLES = 48`.
pub const OA_FREQ_SAMPLES: usize = 48;
/// Incoming path-request frequency window samples.
/// Matches Python 1.2.5 `Interface.IP_FREQ_SAMPLES = 48`.
pub const IP_FREQ_SAMPLES: usize = 48;
/// Outgoing path-request frequency window samples.
/// Matches Python 1.2.5 `Interface.OP_FREQ_SAMPLES = 48`.
pub const OP_FREQ_SAMPLES: usize = 48;
/// Minimum non-zero announce frequency represented by the decay window.
pub const AR_MINFREQ_HZ: f64 = 0.1;
/// Minimum non-zero path-request frequency represented by the decay window.
pub const PR_MINFREQ_HZ: f64 = 0.1;
/// Frequency decay window for announces (seconds).
pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ;
/// Frequency decay window for path requests (seconds).
pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ;
/// Minimum samples required before frequency is considered defined.
/// Matches Python 1.2.4 `Interface.IC_DEQUE_MIN_SAMPLE = 32`.
pub const IC_DEQUE_MIN_SAMPLE: usize = 32;
/// Matches Python 1.2.5 `Interface.IC_DEQUE_MIN_SAMPLE = 2`.
pub const IC_DEQUE_MIN_SAMPLE: usize = 2;
/// Minimum samples required for burst state clearing / egress PR limiting.
/// Matches Python 1.2.5 `Interface.IC_BURST_MIN_SAMPLES = 6`.
pub const IC_BURST_MIN_SAMPLES: usize = 6;
/// Duration interface is treated as "new" (seconds).
/// Matches Python `Interface.IC_NEW_TIME = 2*60*60`.
pub const IC_NEW_TIME: f64 = 7200.0;
/// Burst threshold for new interfaces (announces/sec).
/// Matches Python 1.2.4 `Interface.IC_BURST_FREQ_NEW = 6`.
pub const IC_BURST_FREQ_NEW: f64 = 6.0;
/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ_NEW = 3`.
pub const IC_BURST_FREQ_NEW: f64 = 3.0;
/// Burst threshold for established interfaces (announces/sec).
/// Matches Python 1.2.4 `Interface.IC_BURST_FREQ = 35`.
pub const IC_BURST_FREQ: f64 = 35.0;
/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ = 10`.
pub const IC_BURST_FREQ: f64 = 10.0;
/// Path-request burst threshold for new interfaces (requests/sec).
pub const IC_PR_BURST_FREQ_NEW: f64 = 3.0;
/// Path-request burst threshold for established interfaces (requests/sec).
pub const IC_PR_BURST_FREQ: f64 = 8.0;
/// Burst detection active duration (seconds).
/// Matches Python `Interface.IC_BURST_HOLD = 1*60`.
pub const IC_BURST_HOLD: f64 = 60.0;
/// Matches Python 1.2.5 `Interface.IC_BURST_HOLD = 15`.
pub const IC_BURST_HOLD: f64 = 15.0;
/// Burst penalty delay (seconds).
/// Matches Python 1.2.4 `Interface.IC_BURST_PENALTY = 15`.
/// Matches Python 1.2.5 `Interface.IC_BURST_PENALTY = 15`.
pub const IC_BURST_PENALTY: f64 = 15.0;
/// Optional outgoing path-request limiter threshold (requests/sec).
pub const EC_PR_FREQ: f64 = 5.0;
/// Whether outgoing path-request limiting is active by default.
pub const EGRESS_CONTROL: bool = false;
/// Tunnel timeout (8 hours, in seconds).
/// Matches Python 1.1.6 `Transport.TUNNEL_TIMEOUT = 60*60*8`.
pub const TUNNEL_TIMEOUT: u64 = 28_800;
+443 -30
View File
@@ -1,4 +1,4 @@
//! Per-interface ingress control: announce flood protection.
//! Per-interface ingress/egress control for announce and path-request floods.
//!
//! Each interface owns one `IngressController`. The inbound path consults it
//! on every announce — when the incoming rate crosses the burst threshold the
@@ -15,9 +15,10 @@ use std::time::{Duration, Instant};
use bytes::Bytes;
use crate::constants::{
IA_FREQ_SAMPLES, IC_BURST_FREQ, IC_BURST_FREQ_NEW, IC_BURST_HOLD, IC_BURST_PENALTY,
IC_DEQUE_MIN_SAMPLE, IC_HELD_RELEASE_INTERVAL, IC_NEW_TIME, MAX_HELD_ANNOUNCES,
OA_FREQ_SAMPLES,
AR_FREQ_DECAY, EC_PR_FREQ, EGRESS_CONTROL, IA_FREQ_SAMPLES, IC_BURST_FREQ, IC_BURST_FREQ_NEW,
IC_BURST_HOLD, IC_BURST_MIN_SAMPLES, IC_BURST_PENALTY, IC_DEQUE_MIN_SAMPLE,
IC_HELD_RELEASE_INTERVAL, IC_NEW_TIME, IC_PR_BURST_FREQ, IC_PR_BURST_FREQ_NEW, IP_FREQ_SAMPLES,
MAX_HELD_ANNOUNCES, OA_FREQ_SAMPLES, OP_FREQ_SAMPLES, PR_FREQ_DECAY,
};
/// Per-interface ingress overrides parsed from `[interface.<name>] ic_*` keys.
@@ -27,11 +28,15 @@ pub struct IngressOverrides {
pub enabled: Option<bool>,
pub burst_freq_new: Option<f64>,
pub burst_freq: Option<f64>,
pub pr_burst_freq_new: Option<f64>,
pub pr_burst_freq: Option<f64>,
pub new_time: Option<f64>,
pub burst_hold: Option<f64>,
pub burst_penalty: Option<f64>,
pub max_held: Option<usize>,
pub held_release_interval: Option<f64>,
pub ec_pr_freq: Option<f64>,
pub egress_control: Option<bool>,
}
impl IngressOverrides {
@@ -39,11 +44,15 @@ impl IngressOverrides {
self.enabled.is_none()
&& self.burst_freq_new.is_none()
&& self.burst_freq.is_none()
&& self.pr_burst_freq_new.is_none()
&& self.pr_burst_freq.is_none()
&& self.new_time.is_none()
&& self.burst_hold.is_none()
&& self.burst_penalty.is_none()
&& self.max_held.is_none()
&& self.held_release_interval.is_none()
&& self.ec_pr_freq.is_none()
&& self.egress_control.is_none()
}
}
@@ -65,19 +74,29 @@ pub struct IngressController {
ia_freq_deque: VecDeque<Instant>,
/// Outgoing announce timestamps; capped at `OA_FREQ_SAMPLES`.
oa_freq_deque: VecDeque<Instant>,
/// Incoming path-request timestamps; capped at `IP_FREQ_SAMPLES`.
ip_freq_deque: VecDeque<Instant>,
/// Outgoing path-request timestamps; capped at `OP_FREQ_SAMPLES`.
op_freq_deque: VecDeque<Instant>,
burst_active: bool,
burst_activated: Instant,
pr_burst_active: bool,
pr_burst_activated: Instant,
/// Earliest instant at which the next held announce may be released.
held_release: Instant,
held_announces: HashMap<[u8; 16], HeldAnnounce>,
burst_freq_new: f64,
burst_freq: f64,
pr_burst_freq_new: f64,
pr_burst_freq: f64,
new_time: f64,
burst_hold: f64,
burst_penalty: f64,
max_held: usize,
held_release_interval: f64,
ec_pr_freq: f64,
egress_control: bool,
}
impl IngressController {
@@ -88,17 +107,25 @@ impl IngressController {
enabled: true,
ia_freq_deque: VecDeque::with_capacity(IA_FREQ_SAMPLES),
oa_freq_deque: VecDeque::with_capacity(OA_FREQ_SAMPLES),
ip_freq_deque: VecDeque::with_capacity(IP_FREQ_SAMPLES),
op_freq_deque: VecDeque::with_capacity(OP_FREQ_SAMPLES),
burst_active: false,
burst_activated: now,
pr_burst_active: false,
pr_burst_activated: now,
held_release: now,
held_announces: HashMap::new(),
burst_freq_new: IC_BURST_FREQ_NEW,
burst_freq: IC_BURST_FREQ,
pr_burst_freq_new: IC_PR_BURST_FREQ_NEW,
pr_burst_freq: IC_PR_BURST_FREQ,
new_time: IC_NEW_TIME,
burst_hold: IC_BURST_HOLD,
burst_penalty: IC_BURST_PENALTY,
max_held: MAX_HELD_ANNOUNCES,
held_release_interval: IC_HELD_RELEASE_INTERVAL,
ec_pr_freq: EC_PR_FREQ,
egress_control: EGRESS_CONTROL,
}
}
@@ -125,6 +152,12 @@ impl IngressController {
if let Some(v) = overrides.burst_freq {
ctrl.burst_freq = v;
}
if let Some(v) = overrides.pr_burst_freq_new {
ctrl.pr_burst_freq_new = v;
}
if let Some(v) = overrides.pr_burst_freq {
ctrl.pr_burst_freq = v;
}
if let Some(v) = overrides.new_time {
ctrl.new_time = v;
}
@@ -140,6 +173,12 @@ impl IngressController {
if let Some(v) = overrides.held_release_interval {
ctrl.held_release_interval = v;
}
if let Some(v) = overrides.ec_pr_freq {
ctrl.ec_pr_freq = v;
}
if let Some(v) = overrides.egress_control {
ctrl.egress_control = v;
}
ctrl
}
@@ -151,6 +190,22 @@ impl IngressController {
self.burst_freq_new
}
pub fn pr_burst_freq(&self) -> f64 {
self.pr_burst_freq
}
pub fn pr_burst_freq_new(&self) -> f64 {
self.pr_burst_freq_new
}
pub fn ec_pr_freq(&self) -> f64 {
self.ec_pr_freq
}
pub fn is_egress_control_enabled(&self) -> bool {
self.egress_control
}
pub fn held_release_interval(&self) -> f64 {
self.held_release_interval
}
@@ -171,27 +226,51 @@ impl IngressController {
}
pub fn received_announce(&mut self) {
let now = Instant::now();
if self.ia_freq_deque.len() >= IA_FREQ_SAMPLES {
self.ia_freq_deque.pop_front();
}
self.ia_freq_deque.push_back(now);
push_sample(&mut self.ia_freq_deque, IA_FREQ_SAMPLES, Instant::now());
}
pub fn sent_announce(&mut self) {
let now = Instant::now();
if self.oa_freq_deque.len() >= OA_FREQ_SAMPLES {
self.oa_freq_deque.pop_front();
}
self.oa_freq_deque.push_back(now);
push_sample(&mut self.oa_freq_deque, OA_FREQ_SAMPLES, Instant::now());
}
pub fn received_path_request(&mut self) {
push_sample(&mut self.ip_freq_deque, IP_FREQ_SAMPLES, Instant::now());
}
pub fn sent_path_request(&mut self) {
push_sample(&mut self.op_freq_deque, OP_FREQ_SAMPLES, Instant::now());
}
pub fn incoming_announce_frequency(&self) -> f64 {
frequency_from_deque(&self.ia_freq_deque)
frequency_from_deque(
&self.ia_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(AR_FREQ_DECAY),
)
}
pub fn outgoing_announce_frequency(&self) -> f64 {
frequency_from_deque(&self.oa_freq_deque)
frequency_from_deque(
&self.oa_freq_deque,
1,
Duration::from_secs_f64(AR_FREQ_DECAY),
)
}
pub fn incoming_pr_frequency(&self) -> f64 {
frequency_from_deque(
&self.ip_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(PR_FREQ_DECAY),
)
}
pub fn outgoing_pr_frequency(&self) -> f64 {
frequency_from_deque(
&self.op_freq_deque,
1,
Duration::from_secs_f64(PR_FREQ_DECAY),
)
}
/// Whether inbound announces should currently be held. Also updates the
@@ -209,13 +288,18 @@ impl IngressController {
self.burst_freq
};
let ia_freq = self.incoming_announce_frequency();
let ia_freq = frequency_from_deque_mut(
&mut self.ia_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(AR_FREQ_DECAY),
);
let now = Instant::now();
if self.burst_active {
if ia_freq < freq_threshold
&& now.duration_since(self.burst_activated)
> Duration::from_secs_f64(self.burst_hold)
&& self.ia_freq_deque.len() >= IC_BURST_MIN_SAMPLES
{
self.burst_active = false;
}
@@ -230,6 +314,58 @@ impl IngressController {
}
}
/// Whether unknown recursive path-request discovery should be suppressed
/// on this ingress interface.
pub fn should_ingress_limit_pr(&mut self) -> bool {
if !self.enabled {
return false;
}
let freq_threshold = if self.age() < self.new_time {
self.pr_burst_freq_new
} else {
self.pr_burst_freq
};
let ip_freq = frequency_from_deque_mut(
&mut self.ip_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(PR_FREQ_DECAY),
);
let now = Instant::now();
if self.pr_burst_active {
if ip_freq < freq_threshold
&& now.duration_since(self.pr_burst_activated)
> Duration::from_secs_f64(self.burst_hold)
{
self.pr_burst_active = false;
}
true
} else if ip_freq > freq_threshold {
self.pr_burst_active = true;
self.pr_burst_activated = now;
true
} else {
false
}
}
/// Whether outgoing path-request transmission should be skipped on this
/// interface. This limiter is off by default in Reticulum 1.2.5.
pub fn should_egress_limit_pr(&mut self) -> bool {
if !self.egress_control {
return false;
}
let op_freq = frequency_from_deque_mut(
&mut self.op_freq_deque,
1,
Duration::from_secs_f64(PR_FREQ_DECAY),
);
op_freq > self.ec_pr_freq && self.op_freq_deque.len() >= IC_BURST_MIN_SAMPLES
}
pub fn hold_announce(&mut self, announce: HeldAnnounce) {
if self.held_announces.contains_key(&announce.destination_hash)
|| self.held_announces.len() < self.max_held
@@ -240,11 +376,12 @@ impl IngressController {
}
/// Release at most one held announce per call — the one with the lowest
/// hop count, so short-path announces win priority. `None` means either
/// the burst is still active, the release cooldown has not elapsed, or
/// the buffer is empty.
/// hop count, so short-path announces win priority. This intentionally
/// does not consult `should_ingress_limit()`: upstream releases held
/// announces based on release time and current announce frequency, even if
/// the displayed burst state has not cleared yet.
pub fn try_release_held(&mut self) -> Option<HeldAnnounce> {
if self.should_ingress_limit() || self.held_announces.is_empty() {
if self.held_announces.is_empty() {
return None;
}
@@ -259,7 +396,12 @@ impl IngressController {
self.burst_freq
};
if self.incoming_announce_frequency() >= freq_threshold {
let ia_freq = frequency_from_deque_mut(
&mut self.ia_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(AR_FREQ_DECAY),
);
if ia_freq >= freq_threshold {
return None;
}
@@ -281,6 +423,18 @@ impl IngressController {
pub fn is_burst_active(&self) -> bool {
self.burst_active
}
pub fn burst_activated(&self) -> Instant {
self.burst_activated
}
pub fn is_pr_burst_active(&self) -> bool {
self.pr_burst_active
}
pub fn pr_burst_activated(&self) -> Instant {
self.pr_burst_activated
}
}
impl Default for IngressController {
@@ -289,32 +443,118 @@ impl Default for IngressController {
}
}
/// Announces-per-second estimate over a timestamp deque. Returns 0 until
/// enough samples have accumulated (`IC_DEQUE_MIN_SAMPLE`) so the first few
/// entries on a new interface cannot trip the limiter by themselves.
fn frequency_from_deque(deque: &VecDeque<Instant>) -> f64 {
fn push_sample(deque: &mut VecDeque<Instant>, cap: usize, now: Instant) {
if deque.len() >= cap {
deque.pop_front();
}
deque.push_back(now);
}
/// Snapshot frequency over a timestamp deque. Stale samples are ignored for
/// observability without mutating the controller from read-only status paths.
fn frequency_from_deque(deque: &VecDeque<Instant>, min_samples: usize, decay: Duration) -> f64 {
let now = Instant::now();
let oldest = deque
.iter()
.find(|sample| sample_age(now, **sample) <= decay);
let Some(oldest) = oldest else {
return 0.0;
};
let n = deque
.iter()
.filter(|sample| sample_age(now, **sample) <= decay)
.count();
frequency_from_parts(n, now, *oldest, min_samples)
}
/// Mutable limiter frequency. Mirrors upstream's decay side effect by dropping
/// one stale oldest sample when the observed window is older than the decay
/// horizon, then calculating from the current sample count and oldest span.
fn frequency_from_deque_mut(
deque: &mut VecDeque<Instant>,
min_samples: usize,
decay: Duration,
) -> f64 {
let n = deque.len();
if n <= IC_DEQUE_MIN_SAMPLE {
if n <= min_samples {
return 0.0;
}
let span = match deque.front() {
Some(oldest) => oldest.elapsed().as_secs_f64(),
None => return 0.0,
let now = Instant::now();
let Some(oldest) = deque.front().copied() else {
return 0.0;
};
if sample_age(now, oldest) > decay {
deque.pop_front();
}
frequency_from_parts(n, now, oldest, min_samples)
}
fn frequency_from_parts(n: usize, now: Instant, oldest: Instant, min_samples: usize) -> f64 {
if n <= min_samples {
return 0.0;
}
let span = sample_age(now, oldest).as_secs_f64();
if span <= 0.0 { 0.0 } else { n as f64 / span }
}
fn sample_age(now: Instant, sample: Instant) -> Duration {
now.checked_duration_since(sample)
.unwrap_or_else(|| Duration::from_secs(0))
}
#[cfg(test)]
mod tests {
use super::*;
fn push_samples(
deque: &mut VecDeque<Instant>,
cap: usize,
count: usize,
oldest_age: f64,
spacing: f64,
) {
let now = Instant::now();
for i in 0..count {
let age = oldest_age - (i as f64 * spacing);
push_sample(deque, cap, now - Duration::from_secs_f64(age.max(0.0)));
}
}
#[test]
fn reticulum_125_control_constants_are_pinned() {
assert_eq!(IA_FREQ_SAMPLES, 48);
assert_eq!(OA_FREQ_SAMPLES, 48);
assert_eq!(IP_FREQ_SAMPLES, 48);
assert_eq!(OP_FREQ_SAMPLES, 48);
assert_eq!(AR_FREQ_DECAY, 10.0);
assert_eq!(PR_FREQ_DECAY, 10.0);
assert_eq!(IC_DEQUE_MIN_SAMPLE, 2);
assert_eq!(IC_BURST_MIN_SAMPLES, 6);
assert_eq!(IC_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_BURST_FREQ, 10.0);
assert_eq!(IC_PR_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_PR_BURST_FREQ, 8.0);
assert_eq!(IC_BURST_HOLD, 15.0);
assert_eq!(IC_BURST_PENALTY, 15.0);
assert_eq!(IC_HELD_RELEASE_INTERVAL, 5.0);
assert_eq!(EC_PR_FREQ, 5.0);
const { assert!(!EGRESS_CONTROL) };
}
#[test]
fn ingress_controller_default_state() {
let ctrl = IngressController::new();
assert!(ctrl.is_enabled());
assert!(!ctrl.is_burst_active());
assert!(!ctrl.is_pr_burst_active());
assert!(!ctrl.is_egress_control_enabled());
assert_eq!(ctrl.pr_burst_freq_new(), IC_PR_BURST_FREQ_NEW);
assert_eq!(ctrl.pr_burst_freq(), IC_PR_BURST_FREQ);
assert_eq!(ctrl.ec_pr_freq(), EC_PR_FREQ);
assert_eq!(ctrl.held_count(), 0);
assert_eq!(ctrl.incoming_announce_frequency(), 0.0);
assert_eq!(ctrl.incoming_pr_frequency(), 0.0);
assert_eq!(ctrl.outgoing_pr_frequency(), 0.0);
}
#[test]
@@ -326,6 +566,179 @@ mod tests {
assert!(!ctrl.should_ingress_limit());
}
#[test]
fn disabled_ingress_control_keeps_frequency_stats() {
let mut ctrl = IngressController::disabled();
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.2);
push_samples(&mut ctrl.ip_freq_deque, IP_FREQ_SAMPLES, 4, 1.0, 0.2);
assert!(!ctrl.should_ingress_limit());
assert!(!ctrl.should_ingress_limit_pr());
assert!(ctrl.incoming_announce_frequency() > 0.0);
assert!(ctrl.incoming_pr_frequency() > 0.0);
}
#[test]
fn announce_frequency_ignores_decayed_samples_for_stats() {
let mut ctrl = IngressController::new();
push_samples(
&mut ctrl.ia_freq_deque,
IA_FREQ_SAMPLES,
IC_DEQUE_MIN_SAMPLE + 2,
AR_FREQ_DECAY + 2.0,
0.1,
);
assert_eq!(ctrl.incoming_announce_frequency(), 0.0);
}
#[test]
fn pr_frequency_ignores_decayed_samples_for_stats() {
let mut ctrl = IngressController::new();
push_samples(
&mut ctrl.ip_freq_deque,
IP_FREQ_SAMPLES,
IC_DEQUE_MIN_SAMPLE + 2,
PR_FREQ_DECAY + 2.0,
0.1,
);
assert_eq!(ctrl.incoming_pr_frequency(), 0.0);
}
#[test]
fn announce_burst_clears_only_with_minimum_remaining_samples() {
let mut ctrl = IngressController::new();
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.1);
assert!(ctrl.should_ingress_limit());
assert!(ctrl.is_burst_active());
ctrl.burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
ctrl.ia_freq_deque.clear();
push_samples(
&mut ctrl.ia_freq_deque,
IA_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES,
AR_FREQ_DECAY + 1.0,
0.1,
);
assert!(ctrl.should_ingress_limit());
assert!(ctrl.is_burst_active());
ctrl.burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
ctrl.ia_freq_deque.clear();
push_samples(
&mut ctrl.ia_freq_deque,
IA_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES + 1,
AR_FREQ_DECAY + 1.0,
0.1,
);
assert!(ctrl.should_ingress_limit());
assert!(!ctrl.is_burst_active());
}
#[test]
fn held_release_poll_does_not_activate_burst_when_nothing_is_held() {
let mut ctrl = IngressController::new();
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.1);
assert!(ctrl.try_release_held().is_none());
assert!(!ctrl.is_burst_active());
}
#[test]
fn held_announces_release_even_if_burst_state_is_waiting_for_clear_samples() {
let mut ctrl = IngressController::new();
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.1);
assert!(ctrl.should_ingress_limit());
assert!(ctrl.is_burst_active());
ctrl.burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
ctrl.ia_freq_deque.clear();
push_samples(
&mut ctrl.ia_freq_deque,
IA_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES,
AR_FREQ_DECAY + 1.0,
0.1,
);
assert!(ctrl.should_ingress_limit());
assert!(ctrl.is_burst_active());
ctrl.held_release = Instant::now() - Duration::from_secs(1);
ctrl.hold_announce(HeldAnnounce {
raw: Bytes::from_static(&[1, 2, 3]),
destination_hash: [0xA5; 16],
hops: 1,
receiving_interface_id: 1,
});
let released = ctrl.try_release_held();
assert!(released.is_some());
assert!(ctrl.is_burst_active());
}
#[test]
fn pr_ingress_burst_activates_and_clears() {
let mut ctrl = IngressController::new();
push_samples(&mut ctrl.ip_freq_deque, IP_FREQ_SAMPLES, 4, 1.0, 0.1);
assert!(ctrl.should_ingress_limit_pr());
assert!(ctrl.is_pr_burst_active());
ctrl.pr_burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
ctrl.ip_freq_deque.clear();
push_samples(
&mut ctrl.ip_freq_deque,
IP_FREQ_SAMPLES,
IC_DEQUE_MIN_SAMPLE + 1,
PR_FREQ_DECAY + 1.0,
0.1,
);
assert!(ctrl.should_ingress_limit_pr());
assert!(!ctrl.is_pr_burst_active());
assert!(!ctrl.should_ingress_limit_pr());
}
#[test]
fn pr_egress_limiting_is_optional_and_requires_six_samples() {
let mut disabled = IngressController::new();
push_samples(
&mut disabled.op_freq_deque,
OP_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES + 2,
1.0,
0.1,
);
assert!(!disabled.should_egress_limit_pr());
let mut ctrl = IngressController::with_overrides(&IngressOverrides {
egress_control: Some(true),
ec_pr_freq: Some(EC_PR_FREQ),
..Default::default()
});
push_samples(
&mut ctrl.op_freq_deque,
OP_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES - 1,
1.0,
0.1,
);
assert!(!ctrl.should_egress_limit_pr());
ctrl.op_freq_deque.clear();
push_samples(
&mut ctrl.op_freq_deque,
OP_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES,
1.0,
0.1,
);
assert!(ctrl.should_egress_limit_pr());
}
#[test]
fn hold_announce_dedups_by_destination() {
let mut ctrl = IngressController::new();
+32 -6
View File
@@ -25,6 +25,30 @@ pub struct LinkEntry {
pub taken_hops: u8,
}
/// Metadata retained when an unvalidated link expires before proof.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExpiredLink {
pub next_hop: Option<[u8; 16]>,
pub interface_id: InterfaceId,
pub remaining_hops: u8,
pub destination_hash: [u8; 16],
pub receiving_interface: InterfaceId,
pub taken_hops: u8,
}
impl From<&LinkEntry> for ExpiredLink {
fn from(entry: &LinkEntry) -> Self {
Self {
next_hop: entry.next_hop,
interface_id: entry.interface_id,
remaining_hops: entry.remaining_hops,
destination_hash: entry.destination_hash,
receiving_interface: entry.receiving_interface,
taken_hops: entry.taken_hops,
}
}
}
pub struct LinkTable {
entries: HashMap<LinkId, LinkEntry>,
}
@@ -73,9 +97,9 @@ impl LinkTable {
/// - Unvalidated links drop once their own `proof_timeout` elapses, since
/// proof never arrived during the establishment window.
///
/// Returns `(total_culled, destinations_that_expired_unvalidated)` — the
/// caller can re-issue path discovery for those destinations.
pub fn cull_stale(&mut self, timeout: f64) -> (usize, Vec<[u8; 16]>) {
/// Returns `(total_culled, expired_unvalidated_links)` — the caller can
/// apply failed-link rediscovery rules using the retained route metadata.
pub fn cull_stale(&mut self, timeout: f64) -> (usize, Vec<ExpiredLink>) {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
@@ -89,7 +113,7 @@ impl LinkTable {
if entry.validated {
entry.timestamp > cutoff
} else if now > entry.proof_timeout {
unvalidated_expired.push(entry.destination_hash);
unvalidated_expired.push(ExpiredLink::from(&*entry));
false
} else {
true
@@ -196,7 +220,9 @@ mod tests {
let (culled, expired_dests) = table.cull_stale(900.0);
assert_eq!(culled, 1);
assert_eq!(expired_dests.len(), 1);
assert_eq!(expired_dests[0], dest_hash);
assert_eq!(expired_dests[0].destination_hash, dest_hash);
assert_eq!(expired_dests[0].receiving_interface, 2);
assert_eq!(expired_dests[0].taken_hops, 0);
assert_eq!(table.len(), 0);
}
@@ -278,7 +304,7 @@ mod tests {
assert_eq!(culled, 2);
assert_eq!(table.len(), 2);
assert_eq!(expired_dests.len(), 1);
assert_eq!(expired_dests[0], [0xA4; 16]);
assert_eq!(expired_dests[0].destination_hash, [0xA4; 16]);
}
#[test]
+35
View File
@@ -397,6 +397,21 @@ pub enum TransportQuery {
DropPath {
dest: [u8; 16],
},
/// Temporarily reject path-table installs for `dest` learned through
/// `interface_id`. Used after link establishment failure so rediscovery can
/// consider alternate interfaces instead of immediately reselecting the
/// path that just failed.
SuppressPathInterface {
dest: [u8; 16],
interface_id: InterfaceId,
duration: f64,
},
/// Temporarily reject path-table installs for `dest` learned through the
/// interface that currently owns the path.
SuppressCurrentPathInterface {
dest: [u8; 16],
duration: f64,
},
DropAnnounceQueues,
GetBlackholedIdentities,
BlackholeIdentity {
@@ -435,6 +450,12 @@ pub enum TransportQuery {
DropAllVia {
next_hop: [u8; 16],
},
/// Drop every cached route from the path table and persist the empty table.
/// Response: `IntResult(count_cleared)`.
DropPathTable,
/// Drop every cached announce snapshot and persist the empty cache.
/// Response: `IntResult(count_cleared)`.
DropRecentAnnounces,
/// Remote-status RPC — interface stats + optional link count, wire-format
/// compatible with `Transport.remote_status_handler`.
RemoteStatus {
@@ -526,6 +547,9 @@ pub struct PathTableRpcEntry {
pub hops: u8,
pub expires: f64,
pub interface: String,
pub interface_id: InterfaceId,
pub interface_mode: InterfaceMode,
pub interface_role: InterfaceRole,
}
#[derive(Debug, Clone)]
@@ -545,6 +569,12 @@ pub struct InterfaceStatRpcEntry {
pub held_announces: u64,
pub incoming_announce_frequency: f64,
pub outgoing_announce_frequency: f64,
pub incoming_pr_frequency: f64,
pub outgoing_pr_frequency: f64,
pub burst_active: bool,
pub burst_activated: f64,
pub pr_burst_active: bool,
pub pr_burst_activated: f64,
pub clients: Option<u64>,
pub announce_rate_target: Option<f64>,
pub announce_rate_grace: Option<u32>,
@@ -572,6 +602,11 @@ pub struct AnnounceRpcEntry {
pub timestamp: f64,
pub public_key: Option<[u8; 64]>,
pub ratchet: Option<[u8; 32]>,
/// `SHA-256(app_name)[:10]` for the announced aspect.
pub name_hash: [u8; 10],
/// True when the cached announce arrived as a path response instead of a
/// fresh network announce.
pub is_path_response: bool,
/// Pinned via `RetainDestination`; the maintenance sweep skips the
/// entry regardless of age while this is `true`.
pub retained: bool,
+59 -2
View File
@@ -63,6 +63,20 @@ impl PathEntry {
now_f64() > self.expires
}
/// Mark an actively used route as live. Reticulum's Python path cull is
/// timestamp based; Rust stores an explicit expiry, so both clocks must
/// move together when traffic proves the route is still useful.
pub fn touch(&mut self) {
let now = now_f64();
let lifetime = if self.expires > self.timestamp {
self.expires - self.timestamp
} else {
path_expiry(InterfaceMode::Full) as f64
};
self.timestamp = now;
self.expires = now + lifetime;
}
/// Most recent blobs to persist — older entries can be regenerated from
/// the wire on replay, so we cap the snapshot at `PERSIST_RANDOM_BLOBS`
/// to keep the on-disk table small.
@@ -112,14 +126,22 @@ impl PathTable {
self.entries.get_mut(dest_hash)
}
pub fn get_live(&self, dest_hash: &[u8; 16]) -> Option<&PathEntry> {
self.entries.get(dest_hash).filter(|e| !e.is_expired())
}
pub fn get_live_mut(&mut self, dest_hash: &[u8; 16]) -> Option<&mut PathEntry> {
self.entries.get_mut(dest_hash).filter(|e| !e.is_expired())
}
/// A path exists and has not yet expired. Callers should prefer this
/// over `get().is_some()` so stale entries are not treated as routable.
pub fn has_path(&self, dest_hash: &[u8; 16]) -> bool {
self.entries.get(dest_hash).is_some_and(|e| !e.is_expired())
self.get_live(dest_hash).is_some()
}
pub fn hops_to(&self, dest_hash: &[u8; 16]) -> Option<u8> {
self.entries.get(dest_hash).map(|e| e.hops)
self.get_live(dest_hash).map(|e| e.hops)
}
pub fn remove(&mut self, dest_hash: &[u8; 16]) -> Option<PathEntry> {
@@ -217,6 +239,10 @@ impl PathTable {
pub fn iter(&self) -> impl Iterator<Item = (&DestHash, &PathEntry)> {
self.entries.iter()
}
pub fn iter_live(&self) -> impl Iterator<Item = (&DestHash, &PathEntry)> {
self.entries.iter().filter(|(_, entry)| !entry.is_expired())
}
}
impl Default for PathTable {
@@ -259,6 +285,37 @@ mod tests {
assert_eq!(table.len(), 1);
}
#[test]
fn expired_entries_are_not_live_paths() {
let mut table = PathTable::new();
let hash = [0xA1; 16];
let mut entry = PathEntry::new(None, 1, 1, InterfaceMode::Gateway);
entry.expires = now_f64() - 1.0;
table.insert(hash, entry);
assert!(table.get(&hash).is_some());
assert!(table.get_live(&hash).is_none());
assert!(table.get_live_mut(&hash).is_none());
assert!(!table.has_path(&hash));
assert_eq!(table.hops_to(&hash), None);
assert_eq!(table.iter().count(), 1);
assert_eq!(table.iter_live().count(), 0);
}
#[test]
fn touch_extends_explicit_expiry_with_original_lifetime() {
let mut entry = PathEntry::new(None, 1, 1, InterfaceMode::Roaming);
let lifetime = entry.expires - entry.timestamp;
entry.timestamp -= 10.0;
entry.expires -= 10.0;
entry.touch();
let new_lifetime = entry.expires - entry.timestamp;
assert!((new_lifetime - lifetime).abs() < 0.001);
assert!(entry.expires > now_f64());
}
#[test]
fn test_path_table_remove() {
let mut table = PathTable::new();
+334 -10
View File
@@ -7,6 +7,7 @@ use std::path::Path;
use rmpv::Value;
use serde::{Deserialize, Serialize};
use crate::constants::PERSIST_RANDOM_BLOBS;
use crate::hashlist::PacketHashlist;
use crate::path_table::PathTable;
@@ -129,6 +130,26 @@ pub struct PythonCachedAnnounce {
pub interface_reference: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PythonTunnelEntry {
pub tunnel_id: [u8; 32],
pub interface_hash: Option<[u8; 32]>,
pub paths: Vec<PythonTunnelPath>,
pub expires: f64,
}
#[derive(Debug, Clone)]
pub struct PythonTunnelPath {
pub destination_hash: [u8; 16],
pub timestamp: f64,
pub received_from: [u8; 16],
pub hops: u8,
pub expires: f64,
pub random_blobs: Vec<[u8; 10]>,
pub interface_hash: Option<[u8; 32]>,
pub packet_hash: [u8; 32],
}
pub fn interface_hash_from_name(name: &str) -> [u8; 32] {
rns_crypto::sha::full_hash(name.as_bytes())
}
@@ -240,12 +261,32 @@ pub fn save_python_announce_cache_for_paths<'a, I>(
interface_names: &HashMap<u64, String>,
announce_cache_dir: &Path,
) -> Result<(), PersistenceError>
where
I: IntoIterator<Item = &'a crate::actor::RecentAnnounce>,
{
save_python_announce_cache_for_paths_and_tunnels(
path_entries,
None,
announces,
interface_names,
announce_cache_dir,
)
}
pub fn save_python_announce_cache_for_paths_and_tunnels<'a, I>(
path_entries: &PathTable,
tunnel_table: Option<&crate::tunnel::TunnelTable>,
announces: I,
interface_names: &HashMap<u64, String>,
announce_cache_dir: &Path,
) -> Result<(), PersistenceError>
where
I: IntoIterator<Item = &'a crate::actor::RecentAnnounce>,
{
std::fs::create_dir_all(announce_cache_dir).map_err(PersistenceError::Io)?;
let announces_by_dest: HashMap<[u8; 16], &crate::actor::RecentAnnounce> =
announces.into_iter().map(|a| (a.dest_hash, a)).collect();
let mut written = std::collections::HashSet::new();
for (dest_hash, path_entry) in path_entries.iter() {
let Some(packet_hash) = path_entry.packet_hash else {
@@ -261,19 +302,61 @@ where
.get(&path_entry.interface_id)
.map(|name| Value::String(name.as_str().into()))
.unwrap_or(Value::Nil);
let value = Value::Array(vec![
Value::Binary(announce.raw_packet.clone()),
write_python_cached_announce(
announce_cache_dir,
&packet_hash,
announce.raw_packet.clone(),
interface_reference,
]);
let mut serialized = Vec::new();
rmpv::encode::write_value(&mut serialized, &value)
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
let path = announce_cache_dir.join(hex::encode(packet_hash));
atomic_write_bytes(&path, &serialized)?;
)?;
written.insert(packet_hash);
}
if let Some(tunnel_table) = tunnel_table {
for tunnel in tunnel_table.iter().map(|(_, tunnel)| tunnel) {
let interface_reference = interface_names
.get(&tunnel.interface_id)
.map(|name| Value::String(name.as_str().into()))
.unwrap_or(Value::Nil);
for (dest_hash, tunnel_path) in &tunnel.tunnel_paths {
let Some(packet_hash) = tunnel_path.packet_hash else {
continue;
};
if written.contains(&packet_hash) {
continue;
}
let Some(announce) = announces_by_dest.get(dest_hash) else {
continue;
};
if announce.raw_packet.is_empty() {
continue;
}
write_python_cached_announce(
announce_cache_dir,
&packet_hash,
announce.raw_packet.clone(),
interface_reference.clone(),
)?;
written.insert(packet_hash);
}
}
}
Ok(())
}
fn write_python_cached_announce(
announce_cache_dir: &Path,
packet_hash: &[u8; 32],
raw_packet: Vec<u8>,
interface_reference: Value,
) -> Result<(), PersistenceError> {
let value = Value::Array(vec![Value::Binary(raw_packet), interface_reference]);
let mut serialized = Vec::new();
rmpv::encode::write_value(&mut serialized, &value)
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
let path = announce_cache_dir.join(hex::encode(packet_hash));
atomic_write_bytes(&path, &serialized)
}
pub fn load_python_cached_announce(
announce_cache_dir: &Path,
packet_hash: &[u8; 32],
@@ -312,6 +395,142 @@ pub fn load_python_cached_announce(
}))
}
pub fn save_python_tunnel_table(
table: &crate::tunnel::TunnelTable,
interface_names: &HashMap<u64, String>,
path: &Path,
) -> Result<(), PersistenceError> {
let mut tunnel_values = Vec::new();
for (_, tunnel) in table.iter() {
let interface_hash = interface_names
.get(&tunnel.interface_id)
.map(|name| Value::Binary(interface_hash_from_name(name).to_vec()))
.unwrap_or(Value::Nil);
let mut path_values = Vec::new();
for (dest_hash, tunnel_path) in &tunnel.tunnel_paths {
let Some(packet_hash) = tunnel_path.packet_hash else {
continue;
};
let received_from = tunnel_path.next_hop.unwrap_or(*dest_hash);
let random_blob_start = tunnel_path
.random_blobs
.len()
.saturating_sub(PERSIST_RANDOM_BLOBS);
let random_blobs = tunnel_path
.random_blobs
.iter()
.skip(random_blob_start)
.map(|blob| Value::Binary(blob.to_vec()))
.collect::<Vec<_>>();
path_values.push(Value::Array(vec![
Value::Binary(dest_hash.to_vec()),
Value::F64(tunnel_path.timestamp),
Value::Binary(received_from.to_vec()),
Value::Integer((tunnel_path.hops as u64).into()),
Value::F64(tunnel_path.expires),
Value::Array(random_blobs),
interface_hash.clone(),
Value::Binary(packet_hash.to_vec()),
]));
}
tunnel_values.push(Value::Array(vec![
Value::Binary(tunnel.tunnel_id.to_vec()),
interface_hash,
Value::Array(path_values),
Value::F64(tunnel.expires),
]));
}
let mut serialized = Vec::new();
rmpv::encode::write_value(&mut serialized, &Value::Array(tunnel_values))
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
atomic_write_bytes(path, &serialized)
}
pub fn load_python_tunnel_table(path: &Path) -> Result<Vec<PythonTunnelEntry>, PersistenceError> {
let data = std::fs::read(path).map_err(PersistenceError::Io)?;
let value = rmpv::decode::read_value(&mut std::io::Cursor::new(data))
.map_err(|e| PersistenceError::Deserialize(e.to_string()))?;
let entries = match value {
Value::Array(entries) => entries,
other => {
return Err(PersistenceError::Deserialize(format!(
"expected tunnels array, got {other:?}"
)));
}
};
let mut out = Vec::new();
for entry in entries {
let fields = match entry {
Value::Array(fields) => fields,
_ => continue,
};
if fields.len() < 4 {
continue;
}
let Some(tunnel_id) = value_bin_array::<32>(&fields[0]) else {
continue;
};
let interface_hash = match &fields[1] {
Value::Nil => None,
value => value_bin_array::<32>(value),
};
let paths = match &fields[2] {
Value::Array(path_entries) => path_entries
.iter()
.filter_map(|path_entry| {
let Value::Array(path_fields) = path_entry else {
return None;
};
if path_fields.len() < 8 {
return None;
}
let destination_hash = value_bin_array::<16>(&path_fields[0])?;
let timestamp = value_f64(&path_fields[1]).unwrap_or(0.0);
let received_from = value_bin_array::<16>(&path_fields[2])?;
let hops = value_u8(&path_fields[3])?;
let expires = value_f64(&path_fields[4]).unwrap_or(0.0);
let random_blobs = match &path_fields[5] {
Value::Array(values) => values
.iter()
.filter_map(value_bin_array::<10>)
.collect::<Vec<_>>(),
_ => Vec::new(),
};
let interface_hash = match &path_fields[6] {
Value::Nil => None,
value => value_bin_array::<32>(value),
};
let packet_hash = value_bin_array::<32>(&path_fields[7])?;
Some(PythonTunnelPath {
destination_hash,
timestamp,
received_from,
hops,
expires,
random_blobs,
interface_hash,
packet_hash,
})
})
.collect::<Vec<_>>(),
_ => Vec::new(),
};
let expires = value_f64(&fields[3]).unwrap_or(0.0);
out.push(PythonTunnelEntry {
tunnel_id,
interface_hash,
paths,
expires,
});
}
Ok(out)
}
fn value_bin_array<const N: usize>(value: &Value) -> Option<[u8; N]> {
let Value::Binary(bytes) = value else {
return None;
@@ -693,14 +912,24 @@ pub struct PersistedTunnelEntry {
/// stale `interface_id` once the matching interface registers.
#[serde(default)]
pub interface_name: Option<String>,
/// Python-compatible stable interface hash for remapping canonical
/// `tunnels` entries across restarts.
#[serde(default)]
pub interface_hash: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersistedTunnelPath {
pub destination_hash: Vec<u8>,
#[serde(default)]
pub next_hop: Option<Vec<u8>>,
pub hops: u8,
pub expires: f64,
pub timestamp: f64,
#[serde(default)]
pub random_blobs: Vec<Vec<u8>>,
#[serde(default)]
pub packet_hash: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -710,8 +939,8 @@ pub struct PersistedTunnelTable {
}
impl PersistedTunnelTable {
pub const CURRENT_VERSION: u32 = 2;
pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2];
pub const CURRENT_VERSION: u32 = 3;
pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2, 3];
}
pub fn save_tunnel_table(
@@ -729,9 +958,19 @@ pub fn save_tunnel_table(
.iter()
.map(|(dest, tp)| PersistedTunnelPath {
destination_hash: dest.to_vec(),
next_hop: tp.next_hop.map(|h| h.to_vec()),
hops: tp.hops,
expires: tp.expires,
timestamp: tp.timestamp,
random_blobs: {
let start = tp.random_blobs.len().saturating_sub(PERSIST_RANDOM_BLOBS);
tp.random_blobs
.iter()
.skip(start)
.map(|b| b.to_vec())
.collect()
},
packet_hash: tp.packet_hash.map(|h| h.to_vec()),
})
.collect();
Some(PersistedTunnelEntry {
@@ -740,6 +979,9 @@ pub fn save_tunnel_table(
expires: entry.expires,
paths,
interface_name: Some(interface_name),
interface_hash: interface_names
.get(&entry.interface_id)
.map(|name| interface_hash_from_name(name).to_vec()),
})
})
.collect();
@@ -937,6 +1179,88 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn save_load_python_tunnel_table_and_tunnel_announce_cache() {
let destination_hash = [0xAB; 16];
let next_hop = [0xBC; 16];
let packet_hash = [0xCD; 32];
let tunnel_id = [0xDE; 32];
let mut paths = HashMap::new();
paths.insert(
destination_hash,
crate::tunnel::TunnelPath {
timestamp: 1234.5,
next_hop: Some(next_hop),
hops: 3,
expires: 9876.5,
random_blobs: vec![[0x44; 10]],
packet_hash: Some(packet_hash),
},
);
let mut tunnels = crate::tunnel::TunnelTable::new();
tunnels.insert(crate::tunnel::TunnelEntry {
tunnel_id,
interface_id: 7,
tunnel_paths: paths,
expires: 9999.5,
});
let mut names = HashMap::new();
names.insert(7, "Interface[Tunnel]".to_string());
let dir = std::env::temp_dir().join("reticulum_rs_test_python_tunnels");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let tunnels_path = dir.join("tunnels");
save_python_tunnel_table(&tunnels, &names, &tunnels_path).unwrap();
let loaded = load_python_tunnel_table(&tunnels_path).unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].tunnel_id, tunnel_id);
assert_eq!(
loaded[0].interface_hash,
Some(interface_hash_from_name("Interface[Tunnel]"))
);
assert_eq!(loaded[0].expires, 9999.5);
assert_eq!(loaded[0].paths.len(), 1);
assert_eq!(loaded[0].paths[0].destination_hash, destination_hash);
assert_eq!(loaded[0].paths[0].received_from, next_hop);
assert_eq!(loaded[0].paths[0].hops, 3);
assert_eq!(loaded[0].paths[0].packet_hash, packet_hash);
let announces = [crate::actor::RecentAnnounce {
dest_hash: destination_hash,
hops: 3,
app_data: None,
timestamp: 1234.5,
public_key: None,
ratchet: None,
raw_packet: vec![0xFE; 42],
retained: false,
name_hash: [0xAB; 10],
}];
let empty_paths = PathTable::new();
let cache_dir = dir.join("cache").join("announces");
save_python_announce_cache_for_paths_and_tunnels(
&empty_paths,
Some(&tunnels),
announces.iter(),
&names,
&cache_dir,
)
.unwrap();
let cached = load_python_cached_announce(&cache_dir, &packet_hash)
.unwrap()
.unwrap();
assert_eq!(cached.raw_packet, vec![0xFE; 42]);
assert_eq!(
cached.interface_reference.as_deref(),
Some("Interface[Tunnel]")
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_save_load_hashlist() {
let mut hashlist = PacketHashlist::new();
+14
View File
@@ -16,9 +16,11 @@ pub struct TunnelEntry {
#[derive(Debug, Clone)]
pub struct TunnelPath {
pub timestamp: f64,
pub next_hop: Option<[u8; 16]>,
pub hops: u8,
pub expires: f64,
pub random_blobs: Vec<[u8; 10]>,
pub packet_hash: Option<[u8; 32]>,
}
pub struct TunnelTable {
@@ -64,6 +66,18 @@ impl TunnelTable {
self.entries.iter_mut()
}
pub fn get_mut_by_interface(&mut self, interface_id: InterfaceId) -> Option<&mut TunnelEntry> {
self.entries
.values_mut()
.find(|entry| entry.interface_id == interface_id)
}
pub fn tunnel_paths(&self) -> impl Iterator<Item = (&[u8; 16], &TunnelPath)> {
self.entries
.values()
.flat_map(|entry| entry.tunnel_paths.iter())
}
pub fn cull_expired(&mut self) -> usize {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)