mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
Merge pull request #17 from ratspeak/feature/api-parity
runtime: complete application API parity and RNode hardening
This commit is contained in:
105 files changed
+48396
-3469
No files matched your search
@@ -29,6 +29,8 @@ jobs:
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
- name: Test (default features)
|
||||
run: cargo test --workspace
|
||||
- name: Build application examples
|
||||
run: cargo build -p rns-runtime --examples
|
||||
- name: Test BLE interface features (Linux/macOS)
|
||||
if: runner.os != 'Windows'
|
||||
run: cargo test -p rns-interface --features ble
|
||||
@@ -47,3 +49,22 @@ jobs:
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
- run: cargo clippy -p rns-interface --features ble --all-targets -- -D warnings
|
||||
- name: Check public API documentation
|
||||
env:
|
||||
RUSTDOCFLAGS: "-D warnings"
|
||||
run: cargo doc --workspace --no-deps
|
||||
- run: cargo check --workspace --no-default-features
|
||||
|
||||
msrv:
|
||||
name: Rust 1.85 MSRV
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@1.85.0
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
- run: cargo check --workspace --all-targets
|
||||
@@ -0,0 +1,14 @@
|
||||
# Changelog
|
||||
|
||||
## 1.1.0 - 2026-07-26
|
||||
|
||||
- Added application-facing Destination, announce, receipt, Link, request,
|
||||
Channel, Buffer, and Resource APIs.
|
||||
- Added resilient long-running Link sessions with recovery, liveness,
|
||||
cancellation, progress, metrics, and responder lifecycle support.
|
||||
- Hardened delivery proofs, shared-instance authority and reconnection, IFAC
|
||||
ingress, persistence, routing snapshots, and orderly shutdown.
|
||||
- Expanded RNode lifecycle, capability, BLE, USB, TCP, serial, and safe
|
||||
`rnodeconf-rs` support.
|
||||
- Added compiled examples and stricter MSRV, Clippy, interoperability, and
|
||||
public-documentation gates.
|
||||
Generated
+11
-10
@@ -1582,7 +1582,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-crypto"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
@@ -1603,7 +1603,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-identity"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"proptest",
|
||||
@@ -1622,7 +1622,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-interface"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bluer",
|
||||
"btleplug",
|
||||
@@ -1632,6 +1632,7 @@ dependencies = [
|
||||
"if-addrs",
|
||||
"jni",
|
||||
"libc",
|
||||
"md-5",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
@@ -1653,7 +1654,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-link"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"proptest",
|
||||
@@ -1669,7 +1670,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-protocol"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"hex",
|
||||
@@ -1686,7 +1687,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-ratkey"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"bip39",
|
||||
@@ -1712,7 +1713,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-runtime"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1738,7 +1739,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-tools"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
@@ -1765,7 +1766,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-transport"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1785,7 +1786,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-wire"
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"rns-crypto",
|
||||
|
||||
+10
-10
@@ -14,7 +14,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
rust-version = "1.85"
|
||||
@@ -80,12 +80,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
|
||||
proptest = "1"
|
||||
|
||||
# Workspace crates
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "1.0.1", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "1.0.1", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "1.0.1" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "1.0.1" }
|
||||
rns-link = { path = "crates/rns-link", version = "1.0.1" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "1.0.1" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "1.0.1" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "1.0.1" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "1.0.1" }
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "1.1.0", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "1.1.0", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "1.1.0" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "1.1.0" }
|
||||
rns-link = { path = "crates/rns-link", version = "1.1.0" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "1.1.0" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "1.1.0" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "1.1.0" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "1.1.0" }
|
||||
@@ -3,6 +3,7 @@ name = "rns-crypto"
|
||||
description = "Cryptographic primitives for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
|
||||
@@ -2,14 +2,25 @@
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use thiserror::Error;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::aes_cbc;
|
||||
use crate::hmac::{hmac_sha256, hmac_verify};
|
||||
use crate::pkcs7;
|
||||
use crate::random::random_16;
|
||||
use crate::random::{random_16, random_bytes};
|
||||
|
||||
/// IV (16) + HMAC (32). A token is this plus the PKCS7-padded ciphertext.
|
||||
pub const TOKEN_OVERHEAD: usize = 48;
|
||||
/// AES block size used by legacy AES-128 tokens.
|
||||
pub const AES128_BLOCKSIZE: usize = 16;
|
||||
/// AES block size used by current AES-256 tokens.
|
||||
pub const AES256_BLOCKSIZE: usize = 16;
|
||||
/// AES-256 token key size: 32-byte signing key + 32-byte encryption key.
|
||||
pub const KEY_LENGTH: usize = 64;
|
||||
/// Legacy AES-128 token key size: 16-byte signing key + 16-byte encryption key.
|
||||
pub const LEGACY_KEY_LENGTH: usize = 32;
|
||||
/// Python `Identity.DERIVED_KEY_LENGTH_LEGACY`.
|
||||
pub const DERIVED_KEY_LENGTH_LEGACY: usize = LEGACY_KEY_LENGTH;
|
||||
|
||||
/// Errors surfaced by [`encrypt`] and [`decrypt`].
|
||||
#[derive(Debug, Error)]
|
||||
@@ -35,12 +46,17 @@ pub enum TokenError {
|
||||
/// 64 → 32/32 (AES-256 + HMAC-SHA256); 32 → 16/16 (AES-128, legacy).
|
||||
fn split_key(key: &[u8]) -> Result<(&[u8], &[u8]), TokenError> {
|
||||
match key.len() {
|
||||
64 => Ok((&key[..32], &key[32..])),
|
||||
32 => Ok((&key[..16], &key[16..])),
|
||||
KEY_LENGTH => Ok((&key[..32], &key[32..])),
|
||||
LEGACY_KEY_LENGTH => Ok((&key[..16], &key[16..])),
|
||||
n => Err(TokenError::InvalidKeyLength(n)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a fresh AES-256 token key with the operating-system CSPRNG.
|
||||
pub fn generate_key() -> Zeroizing<Vec<u8>> {
|
||||
Zeroizing::new(random_bytes(KEY_LENGTH))
|
||||
}
|
||||
|
||||
/// Token encrypt (Modified Fernet — no version byte, no timestamp).
|
||||
/// Wire: `IV(16) || AES-CBC(PKCS7(plaintext)) || HMAC-SHA256(IV || ciphertext)(32)`.
|
||||
pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
|
||||
@@ -112,6 +128,20 @@ mod tests {
|
||||
assert_eq!(&decrypted, plaintext);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_key_is_valid_and_unique() {
|
||||
let first = generate_key();
|
||||
let second = generate_key();
|
||||
|
||||
assert_eq!(first.len(), KEY_LENGTH);
|
||||
assert_eq!(second.len(), KEY_LENGTH);
|
||||
assert_ne!(&*first, &*second);
|
||||
assert_eq!(
|
||||
decrypt(&encrypt(b"generated", &first).unwrap(), &first).unwrap(),
|
||||
b"generated"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encrypt_produces_correct_structure() {
|
||||
let key = [0x42u8; 64];
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-identity"
|
||||
description = "Identity, Destination, and Announce system for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -261,7 +261,7 @@ impl AnnounceData {
|
||||
}
|
||||
|
||||
/// Validate destination-hash binding and first-seen public-key continuity
|
||||
/// after [`verify_signature`] has succeeded.
|
||||
/// after [`Self::verify_signature`] has succeeded.
|
||||
pub fn validate_destination_binding(
|
||||
&self,
|
||||
packet_dest_hash: &[u8; 16],
|
||||
|
||||
@@ -2,9 +2,11 @@ use std::collections::HashMap;
|
||||
|
||||
use rns_crypto::sha::truncated_hash;
|
||||
use rns_crypto::token;
|
||||
use std::fmt;
|
||||
use thiserror::Error;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::identity::Identity;
|
||||
use crate::identity::{DecryptionResult, Identity};
|
||||
use crate::name_hash::name_hash;
|
||||
|
||||
/// Callback invoked on incoming data packets: `fn(plaintext, raw_packet)`.
|
||||
@@ -35,7 +37,10 @@ struct PathResponseCache {
|
||||
}
|
||||
|
||||
// Path-response dedup window (seconds). Matches upstream default.
|
||||
const PR_TAG_WINDOW: f64 = 30.0;
|
||||
/// Path-response tag deduplication window, in seconds.
|
||||
pub const PR_TAG_WINDOW: f64 = 30.0;
|
||||
/// Default GROUP destination key size, in bytes.
|
||||
pub const GROUP_KEY_LENGTH: usize = token::KEY_LENGTH;
|
||||
|
||||
/// Separate clocks used while constructing an announce: a persisted 40-bit
|
||||
/// ordering value for the wire and a local elapsed-time value for cache expiry.
|
||||
@@ -108,6 +113,76 @@ pub enum DestinationError {
|
||||
Identity(#[from] crate::identity::IdentityError),
|
||||
#[error("invalid announce clock value: {0}")]
|
||||
InvalidAnnounceTime(f64),
|
||||
#[error("name component contains a dot: {0}")]
|
||||
InvalidNameComponent(String),
|
||||
#[error("operation requires a GROUP destination")]
|
||||
NotGroup,
|
||||
#[error("invalid GROUP key length: expected 32 or 64, got {0}")]
|
||||
InvalidGroupKeyLength(usize),
|
||||
#[error("operation requires a SINGLE destination")]
|
||||
NotSingle,
|
||||
#[error("operation requires an inbound destination")]
|
||||
NotInbound,
|
||||
#[error("identity does not address this destination")]
|
||||
IdentityMismatch,
|
||||
#[error("identity cannot sign")]
|
||||
SigningUnavailable,
|
||||
}
|
||||
|
||||
/// Wire-shape controls for [`Destination::pack_packet`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct DestinationPacketOptions {
|
||||
/// DATA, ANNOUNCE, LINKREQUEST, or PROOF.
|
||||
pub packet_type: rns_wire::flags::PacketType,
|
||||
/// One-byte packet context.
|
||||
pub context: rns_wire::context::PacketContext,
|
||||
/// Context flag bit carried in the packet flags.
|
||||
pub context_flag: bool,
|
||||
/// Header1 for ordinary packets, Header2 for transport-wrapped packets.
|
||||
pub header_type: rns_wire::flags::HeaderType,
|
||||
/// Broadcast or transport propagation mode.
|
||||
pub transport_type: rns_wire::flags::TransportType,
|
||||
/// Required for Header2 packets and ignored for Header1 packets.
|
||||
pub transport_id: Option<[u8; 16]>,
|
||||
}
|
||||
|
||||
impl Default for DestinationPacketOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
packet_type: rns_wire::flags::PacketType::Data,
|
||||
context: rns_wire::context::PacketContext::None,
|
||||
context_flag: false,
|
||||
header_type: rns_wire::flags::HeaderType::Header1,
|
||||
transport_type: rns_wire::flags::TransportType::Broadcast,
|
||||
transport_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Destination-aware packed packet plus outbound ratchet metadata.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PackedDestinationPacket {
|
||||
/// Complete packet with raw bytes and cached hashes.
|
||||
pub packet: rns_wire::packet::Packet,
|
||||
/// Ratchet used for SINGLE-destination encryption, if any.
|
||||
pub ratchet_id: Option<[u8; crate::identity::RATCHET_ID_LENGTH]>,
|
||||
}
|
||||
|
||||
/// Errors from destination-aware packet construction.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum DestinationPacketError {
|
||||
#[error(transparent)]
|
||||
Destination(#[from] DestinationError),
|
||||
#[error(transparent)]
|
||||
Packet(#[from] rns_wire::packet::PacketError),
|
||||
#[error("SINGLE packet encryption requires its destination identity")]
|
||||
MissingIdentity,
|
||||
#[error("Header2 packets require a transport id")]
|
||||
MissingTransportId,
|
||||
#[error("ordinary Link packets must use the Link runtime")]
|
||||
LinkRuntimeRequired,
|
||||
#[error("LRPROOF packets require a Link destination")]
|
||||
LrproofRequiresLink,
|
||||
}
|
||||
|
||||
pub struct Destination {
|
||||
@@ -116,10 +191,14 @@ pub struct Destination {
|
||||
pub hash: [u8; 16],
|
||||
pub name_hash: [u8; 10],
|
||||
pub app_name: String,
|
||||
/// Human-readable full destination name, including the identity hash.
|
||||
pub name: String,
|
||||
/// Identity hash bound into this destination address, when applicable.
|
||||
pub identity_hash: Option<[u8; 16]>,
|
||||
pub proof_strategy: ProofStrategy,
|
||||
/// If set, incoming data is signature-checked but not decrypted.
|
||||
pub only_validate_signature: bool,
|
||||
group_key: Option<Vec<u8>>,
|
||||
group_key: Option<Zeroizing<Vec<u8>>>,
|
||||
|
||||
// Identity auto-generated for an IN destination when none was supplied;
|
||||
// callers retrieve it via [`auto_identity`] or [`take_auto_identity`].
|
||||
@@ -151,6 +230,57 @@ pub struct Destination {
|
||||
}
|
||||
|
||||
impl Destination {
|
||||
pub const PR_TAG_WINDOW: f64 = PR_TAG_WINDOW;
|
||||
pub const RATCHET_COUNT: usize = rns_wire::constants::RATCHET_COUNT;
|
||||
pub const RATCHET_INTERVAL: u64 = rns_wire::constants::RATCHET_INTERVAL;
|
||||
|
||||
/// Build a full dotted destination name from an app name and aspects.
|
||||
///
|
||||
/// App and aspect arguments are individual components and therefore must
|
||||
/// not contain dots. An identity hash is appended when supplied.
|
||||
pub fn expand_name(
|
||||
identity: Option<&Identity>,
|
||||
app_name: &str,
|
||||
aspects: &[&str],
|
||||
) -> Result<String, DestinationError> {
|
||||
if app_name.contains('.') {
|
||||
return Err(DestinationError::InvalidNameComponent(app_name.to_string()));
|
||||
}
|
||||
if let Some(aspect) = aspects.iter().find(|aspect| aspect.contains('.')) {
|
||||
return Err(DestinationError::InvalidNameComponent(
|
||||
(*aspect).to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let identity_component = usize::from(identity.is_some());
|
||||
let mut components = Vec::with_capacity(1 + aspects.len() + identity_component);
|
||||
components.push(app_name.to_string());
|
||||
components.extend(aspects.iter().map(|aspect| (*aspect).to_string()));
|
||||
if let Some(identity) = identity {
|
||||
components.push(identity.hexhash());
|
||||
}
|
||||
Ok(components.join("."))
|
||||
}
|
||||
|
||||
/// Split a full dotted name into its app name and remaining aspects.
|
||||
pub fn app_and_aspects_from_name(full_name: &str) -> (&str, Vec<&str>) {
|
||||
let mut components = full_name.split('.');
|
||||
let app_name = components.next().unwrap_or_default();
|
||||
(app_name, components.collect())
|
||||
}
|
||||
|
||||
/// Create a destination from separate app and aspect components.
|
||||
pub fn new_with_aspects(
|
||||
identity: Option<&Identity>,
|
||||
direction: Direction,
|
||||
dest_type: DestType,
|
||||
app_name: &str,
|
||||
aspects: &[&str],
|
||||
) -> Result<Self, DestinationError> {
|
||||
let full_name = Self::expand_name(None, app_name, aspects)?;
|
||||
Self::new(identity, direction, dest_type, &full_name)
|
||||
}
|
||||
|
||||
/// Create a new destination.
|
||||
///
|
||||
/// For SINGLE/GROUP inbound destinations, a new identity is generated
|
||||
@@ -182,6 +312,7 @@ impl Destination {
|
||||
|
||||
let nh = name_hash(&hash_name);
|
||||
let hash = Self::compute_hash(&nh, Some(&id_ref));
|
||||
let name = format!("{hash_name}.{}", hex::encode(id_ref));
|
||||
|
||||
Ok(Self {
|
||||
dest_type,
|
||||
@@ -189,6 +320,8 @@ impl Destination {
|
||||
hash,
|
||||
name_hash: nh,
|
||||
app_name: app_name.to_string(),
|
||||
name,
|
||||
identity_hash: Some(id_ref),
|
||||
proof_strategy: ProofStrategy::ProveNone,
|
||||
only_validate_signature: false,
|
||||
group_key: None,
|
||||
@@ -220,6 +353,8 @@ impl Destination {
|
||||
hash,
|
||||
name_hash: nh,
|
||||
app_name: app_name.to_string(),
|
||||
name: app_name.to_string(),
|
||||
identity_hash: None,
|
||||
proof_strategy: ProofStrategy::ProveNone,
|
||||
only_validate_signature: false,
|
||||
group_key: None,
|
||||
@@ -249,6 +384,10 @@ impl Destination {
|
||||
hash,
|
||||
name_hash: nh,
|
||||
app_name: app_name.to_string(),
|
||||
name: identity
|
||||
.map(|identity| format!("{app_name}.{}", identity.hexhash()))
|
||||
.unwrap_or_else(|| app_name.to_string()),
|
||||
identity_hash: identity.map(|identity| identity.hash),
|
||||
proof_strategy: ProofStrategy::ProveNone,
|
||||
only_validate_signature: false,
|
||||
group_key: None,
|
||||
@@ -300,7 +439,42 @@ impl Destination {
|
||||
|
||||
/// Set the pre-shared key used for GROUP encryption.
|
||||
pub fn set_group_key(&mut self, key: Vec<u8>) {
|
||||
self.group_key = Some(key);
|
||||
self.group_key = Some(Zeroizing::new(key));
|
||||
}
|
||||
|
||||
/// Generate and install a fresh AES-256 GROUP destination key.
|
||||
pub fn generate_group_key(&mut self) -> Result<(), DestinationError> {
|
||||
if self.dest_type != DestType::Group {
|
||||
return Err(DestinationError::NotGroup);
|
||||
}
|
||||
self.group_key = Some(token::generate_key());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate and install a GROUP destination key.
|
||||
///
|
||||
/// The 64-byte AES-256 form is generated by default; the 32-byte legacy
|
||||
/// AES-128 form remains accepted for wire compatibility.
|
||||
pub fn load_group_key(&mut self, key: &[u8]) -> Result<(), DestinationError> {
|
||||
if self.dest_type != DestType::Group {
|
||||
return Err(DestinationError::NotGroup);
|
||||
}
|
||||
if key.len() != token::LEGACY_KEY_LENGTH && key.len() != GROUP_KEY_LENGTH {
|
||||
return Err(DestinationError::InvalidGroupKeyLength(key.len()));
|
||||
}
|
||||
self.group_key = Some(Zeroizing::new(key.to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Borrow the installed GROUP key.
|
||||
pub fn group_key(&self) -> Result<&[u8], DestinationError> {
|
||||
if self.dest_type != DestType::Group {
|
||||
return Err(DestinationError::NotGroup);
|
||||
}
|
||||
self.group_key
|
||||
.as_ref()
|
||||
.map(|key| key.as_slice())
|
||||
.ok_or(DestinationError::EncryptionUnavailable)
|
||||
}
|
||||
|
||||
/// Identity auto-generated at construction (IN + SINGLE/GROUP without a caller-provided identity).
|
||||
@@ -329,11 +503,125 @@ impl Destination {
|
||||
if self.dest_type != DestType::Single {
|
||||
return Err(DestinationError::ProveNotSingle);
|
||||
}
|
||||
self.ensure_identity(identity)?;
|
||||
identity
|
||||
.prove(packet_hash, implicit_proof)
|
||||
.map_err(DestinationError::Identity)
|
||||
}
|
||||
|
||||
/// Sign a message with the identity bound to this SINGLE destination.
|
||||
pub fn sign(&self, message: &[u8], identity: &Identity) -> Result<[u8; 64], DestinationError> {
|
||||
if self.dest_type != DestType::Single {
|
||||
return Err(DestinationError::NotSingle);
|
||||
}
|
||||
self.ensure_identity(identity)?;
|
||||
identity
|
||||
.sign(message)
|
||||
.ok_or(DestinationError::SigningUnavailable)
|
||||
}
|
||||
|
||||
/// Pack one packet with Python-compatible destination encryption rules.
|
||||
///
|
||||
/// Announce and LinkRequest packets are plaintext. Resource payload,
|
||||
/// Resource proof, keepalive, cache-request, and LRPROOF contexts are also
|
||||
/// already protected or intentionally plaintext and therefore bypass
|
||||
/// destination encryption. Other SINGLE/GROUP packets are encrypted here.
|
||||
///
|
||||
/// Ordinary Link packets remain owned by `LinkSession`; LRPROOF is the
|
||||
/// sole Link context accepted by this stateless builder.
|
||||
pub fn pack_packet(
|
||||
&self,
|
||||
data: &[u8],
|
||||
identity: Option<&Identity>,
|
||||
remote_ratchet_pub: Option<&[u8; 32]>,
|
||||
options: DestinationPacketOptions,
|
||||
) -> Result<PackedDestinationPacket, DestinationPacketError> {
|
||||
use rns_wire::context::PacketContext;
|
||||
use rns_wire::flags::{DestinationType, HeaderType, PacketType};
|
||||
|
||||
if options.context == PacketContext::Lrproof && self.dest_type != DestType::Link {
|
||||
return Err(DestinationPacketError::LrproofRequiresLink);
|
||||
}
|
||||
if self.dest_type == DestType::Link && options.context != PacketContext::Lrproof {
|
||||
return Err(DestinationPacketError::LinkRuntimeRequired);
|
||||
}
|
||||
|
||||
let bypass_encryption = matches!(
|
||||
options.packet_type,
|
||||
PacketType::Announce | PacketType::LinkRequest
|
||||
) || (options.packet_type == PacketType::Proof
|
||||
&& options.context == PacketContext::ResourcePrf)
|
||||
|| options.context.is_plaintext_context()
|
||||
|| options.context == PacketContext::Lrproof;
|
||||
|
||||
let selected_ratchet = remote_ratchet_pub.or(self.remote_ratchet_pub.as_ref());
|
||||
let (payload, ratchet_id) = if bypass_encryption {
|
||||
(data.to_vec(), None)
|
||||
} else {
|
||||
match self.dest_type {
|
||||
DestType::Plain => (data.to_vec(), None),
|
||||
DestType::Single => {
|
||||
let identity = identity.ok_or(DestinationPacketError::MissingIdentity)?;
|
||||
self.ensure_identity(identity)?;
|
||||
let ciphertext = identity
|
||||
.encrypt(data, selected_ratchet)
|
||||
.map_err(DestinationError::Identity)?;
|
||||
let ratchet_id = selected_ratchet.map(Identity::ratchet_id);
|
||||
(ciphertext, ratchet_id)
|
||||
}
|
||||
DestType::Group => {
|
||||
let key = self
|
||||
.group_key
|
||||
.as_ref()
|
||||
.ok_or(DestinationError::EncryptionUnavailable)?;
|
||||
(
|
||||
token::encrypt(data, key)
|
||||
.map_err(|_| DestinationError::DecryptionFailed)?,
|
||||
None,
|
||||
)
|
||||
}
|
||||
DestType::Link => unreachable!("ordinary Link packets rejected above"),
|
||||
}
|
||||
};
|
||||
|
||||
let destination_type = if options.context == PacketContext::Lrproof {
|
||||
DestinationType::Link
|
||||
} else {
|
||||
match self.dest_type {
|
||||
DestType::Single => DestinationType::Single,
|
||||
DestType::Group => DestinationType::Group,
|
||||
DestType::Plain => DestinationType::Plain,
|
||||
DestType::Link => DestinationType::Link,
|
||||
}
|
||||
};
|
||||
let transport_id = match options.header_type {
|
||||
HeaderType::Header1 => None,
|
||||
HeaderType::Header2 => Some(
|
||||
options
|
||||
.transport_id
|
||||
.ok_or(DestinationPacketError::MissingTransportId)?,
|
||||
),
|
||||
};
|
||||
let packet = rns_wire::packet::Packet::new(
|
||||
rns_wire::header::PacketHeader {
|
||||
flags: rns_wire::flags::PacketFlags {
|
||||
header_type: options.header_type,
|
||||
context_flag: options.context_flag,
|
||||
transport_type: options.transport_type,
|
||||
destination_type,
|
||||
packet_type: options.packet_type,
|
||||
},
|
||||
hops: 0,
|
||||
transport_id,
|
||||
destination_hash: self.hash,
|
||||
context: options.context,
|
||||
},
|
||||
payload,
|
||||
)?;
|
||||
|
||||
Ok(PackedDestinationPacket { packet, ratchet_id })
|
||||
}
|
||||
|
||||
/// Encrypt data for this destination.
|
||||
///
|
||||
/// For SINGLE destinations a `remote_ratchet_pub` replaces the identity's
|
||||
@@ -346,9 +634,12 @@ impl Destination {
|
||||
) -> Result<Vec<u8>, DestinationError> {
|
||||
match self.dest_type {
|
||||
DestType::Plain => Ok(plaintext.to_vec()),
|
||||
DestType::Single => identity
|
||||
.encrypt(plaintext, remote_ratchet_pub)
|
||||
.map_err(DestinationError::Identity),
|
||||
DestType::Single => {
|
||||
self.ensure_identity(identity)?;
|
||||
identity
|
||||
.encrypt(plaintext, remote_ratchet_pub)
|
||||
.map_err(DestinationError::Identity)
|
||||
}
|
||||
DestType::Group => {
|
||||
let key = self
|
||||
.group_key
|
||||
@@ -375,9 +666,24 @@ impl Destination {
|
||||
identity: &Identity,
|
||||
ratchet_keys: Option<&[[u8; 32]]>,
|
||||
) -> Result<Vec<u8>, DestinationError> {
|
||||
self.decrypt_with_ratchet_id(ciphertext, identity, ratchet_keys)
|
||||
.map(|result| result.plaintext)
|
||||
}
|
||||
|
||||
/// Decrypt data and report which retained ratchet authenticated it.
|
||||
pub fn decrypt_with_ratchet_id(
|
||||
&self,
|
||||
ciphertext: &[u8],
|
||||
identity: &Identity,
|
||||
ratchet_keys: Option<&[[u8; 32]]>,
|
||||
) -> Result<DecryptionResult, DestinationError> {
|
||||
match self.dest_type {
|
||||
DestType::Plain => Ok(ciphertext.to_vec()),
|
||||
DestType::Plain => Ok(DecryptionResult {
|
||||
plaintext: ciphertext.to_vec(),
|
||||
ratchet_id: None,
|
||||
}),
|
||||
DestType::Single => {
|
||||
self.ensure_identity(identity)?;
|
||||
let ratchet_refs: Option<Vec<&[u8; 32]>> = if self.ratchets_enabled {
|
||||
ratchet_keys.map(|keys| keys.iter().collect())
|
||||
} else {
|
||||
@@ -385,7 +691,7 @@ impl Destination {
|
||||
};
|
||||
let enforce = self.ratchets_enforced;
|
||||
identity
|
||||
.decrypt(ciphertext, ratchet_refs.as_deref(), enforce)
|
||||
.decrypt_with_ratchet_id(ciphertext, ratchet_refs.as_deref(), enforce)
|
||||
.map_err(DestinationError::Identity)
|
||||
}
|
||||
DestType::Group => {
|
||||
@@ -393,7 +699,12 @@ impl Destination {
|
||||
.group_key
|
||||
.as_ref()
|
||||
.ok_or(DestinationError::EncryptionUnavailable)?;
|
||||
token::decrypt(ciphertext, key).map_err(|_| DestinationError::DecryptionFailed)
|
||||
token::decrypt(ciphertext, key)
|
||||
.map(|plaintext| DecryptionResult {
|
||||
plaintext,
|
||||
ratchet_id: None,
|
||||
})
|
||||
.map_err(|_| DestinationError::DecryptionFailed)
|
||||
}
|
||||
DestType::Link => Err(DestinationError::EncryptionUnavailable),
|
||||
}
|
||||
@@ -504,16 +815,46 @@ impl Destination {
|
||||
packet_type: u8,
|
||||
data: &[u8],
|
||||
identity: &Identity,
|
||||
) -> Result<Option<Vec<u8>>, DestinationError> {
|
||||
self.receive_packet(packet_type, data, data, identity)
|
||||
}
|
||||
|
||||
/// Decrypt and dispatch an incoming packet while preserving the complete
|
||||
/// raw packet for the packet callback.
|
||||
///
|
||||
/// Runtime dispatchers should prefer this over [`Self::receive`]. The
|
||||
/// latter remains available for callers that only have the packet payload.
|
||||
pub fn receive_packet(
|
||||
&self,
|
||||
packet_type: u8,
|
||||
data: &[u8],
|
||||
raw_packet: &[u8],
|
||||
identity: &Identity,
|
||||
) -> Result<Option<Vec<u8>>, DestinationError> {
|
||||
self.receive_packet_with_ratchets(packet_type, data, raw_packet, identity, None)
|
||||
}
|
||||
|
||||
/// Decrypt and dispatch an incoming packet using retained ratchet keys.
|
||||
///
|
||||
/// Live destination runtimes use this form when they own a persistent
|
||||
/// ratchet ring. LINKREQUEST packets still bypass destination decryption.
|
||||
pub fn receive_packet_with_ratchets(
|
||||
&self,
|
||||
packet_type: u8,
|
||||
data: &[u8],
|
||||
raw_packet: &[u8],
|
||||
identity: &Identity,
|
||||
ratchet_keys: Option<&[[u8; 32]]>,
|
||||
) -> Result<Option<Vec<u8>>, DestinationError> {
|
||||
if packet_type == 0x02 {
|
||||
return Ok(Some(data.to_vec()));
|
||||
}
|
||||
|
||||
let plaintext = self.decrypt(data, identity)?;
|
||||
let plaintext = self.decrypt_with_ratchets(data, identity, ratchet_keys)?;
|
||||
|
||||
if packet_type == 0x00 {
|
||||
if let Some(ref cb) = self.packet_callback {
|
||||
cb(&plaintext, data);
|
||||
cb(&plaintext, raw_packet);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -546,6 +887,10 @@ impl Destination {
|
||||
self.accept_link_requests = accept;
|
||||
}
|
||||
|
||||
pub fn accepts_links(&self) -> bool {
|
||||
self.accept_link_requests
|
||||
}
|
||||
|
||||
/// Enable ratchet forward secrecy. If `enforce`, non-ratchet inbound ciphertext is rejected.
|
||||
pub fn enable_ratchets(&mut self, enforce: bool) {
|
||||
self.ratchets_enabled = true;
|
||||
@@ -614,10 +959,10 @@ impl Destination {
|
||||
) -> Result<(Vec<u8>, bool), DestinationError> {
|
||||
let time = AnnounceTime::new(time.wire, time.cache)?;
|
||||
if self.dest_type != DestType::Single {
|
||||
return Err(DestinationError::EncryptionUnavailable);
|
||||
return Err(DestinationError::NotSingle);
|
||||
}
|
||||
if self.direction != Direction::In {
|
||||
return Err(DestinationError::EncryptionUnavailable);
|
||||
return Err(DestinationError::NotInbound);
|
||||
}
|
||||
|
||||
self.path_responses
|
||||
@@ -789,6 +1134,26 @@ impl Destination {
|
||||
pub fn hex_hash(&self) -> String {
|
||||
hex::encode(self.hash)
|
||||
}
|
||||
|
||||
/// Python-compatible spelling for the destination's hexadecimal hash.
|
||||
pub fn hexhash(&self) -> String {
|
||||
self.hex_hash()
|
||||
}
|
||||
|
||||
fn ensure_identity(&self, identity: &Identity) -> Result<(), DestinationError> {
|
||||
if self.identity_hash != Some(identity.hash)
|
||||
|| Self::compute_hash(&self.name_hash, Some(&identity.hash)) != self.hash
|
||||
{
|
||||
return Err(DestinationError::IdentityMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Destination {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "<{}:{}>", self.name, self.hex_hash())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -802,6 +1167,12 @@ mod tests {
|
||||
Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap();
|
||||
assert_eq!(dest.dest_type, DestType::Single);
|
||||
assert_ne!(dest.hash, [0u8; 16]);
|
||||
assert_eq!(dest.identity_hash, Some(id.hash));
|
||||
assert_eq!(dest.name, format!("test.app.{}", id.hexhash()));
|
||||
assert_eq!(
|
||||
dest.to_string(),
|
||||
format!("<test.app.{}:{}>", id.hexhash(), dest.hexhash())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -888,6 +1259,107 @@ mod tests {
|
||||
assert_eq!(dest.hash, computed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn name_helpers_match_component_constructor() {
|
||||
let id = Identity::new();
|
||||
let expanded = Destination::expand_name(Some(&id), "test", &["service", "chat"]).unwrap();
|
||||
assert_eq!(expanded, format!("test.service.chat.{}", id.hexhash()));
|
||||
assert!(Destination::expand_name(None, "test.app", &[]).is_err());
|
||||
assert!(Destination::expand_name(None, "test", &["bad.aspect"]).is_err());
|
||||
|
||||
let (app_name, aspects) = Destination::app_and_aspects_from_name("test.service.chat");
|
||||
assert_eq!(app_name, "test");
|
||||
assert_eq!(aspects, vec!["service", "chat"]);
|
||||
|
||||
let from_parts = Destination::new_with_aspects(
|
||||
Some(&id),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
"test",
|
||||
&["service", "chat"],
|
||||
)
|
||||
.unwrap();
|
||||
let from_full = Destination::new(
|
||||
Some(&id),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
"test.service.chat",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(from_parts.hash, from_full.hash);
|
||||
assert_eq!(from_parts.name, expanded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_key_api_generates_valid_keys() {
|
||||
let identity = Identity::new();
|
||||
let mut group = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::In,
|
||||
DestType::Group,
|
||||
"test.group",
|
||||
)
|
||||
.unwrap();
|
||||
group.generate_group_key().unwrap();
|
||||
assert_eq!(group.group_key().unwrap().len(), GROUP_KEY_LENGTH);
|
||||
|
||||
let ciphertext = group.encrypt(b"group plaintext", &identity, None).unwrap();
|
||||
assert_eq!(
|
||||
group.decrypt(&ciphertext, &identity).unwrap(),
|
||||
b"group plaintext"
|
||||
);
|
||||
|
||||
let legacy = [0xA5; 32];
|
||||
group.load_group_key(&legacy).unwrap();
|
||||
assert_eq!(group.group_key().unwrap(), legacy);
|
||||
assert!(matches!(
|
||||
group.load_group_key(&[0u8; 31]),
|
||||
Err(DestinationError::InvalidGroupKeyLength(31))
|
||||
));
|
||||
|
||||
let mut plain =
|
||||
Destination::new(None, Direction::In, DestType::Plain, "test.plain").unwrap();
|
||||
assert!(matches!(
|
||||
plain.generate_group_key(),
|
||||
Err(DestinationError::NotGroup)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destination_sign_rejects_unbound_identity() {
|
||||
let identity = Identity::new();
|
||||
let other = Identity::new();
|
||||
let destination = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::In,
|
||||
DestType::Single,
|
||||
"test.sign",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let signature = destination.sign(b"signed", &identity).unwrap();
|
||||
assert!(identity.verify(b"signed", &signature));
|
||||
assert!(matches!(
|
||||
destination.sign(b"signed", &other),
|
||||
Err(DestinationError::IdentityMismatch)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_links_can_be_queried_and_changed() {
|
||||
let identity = Identity::new();
|
||||
let mut destination = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::In,
|
||||
DestType::Single,
|
||||
"test.links",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(destination.accepts_links());
|
||||
destination.set_accepts_links(false);
|
||||
assert!(!destination.accepts_links());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_only_validate_signature_flag() {
|
||||
let id = Identity::new();
|
||||
@@ -920,6 +1392,67 @@ mod tests {
|
||||
assert!(dest.prove(b"test", &id, true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receive_packet_dispatches_plaintext_with_complete_raw_packet() {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
let identity = Identity::new();
|
||||
let mut inbound = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::In,
|
||||
DestType::Single,
|
||||
"test.receive",
|
||||
)
|
||||
.unwrap();
|
||||
let outbound = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
"test.receive",
|
||||
)
|
||||
.unwrap();
|
||||
let plaintext = b"destination callback";
|
||||
let ciphertext = outbound.encrypt(plaintext, &identity, None).unwrap();
|
||||
let raw_packet = [b"header".as_slice(), ciphertext.as_slice()].concat();
|
||||
let observed = Arc::new(Mutex::new(None));
|
||||
let callback_observed = Arc::clone(&observed);
|
||||
inbound.set_packet_callback(Box::new(move |data, raw| {
|
||||
*callback_observed.lock().unwrap() = Some((data.to_vec(), raw.to_vec()));
|
||||
}));
|
||||
|
||||
let decrypted = inbound
|
||||
.receive_packet(0x00, &ciphertext, &raw_packet, &identity)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(decrypted, plaintext);
|
||||
assert_eq!(
|
||||
*observed.lock().unwrap(),
|
||||
Some((plaintext.to_vec(), raw_packet))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proof_strategy_honors_application_decision() {
|
||||
let identity = Identity::new();
|
||||
let mut destination = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::In,
|
||||
DestType::Single,
|
||||
"test.proof",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(!destination.should_prove(b"packet"));
|
||||
destination.set_proof_strategy(ProofStrategy::ProveAll);
|
||||
assert!(destination.should_prove(b"packet"));
|
||||
destination.set_proof_strategy(ProofStrategy::ProveApp);
|
||||
assert!(!destination.should_prove(b"packet"));
|
||||
destination.set_proof_requested_callback(Box::new(|packet| packet == b"allowed"));
|
||||
assert!(destination.should_prove(b"allowed"));
|
||||
assert!(!destination.should_prove(b"denied"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encrypt_with_ratchet() {
|
||||
let id = Identity::new();
|
||||
@@ -938,6 +1471,170 @@ mod tests {
|
||||
let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes];
|
||||
let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap();
|
||||
assert_eq!(&pt[..], plaintext);
|
||||
|
||||
let mut inbound =
|
||||
Destination::new(Some(&id), Direction::In, DestType::Single, "test.app").unwrap();
|
||||
inbound.enable_ratchets(false);
|
||||
let decrypted = inbound
|
||||
.decrypt_with_ratchet_id(&ct, &id, Some(&[ratchet_prv_bytes]))
|
||||
.unwrap();
|
||||
assert_eq!(decrypted.plaintext, plaintext);
|
||||
assert_eq!(
|
||||
decrypted.ratchet_id,
|
||||
Some(Identity::ratchet_id(&ratchet_pub))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destination_packet_builder_encrypts_single_data_and_reports_ratchet() {
|
||||
let identity = Identity::new();
|
||||
let destination = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
"test.packet-builder",
|
||||
)
|
||||
.unwrap();
|
||||
let ratchet_private = rns_crypto::x25519::X25519PrivateKey::generate();
|
||||
let ratchet_public = ratchet_private.public_key().to_bytes();
|
||||
let packed = destination
|
||||
.pack_packet(
|
||||
b"builder payload",
|
||||
Some(&identity),
|
||||
Some(&ratchet_public),
|
||||
DestinationPacketOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
packed.packet.header.flags.packet_type,
|
||||
rns_wire::flags::PacketType::Data
|
||||
);
|
||||
assert_eq!(
|
||||
packed.packet.header.flags.destination_type,
|
||||
rns_wire::flags::DestinationType::Single
|
||||
);
|
||||
assert_ne!(packed.packet.data(), b"builder payload");
|
||||
assert_eq!(
|
||||
packed.ratchet_id,
|
||||
Some(Identity::ratchet_id(&ratchet_public))
|
||||
);
|
||||
let private = ratchet_private.to_bytes();
|
||||
let plaintext = identity
|
||||
.decrypt(packed.packet.data(), Some(&[&private]), false)
|
||||
.unwrap();
|
||||
assert_eq!(plaintext, b"builder payload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destination_packet_builder_preserves_python_plaintext_cases() {
|
||||
use rns_wire::context::PacketContext;
|
||||
use rns_wire::flags::PacketType;
|
||||
|
||||
let identity = Identity::new();
|
||||
let destination = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
"test.packet-plaintext",
|
||||
)
|
||||
.unwrap();
|
||||
let cases = [
|
||||
(PacketType::Announce, PacketContext::None),
|
||||
(PacketType::LinkRequest, PacketContext::None),
|
||||
(PacketType::Proof, PacketContext::ResourcePrf),
|
||||
(PacketType::Data, PacketContext::Resource),
|
||||
(PacketType::Data, PacketContext::Keepalive),
|
||||
(PacketType::Data, PacketContext::CacheRequest),
|
||||
];
|
||||
|
||||
for (packet_type, context) in cases {
|
||||
let packed = destination
|
||||
.pack_packet(
|
||||
b"already protected",
|
||||
None,
|
||||
None,
|
||||
DestinationPacketOptions {
|
||||
packet_type,
|
||||
context,
|
||||
..DestinationPacketOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(packed.packet.data(), b"already protected");
|
||||
assert_eq!(packed.ratchet_id, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destination_packet_builder_validates_header2_and_link_ownership() {
|
||||
use rns_wire::context::PacketContext;
|
||||
use rns_wire::flags::{HeaderType, TransportType};
|
||||
|
||||
let plain =
|
||||
Destination::new(None, Direction::Out, DestType::Plain, "test.header2").unwrap();
|
||||
assert!(matches!(
|
||||
plain.pack_packet(
|
||||
b"payload",
|
||||
None,
|
||||
None,
|
||||
DestinationPacketOptions {
|
||||
header_type: HeaderType::Header2,
|
||||
transport_type: TransportType::Transport,
|
||||
..DestinationPacketOptions::default()
|
||||
}
|
||||
),
|
||||
Err(DestinationPacketError::MissingTransportId)
|
||||
));
|
||||
let transport_id = [0xA5; 16];
|
||||
let packed = plain
|
||||
.pack_packet(
|
||||
b"payload",
|
||||
None,
|
||||
None,
|
||||
DestinationPacketOptions {
|
||||
header_type: HeaderType::Header2,
|
||||
transport_type: TransportType::Transport,
|
||||
transport_id: Some(transport_id),
|
||||
..DestinationPacketOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(packed.packet.header.transport_id, Some(transport_id));
|
||||
assert!(matches!(
|
||||
plain.pack_packet(
|
||||
b"invalid proof",
|
||||
None,
|
||||
None,
|
||||
DestinationPacketOptions {
|
||||
context: PacketContext::Lrproof,
|
||||
..DestinationPacketOptions::default()
|
||||
}
|
||||
),
|
||||
Err(DestinationPacketError::LrproofRequiresLink)
|
||||
));
|
||||
|
||||
let link = Destination::new(None, Direction::Out, DestType::Link, "test.link").unwrap();
|
||||
assert!(matches!(
|
||||
link.pack_packet(b"payload", None, None, DestinationPacketOptions::default()),
|
||||
Err(DestinationPacketError::LinkRuntimeRequired)
|
||||
));
|
||||
let proof = link
|
||||
.pack_packet(
|
||||
b"link request proof",
|
||||
None,
|
||||
None,
|
||||
DestinationPacketOptions {
|
||||
context: PacketContext::Lrproof,
|
||||
..DestinationPacketOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(proof.packet.data(), b"link request proof");
|
||||
assert_eq!(
|
||||
proof.packet.header.flags.destination_type,
|
||||
rns_wire::flags::DestinationType::Link
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1088,4 +1785,27 @@ mod tests {
|
||||
Err(DestinationError::InvalidAnnounceTime(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn announce_rejects_wrong_destination_shape_precisely() {
|
||||
let identity = Identity::new();
|
||||
let mut group =
|
||||
Destination::new(None, Direction::In, DestType::Group, "test.group").unwrap();
|
||||
assert!(matches!(
|
||||
group.announce_packet(&identity, None, None, false, None, 1.0),
|
||||
Err(DestinationError::NotSingle)
|
||||
));
|
||||
|
||||
let mut outbound = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
"test.out",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
outbound.announce_packet(&identity, None, None, false, None, 1.0),
|
||||
Err(DestinationError::NotInbound)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,22 @@ use thiserror::Error;
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::persistence;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Elliptic curve used for identity encryption and ratchets.
|
||||
pub const CURVE: &str = "Curve25519";
|
||||
/// Combined X25519 and Ed25519 public/private key size, in bits.
|
||||
pub const KEY_SIZE_BITS: usize = 512;
|
||||
/// X25519 ratchet key size, in bits.
|
||||
pub const RATCHET_SIZE_BITS: usize = 256;
|
||||
/// X25519 ratchet key size, in bytes (Python `Identity.RATCHETSIZE`).
|
||||
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
|
||||
/// Addressable identity hash size, in bits.
|
||||
pub const HASH_LENGTH_BITS: usize = 128;
|
||||
/// Ratchet identifier size, in bytes.
|
||||
pub const RATCHET_ID_LENGTH: usize = 10;
|
||||
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
|
||||
pub const DERIVED_KEY_LENGTH: usize = 64;
|
||||
|
||||
@@ -64,6 +77,15 @@ pub struct Identity {
|
||||
backend: Option<Arc<dyn LocalKeyBackend>>,
|
||||
}
|
||||
|
||||
/// Successful identity decryption plus the ratchet that authenticated it.
|
||||
///
|
||||
/// `ratchet_id` is absent when the identity's base key performed decryption.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DecryptionResult {
|
||||
pub plaintext: Vec<u8>,
|
||||
pub ratchet_id: Option<[u8; RATCHET_ID_LENGTH]>,
|
||||
}
|
||||
|
||||
impl Clone for Identity {
|
||||
/// Software identities clone their key material; hardware-backed identities
|
||||
/// share the same `LocalKeyBackend` (Arc) — there is no extractable key to copy.
|
||||
@@ -92,6 +114,12 @@ impl Default for Identity {
|
||||
}
|
||||
|
||||
impl Identity {
|
||||
pub const CURVE: &'static str = CURVE;
|
||||
pub const KEY_SIZE_BITS: usize = KEY_SIZE_BITS;
|
||||
pub const RATCHET_SIZE_BITS: usize = RATCHET_SIZE_BITS;
|
||||
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
|
||||
pub const HASH_LENGTH_BITS: usize = HASH_LENGTH_BITS;
|
||||
|
||||
pub fn new() -> Self {
|
||||
let prv = X25519PrivateKey::generate();
|
||||
let sig_prv = Ed25519PrivateKey::generate();
|
||||
@@ -216,6 +244,11 @@ impl Identity {
|
||||
key
|
||||
}
|
||||
|
||||
/// Lowercase, delimiter-free hexadecimal identity hash.
|
||||
pub fn hexhash(&self) -> String {
|
||||
hex::encode(self.hash)
|
||||
}
|
||||
|
||||
pub fn has_private_key(&self) -> bool {
|
||||
self.prv.is_some() && self.sig_prv.is_some()
|
||||
}
|
||||
@@ -294,6 +327,21 @@ impl Identity {
|
||||
ratchets: Option<&[&[u8; 32]]>,
|
||||
enforce_ratchets: bool,
|
||||
) -> Result<Vec<u8>, IdentityError> {
|
||||
self.decrypt_with_ratchet_id(ciphertext, ratchets, enforce_ratchets)
|
||||
.map(|result| result.plaintext)
|
||||
}
|
||||
|
||||
/// Decrypt ciphertext and report the ratchet key that authenticated it.
|
||||
///
|
||||
/// The identifier is `SHA-256(ratchet_public_key)[:10]`, matching the
|
||||
/// reference implementation. Base-identity decryption returns no ratchet
|
||||
/// identifier.
|
||||
pub fn decrypt_with_ratchet_id(
|
||||
&self,
|
||||
ciphertext: &[u8],
|
||||
ratchets: Option<&[&[u8; 32]]>,
|
||||
enforce_ratchets: bool,
|
||||
) -> Result<DecryptionResult, IdentityError> {
|
||||
if ciphertext.len() < 32 {
|
||||
return Err(IdentityError::DecryptionFailed);
|
||||
}
|
||||
@@ -311,7 +359,12 @@ impl Identity {
|
||||
shared.zeroize();
|
||||
if let Ok(derived) = derived_result {
|
||||
if let Ok(plaintext) = token::decrypt(ct, &derived) {
|
||||
return Ok(plaintext);
|
||||
return Ok(DecryptionResult {
|
||||
plaintext,
|
||||
ratchet_id: Some(Self::ratchet_id(
|
||||
&ratchet_prv.public_key().to_bytes(),
|
||||
)),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -337,7 +390,18 @@ impl Identity {
|
||||
let derived = derived_result?;
|
||||
let plaintext =
|
||||
token::decrypt(ct, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
|
||||
Ok(plaintext)
|
||||
Ok(DecryptionResult {
|
||||
plaintext,
|
||||
ratchet_id: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Derive the stable 80-bit identifier for a ratchet public key.
|
||||
pub fn ratchet_id(ratchet_public_key: &[u8; 32]) -> [u8; RATCHET_ID_LENGTH] {
|
||||
let full = rns_crypto::sha::sha256(ratchet_public_key);
|
||||
let mut id = [0u8; RATCHET_ID_LENGTH];
|
||||
id.copy_from_slice(&full[..RATCHET_ID_LENGTH]);
|
||||
id
|
||||
}
|
||||
|
||||
/// Sign `packet_hash` and return proof bytes.
|
||||
@@ -371,6 +435,12 @@ impl Identity {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Identity {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "<{}>", self.hexhash())
|
||||
}
|
||||
}
|
||||
|
||||
// Msgpack envelope wrapping the raw 64-byte private key on disk.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct IdentityPersisted {
|
||||
@@ -384,6 +454,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_generate_identity() {
|
||||
let id = Identity::new();
|
||||
assert_eq!(Identity::CURVE, "Curve25519");
|
||||
assert_eq!(Identity::RATCHETSIZE, 32);
|
||||
assert!(id.has_private_key());
|
||||
assert_ne!(id.hash, [0u8; 16]);
|
||||
}
|
||||
@@ -443,8 +515,38 @@ mod tests {
|
||||
assert!(id.decrypt(&ct, None, false).is_err());
|
||||
|
||||
let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes];
|
||||
let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap();
|
||||
assert_eq!(&pt, plaintext);
|
||||
let decrypted = id
|
||||
.decrypt_with_ratchet_id(&ct, Some(&ratchets), false)
|
||||
.unwrap();
|
||||
assert_eq!(&decrypted.plaintext, plaintext);
|
||||
assert_eq!(
|
||||
decrypted.ratchet_id,
|
||||
Some(Identity::ratchet_id(&ratchet_pub))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_identity_decryption_reports_no_ratchet() {
|
||||
let id = Identity::new();
|
||||
let ciphertext = id.encrypt(b"base identity", None).unwrap();
|
||||
let decrypted = id
|
||||
.decrypt_with_ratchet_id(&ciphertext, None, false)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(decrypted.plaintext, b"base identity");
|
||||
assert_eq!(decrypted.ratchet_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_metadata_and_display_match_wire_identity() {
|
||||
let id = Identity::new();
|
||||
|
||||
assert_eq!(CURVE, "Curve25519");
|
||||
assert_eq!(KEY_SIZE_BITS, id.get_public_key().len() * 8);
|
||||
assert_eq!(RATCHET_SIZE_BITS, 32 * 8);
|
||||
assert_eq!(HASH_LENGTH_BITS, id.hash.len() * 8);
|
||||
assert_eq!(id.hexhash(), hex::encode(id.hash));
|
||||
assert_eq!(id.to_string(), format!("<{}>", hex::encode(id.hash)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,8 +2,12 @@ use rns_crypto::hkdf::hkdf_sha256;
|
||||
use rns_crypto::sha::sha256;
|
||||
use thiserror::Error;
|
||||
|
||||
// Fixed IFAC HKDF salt. Shared with the Python reference; changing it breaks interop.
|
||||
const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
|
||||
/// Fixed IFAC HKDF salt shared with the Python reference.
|
||||
///
|
||||
/// This is public for applications that need to derive or inspect
|
||||
/// Python-compatible IFAC material outside the runtime helper. Changing it
|
||||
/// would break interoperability.
|
||||
pub const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum IfacError {
|
||||
|
||||
@@ -203,10 +203,23 @@ mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn unique_test_dir(label: &str) -> PathBuf {
|
||||
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!(
|
||||
"reticulum-{label}-{}-{}-{id}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos()
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_atomic_write_and_read() {
|
||||
let dir = std::env::temp_dir().join("reticulum_test_persistence");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let dir = unique_test_dir("persistence");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("test_atomic");
|
||||
|
||||
atomic_write(&path, b"hello world").unwrap();
|
||||
@@ -220,21 +233,19 @@ mod tests {
|
||||
"Windows must replace an existing state file instead of failing after the first write"
|
||||
);
|
||||
|
||||
let _ = fs::remove_file(&path);
|
||||
let _ = fs::remove_dir(&dir);
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_read_nonexistent() {
|
||||
let path = PathBuf::from("/tmp/reticulum_nonexistent_file_xyz");
|
||||
let path = unique_test_dir("nonexistent").join("missing");
|
||||
let result = read_file(&path).unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bounded_read_rejects_oversize_file() {
|
||||
let dir = std::env::temp_dir().join("reticulum_test_bounded_read");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
let dir = unique_test_dir("bounded-read");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("bounded");
|
||||
fs::write(&path, [0xA5; 17]).unwrap();
|
||||
@@ -248,8 +259,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_atomic_write_faults_before_rename_preserve_previous_file() {
|
||||
let dir = std::env::temp_dir().join("reticulum_test_atomic_faults");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
let dir = unique_test_dir("atomic-faults");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
fs::write(&path, b"previous").unwrap();
|
||||
@@ -272,8 +282,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_atomic_write_final_readback_failure_is_reported() {
|
||||
let dir = std::env::temp_dir().join("reticulum_test_atomic_readback_fault");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
let dir = unique_test_dir("atomic-readback-fault");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
fs::write(&path, b"previous").unwrap();
|
||||
@@ -292,8 +301,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn concurrent_atomic_writers_do_not_share_temp_paths() {
|
||||
let dir = std::env::temp_dir().join("reticulum_test_atomic_concurrent");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
let dir = unique_test_dir("atomic-concurrent");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
|
||||
|
||||
@@ -424,6 +424,110 @@ impl RatchetRing {
|
||||
}
|
||||
}
|
||||
|
||||
/// A verified ratchet ring bound to one crash-safe persistence path.
|
||||
///
|
||||
/// This is the high-level counterpart to Python's
|
||||
/// `Destination.enable_ratchets(path)`: opening loads and verifies an existing
|
||||
/// Python-compatible ring or creates a signed empty one. Rotations persist a
|
||||
/// candidate before replacing the live secret state.
|
||||
pub struct PersistentRatchetRing {
|
||||
path: PathBuf,
|
||||
ring: RatchetRing,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PersistentRatchetRing {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("PersistentRatchetRing")
|
||||
.field("path", &self.path)
|
||||
.field("retained_keys", &self.ring.len())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl PersistentRatchetRing {
|
||||
/// Load and verify `path`, or initialize it with a signed empty ring.
|
||||
pub fn open(path: impl AsRef<Path>, identity: &Identity) -> std::io::Result<Self> {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let ring = if path.is_file() {
|
||||
RatchetRing::load_verified(&path, identity)?.into_ring()
|
||||
} else {
|
||||
let ring = RatchetRing::new();
|
||||
ring.save_verified(&path, identity)?;
|
||||
ring
|
||||
};
|
||||
Ok(Self { path, ring })
|
||||
}
|
||||
|
||||
/// Persistence path for this ring.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Borrow the underlying secret ring for policy inspection.
|
||||
pub fn ring(&self) -> &RatchetRing {
|
||||
&self.ring
|
||||
}
|
||||
|
||||
/// Most recently persisted ratchet public key.
|
||||
pub fn current_public_key(&self) -> Option<[u8; 32]> {
|
||||
self.ring.current_public_key()
|
||||
}
|
||||
|
||||
/// Retained private keys, newest first, for destination decryption.
|
||||
pub fn private_keys(&self) -> &[[u8; 32]] {
|
||||
self.ring.private_keys()
|
||||
}
|
||||
|
||||
/// Number of retained private ratchets.
|
||||
pub fn len(&self) -> usize {
|
||||
self.ring.len()
|
||||
}
|
||||
|
||||
/// Whether no ratchet has been generated yet.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.ring.is_empty()
|
||||
}
|
||||
|
||||
/// Return a usable current public key, rotating first when due.
|
||||
pub fn ensure_current(&mut self, identity: &Identity) -> std::io::Result<[u8; 32]> {
|
||||
self.ensure_current_at(identity, wall_time_secs())
|
||||
}
|
||||
|
||||
/// Deterministic form of [`Self::ensure_current`] for runtime/tests.
|
||||
pub fn ensure_current_at(
|
||||
&mut self,
|
||||
identity: &Identity,
|
||||
now: f64,
|
||||
) -> std::io::Result<[u8; 32]> {
|
||||
if self.ring.is_empty() || self.ring.needs_rotation_at(now) {
|
||||
self.rotate_at(identity, now)
|
||||
} else {
|
||||
self.ring
|
||||
.current_public_key()
|
||||
.ok_or_else(|| invalid_data("ratchet ring has no current key"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Force a crash-safe rotation now.
|
||||
pub fn rotate(&mut self, identity: &Identity) -> std::io::Result<[u8; 32]> {
|
||||
self.rotate_at(identity, wall_time_secs())
|
||||
}
|
||||
|
||||
/// Force a crash-safe rotation at an explicit wall-clock time.
|
||||
pub fn rotate_at(&mut self, identity: &Identity, now: f64) -> std::io::Result<[u8; 32]> {
|
||||
if !now.is_finite() || now < 0.0 {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"ratchet rotation time must be finite and non-negative",
|
||||
));
|
||||
}
|
||||
let prepared = self.ring.prepare_rotation_at(now);
|
||||
prepared.ring().save_verified(&self.path, identity)?;
|
||||
Ok(self.ring.commit_prepared_rotation(prepared))
|
||||
}
|
||||
}
|
||||
|
||||
struct DecodedRatchetRing {
|
||||
ring: RatchetRing,
|
||||
signature: [u8; 64],
|
||||
@@ -842,6 +946,61 @@ mod tests {
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_ring_initializes_rotates_and_verifies_before_use() {
|
||||
let identity = Identity::new();
|
||||
let wrong_identity = Identity::new();
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"reticulum_persistent_ratchets_{}",
|
||||
identity.hexhash()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ratchets");
|
||||
|
||||
let mut persistent = PersistentRatchetRing::open(&path, &identity).unwrap();
|
||||
assert!(path.is_file());
|
||||
assert!(persistent.is_empty());
|
||||
let first = persistent.ensure_current_at(&identity, 100.0).unwrap();
|
||||
assert_eq!(persistent.current_public_key(), Some(first));
|
||||
assert_eq!(persistent.len(), 1);
|
||||
|
||||
assert!(PersistentRatchetRing::open(&path, &wrong_identity).is_err());
|
||||
let mut reloaded = PersistentRatchetRing::open(&path, &identity).unwrap();
|
||||
assert_eq!(reloaded.current_public_key(), Some(first));
|
||||
let second = reloaded.ensure_current_at(&identity, 200.0).unwrap();
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(reloaded.len(), 2);
|
||||
assert_eq!(
|
||||
RatchetRing::load_verified(&path, &identity)
|
||||
.unwrap()
|
||||
.ring()
|
||||
.current_public_key(),
|
||||
Some(second)
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_ring_does_not_commit_when_rotation_cannot_be_saved() {
|
||||
let identity = Identity::new();
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"reticulum_persistent_ratchet_failure_{}",
|
||||
identity.hexhash()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ratchets");
|
||||
let mut persistent = PersistentRatchetRing::open(&path, &identity).unwrap();
|
||||
let first = persistent.ensure_current_at(&identity, 100.0).unwrap();
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(persistent.rotate_at(&identity, 200.0).is_err());
|
||||
assert_eq!(persistent.current_public_key(), Some(first));
|
||||
assert_eq!(persistent.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verified_ring_file_is_python_map_of_signed_binary_keys() {
|
||||
let dir = std::env::temp_dir().join("reticulum_ratchet_python_wire");
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-interface"
|
||||
description = "Network interface trait and implementations for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
@@ -34,6 +35,7 @@ rand = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
md-5 = { workspace = true }
|
||||
|
||||
# Apple BLE Peripheral (CoreBluetooth GATT server, iOS + macOS).
|
||||
# Version pinned to match btleplug's internal objc2 version so the shared
|
||||
@@ -49,6 +51,9 @@ objc2-core-bluetooth = "0.2"
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
# Keepalive-tuning tests read socket options back via getsockopt.
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
+1310
-322
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1737,6 +1737,7 @@ pub async fn spawn_auto_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -407,6 +407,7 @@ pub async fn spawn_ax25kiss_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
//! buffers. Inbound deframer is capped (vs Python's unbounded) to avoid
|
||||
//! malformed-peer memory blow-up.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -16,8 +17,12 @@ use tokio::sync::mpsc;
|
||||
|
||||
use crate::hdlc;
|
||||
use crate::socket_tuning::{iface_addr_for, set_keepalive_tuned, set_socket_buffers};
|
||||
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
|
||||
use rns_transport::messages::{InboundPacket, TransportMessage};
|
||||
use crate::traits::{
|
||||
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
|
||||
};
|
||||
use rns_transport::messages::{
|
||||
InboundPacket, InterfaceInspectionSnapshot, InterfaceInspectionSource, TransportMessage,
|
||||
};
|
||||
|
||||
/// 1 MiB MTU — also the SO_RCVBUF/SNDBUF target (kernel clamps).
|
||||
pub const HW_MTU: u32 = 1_048_576;
|
||||
@@ -37,8 +42,21 @@ pub const TCP_PROBES: u32 = 12;
|
||||
/// Linux TCP_USER_TIMEOUT — drops stuck conns when peer goes silent without RST.
|
||||
pub const TCP_USER_TIMEOUT: u32 = 24;
|
||||
|
||||
pub const BLOCK_FAST_FLAPPING: bool = true;
|
||||
pub const FAST_FLAPPING_THRESHOLD: Duration = Duration::from_secs(20);
|
||||
pub const FAST_FLAPPING_GRACE: u64 = 5;
|
||||
pub const FAST_FLAPPING_BLOCK_TIME: Duration = Duration::from_secs(12 * 60 * 60);
|
||||
|
||||
const TX_CHANNEL_DEPTH: usize = 1024;
|
||||
|
||||
/// Bounds process-global fast-flap state to a conservative few hundred KiB.
|
||||
///
|
||||
/// Once full, unexpired tracked (including blocked) IPs retain their state and
|
||||
/// new IPs remain admissible but are not tracked. Strictly expired entries can
|
||||
/// be reclaimed. This prevents an address spray from turning the abuse
|
||||
/// safeguard itself into an unbounded allocation.
|
||||
const MAX_TRACKED_FAST_FLAP_IPS: usize = 4096;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BackboneServerConfig {
|
||||
pub name: String,
|
||||
@@ -48,6 +66,14 @@ pub struct BackboneServerConfig {
|
||||
pub mode: InterfaceMode,
|
||||
/// Optional kernel ifname; binds to its current IP (falls back to `listen_ip`).
|
||||
pub device: Option<String>,
|
||||
/// Reject an IP after more than `fast_flapping_grace` short connections.
|
||||
pub block_fast_flapping: bool,
|
||||
/// Connections shorter than this duration count as fast flaps.
|
||||
pub fast_flapping_threshold: Duration,
|
||||
/// Number of short connections tolerated before blocking starts.
|
||||
pub fast_flapping_grace: u64,
|
||||
/// Time since the latest short connection before its state expires.
|
||||
pub fast_flapping_block_time: Duration,
|
||||
}
|
||||
|
||||
impl BackboneServerConfig {
|
||||
@@ -59,6 +85,10 @@ impl BackboneServerConfig {
|
||||
prefer_ipv6: false,
|
||||
mode: InterfaceMode::Full,
|
||||
device: None,
|
||||
block_fast_flapping: BLOCK_FAST_FLAPPING,
|
||||
fast_flapping_threshold: FAST_FLAPPING_THRESHOLD,
|
||||
fast_flapping_grace: FAST_FLAPPING_GRACE,
|
||||
fast_flapping_block_time: FAST_FLAPPING_BLOCK_TIME,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,6 +118,222 @@ impl BackboneClientConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct FastFlapPolicy {
|
||||
enabled: bool,
|
||||
threshold: Duration,
|
||||
grace: u64,
|
||||
block_time: Duration,
|
||||
}
|
||||
|
||||
impl From<&BackboneServerConfig> for FastFlapPolicy {
|
||||
fn from(config: &BackboneServerConfig) -> Self {
|
||||
Self {
|
||||
enabled: config.block_fast_flapping,
|
||||
threshold: config.fast_flapping_threshold,
|
||||
grace: config.fast_flapping_grace,
|
||||
block_time: config.fast_flapping_block_time,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait MonotonicClock: Send + Sync {
|
||||
fn now(&self) -> Duration;
|
||||
}
|
||||
|
||||
struct SystemMonotonicClock;
|
||||
|
||||
impl MonotonicClock for SystemMonotonicClock {
|
||||
fn now(&self) -> Duration {
|
||||
static EPOCH: OnceLock<Instant> = OnceLock::new();
|
||||
EPOCH.get_or_init(Instant::now).elapsed()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct FastFlapEntry {
|
||||
last_flap: Duration,
|
||||
flaps: u64,
|
||||
}
|
||||
|
||||
struct FastFlapTable {
|
||||
entries: HashMap<IpAddr, FastFlapEntry>,
|
||||
capacity: usize,
|
||||
}
|
||||
|
||||
impl FastFlapTable {
|
||||
fn new(capacity: usize) -> Self {
|
||||
Self {
|
||||
entries: HashMap::new(),
|
||||
capacity,
|
||||
}
|
||||
}
|
||||
|
||||
fn prune_expired(&mut self, now: Duration, block_time: Duration) {
|
||||
self.entries
|
||||
.retain(|_, entry| now.saturating_sub(entry.last_flap) <= block_time);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FastFlapRuntime {
|
||||
clock: Arc<dyn MonotonicClock>,
|
||||
table: Arc<Mutex<FastFlapTable>>,
|
||||
}
|
||||
|
||||
impl FastFlapRuntime {
|
||||
fn production() -> Self {
|
||||
static TABLE: OnceLock<Arc<Mutex<FastFlapTable>>> = OnceLock::new();
|
||||
Self {
|
||||
clock: Arc::new(SystemMonotonicClock),
|
||||
table: Arc::clone(TABLE.get_or_init(|| {
|
||||
Arc::new(Mutex::new(FastFlapTable::new(MAX_TRACKED_FAST_FLAP_IPS)))
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
fn admit(&self, remote_ip: IpAddr, policy: FastFlapPolicy) -> FastFlapAdmission {
|
||||
let started_at = self.clock.now();
|
||||
if !policy.enabled {
|
||||
return FastFlapAdmission::Allowed(FastFlapConnection {
|
||||
remote_ip,
|
||||
started_at: Some(started_at),
|
||||
policy,
|
||||
runtime: self.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = table.entries.get(&remote_ip).copied() {
|
||||
if started_at.saturating_sub(entry.last_flap) > policy.block_time {
|
||||
table.entries.remove(&remote_ip);
|
||||
} else if entry.flaps > policy.grace {
|
||||
return FastFlapAdmission::Rejected { flaps: entry.flaps };
|
||||
}
|
||||
} else if table.entries.len() >= table.capacity {
|
||||
table.prune_expired(started_at, policy.block_time);
|
||||
}
|
||||
drop(table);
|
||||
|
||||
FastFlapAdmission::Allowed(FastFlapConnection {
|
||||
remote_ip,
|
||||
started_at: Some(started_at),
|
||||
policy,
|
||||
runtime: self.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn record_disconnect(&self, remote_ip: IpAddr, started_at: Duration, policy: FastFlapPolicy) {
|
||||
if !policy.enabled {
|
||||
return;
|
||||
}
|
||||
|
||||
let now = self.clock.now();
|
||||
if now.saturating_sub(started_at) >= policy.threshold {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = table.entries.get_mut(&remote_ip) {
|
||||
entry.last_flap = now;
|
||||
entry.flaps = entry.flaps.saturating_add(1);
|
||||
return;
|
||||
}
|
||||
if table.entries.len() >= table.capacity {
|
||||
table.prune_expired(now, policy.block_time);
|
||||
}
|
||||
if table.entries.len() >= table.capacity {
|
||||
tracing::debug!(
|
||||
remote_ip = %remote_ip,
|
||||
capacity = table.capacity,
|
||||
"backbone fast-flap table is full; declining to track new IP",
|
||||
);
|
||||
return;
|
||||
}
|
||||
table.entries.insert(
|
||||
remote_ip,
|
||||
FastFlapEntry {
|
||||
last_flap: now,
|
||||
flaps: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn inspection_snapshot(
|
||||
&self,
|
||||
policy: FastFlapPolicy,
|
||||
active_clients: &AtomicU64,
|
||||
) -> InterfaceInspectionSnapshot {
|
||||
let blocked_ips = if policy.enabled {
|
||||
let now = self.clock.now();
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
table.prune_expired(now, policy.block_time);
|
||||
table
|
||||
.entries
|
||||
.values()
|
||||
.filter(|entry| entry.flaps > policy.grace)
|
||||
.count() as u64
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
InterfaceInspectionSnapshot {
|
||||
active_clients: Some(active_clients.load(Ordering::Relaxed)),
|
||||
blocked_ips: Some(blocked_ips),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum FastFlapAdmission {
|
||||
Allowed(FastFlapConnection),
|
||||
Rejected { flaps: u64 },
|
||||
}
|
||||
|
||||
struct FastFlapConnection {
|
||||
remote_ip: IpAddr,
|
||||
started_at: Option<Duration>,
|
||||
policy: FastFlapPolicy,
|
||||
runtime: FastFlapRuntime,
|
||||
}
|
||||
|
||||
impl FastFlapConnection {
|
||||
fn record_disconnect(&mut self) {
|
||||
if let Some(started_at) = self.started_at.take() {
|
||||
self.runtime
|
||||
.record_disconnect(self.remote_ip, started_at, self.policy);
|
||||
}
|
||||
}
|
||||
|
||||
fn disconnected(mut self) {
|
||||
self.record_disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FastFlapConnection {
|
||||
fn drop(&mut self) {
|
||||
// The guard lives in the child read-task future, so cancellation and
|
||||
// panic exits account for the connection just like normal EOF/errors.
|
||||
self.record_disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
struct ActiveClientGuard {
|
||||
active_clients: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
impl ActiveClientGuard {
|
||||
fn new(active_clients: Arc<AtomicU64>) -> Self {
|
||||
active_clients.fetch_add(1, Ordering::Relaxed);
|
||||
Self { active_clients }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ActiveClientGuard {
|
||||
fn drop(&mut self) {
|
||||
self.active_clients.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn keepalive_durations() -> (Duration, Duration, u32, Duration) {
|
||||
(
|
||||
Duration::from_secs(TCP_PROBE_AFTER as u64),
|
||||
@@ -220,6 +466,25 @@ pub async fn spawn_backbone_server(
|
||||
id_gen: Arc<AtomicU64>,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
spawn_backbone_server_with_runtime(
|
||||
config,
|
||||
id,
|
||||
id_gen,
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
FastFlapRuntime::production(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn spawn_backbone_server_with_runtime(
|
||||
config: BackboneServerConfig,
|
||||
id: InterfaceId,
|
||||
id_gen: Arc<AtomicU64>,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
fast_flap_runtime: FastFlapRuntime,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let listen_ip = resolve_listen_addr(&config);
|
||||
let bind_addr = if listen_ip.starts_with('[') {
|
||||
@@ -230,6 +495,26 @@ pub async fn spawn_backbone_server(
|
||||
format!("{}:{}", listen_ip, config.listen_port)
|
||||
};
|
||||
let listener = TcpListener::bind(&bind_addr).await?;
|
||||
spawn_backbone_server_on_listener(
|
||||
config,
|
||||
id,
|
||||
id_gen,
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
fast_flap_runtime,
|
||||
listener,
|
||||
)
|
||||
}
|
||||
|
||||
fn spawn_backbone_server_on_listener(
|
||||
config: BackboneServerConfig,
|
||||
id: InterfaceId,
|
||||
id_gen: Arc<AtomicU64>,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
fast_flap_runtime: FastFlapRuntime,
|
||||
listener: TcpListener,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let local_addr = listener.local_addr()?;
|
||||
tracing::info!(name = %config.name, addr = %local_addr, "backbone server listening");
|
||||
|
||||
@@ -237,6 +522,14 @@ pub async fn spawn_backbone_server(
|
||||
let online2 = online.clone();
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let fast_flap_policy = FastFlapPolicy::from(&config);
|
||||
let active_clients = Arc::new(AtomicU64::new(0));
|
||||
let inspection_runtime = fast_flap_runtime.clone();
|
||||
let inspection_active_clients = Arc::clone(&active_clients);
|
||||
let inspection = InterfaceInspectionSource::new(move || {
|
||||
inspection_runtime.inspection_snapshot(fast_flap_policy, inspection_active_clients.as_ref())
|
||||
});
|
||||
let task_active_clients = Arc::clone(&active_clients);
|
||||
|
||||
// Parent listener is inbound-only; drain task warns on stray writes.
|
||||
let (tx, mut listener_rx) = mpsc::channel::<Bytes>(1);
|
||||
@@ -254,6 +547,19 @@ pub async fn spawn_backbone_server(
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((stream, peer)) => {
|
||||
let fast_flap_connection =
|
||||
match fast_flap_runtime.admit(peer.ip(), fast_flap_policy) {
|
||||
FastFlapAdmission::Allowed(connection) => connection,
|
||||
FastFlapAdmission::Rejected { flaps } => {
|
||||
tracing::warn!(
|
||||
remote_ip = %peer.ip(),
|
||||
flaps,
|
||||
"backbone: rejecting fast-flapping connection",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
|
||||
let client_name = format!("{}/client_{}", config.name, client_id);
|
||||
tracing::info!(
|
||||
@@ -279,9 +585,13 @@ pub async fn spawn_backbone_server(
|
||||
let transport_tx2 = transport_tx.clone();
|
||||
let dereg_tx = transport_tx.clone();
|
||||
let cname = client_name.clone();
|
||||
let active_client_guard =
|
||||
ActiveClientGuard::new(Arc::clone(&task_active_clients));
|
||||
let read_handle = tokio::spawn(async move {
|
||||
let _active_client_guard = active_client_guard;
|
||||
backbone_read_loop(reader, client_id, transport_tx2, c_online_r, c_rxb_r)
|
||||
.await;
|
||||
fast_flap_connection.disconnected();
|
||||
tracing::info!(name = %cname, "backbone client disconnected");
|
||||
// Proactive notify so broadcasts don't target dead tx.
|
||||
let _ = dereg_tx
|
||||
@@ -305,10 +615,14 @@ pub async fn spawn_backbone_server(
|
||||
online: c_online,
|
||||
rxb: Some(c_rxb),
|
||||
txb: Some(c_txb),
|
||||
inspection: None,
|
||||
tx: c_tx,
|
||||
read_task: read_handle,
|
||||
};
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("backbone handle registry closed");
|
||||
break;
|
||||
}
|
||||
@@ -338,6 +652,7 @@ pub async fn spawn_backbone_server(
|
||||
online,
|
||||
rxb: Some(Arc::new(AtomicU64::new(0))),
|
||||
txb: Some(Arc::new(AtomicU64::new(0))),
|
||||
inspection: Some(inspection),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -506,6 +821,7 @@ pub async fn spawn_backbone_client(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -514,6 +830,102 @@ pub async fn spawn_backbone_client(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestClock {
|
||||
now: Arc<Mutex<Duration>>,
|
||||
}
|
||||
|
||||
impl TestClock {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
now: Arc::new(Mutex::new(Duration::ZERO)),
|
||||
}
|
||||
}
|
||||
|
||||
fn advance(&self, duration: Duration) {
|
||||
let mut now = self.now.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*now = now
|
||||
.checked_add(duration)
|
||||
.expect("test monotonic clock overflow");
|
||||
}
|
||||
}
|
||||
|
||||
impl MonotonicClock for TestClock {
|
||||
fn now(&self) -> Duration {
|
||||
*self.now.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
fn test_runtime(capacity: usize) -> (FastFlapRuntime, TestClock) {
|
||||
let clock = TestClock::new();
|
||||
(
|
||||
FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table: Arc::new(Mutex::new(FastFlapTable::new(capacity))),
|
||||
},
|
||||
clock,
|
||||
)
|
||||
}
|
||||
|
||||
fn default_policy() -> FastFlapPolicy {
|
||||
FastFlapPolicy {
|
||||
enabled: BLOCK_FAST_FLAPPING,
|
||||
threshold: FAST_FLAPPING_THRESHOLD,
|
||||
grace: FAST_FLAPPING_GRACE,
|
||||
block_time: FAST_FLAPPING_BLOCK_TIME,
|
||||
}
|
||||
}
|
||||
|
||||
fn allow_connection(
|
||||
runtime: &FastFlapRuntime,
|
||||
ip: IpAddr,
|
||||
policy: FastFlapPolicy,
|
||||
) -> FastFlapConnection {
|
||||
match runtime.admit(ip, policy) {
|
||||
FastFlapAdmission::Allowed(connection) => connection,
|
||||
FastFlapAdmission::Rejected { flaps } => {
|
||||
panic!("expected connection from {ip} to be allowed, recorded flaps: {flaps}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_rejected(runtime: &FastFlapRuntime, ip: IpAddr, policy: FastFlapPolicy) {
|
||||
assert!(matches!(
|
||||
runtime.admit(ip, policy),
|
||||
FastFlapAdmission::Rejected { .. }
|
||||
));
|
||||
}
|
||||
|
||||
fn record_short_connection(
|
||||
runtime: &FastFlapRuntime,
|
||||
clock: &TestClock,
|
||||
ip: IpAddr,
|
||||
policy: FastFlapPolicy,
|
||||
) {
|
||||
let connection = allow_connection(runtime, ip, policy);
|
||||
clock.advance(Duration::from_millis(1));
|
||||
connection.disconnected();
|
||||
}
|
||||
|
||||
fn tracked_flaps(runtime: &FastFlapRuntime, ip: IpAddr) -> Option<u64> {
|
||||
runtime
|
||||
.table
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.entries
|
||||
.get(&ip)
|
||||
.map(|entry| entry.flaps)
|
||||
}
|
||||
|
||||
fn inspection_snapshot(handle: &InterfaceHandle) -> InterfaceInspectionSnapshot {
|
||||
handle
|
||||
.inspection
|
||||
.as_ref()
|
||||
.expect("backbone listener exposes aggregate inspection")
|
||||
.snapshot()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_backbone_server_config() {
|
||||
@@ -521,6 +933,13 @@ mod tests {
|
||||
assert_eq!(cfg.listen_port, 4243);
|
||||
assert!(!cfg.prefer_ipv6);
|
||||
assert!(cfg.device.is_none());
|
||||
assert!(cfg.block_fast_flapping);
|
||||
assert_eq!(cfg.fast_flapping_threshold, Duration::from_secs(20));
|
||||
assert_eq!(cfg.fast_flapping_grace, 5);
|
||||
assert_eq!(
|
||||
cfg.fast_flapping_block_time,
|
||||
Duration::from_secs(12 * 60 * 60)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -573,6 +992,316 @@ mod tests {
|
||||
assert!(mtu >= rns_wire::constants::MTU as u32 / 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_flap_grace_is_strictly_greater_than_five() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let policy = default_policy();
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
|
||||
|
||||
// Upstream's strict `flaps > grace` admits and records six short
|
||||
// connections for grace=5. The following (seventh) admission blocks.
|
||||
for _ in 0..=policy.grace {
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
}
|
||||
assert_eq!(tracked_flaps(&runtime, ip), Some(6));
|
||||
assert_rejected(&runtime, ip, policy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threshold_and_expiry_boundaries_are_strict() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let stable_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2));
|
||||
let blocked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 3));
|
||||
|
||||
let stable = allow_connection(&runtime, stable_ip, policy);
|
||||
clock.advance(policy.threshold);
|
||||
stable.disconnected();
|
||||
assert_eq!(tracked_flaps(&runtime, stable_ip), None);
|
||||
|
||||
record_short_connection(&runtime, &clock, blocked_ip, policy);
|
||||
clock.advance(policy.block_time);
|
||||
assert_rejected(&runtime, blocked_ip, policy);
|
||||
clock.advance(Duration::from_nanos(1));
|
||||
let readmitted = allow_connection(&runtime, blocked_ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, blocked_ip), None);
|
||||
readmitted.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_connection_does_not_reset_existing_flaps() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 1;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 4));
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
let stable = allow_connection(&runtime, ip, policy);
|
||||
clock.advance(policy.threshold);
|
||||
stable.disconnected();
|
||||
assert_eq!(tracked_flaps(&runtime, ip), Some(1));
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, ip), Some(2));
|
||||
assert_rejected(&runtime, ip, policy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_connection_does_not_refresh_expiry() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 5));
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
clock.advance(policy.block_time - Duration::from_nanos(1));
|
||||
assert_rejected(&runtime, ip, policy);
|
||||
clock.advance(Duration::from_nanos(2));
|
||||
let readmitted = allow_connection(&runtime, ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, ip), None);
|
||||
readmitted.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_policy_neither_tracks_nor_blocks() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.enabled = false;
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 6));
|
||||
|
||||
for _ in 0..10 {
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
}
|
||||
assert_eq!(tracked_flaps(&runtime, ip), None);
|
||||
let admitted = allow_connection(&runtime, ip, policy);
|
||||
admitted.disconnected();
|
||||
let active_clients = AtomicU64::new(0);
|
||||
assert_eq!(
|
||||
runtime.inspection_snapshot(policy, &active_clients),
|
||||
InterfaceInspectionSnapshot {
|
||||
active_clients: Some(0),
|
||||
blocked_ips: Some(0),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_uses_strict_grace_and_expiry_boundaries() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let policy = default_policy();
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 12));
|
||||
let active_clients = AtomicU64::new(3);
|
||||
|
||||
for _ in 0..policy.grace {
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
}
|
||||
assert_eq!(
|
||||
runtime.inspection_snapshot(policy, &active_clients),
|
||||
InterfaceInspectionSnapshot {
|
||||
active_clients: Some(3),
|
||||
blocked_ips: Some(0),
|
||||
}
|
||||
);
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.inspection_snapshot(policy, &active_clients)
|
||||
.blocked_ips,
|
||||
Some(1)
|
||||
);
|
||||
clock.advance(policy.block_time);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.inspection_snapshot(policy, &active_clients)
|
||||
.blocked_ips,
|
||||
Some(1)
|
||||
);
|
||||
clock.advance(Duration::from_nanos(1));
|
||||
assert_eq!(
|
||||
runtime
|
||||
.inspection_snapshot(policy, &active_clients)
|
||||
.blocked_ips,
|
||||
Some(0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_inspection_snapshots_are_live_and_non_destructive() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 13));
|
||||
let active_clients = AtomicU64::new(1);
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
|
||||
let first = runtime.inspection_snapshot(policy, &active_clients);
|
||||
let second = runtime.inspection_snapshot(policy, &active_clients);
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(first.active_clients, Some(1));
|
||||
assert_eq!(first.blocked_ips, Some(1));
|
||||
|
||||
active_clients.store(2, Ordering::Relaxed);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.inspection_snapshot(policy, &active_clients)
|
||||
.active_clients,
|
||||
Some(2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_is_ip_scoped() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let blocked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 7));
|
||||
let other_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 8));
|
||||
|
||||
record_short_connection(&runtime, &clock, blocked_ip, policy);
|
||||
assert_rejected(&runtime, blocked_ip, policy);
|
||||
let other = allow_connection(&runtime, other_ip, policy);
|
||||
other.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_share_one_process_global_ip_keyspace() {
|
||||
let clock = TestClock::new();
|
||||
let table = Arc::new(Mutex::new(FastFlapTable::new(16)));
|
||||
let first_listener = FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table: Arc::clone(&table),
|
||||
};
|
||||
let second_listener = FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table,
|
||||
};
|
||||
let policy = default_policy();
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9));
|
||||
|
||||
for index in 0..=policy.grace {
|
||||
let listener = if index % 2 == 0 {
|
||||
&first_listener
|
||||
} else {
|
||||
&second_listener
|
||||
};
|
||||
record_short_connection(listener, &clock, ip, policy);
|
||||
}
|
||||
assert_rejected(&first_listener, ip, policy);
|
||||
assert_rejected(&second_listener, ip, policy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_table_preserves_unexpired_entries_and_reuses_expired_slots() {
|
||||
let (runtime, clock) = test_runtime(1);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let tracked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10));
|
||||
let untracked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 11));
|
||||
|
||||
record_short_connection(&runtime, &clock, tracked_ip, policy);
|
||||
record_short_connection(&runtime, &clock, untracked_ip, policy);
|
||||
|
||||
assert_eq!(tracked_flaps(&runtime, tracked_ip), Some(1));
|
||||
assert_eq!(tracked_flaps(&runtime, untracked_ip), None);
|
||||
assert_rejected(&runtime, tracked_ip, policy);
|
||||
let untracked = allow_connection(&runtime, untracked_ip, policy);
|
||||
untracked.disconnected();
|
||||
|
||||
clock.advance(policy.block_time + Duration::from_nanos(1));
|
||||
record_short_connection(&runtime, &clock, untracked_ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, tracked_ip), None);
|
||||
assert_eq!(tracked_flaps(&runtime, untracked_ip), Some(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aborted_child_read_task_records_short_connection() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
.unwrap();
|
||||
let listen_addr = listener.local_addr().unwrap();
|
||||
let config =
|
||||
BackboneServerConfig::new("abort-accounting-test", "127.0.0.1", listen_addr.port());
|
||||
let id_gen = Arc::new(AtomicU64::new(100));
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(8);
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel(8);
|
||||
let parent = spawn_backbone_server_on_listener(
|
||||
config,
|
||||
1,
|
||||
id_gen,
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
runtime.clone(),
|
||||
listener,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
|
||||
|
||||
let _stream = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let child = tokio::time::timeout(Duration::from_secs(1), handle_rx.recv())
|
||||
.await
|
||||
.expect("accepted child handle timed out")
|
||||
.expect("child handle channel closed");
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(1));
|
||||
clock.advance(Duration::from_millis(1));
|
||||
child.read_task.abort();
|
||||
let _ = child.read_task.await;
|
||||
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
|
||||
assert_eq!(
|
||||
tracked_flaps(&runtime, IpAddr::V4(Ipv4Addr::LOCALHOST)),
|
||||
Some(1)
|
||||
);
|
||||
parent.read_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_admission_does_not_consume_child_id_or_handle() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
.unwrap();
|
||||
let listen_addr = listener.local_addr().unwrap();
|
||||
let mut config =
|
||||
BackboneServerConfig::new("blocked-id-test", "127.0.0.1", listen_addr.port());
|
||||
config.fast_flapping_grace = 0;
|
||||
let id_gen = Arc::new(AtomicU64::new(100));
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(8);
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel(8);
|
||||
let parent = spawn_backbone_server_on_listener(
|
||||
config,
|
||||
1,
|
||||
Arc::clone(&id_gen),
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
runtime,
|
||||
listener,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
|
||||
|
||||
let mut stream = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let mut byte = [0u8; 1];
|
||||
let closed = tokio::time::timeout(Duration::from_secs(1), stream.read(&mut byte))
|
||||
.await
|
||||
.expect("blocked connection was not closed");
|
||||
assert!(matches!(closed, Ok(0) | Err(_)));
|
||||
assert_eq!(id_gen.load(Ordering::SeqCst), 100);
|
||||
assert!(handle_rx.try_recv().is_err());
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
|
||||
assert_eq!(inspection_snapshot(&parent).blocked_ips, Some(1));
|
||||
|
||||
parent.read_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_backbone_max_reconnect_dereg() {
|
||||
// Connect attempts to a port nobody is listening on; with
|
||||
|
||||
@@ -6656,6 +6656,7 @@ pub async fn spawn_ble_peer_interface(
|
||||
online: interface_online_flag(),
|
||||
txb: Some(shared_txb),
|
||||
rxb: Some(shared_rxb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,7 +11,9 @@ use tokio::net::TcpStream;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::hdlc;
|
||||
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
|
||||
use crate::traits::{
|
||||
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
|
||||
};
|
||||
use rns_transport::messages::{InboundPacket, TransportMessage};
|
||||
|
||||
pub const DEFAULT_SAM_ADDRESS: &str = "127.0.0.1";
|
||||
@@ -581,6 +583,7 @@ pub async fn spawn_i2p_client(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -775,11 +778,15 @@ pub async fn spawn_i2p_server(
|
||||
online: c_online,
|
||||
rxb: Some(c_rxb),
|
||||
txb: Some(c_txb),
|
||||
inspection: None,
|
||||
tx: c_tx,
|
||||
read_task: c_read_task,
|
||||
};
|
||||
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("I2P server: handle registry channel closed");
|
||||
online_task.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
@@ -812,6 +819,7 @@ pub async fn spawn_i2p_server(
|
||||
online,
|
||||
rxb: Some(Arc::new(AtomicU64::new(0))),
|
||||
txb: Some(Arc::new(AtomicU64::new(0))),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -276,6 +276,7 @@ pub async fn spawn_kiss_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub mod android_usb;
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
mod android_usb_lifecycle;
|
||||
pub mod auto;
|
||||
pub mod ax25kiss;
|
||||
pub mod backbone;
|
||||
@@ -29,11 +31,21 @@ pub mod local;
|
||||
pub mod pipe;
|
||||
pub mod rnode;
|
||||
pub mod rnode_admin;
|
||||
pub mod rnode_capabilities;
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android",
|
||||
test
|
||||
))]
|
||||
mod rnode_capability_preflight;
|
||||
#[cfg(feature = "serial")]
|
||||
pub mod rnode_multi;
|
||||
pub mod rnode_protocol;
|
||||
#[cfg(feature = "serial")]
|
||||
pub mod serial;
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(feature = "serial")]
|
||||
mod serial_io;
|
||||
pub mod socket_tuning;
|
||||
pub mod tcp;
|
||||
|
||||
@@ -9,7 +9,9 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::hdlc;
|
||||
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
|
||||
use crate::traits::{
|
||||
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
|
||||
};
|
||||
use rns_transport::messages::{InboundPacket, TransportMessage};
|
||||
|
||||
pub const LOCAL_MTU: u32 = 262_144;
|
||||
@@ -28,6 +30,18 @@ pub fn socket_path(data_dir: Option<&std::path::Path>) -> std::path::PathBuf {
|
||||
}
|
||||
|
||||
pub const FALLBACK_TCP_PORT: u16 = 37428;
|
||||
#[cfg(unix)]
|
||||
const LOCAL_RECONNECT_WAIT_SECS: u64 = 8;
|
||||
|
||||
#[cfg(all(unix, not(test)))]
|
||||
fn local_reconnect_wait() -> std::time::Duration {
|
||||
std::time::Duration::from_secs(LOCAL_RECONNECT_WAIT_SECS)
|
||||
}
|
||||
|
||||
#[cfg(all(unix, test))]
|
||||
fn local_reconnect_wait() -> std::time::Duration {
|
||||
std::time::Duration::from_millis(50)
|
||||
}
|
||||
|
||||
pub fn socket_path_for(instance_name: &str) -> String {
|
||||
format!("/tmp/rns_{}.sock", instance_name)
|
||||
@@ -148,6 +162,81 @@ async fn local_write_loop<W: AsyncWriteExt + Unpin>(
|
||||
online.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
enum LocalClientConnectionEnd {
|
||||
Disconnected,
|
||||
Detached,
|
||||
}
|
||||
|
||||
/// Drive both halves of one initiating local-client connection in a single
|
||||
/// task. Keeping the persistent outbound receiver here lets the Unix client
|
||||
/// retain one stable `InterfaceHandle` while replacing only the socket after a
|
||||
/// shared-instance restart.
|
||||
#[cfg(unix)]
|
||||
async fn run_local_client_connection<R, W>(
|
||||
mut reader: R,
|
||||
mut writer: W,
|
||||
rx: &mut mpsc::Receiver<Bytes>,
|
||||
interface_id: InterfaceId,
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
rxb: &AtomicU64,
|
||||
txb: &AtomicU64,
|
||||
) -> LocalClientConnectionEnd
|
||||
where
|
||||
R: AsyncReadExt + Unpin,
|
||||
W: AsyncWriteExt + Unpin,
|
||||
{
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut deframer = hdlc::HdlcDeframer::new();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
read = reader.read(&mut buf) => {
|
||||
match read {
|
||||
Ok(0) => {
|
||||
tracing::info!(interface_id, "local client read: EOF");
|
||||
return LocalClientConnectionEnd::Disconnected;
|
||||
}
|
||||
Ok(n) => {
|
||||
rxb.fetch_add(n as u64, Ordering::Relaxed);
|
||||
for frame in deframer.feed(&buf[..n]) {
|
||||
if frame.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let msg = TransportMessage::Inbound(InboundPacket {
|
||||
raw: Bytes::from(frame),
|
||||
interface_id,
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
});
|
||||
if transport_tx.send(msg).await.is_err() {
|
||||
tracing::warn!(interface_id, "transport channel closed");
|
||||
return LocalClientConnectionEnd::Detached;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(interface_id, %error, "local client read error");
|
||||
return LocalClientConnectionEnd::Disconnected;
|
||||
}
|
||||
}
|
||||
}
|
||||
outbound = rx.recv() => {
|
||||
let Some(data) = outbound else {
|
||||
return LocalClientConnectionEnd::Detached;
|
||||
};
|
||||
let framed = hdlc::frame(&data);
|
||||
if let Err(error) = writer.write_all(&framed).await {
|
||||
tracing::warn!(interface_id, %error, "local client write error");
|
||||
return LocalClientConnectionEnd::Disconnected;
|
||||
}
|
||||
txb.fetch_add(framed.len() as u64, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-stream wiring shared by both platform variants: write loop, read task,
|
||||
/// and the connection's `InterfaceHandle`. `dereg_on_disconnect` is set for
|
||||
/// accepted server-side clients so transport drops them immediately on EOF.
|
||||
@@ -202,6 +291,7 @@ where
|
||||
online,
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
}
|
||||
@@ -231,6 +321,7 @@ fn server_listener_handle(
|
||||
online,
|
||||
rxb: Some(Arc::new(AtomicU64::new(0))),
|
||||
txb: Some(Arc::new(AtomicU64::new(0))),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
}
|
||||
@@ -336,7 +427,10 @@ mod platform {
|
||||
transport_tx.clone(),
|
||||
true,
|
||||
);
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("local handle registry closed");
|
||||
break;
|
||||
}
|
||||
@@ -358,19 +452,97 @@ mod platform {
|
||||
id: InterfaceId,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let stream = connect_unix_stream(&config.socket_path).await?;
|
||||
let initial_stream = connect_unix_stream(&config.socket_path).await?;
|
||||
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local client connected");
|
||||
|
||||
let (reader, writer) = stream.into_split();
|
||||
Ok(wire_local_stream(
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let rxb = Arc::new(AtomicU64::new(0));
|
||||
let txb = Arc::new(AtomicU64::new(0));
|
||||
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
|
||||
|
||||
let task_online = online.clone();
|
||||
let task_rxb = rxb.clone();
|
||||
let task_txb = txb.clone();
|
||||
let task_name = config.name.clone();
|
||||
let task_socket_path = config.socket_path.clone();
|
||||
let read_task = tokio::spawn(async move {
|
||||
let mut stream = initial_stream;
|
||||
loop {
|
||||
let (reader, writer) = stream.into_split();
|
||||
let end = run_local_client_connection(
|
||||
reader,
|
||||
writer,
|
||||
&mut rx,
|
||||
id,
|
||||
&transport_tx,
|
||||
&task_rxb,
|
||||
&task_txb,
|
||||
)
|
||||
.await;
|
||||
task_online.store(false, Ordering::SeqCst);
|
||||
|
||||
if matches!(end, LocalClientConnectionEnd::Detached)
|
||||
|| transport_tx.is_closed()
|
||||
|| rx.is_closed()
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
tracing::warn!(
|
||||
name = %task_name,
|
||||
path = %display_socket_path(&task_socket_path),
|
||||
wait_seconds = LOCAL_RECONNECT_WAIT_SECS,
|
||||
"local shared-instance connection lost; reconnecting"
|
||||
);
|
||||
loop {
|
||||
tokio::time::sleep(local_reconnect_wait()).await;
|
||||
if transport_tx.is_closed() || rx.is_closed() {
|
||||
return;
|
||||
}
|
||||
match connect_unix_stream(&task_socket_path).await {
|
||||
Ok(connected) => {
|
||||
stream = connected;
|
||||
task_online.store(true, Ordering::SeqCst);
|
||||
tracing::info!(
|
||||
name = %task_name,
|
||||
path = %display_socket_path(&task_socket_path),
|
||||
"local shared-instance client reconnected"
|
||||
);
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::debug!(
|
||||
name = %task_name,
|
||||
path = %display_socket_path(&task_socket_path),
|
||||
%error,
|
||||
"local shared-instance reconnect failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
config.name.clone(),
|
||||
None,
|
||||
reader,
|
||||
writer,
|
||||
transport_tx,
|
||||
false,
|
||||
))
|
||||
parent_id: None,
|
||||
name: config.name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,7 +596,10 @@ mod platform {
|
||||
transport_tx.clone(),
|
||||
true,
|
||||
);
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("local handle registry closed");
|
||||
break;
|
||||
}
|
||||
@@ -678,4 +853,86 @@ mod tests {
|
||||
server_handle.read_task.abort();
|
||||
let _ = std::fs::remove_file(&socket_path);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn test_local_client_reconnects_after_server_restart() {
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
|
||||
let id_gen = Arc::new(AtomicU64::new(900));
|
||||
let socket_path = unique_test_socket_path("reticulum_reconnect_test");
|
||||
|
||||
let server_config = || LocalServerConfig {
|
||||
socket_path: socket_path.clone(),
|
||||
name: "restartable-local-server".to_string(),
|
||||
};
|
||||
let server_handle = spawn_local_server(
|
||||
server_config(),
|
||||
id_gen.clone(),
|
||||
transport_tx.clone(),
|
||||
handle_tx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let client_handle = spawn_local_client(
|
||||
LocalClientConfig {
|
||||
socket_path: socket_path.clone(),
|
||||
name: "persistent-local-client".to_string(),
|
||||
},
|
||||
88,
|
||||
transport_tx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let first_accepted =
|
||||
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
|
||||
.await
|
||||
.expect("timeout waiting for first accepted client")
|
||||
.expect("handle channel closed");
|
||||
|
||||
server_handle.read_task.abort();
|
||||
first_accepted.read_task.abort();
|
||||
drop(first_accepted.tx);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(3), async {
|
||||
while client_handle.online.load(Ordering::SeqCst) {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("client did not observe server shutdown");
|
||||
|
||||
let restarted_server =
|
||||
spawn_local_server(server_config(), id_gen, transport_tx.clone(), handle_tx)
|
||||
.await
|
||||
.unwrap();
|
||||
let second_accepted =
|
||||
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
|
||||
.await
|
||||
.expect("client did not reconnect to restarted server")
|
||||
.expect("handle channel closed");
|
||||
assert!(
|
||||
client_handle.online.load(Ordering::SeqCst),
|
||||
"stable client handle must return online after reconnect"
|
||||
);
|
||||
|
||||
let payload = Bytes::from_static(b"after shared restart");
|
||||
second_accepted.tx.send(payload.clone()).await.unwrap();
|
||||
let inbound = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
|
||||
.await
|
||||
.expect("timeout waiting for post-restart frame")
|
||||
.expect("transport channel closed");
|
||||
match inbound {
|
||||
TransportMessage::Inbound(packet) => {
|
||||
assert_eq!(packet.interface_id, 88);
|
||||
assert_eq!(packet.raw, payload);
|
||||
}
|
||||
other => panic!("unexpected post-restart message: {other:?}"),
|
||||
}
|
||||
|
||||
restarted_server.read_task.abort();
|
||||
second_accepted.read_task.abort();
|
||||
drop(second_accepted.tx);
|
||||
client_handle.read_task.abort();
|
||||
let _ = std::fs::remove_file(&socket_path);
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,7 @@ pub async fn spawn_pipe_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
+6245
-213
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,855 @@
|
||||
//! Privacy-bounded, read-only RNode capability parsing.
|
||||
//!
|
||||
//! RNode EEPROM identity information contains serial, manufacturing, checksum,
|
||||
//! signature, and other device-specific bytes. This module validates the
|
||||
//! immutable identity prefix in place, then returns only copyable product/model
|
||||
//! codes and reviewed radio limits. It never retains the source image or
|
||||
//! exposes identity, signature, configuration, or raw EEPROM fields.
|
||||
|
||||
use md5::{Digest, Md5};
|
||||
|
||||
use crate::rnode::{RNodeConfigValidationError, RNodeRadioSettings};
|
||||
|
||||
const PRODUCT_ADDRESS: usize = 0x00;
|
||||
const MODEL_ADDRESS: usize = 0x01;
|
||||
const IDENTITY_CHECKSUM_INPUT_END: usize = 0x0B;
|
||||
const CHECKSUM_ADDRESS: usize = 0x0B;
|
||||
const CHECKSUM_END: usize = 0x1B;
|
||||
const INFO_LOCK_ADDRESS: usize = 0x9B;
|
||||
const REQUIRED_EEPROM_LEN: usize = INFO_LOCK_ADDRESS + 1;
|
||||
const INFO_LOCK_BYTE: u8 = 0x73;
|
||||
|
||||
/// A validated, privacy-bounded RNode capability description.
|
||||
///
|
||||
/// The value owns no EEPROM bytes and contains no stable device identifier.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct RNodeCapabilities {
|
||||
product_code: u8,
|
||||
model_code: u8,
|
||||
radio: RNodeRadioCapabilities,
|
||||
}
|
||||
|
||||
impl RNodeCapabilities {
|
||||
/// The RNode product code stored in the validated identity prefix.
|
||||
pub const fn product_code(self) -> u8 {
|
||||
self.product_code
|
||||
}
|
||||
|
||||
/// A reviewed display name for the product code, when one is known.
|
||||
///
|
||||
/// This is a static code-table lookup; no label is read from or retained
|
||||
/// from the EEPROM image.
|
||||
pub const fn product_name(self) -> Option<&'static str> {
|
||||
rnode_product_name(self.product_code)
|
||||
}
|
||||
|
||||
/// The exact, unnormalised RNode model code stored in the identity prefix.
|
||||
pub const fn model_code(self) -> u8 {
|
||||
self.model_code
|
||||
}
|
||||
|
||||
/// Reviewed radio limits for the model, or [`RNodeRadioCapabilities::Unknown`].
|
||||
pub const fn radio(self) -> RNodeRadioCapabilities {
|
||||
self.radio
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a validated model has a reviewed radio capability profile.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeRadioCapabilities {
|
||||
/// The model maps to a reviewed, internally consistent numeric profile.
|
||||
Known(RNodeKnownRadioCapabilities),
|
||||
/// The model is unknown, ambiguous, or deliberately quarantined.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Reviewed numeric limits for a known RNode radio model.
|
||||
///
|
||||
/// For a dual-radio product, these limits describe the reviewed generic/main
|
||||
/// RNode radio profile. They do not claim to span every band supported by each
|
||||
/// physically present secondary radio.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct RNodeKnownRadioCapabilities {
|
||||
family: RNodeRadioFamily,
|
||||
min_frequency_hz: u32,
|
||||
max_frequency_hz: u32,
|
||||
max_tx_power_dbm: u8,
|
||||
}
|
||||
|
||||
impl RNodeKnownRadioCapabilities {
|
||||
/// The radio family associated with the model.
|
||||
pub const fn family(self) -> RNodeRadioFamily {
|
||||
self.family
|
||||
}
|
||||
|
||||
/// The inclusive lower frequency bound in hertz.
|
||||
pub const fn min_frequency_hz(self) -> u32 {
|
||||
self.min_frequency_hz
|
||||
}
|
||||
|
||||
/// The inclusive upper frequency bound in hertz.
|
||||
pub const fn max_frequency_hz(self) -> u32 {
|
||||
self.max_frequency_hz
|
||||
}
|
||||
|
||||
/// The inclusive maximum transmit power in dBm.
|
||||
pub const fn max_tx_power_dbm(self) -> u8 {
|
||||
self.max_tx_power_dbm
|
||||
}
|
||||
|
||||
/// Whether `frequency_hz` lies within the inclusive reviewed bounds.
|
||||
pub const fn supports_frequency(self, frequency_hz: u32) -> bool {
|
||||
frequency_hz >= self.min_frequency_hz && frequency_hz <= self.max_frequency_hz
|
||||
}
|
||||
|
||||
/// Whether `tx_power_dbm` is at or below the inclusive reviewed maximum.
|
||||
pub const fn supports_tx_power(self, tx_power_dbm: u8) -> bool {
|
||||
tx_power_dbm <= self.max_tx_power_dbm
|
||||
}
|
||||
}
|
||||
|
||||
/// Radio families represented by reviewed RNode model profiles.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeRadioFamily {
|
||||
Sx1262,
|
||||
Sx1268,
|
||||
Sx1276,
|
||||
Sx1278,
|
||||
Sx1280,
|
||||
/// A dual-radio product.
|
||||
///
|
||||
/// Its numeric capability bounds describe the reviewed generic/main radio
|
||||
/// profile, not every band of the physically present secondary radio.
|
||||
Sx1262AndSx1280,
|
||||
}
|
||||
|
||||
/// Why a capability image could not be accepted.
|
||||
///
|
||||
/// Errors intentionally contain no EEPROM contents, hashes, or identity
|
||||
/// values.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeCapabilityParseError {
|
||||
#[error("RNode EEPROM image is too short (need {required} bytes, got {actual})")]
|
||||
TooShort { required: usize, actual: usize },
|
||||
#[error("RNode identity information is not locked")]
|
||||
InfoNotLocked,
|
||||
#[error("RNode identity checksum is invalid")]
|
||||
ChecksumMismatch,
|
||||
}
|
||||
|
||||
/// Model-specific classification for a validated RNode capability image.
|
||||
///
|
||||
/// `Verified` means the exact model has a reviewed capability profile.
|
||||
/// `Unverified` means the exact stored model is unknown or quarantined, so no
|
||||
/// model profile was inferred. A `Verified` classification alone does not
|
||||
/// admit radio settings; use [`admit_rnode_radio_settings`] for that.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeRadioAdmission {
|
||||
Verified { product_code: u8, model_code: u8 },
|
||||
Unverified { product_code: u8, model_code: u8 },
|
||||
}
|
||||
|
||||
impl RNodeRadioAdmission {
|
||||
/// Validated EEPROM product code associated with this admission result.
|
||||
pub const fn product_code(self) -> u8 {
|
||||
match self {
|
||||
Self::Verified { product_code, .. } | Self::Unverified { product_code, .. } => {
|
||||
product_code
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact, unnormalised EEPROM model code associated with this result.
|
||||
pub const fn model_code(self) -> u8 {
|
||||
match self {
|
||||
Self::Verified { model_code, .. } | Self::Unverified { model_code, .. } => model_code,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a reviewed model-specific profile was available.
|
||||
pub const fn is_verified(self) -> bool {
|
||||
matches!(self, Self::Verified { .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed failure from model-specific RNode radio admission.
|
||||
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeRadioAdmissionError {
|
||||
#[error("generic RNode radio settings are invalid: {0}")]
|
||||
GenericValidation(#[source] RNodeConfigValidationError),
|
||||
#[error("frequency {requested_hz} Hz is outside verified model range {min_hz}..={max_hz} Hz")]
|
||||
FrequencyOutOfRange {
|
||||
requested_hz: u32,
|
||||
min_hz: u32,
|
||||
max_hz: u32,
|
||||
},
|
||||
#[error("TX power {requested_dbm} dBm exceeds verified model maximum {max_dbm} dBm")]
|
||||
TxPowerExceedsMaximum { requested_dbm: u8, max_dbm: u8 },
|
||||
}
|
||||
|
||||
/// Validate an EEPROM image and retain only non-identifying capability data.
|
||||
///
|
||||
/// Validation requires bytes through the identity-information lock at `0x9b`.
|
||||
/// The MD5 checksum is calculated over the exact stored bytes `0x00..0x0b`;
|
||||
/// model aliases are deliberately not normalised before validation. Bytes
|
||||
/// after the identity prefix, including the signature region, are ignored.
|
||||
pub fn parse_rnode_capabilities(
|
||||
eeprom: &[u8],
|
||||
) -> Result<RNodeCapabilities, RNodeCapabilityParseError> {
|
||||
if eeprom.len() < REQUIRED_EEPROM_LEN {
|
||||
return Err(RNodeCapabilityParseError::TooShort {
|
||||
required: REQUIRED_EEPROM_LEN,
|
||||
actual: eeprom.len(),
|
||||
});
|
||||
}
|
||||
if eeprom[INFO_LOCK_ADDRESS] != INFO_LOCK_BYTE {
|
||||
return Err(RNodeCapabilityParseError::InfoNotLocked);
|
||||
}
|
||||
|
||||
let calculated: [u8; 16] = Md5::digest(&eeprom[..IDENTITY_CHECKSUM_INPUT_END]).into();
|
||||
if calculated != eeprom[CHECKSUM_ADDRESS..CHECKSUM_END] {
|
||||
return Err(RNodeCapabilityParseError::ChecksumMismatch);
|
||||
}
|
||||
|
||||
let product_code = eeprom[PRODUCT_ADDRESS];
|
||||
let model_code = eeprom[MODEL_ADDRESS];
|
||||
let radio = rnode_model_capabilities(model_code);
|
||||
|
||||
Ok(RNodeCapabilities {
|
||||
product_code,
|
||||
model_code,
|
||||
radio,
|
||||
})
|
||||
}
|
||||
|
||||
/// Classify a validated model without admitting radio settings.
|
||||
///
|
||||
/// `capabilities` can only be obtained from a successfully validated EEPROM
|
||||
/// image. Unknown, aliased, ambiguous, and quarantined model codes return
|
||||
/// [`RNodeRadioAdmission::Unverified`] without normalisation or an inferred
|
||||
/// profile.
|
||||
pub fn classify_rnode_radio_capabilities(capabilities: RNodeCapabilities) -> RNodeRadioAdmission {
|
||||
let product_code = capabilities.product_code();
|
||||
let model_code = capabilities.model_code();
|
||||
match capabilities.radio() {
|
||||
RNodeRadioCapabilities::Known(_) => RNodeRadioAdmission::Verified {
|
||||
product_code,
|
||||
model_code,
|
||||
},
|
||||
RNodeRadioCapabilities::Unknown => RNodeRadioAdmission::Unverified {
|
||||
product_code,
|
||||
model_code,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the sole lower-layer RF admission policy to validated capabilities.
|
||||
///
|
||||
/// Generic RNode validation runs first. Known exact model codes then enforce
|
||||
/// their inclusive frequency range and maximum TX power. Unknown, aliased,
|
||||
/// ambiguous, and quarantined model codes continue as an explicit
|
||||
/// [`RNodeRadioAdmission::Unverified`] result without normalisation or an
|
||||
/// inferred profile.
|
||||
pub fn admit_rnode_radio_settings(
|
||||
capabilities: RNodeCapabilities,
|
||||
settings: RNodeRadioSettings,
|
||||
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
|
||||
settings
|
||||
.validate()
|
||||
.map_err(RNodeRadioAdmissionError::GenericValidation)?;
|
||||
|
||||
if let RNodeRadioCapabilities::Known(radio) = capabilities.radio() {
|
||||
if !radio.supports_frequency(settings.frequency) {
|
||||
return Err(RNodeRadioAdmissionError::FrequencyOutOfRange {
|
||||
requested_hz: settings.frequency,
|
||||
min_hz: radio.min_frequency_hz(),
|
||||
max_hz: radio.max_frequency_hz(),
|
||||
});
|
||||
}
|
||||
if !radio.supports_tx_power(settings.tx_power) {
|
||||
return Err(RNodeRadioAdmissionError::TxPowerExceedsMaximum {
|
||||
requested_dbm: settings.tx_power,
|
||||
max_dbm: radio.max_tx_power_dbm(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(classify_rnode_radio_capabilities(capabilities))
|
||||
}
|
||||
|
||||
/// Return the reviewed display name for an RNode product code.
|
||||
///
|
||||
/// Unknown product codes return `None`. Names are static code-table values and
|
||||
/// are never read from device-controlled EEPROM data.
|
||||
pub const fn rnode_product_name(product_code: u8) -> Option<&'static str> {
|
||||
Some(match product_code {
|
||||
0x03 => "RNode",
|
||||
0x10 => "RAK4631",
|
||||
0x15 => "LilyGO T-Echo",
|
||||
0x20 => "openCom XL",
|
||||
0xB0 => "LilyGO LoRa32 v2.0",
|
||||
0xB1 => "LilyGO LoRa32 v2.1",
|
||||
0xB2 => "LilyGO LoRa32 v1.0",
|
||||
0xC0 => "Heltec LoRa32 v2",
|
||||
0xC1 => "Heltec LoRa32 v3",
|
||||
0xC2 => "Heltec Mesh Node T114",
|
||||
0xC3 => "Heltec LoRa32 v4",
|
||||
0xD0 => "LilyGO T-Deck",
|
||||
0xE0 => "LilyGO T-Beam",
|
||||
0xEA => "LilyGO T-Beam Supreme",
|
||||
0xEB => "Seeed XIAO ESP32S3 Wio-SX1262",
|
||||
0xF0 => "Hombrew RNode",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Return the reviewed radio capabilities for an exact RNode model code.
|
||||
///
|
||||
/// Unknown, ambiguous, and quarantined model codes return
|
||||
/// [`RNodeRadioCapabilities::Unknown`]. In particular, EEPROM aliases are not
|
||||
/// normalised by this lookup. Model codes `0xA6`, `0xAA`, and `0xC8` remain
|
||||
/// quarantined because the trusted Rust sources do not establish a single,
|
||||
/// internally consistent numeric capability profile for them.
|
||||
pub fn rnode_model_capabilities(model_code: u8) -> RNodeRadioCapabilities {
|
||||
KNOWN_RADIOS
|
||||
.iter()
|
||||
.find_map(|(candidate, profile)| (*candidate == model_code).then_some(*profile))
|
||||
.map(RNodeRadioCapabilities::Known)
|
||||
.unwrap_or(RNodeRadioCapabilities::Unknown)
|
||||
}
|
||||
|
||||
const fn known(
|
||||
family: RNodeRadioFamily,
|
||||
min_frequency_hz: u32,
|
||||
max_frequency_hz: u32,
|
||||
max_tx_power_dbm: u8,
|
||||
) -> RNodeKnownRadioCapabilities {
|
||||
RNodeKnownRadioCapabilities {
|
||||
family,
|
||||
min_frequency_hz,
|
||||
max_frequency_hz,
|
||||
max_tx_power_dbm,
|
||||
}
|
||||
}
|
||||
|
||||
// Reviewed numeric profiles owned by this lower-core module. Firmware
|
||||
// filenames and human labels intentionally do not cross this boundary.
|
||||
// Models with aliases, contradictory ranges, ambiguous evidence, or explicitly
|
||||
// unknown limits are absent and therefore resolve to Unknown.
|
||||
const KNOWN_RADIOS: &[(u8, RNodeKnownRadioCapabilities)] = &[
|
||||
(
|
||||
0xA4,
|
||||
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 14),
|
||||
),
|
||||
(
|
||||
0xA9,
|
||||
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xA1,
|
||||
known(RNodeRadioFamily::Sx1268, 410_000_000, 525_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xA5,
|
||||
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xAC,
|
||||
known(RNodeRadioFamily::Sx1280, 2_400_000_000, 2_500_000_000, 20),
|
||||
),
|
||||
(
|
||||
0xA2,
|
||||
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xA7,
|
||||
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xA3,
|
||||
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xA8,
|
||||
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xB3,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xB8,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xB4,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xB9,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xBA,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xBB,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xC4,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xC9,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xC5,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xCA,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xC6,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xC7,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xE4,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xE9,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xD4,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xD9,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xDB,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xDC,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xE3,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xE8,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0x11,
|
||||
known(RNodeRadioFamily::Sx1262, 430_000_000, 510_000_000, 22),
|
||||
),
|
||||
(
|
||||
0x12,
|
||||
known(RNodeRadioFamily::Sx1262, 779_000_000, 928_000_000, 22),
|
||||
),
|
||||
(
|
||||
0x13,
|
||||
known(
|
||||
RNodeRadioFamily::Sx1262AndSx1280,
|
||||
430_000_000,
|
||||
510_000_000,
|
||||
22,
|
||||
),
|
||||
),
|
||||
(
|
||||
0x14,
|
||||
known(
|
||||
RNodeRadioFamily::Sx1262AndSx1280,
|
||||
779_000_000,
|
||||
928_000_000,
|
||||
22,
|
||||
),
|
||||
),
|
||||
(
|
||||
0x17,
|
||||
known(RNodeRadioFamily::Sx1262, 779_000_000, 928_000_000, 22),
|
||||
),
|
||||
(
|
||||
0x21,
|
||||
known(
|
||||
RNodeRadioFamily::Sx1262AndSx1280,
|
||||
820_000_000,
|
||||
960_000_000,
|
||||
22,
|
||||
),
|
||||
),
|
||||
(
|
||||
0xDE,
|
||||
known(RNodeRadioFamily::Sx1262, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xDD,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PRODUCT: u8 = 0x03;
|
||||
const QUARANTINED_MODELS: &[u8] = &[0x04, 0x09, 0x16, 0xA6, 0xAA, 0xC8, 0xFE, 0xFF];
|
||||
|
||||
fn image(model: u8) -> [u8; REQUIRED_EEPROM_LEN] {
|
||||
let mut bytes = [0xA5; REQUIRED_EEPROM_LEN];
|
||||
bytes[PRODUCT_ADDRESS] = PRODUCT;
|
||||
bytes[MODEL_ADDRESS] = model;
|
||||
bytes[0x02] = 0x07;
|
||||
bytes[0x03..0x07].copy_from_slice(&0x1122_3344_u32.to_be_bytes());
|
||||
bytes[0x07..0x0B].copy_from_slice(&0x5566_7788_u32.to_be_bytes());
|
||||
let checksum: [u8; 16] = Md5::digest(&bytes[..IDENTITY_CHECKSUM_INPUT_END]).into();
|
||||
bytes[CHECKSUM_ADDRESS..CHECKSUM_END].copy_from_slice(&checksum);
|
||||
bytes[INFO_LOCK_ADDRESS] = INFO_LOCK_BYTE;
|
||||
bytes
|
||||
}
|
||||
|
||||
fn settings(frequency: u32, tx_power: u8) -> RNodeRadioSettings {
|
||||
RNodeRadioSettings::new(frequency, 125_000, 7, 5, tx_power)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_every_byte_through_info_lock() {
|
||||
let short = &image(0xA4)[..REQUIRED_EEPROM_LEN - 1];
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(short),
|
||||
Err(RNodeCapabilityParseError::TooShort {
|
||||
required: 156,
|
||||
actual: 155,
|
||||
})
|
||||
);
|
||||
|
||||
let exact = image(0xA4);
|
||||
assert!(parse_rnode_capabilities(&exact).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unlocked_identity_information_before_checksum_validation() {
|
||||
let mut bytes = image(0xA4);
|
||||
bytes[INFO_LOCK_ADDRESS] = 0x00;
|
||||
bytes[CHECKSUM_ADDRESS] ^= 0xFF;
|
||||
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(&bytes),
|
||||
Err(RNodeCapabilityParseError::InfoNotLocked)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_covers_exact_identity_prefix_without_model_normalisation() {
|
||||
let mut bytes = image(0x04);
|
||||
let parsed = parse_rnode_capabilities(&bytes).expect("raw model checksum should validate");
|
||||
assert_eq!(parsed.model_code(), 0x04);
|
||||
assert_eq!(parsed.radio(), RNodeRadioCapabilities::Unknown);
|
||||
|
||||
// Replacing the raw alias with its nominal model invalidates the exact
|
||||
// stored checksum; the parser must not normalise it first.
|
||||
bytes[MODEL_ADDRESS] = 0xB4;
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(&bytes),
|
||||
Err(RNodeCapabilityParseError::ChecksumMismatch)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_any_identity_prefix_checksum_mismatch() {
|
||||
for address in 0..IDENTITY_CHECKSUM_INPUT_END {
|
||||
let mut bytes = image(0xA4);
|
||||
bytes[address] ^= 0x01;
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(&bytes),
|
||||
Err(RNodeCapabilityParseError::ChecksumMismatch),
|
||||
"identity byte {address:#04x} was not covered"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_only_reviewed_codes_and_known_numeric_bounds() {
|
||||
let parsed = parse_rnode_capabilities(&image(0xAC)).expect("valid known model");
|
||||
assert_eq!(parsed.product_code(), PRODUCT);
|
||||
assert_eq!(parsed.product_name(), Some("RNode"));
|
||||
assert_eq!(parsed.model_code(), 0xAC);
|
||||
assert_eq!(
|
||||
parsed.radio(),
|
||||
RNodeRadioCapabilities::Known(known(
|
||||
RNodeRadioFamily::Sx1280,
|
||||
2_400_000_000,
|
||||
2_500_000_000,
|
||||
20,
|
||||
))
|
||||
);
|
||||
|
||||
let low_band = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
|
||||
assert_eq!(
|
||||
low_band.radio(),
|
||||
RNodeRadioCapabilities::Known(known(
|
||||
RNodeRadioFamily::Sx1262,
|
||||
430_000_000,
|
||||
510_000_000,
|
||||
22,
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_support_helpers_include_both_boundaries() {
|
||||
let parsed = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
|
||||
let RNodeRadioCapabilities::Known(radio) = parsed.radio() else {
|
||||
panic!("model 0x11 must have a reviewed profile");
|
||||
};
|
||||
|
||||
assert!(radio.supports_frequency(430_000_000));
|
||||
assert!(radio.supports_frequency(510_000_000));
|
||||
assert!(!radio.supports_frequency(429_999_999));
|
||||
assert!(!radio.supports_frequency(510_000_001));
|
||||
|
||||
assert!(radio.supports_tx_power(0));
|
||||
assert!(radio.supports_tx_power(22));
|
||||
assert!(!radio.supports_tx_power(23));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_model_admission_includes_frequency_and_power_boundaries() {
|
||||
let capabilities = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
|
||||
|
||||
assert_eq!(
|
||||
admit_rnode_radio_settings(capabilities, settings(430_000_000, 0)),
|
||||
Ok(RNodeRadioAdmission::Verified {
|
||||
product_code: PRODUCT,
|
||||
model_code: 0x11,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
admit_rnode_radio_settings(capabilities, settings(510_000_000, 22)),
|
||||
Ok(RNodeRadioAdmission::Verified {
|
||||
product_code: PRODUCT,
|
||||
model_code: 0x11,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
classify_rnode_radio_capabilities(capabilities),
|
||||
RNodeRadioAdmission::Verified {
|
||||
product_code: PRODUCT,
|
||||
model_code: 0x11,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_model_admission_returns_typed_frequency_and_power_mismatches() {
|
||||
let capabilities = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
|
||||
|
||||
for (frequency, expected) in [
|
||||
(
|
||||
429_999_999,
|
||||
RNodeRadioAdmissionError::FrequencyOutOfRange {
|
||||
requested_hz: 429_999_999,
|
||||
min_hz: 430_000_000,
|
||||
max_hz: 510_000_000,
|
||||
},
|
||||
),
|
||||
(
|
||||
510_000_001,
|
||||
RNodeRadioAdmissionError::FrequencyOutOfRange {
|
||||
requested_hz: 510_000_001,
|
||||
min_hz: 430_000_000,
|
||||
max_hz: 510_000_000,
|
||||
},
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
admit_rnode_radio_settings(capabilities, settings(frequency, 22)),
|
||||
Err(expected)
|
||||
);
|
||||
}
|
||||
|
||||
let error = admit_rnode_radio_settings(capabilities, settings(430_000_000, 23));
|
||||
assert_eq!(
|
||||
error,
|
||||
Err(RNodeRadioAdmissionError::TxPowerExceedsMaximum {
|
||||
requested_dbm: 23,
|
||||
max_dbm: 22,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_and_quarantined_admission_is_explicitly_unverified() {
|
||||
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
|
||||
let capabilities =
|
||||
parse_rnode_capabilities(&image(model)).expect("valid identity image");
|
||||
assert_eq!(
|
||||
classify_rnode_radio_capabilities(capabilities),
|
||||
RNodeRadioAdmission::Unverified {
|
||||
product_code: PRODUCT,
|
||||
model_code: model,
|
||||
},
|
||||
"model {model:#04x} classification must remain unverified"
|
||||
);
|
||||
assert_eq!(
|
||||
admit_rnode_radio_settings(capabilities, settings(868_000_000, 37)),
|
||||
Ok(RNodeRadioAdmission::Unverified {
|
||||
product_code: PRODUCT,
|
||||
model_code: model,
|
||||
}),
|
||||
"model {model:#04x} must remain unverified"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_validation_precedes_known_and_unverified_model_policy() {
|
||||
for model in [0x11, 0xA6] {
|
||||
let capabilities = parse_rnode_capabilities(&image(model)).expect("valid identity");
|
||||
let error = admit_rnode_radio_settings(capabilities, settings(1, 23))
|
||||
.expect_err("model policy must not bypass generic validation");
|
||||
assert!(
|
||||
matches!(error, RNodeRadioAdmissionError::GenericValidation(_)),
|
||||
"model {model:#04x} did not fail generic validation first: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn product_names_are_closed_static_lookups() {
|
||||
const PRODUCTS: &[(u8, &str)] = &[
|
||||
(0x03, "RNode"),
|
||||
(0x10, "RAK4631"),
|
||||
(0x15, "LilyGO T-Echo"),
|
||||
(0x20, "openCom XL"),
|
||||
(0xB0, "LilyGO LoRa32 v2.0"),
|
||||
(0xB1, "LilyGO LoRa32 v2.1"),
|
||||
(0xB2, "LilyGO LoRa32 v1.0"),
|
||||
(0xC0, "Heltec LoRa32 v2"),
|
||||
(0xC1, "Heltec LoRa32 v3"),
|
||||
(0xC2, "Heltec Mesh Node T114"),
|
||||
(0xC3, "Heltec LoRa32 v4"),
|
||||
(0xD0, "LilyGO T-Deck"),
|
||||
(0xE0, "LilyGO T-Beam"),
|
||||
(0xEA, "LilyGO T-Beam Supreme"),
|
||||
(0xEB, "Seeed XIAO ESP32S3 Wio-SX1262"),
|
||||
(0xF0, "Hombrew RNode"),
|
||||
];
|
||||
|
||||
for (index, (code, name)) in PRODUCTS.iter().enumerate() {
|
||||
assert_eq!(rnode_product_name(*code), Some(*name));
|
||||
assert!(
|
||||
!PRODUCTS[..index].iter().any(|(earlier, _)| earlier == code),
|
||||
"duplicate product code {code:#04x}"
|
||||
);
|
||||
}
|
||||
assert_eq!(rnode_product_name(0x00), None);
|
||||
assert_eq!(rnode_product_name(0xFF), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_and_quarantined_models_never_invent_limits() {
|
||||
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
|
||||
let parsed = parse_rnode_capabilities(&image(model)).expect("valid identity image");
|
||||
assert_eq!(parsed.model_code(), model);
|
||||
assert_eq!(
|
||||
parsed.radio(),
|
||||
RNodeRadioCapabilities::Unknown,
|
||||
"model {model:#04x} must remain unknown"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_model_lookup_is_closed_and_does_not_normalise_quarantine() {
|
||||
assert_eq!(
|
||||
rnode_model_capabilities(0xA4),
|
||||
RNodeRadioCapabilities::Known(known(
|
||||
RNodeRadioFamily::Sx1278,
|
||||
410_000_000,
|
||||
525_000_000,
|
||||
14,
|
||||
))
|
||||
);
|
||||
|
||||
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
|
||||
assert_eq!(
|
||||
rnode_model_capabilities(model),
|
||||
RNodeRadioCapabilities::Unknown,
|
||||
"model {model:#04x} must remain unknown"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signature_and_other_ignored_bytes_do_not_affect_result() {
|
||||
let baseline_image = image(0xA4);
|
||||
let baseline = parse_rnode_capabilities(&baseline_image).expect("valid image");
|
||||
let mut mutated = baseline_image;
|
||||
|
||||
for (index, byte) in mutated[CHECKSUM_END..INFO_LOCK_ADDRESS]
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
{
|
||||
*byte = index as u8;
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(&mutated),
|
||||
Ok(baseline),
|
||||
"signature and non-capability bytes must be ignored"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_model_table_is_unique_valid_and_excludes_quarantine() {
|
||||
assert_eq!(KNOWN_RADIOS.len(), 37);
|
||||
|
||||
for (index, (model, profile)) in KNOWN_RADIOS.iter().enumerate() {
|
||||
assert!(
|
||||
!QUARANTINED_MODELS.contains(model),
|
||||
"quarantined model {model:#04x} entered the known table"
|
||||
);
|
||||
assert!(
|
||||
profile.min_frequency_hz() < profile.max_frequency_hz(),
|
||||
"model {model:#04x} has inverted frequency limits"
|
||||
);
|
||||
assert!(
|
||||
profile.max_tx_power_dbm() > 0,
|
||||
"model {model:#04x} has a non-positive maximum TX power"
|
||||
);
|
||||
assert!(
|
||||
!KNOWN_RADIOS[..index]
|
||||
.iter()
|
||||
.any(|(earlier, _)| earlier == model),
|
||||
"duplicate model {model:#04x}"
|
||||
);
|
||||
assert_eq!(
|
||||
rnode_model_capabilities(*model),
|
||||
RNodeRadioCapabilities::Known(*profile),
|
||||
"model {model:#04x} did not round-trip through lookup"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
//! Bounded, transport-independent RNode capability preflight state.
|
||||
//!
|
||||
//! Transport owners retain their stream, writer, clock, and cancellation
|
||||
//! policy. This module owns only strict framing, bounded admission state, and
|
||||
//! privacy-safe errors so serial/TCP, BLE, and USB can share one policy without
|
||||
//! sharing transport lifecycle machinery.
|
||||
|
||||
use crate::kiss;
|
||||
use crate::rnode::{CMD_ERROR, CMD_ROM_READ, RNodeCapabilityAdmissionError, RNodeRadioSettings};
|
||||
use crate::rnode_capabilities::{
|
||||
RNodeRadioAdmission, admit_rnode_radio_settings, parse_rnode_capabilities,
|
||||
};
|
||||
use crate::rnode_protocol::{
|
||||
RNodeFrameRejection, RNodeProtocolEffect, RNodeProtocolState, RNodeProtocolTarget,
|
||||
};
|
||||
|
||||
#[cfg(all(not(test), any(feature = "serial", feature = "rnode-tcp")))]
|
||||
pub(crate) const RNODE_CAPABILITY_PREFLIGHT_DEADLINE: std::time::Duration =
|
||||
std::time::Duration::from_secs(5);
|
||||
#[cfg(all(test, any(feature = "serial", feature = "rnode-tcp")))]
|
||||
pub(crate) const RNODE_CAPABILITY_PREFLIGHT_DEADLINE: std::time::Duration =
|
||||
std::time::Duration::from_secs(1);
|
||||
pub(crate) const RNODE_CAPABILITY_READ_BUFFER_BYTES: usize = 1024;
|
||||
const RNODE_CAPABILITY_MAX_READS: usize = 128;
|
||||
const RNODE_CAPABILITY_MAX_INPUT_BYTES: usize = 4 * 1024;
|
||||
const RNODE_CAPABILITY_MAX_FRAMES: usize = 128;
|
||||
|
||||
pub(crate) fn build_rnode_capability_request() -> Vec<u8> {
|
||||
kiss::frame_with_command(CMD_ROM_READ, &[0])
|
||||
}
|
||||
|
||||
pub(crate) struct RNodeCapabilityPreflight {
|
||||
deframer: kiss::RawKissDeframer,
|
||||
protocol_state: RNodeProtocolState,
|
||||
settings: RNodeRadioSettings,
|
||||
admission: Option<RNodeRadioAdmission>,
|
||||
read_count: usize,
|
||||
input_bytes: usize,
|
||||
frame_count: usize,
|
||||
}
|
||||
|
||||
impl RNodeCapabilityPreflight {
|
||||
pub(crate) fn new(settings: RNodeRadioSettings) -> Self {
|
||||
Self {
|
||||
deframer: kiss::RawKissDeframer::new(),
|
||||
protocol_state: RNodeProtocolState::new(RNodeProtocolTarget::new(
|
||||
settings.frequency,
|
||||
settings.bandwidth,
|
||||
settings.spreading_factor,
|
||||
settings.coding_rate,
|
||||
settings.tx_power,
|
||||
)),
|
||||
settings,
|
||||
admission: None,
|
||||
read_count: 0,
|
||||
input_bytes: 0,
|
||||
frame_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume one bounded transport read.
|
||||
///
|
||||
/// `CMD_DATA` and EEPROM payloads never leave this state machine. Unknown
|
||||
/// non-data controls are ignored after strict deframing; supported generic
|
||||
/// controls are reduced into the generation-private protocol state.
|
||||
pub(crate) fn observe_read(
|
||||
&mut self,
|
||||
bytes: &[u8],
|
||||
) -> Result<Option<RNodeRadioAdmission>, RNodeCapabilityAdmissionError> {
|
||||
self.read_count = self.read_count.saturating_add(1);
|
||||
if self.read_count > RNODE_CAPABILITY_MAX_READS {
|
||||
return Err(RNodeCapabilityAdmissionError::ReadLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_READS,
|
||||
});
|
||||
}
|
||||
if bytes.len() > RNODE_CAPABILITY_READ_BUFFER_BYTES {
|
||||
return Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_READ_BUFFER_BYTES,
|
||||
});
|
||||
}
|
||||
self.input_bytes = self.input_bytes.saturating_add(bytes.len());
|
||||
if self.input_bytes > RNODE_CAPABILITY_MAX_INPUT_BYTES {
|
||||
return Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_INPUT_BYTES,
|
||||
});
|
||||
}
|
||||
|
||||
for (command, payload) in self.deframer.feed(bytes) {
|
||||
self.frame_count = self.frame_count.saturating_add(1);
|
||||
if self.frame_count > RNODE_CAPABILITY_MAX_FRAMES {
|
||||
return Err(RNodeCapabilityAdmissionError::FrameLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_FRAMES,
|
||||
});
|
||||
}
|
||||
|
||||
if command == kiss::CMD_DATA {
|
||||
continue;
|
||||
}
|
||||
if command == CMD_ROM_READ {
|
||||
if self.admission.is_some() {
|
||||
return Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse);
|
||||
}
|
||||
let capabilities = parse_rnode_capabilities(&payload)
|
||||
.map_err(RNodeCapabilityAdmissionError::CapabilityImage)?;
|
||||
self.admission = Some(
|
||||
admit_rnode_radio_settings(capabilities, self.settings)
|
||||
.map_err(RNodeCapabilityAdmissionError::RadioSettings)?,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if command == CMD_ERROR {
|
||||
return Err(RNodeCapabilityAdmissionError::DeviceError);
|
||||
}
|
||||
|
||||
match self.protocol_state.apply_frame(command, &payload) {
|
||||
RNodeProtocolEffect::Rejected(RNodeFrameRejection::UnknownCommand) => {}
|
||||
RNodeProtocolEffect::Rejected(rejection) => {
|
||||
return Err(RNodeCapabilityAdmissionError::MalformedProtocolFrame {
|
||||
rejection,
|
||||
});
|
||||
}
|
||||
RNodeProtocolEffect::RadioInitialisationFault => {
|
||||
unreachable!("CMD_ERROR is rejected before protocol reduction")
|
||||
}
|
||||
RNodeProtocolEffect::EvidenceChanged(_)
|
||||
| RNodeProtocolEffect::FlowPermissionChanged(_)
|
||||
| RNodeProtocolEffect::Reset
|
||||
| RNodeProtocolEffect::NoChange => {}
|
||||
}
|
||||
}
|
||||
|
||||
let evidence = self.protocol_state.evidence();
|
||||
if self.protocol_state.detection_observed() && !evidence.detected {
|
||||
return Err(RNodeCapabilityAdmissionError::DetectionRejected);
|
||||
}
|
||||
if evidence
|
||||
.firmware
|
||||
.is_some_and(|firmware| !firmware.is_supported())
|
||||
{
|
||||
return Err(RNodeCapabilityAdmissionError::UnsupportedFirmware);
|
||||
}
|
||||
Ok((evidence.detected && evidence.firmware.is_some())
|
||||
.then_some(self.admission)
|
||||
.flatten())
|
||||
}
|
||||
|
||||
/// Return the only preflight evidence that may seed active readiness.
|
||||
///
|
||||
/// Configuration, radio, and flow frames observed before the runtime sends
|
||||
/// its admitted init sequence may be stale. They remain reduced privately
|
||||
/// during preflight but never cross the admission boundary.
|
||||
pub(crate) fn into_protocol_state(self) -> RNodeProtocolState {
|
||||
let target = self.protocol_state.target();
|
||||
let evidence = self.protocol_state.evidence();
|
||||
let mut admitted = RNodeProtocolState::new(target);
|
||||
if evidence.detected {
|
||||
admitted.apply_frame(crate::rnode::CMD_DETECT, &[crate::rnode::DETECT_RESP]);
|
||||
}
|
||||
if let Some(firmware) = evidence.firmware {
|
||||
admitted.apply_frame(
|
||||
crate::rnode::CMD_FW_VERSION,
|
||||
&[firmware.major, firmware.minor],
|
||||
);
|
||||
}
|
||||
admitted
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use md5::{Digest, Md5};
|
||||
|
||||
use super::*;
|
||||
use crate::rnode::{
|
||||
CMD_DETECT, CMD_FW_VERSION, DETECT_RESP, REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN,
|
||||
};
|
||||
|
||||
fn settings(frequency: u32, tx_power: u8) -> RNodeRadioSettings {
|
||||
RNodeRadioSettings::new(frequency, 125_000, 7, 5, tx_power)
|
||||
}
|
||||
|
||||
fn eeprom(model: u8) -> Vec<u8> {
|
||||
let mut bytes = vec![0xFF; 1024];
|
||||
bytes[0] = 0x03;
|
||||
bytes[1] = model;
|
||||
bytes[2..11].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
let checksum: [u8; 16] = Md5::digest(&bytes[..11]).into();
|
||||
bytes[11..27].copy_from_slice(&checksum);
|
||||
// Exercise both extended-KISS escape forms outside the validated
|
||||
// identity prefix.
|
||||
bytes[100] = kiss::FEND;
|
||||
bytes[101] = kiss::FESC;
|
||||
bytes[0x9B] = 0x73;
|
||||
bytes
|
||||
}
|
||||
|
||||
fn observe_chunked(
|
||||
preflight: &mut RNodeCapabilityPreflight,
|
||||
bytes: &[u8],
|
||||
) -> Result<Option<RNodeRadioAdmission>, RNodeCapabilityAdmissionError> {
|
||||
let mut admission = None;
|
||||
for chunk in bytes.chunks(257) {
|
||||
admission = preflight.observe_read(chunk)?.or(admission);
|
||||
}
|
||||
Ok(admission)
|
||||
}
|
||||
|
||||
fn admitted_frames(model: u8) -> Vec<u8> {
|
||||
let mut frames = Vec::new();
|
||||
kiss::frame_with_command_into(CMD_DETECT, &[DETECT_RESP], &mut frames);
|
||||
kiss::frame_with_command_into(
|
||||
CMD_FW_VERSION,
|
||||
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN],
|
||||
&mut frames,
|
||||
);
|
||||
kiss::frame_with_command_into(CMD_ROM_READ, &eeprom(model), &mut frames);
|
||||
frames
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_request_is_one_standalone_rom_read_zero_frame() {
|
||||
assert_eq!(
|
||||
build_rnode_capability_request(),
|
||||
kiss::frame_with_command(CMD_ROM_READ, &[0])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragmented_and_escaped_eeprom_admits_verified_model() {
|
||||
let bytes = admitted_frames(0xB8);
|
||||
assert!(bytes.contains(&kiss::FESC));
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let result = observe_chunked(&mut preflight, &bytes).unwrap();
|
||||
assert!(matches!(result, Some(RNodeRadioAdmission::Verified { .. })));
|
||||
assert!(preflight.into_protocol_state().evidence().detected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validated_unknown_model_is_explicitly_unverified() {
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert!(matches!(
|
||||
observe_chunked(&mut preflight, &admitted_frames(0xFE)).unwrap(),
|
||||
Some(RNodeRadioAdmission::Unverified {
|
||||
model_code: 0xFE,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_and_wrong_commands_do_not_satisfy_or_escape_preflight() {
|
||||
let mut bytes = Vec::new();
|
||||
kiss::frame_with_command_into(kiss::CMD_DATA, b"private packet", &mut bytes);
|
||||
kiss::frame_with_command_into(crate::rnode::CMD_PLATFORM, &[0x80], &mut bytes);
|
||||
kiss::frame_with_command_into(CMD_ROM_READ.wrapping_add(1), &eeprom(0xB8), &mut bytes);
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(observe_chunked(&mut preflight, &bytes).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_control_device_error_and_invalid_image_fail_closed() {
|
||||
let mut malformed = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let malformed_frame = kiss::frame_with_command(CMD_FW_VERSION, &[1]);
|
||||
assert!(matches!(
|
||||
malformed.observe_read(&malformed_frame),
|
||||
Err(RNodeCapabilityAdmissionError::MalformedProtocolFrame { .. })
|
||||
));
|
||||
|
||||
let mut device_error = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
device_error.observe_read(&kiss::frame_with_command(CMD_ERROR, &[0x7F])),
|
||||
Err(RNodeCapabilityAdmissionError::DeviceError)
|
||||
);
|
||||
|
||||
let mut invalid = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert!(matches!(
|
||||
invalid.observe_read(&kiss::frame_with_command(CMD_ROM_READ, &[0; 8])),
|
||||
Err(RNodeCapabilityAdmissionError::CapabilityImage(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_model_mismatch_and_bounds_are_typed() {
|
||||
let mut mismatch = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let result = observe_chunked(&mut mismatch, &admitted_frames(0xB4));
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RNodeCapabilityAdmissionError::RadioSettings(
|
||||
crate::rnode_capabilities::RNodeRadioAdmissionError::FrequencyOutOfRange { .. }
|
||||
))
|
||||
));
|
||||
|
||||
let mut bounded = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
for _ in 0..RNODE_CAPABILITY_MAX_READS {
|
||||
assert_eq!(bounded.observe_read(&[]).unwrap(), None);
|
||||
}
|
||||
assert_eq!(
|
||||
bounded.observe_read(&[]),
|
||||
Err(RNodeCapabilityAdmissionError::ReadLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_READS
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_detection_unsupported_firmware_and_duplicate_rom_are_typed() {
|
||||
let mut detection = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
detection.observe_read(&kiss::frame_with_command(CMD_DETECT, &[0])),
|
||||
Err(RNodeCapabilityAdmissionError::DetectionRejected)
|
||||
);
|
||||
|
||||
let mut firmware = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
firmware.observe_read(&kiss::frame_with_command(
|
||||
CMD_FW_VERSION,
|
||||
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN - 1],
|
||||
)),
|
||||
Err(RNodeCapabilityAdmissionError::UnsupportedFirmware)
|
||||
);
|
||||
|
||||
let mut duplicate = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
observe_chunked(
|
||||
&mut duplicate,
|
||||
&kiss::frame_with_command(CMD_ROM_READ, &eeprom(0xB8)),
|
||||
)
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
observe_chunked(
|
||||
&mut duplicate,
|
||||
&kiss::frame_with_command(CMD_ROM_READ, &eeprom(0xB8)),
|
||||
),
|
||||
Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cumulative_input_and_frame_limits_fail_closed() {
|
||||
let mut input = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let chunk = vec![0; RNODE_CAPABILITY_READ_BUFFER_BYTES];
|
||||
for _ in 0..(RNODE_CAPABILITY_MAX_INPUT_BYTES / chunk.len()) {
|
||||
assert_eq!(input.observe_read(&chunk).unwrap(), None);
|
||||
}
|
||||
assert_eq!(
|
||||
input.observe_read(&[0]),
|
||||
Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_INPUT_BYTES
|
||||
})
|
||||
);
|
||||
|
||||
let mut frame_bytes = Vec::new();
|
||||
for _ in 0..=RNODE_CAPABILITY_MAX_FRAMES {
|
||||
kiss::frame_with_command_into(crate::rnode::CMD_PLATFORM, &[0], &mut frame_bytes);
|
||||
}
|
||||
let mut frames = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
frames.observe_read(&frame_bytes),
|
||||
Err(RNodeCapabilityAdmissionError::FrameLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_FRAMES
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_frame_never_admits_and_is_not_replayed() {
|
||||
let bytes = admitted_frames(0xB8);
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
observe_chunked(&mut preflight, &bytes[..bytes.len() - 1]).unwrap(),
|
||||
None
|
||||
);
|
||||
drop(preflight);
|
||||
|
||||
let mut fresh = kiss::RawKissDeframer::new();
|
||||
assert!(fresh.feed(&bytes[bytes.len() - 1..]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_pre_init_radio_evidence_cannot_make_admitted_seed_ready() {
|
||||
let settings = settings(868_000_000, 14);
|
||||
let mut bytes = Vec::new();
|
||||
kiss::frame_with_command_into(
|
||||
crate::rnode::CMD_FREQUENCY,
|
||||
&settings.frequency.to_be_bytes(),
|
||||
&mut bytes,
|
||||
);
|
||||
kiss::frame_with_command_into(
|
||||
crate::rnode::CMD_BANDWIDTH,
|
||||
&settings.bandwidth.to_be_bytes(),
|
||||
&mut bytes,
|
||||
);
|
||||
kiss::frame_with_command_into(
|
||||
crate::rnode::CMD_SF,
|
||||
&[settings.spreading_factor],
|
||||
&mut bytes,
|
||||
);
|
||||
kiss::frame_with_command_into(crate::rnode::CMD_CR, &[settings.coding_rate], &mut bytes);
|
||||
kiss::frame_with_command_into(crate::rnode::CMD_TXPOWER, &[settings.tx_power], &mut bytes);
|
||||
kiss::frame_with_command_into(
|
||||
crate::rnode::CMD_RADIO_STATE,
|
||||
&[crate::rnode::RADIO_STATE_ON],
|
||||
&mut bytes,
|
||||
);
|
||||
bytes.extend_from_slice(&admitted_frames(0xB8));
|
||||
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings);
|
||||
assert!(observe_chunked(&mut preflight, &bytes).unwrap().is_some());
|
||||
let seed = preflight.into_protocol_state();
|
||||
assert!(seed.evidence().detected);
|
||||
assert!(seed.evidence().firmware.is_some());
|
||||
assert_eq!(seed.evidence().frequency, None);
|
||||
assert_eq!(seed.evidence().radio_state, None);
|
||||
assert!(matches!(
|
||||
seed.readiness(),
|
||||
crate::rnode_protocol::RNodeReadiness::Blocked(
|
||||
crate::rnode_protocol::RNodeReadinessBlocker::Missing(
|
||||
crate::rnode_protocol::RNodeReadinessEvidence::Frequency
|
||||
)
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -482,6 +482,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
online: sub_onlines[i].clone(),
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
inspection: None,
|
||||
tx: sub_tx,
|
||||
read_task: sub_read_task,
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -188,6 +188,7 @@ pub async fn spawn_serial_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -8,7 +8,9 @@ use tokio::sync::mpsc;
|
||||
|
||||
use crate::hdlc;
|
||||
use crate::kiss;
|
||||
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
|
||||
use crate::traits::{
|
||||
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
|
||||
};
|
||||
use rns_transport::messages::{InboundPacket, TransportMessage};
|
||||
|
||||
pub const RECONNECT_WAIT_INITIAL: u64 = 5;
|
||||
@@ -100,8 +102,10 @@ fn address_for_device(device: &str, prefer_ipv6: bool) -> Option<std::net::IpAdd
|
||||
.filter(|a| a.name == device)
|
||||
.map(|a| a.ip())
|
||||
.collect();
|
||||
if prefer_ipv6 && let Some(v6) = on_dev.iter().find(|ip| ip.is_ipv6()) {
|
||||
return Some(*v6);
|
||||
if prefer_ipv6 {
|
||||
if let Some(v6) = on_dev.iter().find(|ip| ip.is_ipv6()) {
|
||||
return Some(*v6);
|
||||
}
|
||||
}
|
||||
on_dev
|
||||
.iter()
|
||||
@@ -437,6 +441,7 @@ pub async fn spawn_tcp_client(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -505,6 +510,7 @@ async fn spawn_tcp_accepted(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
}
|
||||
@@ -560,7 +566,10 @@ pub async fn spawn_tcp_server(
|
||||
mode,
|
||||
)
|
||||
.await;
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("handle registry channel closed, stopping accept loop");
|
||||
break;
|
||||
}
|
||||
@@ -591,6 +600,7 @@ pub async fn spawn_tcp_server(
|
||||
online,
|
||||
rxb: Some(Arc::new(AtomicU64::new(0))),
|
||||
txb: Some(Arc::new(AtomicU64::new(0))),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -20,10 +20,36 @@ pub struct InterfaceHandle {
|
||||
pub online: Arc<AtomicBool>,
|
||||
pub rxb: Option<Arc<AtomicU64>>,
|
||||
pub txb: Option<Arc<AtomicU64>>,
|
||||
/// Optional live aggregate inspection source carried into the transport
|
||||
/// actor. This field intentionally makes pre-freeze struct literals update
|
||||
/// explicitly so new interface drivers choose whether they expose stats.
|
||||
pub inspection: Option<rns_transport::messages::InterfaceInspectionSource>,
|
||||
pub tx: mpsc::Sender<Bytes>,
|
||||
pub read_task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
/// Deliver a dynamically accepted interface to its owner.
|
||||
///
|
||||
/// A failed handoff returns the handle to this producer. The producer must
|
||||
/// finish disposing of the exact child it created rather than detaching its
|
||||
/// read task when the receiving runtime has gone away.
|
||||
pub(crate) async fn handoff_accepted_interface(
|
||||
handle_tx: &mpsc::Sender<InterfaceHandle>,
|
||||
handle: InterfaceHandle,
|
||||
) -> Result<(), ()> {
|
||||
match handle_tx.send(handle).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(mpsc::error::SendError(handle)) => {
|
||||
handle
|
||||
.online
|
||||
.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
handle.read_task.abort();
|
||||
let _ = handle.read_task.await;
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface operating mode. Byte values are on-wire constants.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
@@ -160,6 +186,19 @@ pub enum InterfaceError {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
struct TaskExitGuard {
|
||||
exited: Option<tokio::sync::oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl Drop for TaskExitGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(exited) = self.exited.take() {
|
||||
let _ = exited.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_optimise_mtu() {
|
||||
@@ -239,4 +278,90 @@ mod tests {
|
||||
assert_eq!(EC_PR_FREQ, 5.0);
|
||||
const { assert!(!EGRESS_CONTROL) };
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_accepted_interface_is_stopped_and_disposed() {
|
||||
let (handle_tx, handle_rx) = mpsc::channel(1);
|
||||
drop(handle_rx);
|
||||
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let (interface_tx, mut interface_rx) = mpsc::channel(1);
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let (exited_tx, exited_rx) = tokio::sync::oneshot::channel();
|
||||
let read_task = tokio::spawn(async move {
|
||||
let _exit_guard = TaskExitGuard {
|
||||
exited: Some(exited_tx),
|
||||
};
|
||||
let _ = started_tx.send(());
|
||||
std::future::pending::<()>().await;
|
||||
});
|
||||
started_rx.await.expect("read task should start");
|
||||
|
||||
let handle = InterfaceHandle {
|
||||
id: 1,
|
||||
parent_id: Some(0),
|
||||
name: "rejected-child".to_string(),
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection::default(),
|
||||
bitrate: 1,
|
||||
mtu: 1,
|
||||
online: Arc::clone(&online),
|
||||
rxb: None,
|
||||
txb: None,
|
||||
inspection: None,
|
||||
tx: interface_tx,
|
||||
read_task,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
handoff_accepted_interface(&handle_tx, handle).await,
|
||||
Err(())
|
||||
);
|
||||
assert!(!online.load(Ordering::SeqCst));
|
||||
exited_rx
|
||||
.await
|
||||
.expect("helper should await exact read-task termination");
|
||||
assert_eq!(
|
||||
interface_rx.recv().await,
|
||||
None,
|
||||
"rejected handle resources should be dropped"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepted_interface_handoff_preserves_live_handle() {
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel(1);
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let (interface_tx, _interface_rx) = mpsc::channel(1);
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let read_task = tokio::spawn(async move {
|
||||
let _ = started_tx.send(());
|
||||
std::future::pending::<()>().await;
|
||||
});
|
||||
started_rx.await.expect("read task should start");
|
||||
|
||||
let handle = InterfaceHandle {
|
||||
id: 2,
|
||||
parent_id: Some(0),
|
||||
name: "accepted-child".to_string(),
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection::default(),
|
||||
bitrate: 1,
|
||||
mtu: 1,
|
||||
online: Arc::clone(&online),
|
||||
rxb: None,
|
||||
txb: None,
|
||||
inspection: None,
|
||||
tx: interface_tx,
|
||||
read_task,
|
||||
};
|
||||
|
||||
assert_eq!(handoff_accepted_interface(&handle_tx, handle).await, Ok(()));
|
||||
let delivered = handle_rx.recv().await.expect("handle should be delivered");
|
||||
assert!(online.load(Ordering::SeqCst));
|
||||
assert!(!delivered.read_task.is_finished());
|
||||
|
||||
delivered.read_task.abort();
|
||||
let _ = delivered.read_task.await;
|
||||
}
|
||||
}
|
||||
@@ -180,6 +180,7 @@ pub async fn spawn_udp_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-link"
|
||||
description = "Link layer and encrypted channel for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
|
||||
@@ -89,6 +89,10 @@ impl KeepaliveState {
|
||||
|
||||
/// Whether the initiator should emit a keepalive now (jitter applied).
|
||||
pub fn should_send_keepalive(&self) -> bool {
|
||||
self.should_send_keepalive_at(Instant::now())
|
||||
}
|
||||
|
||||
pub(crate) fn should_send_keepalive_at(&self, now: Instant) -> bool {
|
||||
let jittered = if self.jitter_negative {
|
||||
self.keepalive_interval
|
||||
.saturating_sub(self.jitter_offset)
|
||||
@@ -97,37 +101,53 @@ impl KeepaliveState {
|
||||
self.keepalive_interval + self.jitter_offset
|
||||
};
|
||||
|
||||
let inbound_elapsed = self.last_inbound.elapsed();
|
||||
let inbound_elapsed = now.saturating_duration_since(self.last_inbound);
|
||||
let outbound_elapsed = self
|
||||
.last_outbound
|
||||
.or(self.activated_at)
|
||||
.map(|baseline| now.saturating_duration_since(baseline))
|
||||
.unwrap_or(inbound_elapsed);
|
||||
let keepalive_elapsed = self
|
||||
.last_keepalive_sent
|
||||
.map(|t| t.elapsed())
|
||||
.map(|last_keepalive| now.saturating_duration_since(last_keepalive))
|
||||
.unwrap_or(Duration::MAX);
|
||||
|
||||
self.is_initiator && inbound_elapsed >= jittered && keepalive_elapsed >= jittered
|
||||
self.is_initiator
|
||||
&& (inbound_elapsed >= jittered || outbound_elapsed >= jittered)
|
||||
&& keepalive_elapsed >= jittered
|
||||
}
|
||||
|
||||
pub(crate) fn should_respond_to_keepalive_at(&self, now: Instant) -> bool {
|
||||
!self.is_initiator
|
||||
&& self
|
||||
.last_outbound
|
||||
.map(|last_outbound| {
|
||||
now.saturating_duration_since(last_outbound) >= self.keepalive_interval
|
||||
})
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Whether the link should transition to STALE.
|
||||
///
|
||||
/// Uses the most recent of inbound, proof, or activation as the baseline so a
|
||||
/// link that just came up isn't immediately flagged stale on a quiet channel.
|
||||
/// Uses only peer evidence — inbound traffic, proof, or activation — as the
|
||||
/// baseline. Local outbound traffic cannot prove that the peer remains alive.
|
||||
pub fn is_stale(&self) -> bool {
|
||||
self.is_stale_at(Instant::now())
|
||||
}
|
||||
|
||||
pub(crate) fn is_stale_at(&self, now: Instant) -> bool {
|
||||
let mut latest = self.last_inbound;
|
||||
if let Some(proof) = self.last_proof {
|
||||
if proof > latest {
|
||||
latest = proof;
|
||||
}
|
||||
}
|
||||
if let Some(outbound) = self.last_outbound {
|
||||
if outbound > latest {
|
||||
latest = outbound;
|
||||
}
|
||||
}
|
||||
if let Some(activated) = self.activated_at {
|
||||
if activated > latest {
|
||||
latest = activated;
|
||||
}
|
||||
}
|
||||
latest.elapsed() >= self.stale_time
|
||||
now.saturating_duration_since(latest) >= self.stale_time
|
||||
}
|
||||
|
||||
/// How long to wait in STALE before tearing the link down.
|
||||
@@ -139,6 +159,16 @@ impl KeepaliveState {
|
||||
self.last_keepalive_sent = Some(Instant::now());
|
||||
}
|
||||
|
||||
pub(crate) fn mark_keepalive_sent_at(&mut self, now: Instant) {
|
||||
self.last_keepalive_sent = Some(now);
|
||||
}
|
||||
|
||||
pub(crate) fn record_keepalive_outbound(&mut self) {
|
||||
let now = Instant::now();
|
||||
self.last_outbound = Some(now);
|
||||
self.last_keepalive_sent = Some(now);
|
||||
}
|
||||
|
||||
pub fn since_inbound(&self) -> Duration {
|
||||
self.last_inbound.elapsed()
|
||||
}
|
||||
@@ -220,6 +250,60 @@ mod tests {
|
||||
assert!(!ks2.should_send_keepalive());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous_inbound_still_schedules_keepalive_when_outbound_is_quiet() {
|
||||
let now = Instant::now();
|
||||
let mut state = KeepaliveState::new(true);
|
||||
state.keepalive_interval = Duration::from_secs(5);
|
||||
state.jitter_offset = Duration::ZERO;
|
||||
state.jitter_negative = false;
|
||||
state.last_inbound = now;
|
||||
state.last_outbound = None;
|
||||
state.activated_at = Some(now - Duration::from_secs(6));
|
||||
state.last_keepalive_sent = Some(now - Duration::from_secs(6));
|
||||
|
||||
assert!(state.should_send_keepalive_at(now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_keepalive_suppresses_duplicate_at_exact_tick_time() {
|
||||
let now = Instant::now();
|
||||
let mut state = KeepaliveState::new(true);
|
||||
state.keepalive_interval = Duration::from_secs(5);
|
||||
state.jitter_offset = Duration::ZERO;
|
||||
state.jitter_negative = false;
|
||||
state.last_inbound = now - Duration::from_secs(6);
|
||||
state.last_outbound = Some(now - Duration::from_secs(6));
|
||||
state.last_keepalive_sent = Some(now - Duration::from_secs(4));
|
||||
|
||||
assert!(!state.should_send_keepalive_at(now));
|
||||
assert!(state.should_send_keepalive_at(now + Duration::from_secs(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_outbound_traffic_does_not_mask_a_stale_peer() {
|
||||
let now = Instant::now();
|
||||
let mut state = KeepaliveState::new(true);
|
||||
state.stale_time = Duration::from_secs(5);
|
||||
state.last_inbound = now - Duration::from_secs(6);
|
||||
state.last_outbound = Some(now);
|
||||
state.last_proof = None;
|
||||
state.activated_at = None;
|
||||
|
||||
assert!(state.is_stale_at(now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responder_suppresses_keepalive_reply_after_recent_outbound() {
|
||||
let now = Instant::now();
|
||||
let mut state = KeepaliveState::new(false);
|
||||
state.keepalive_interval = Duration::from_secs(5);
|
||||
state.last_outbound = Some(now);
|
||||
|
||||
assert!(!state.should_respond_to_keepalive_at(now));
|
||||
assert!(state.should_respond_to_keepalive_at(now + Duration::from_secs(5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stale_detection() {
|
||||
let mut ks = KeepaliveState::new(true);
|
||||
|
||||
+345
-33
@@ -12,7 +12,7 @@ use crate::handshake::{
|
||||
use crate::keepalive::KeepaliveState;
|
||||
use crate::key_derivation::LinkKeys;
|
||||
use crate::mtu_discovery::SignallingData;
|
||||
use crate::request::{RequestReceipt, RequestState};
|
||||
use crate::request::RequestReceipt;
|
||||
|
||||
/// Link lifecycle states.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -37,6 +37,14 @@ pub enum CloseReason {
|
||||
DestinationClosed,
|
||||
}
|
||||
|
||||
/// Latest physical-layer measurements observed for a Link.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct LinkPhyStats {
|
||||
pub rssi: Option<f64>,
|
||||
pub snr: Option<f64>,
|
||||
pub q: Option<f64>,
|
||||
}
|
||||
|
||||
/// Resource acceptance strategy.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum ResourceStrategy {
|
||||
@@ -107,6 +115,9 @@ pub struct Link {
|
||||
/// Truncated SHA-256 of the request's hashable part.
|
||||
pub link_id: [u8; 16],
|
||||
pub state: LinkState,
|
||||
/// Terminal close reason, retained after keys and transient state are
|
||||
/// purged. Remains `None` until an orderly or timeout close occurs.
|
||||
pub teardown_reason: Option<CloseReason>,
|
||||
pub is_initiator: bool,
|
||||
pub mode: u8,
|
||||
|
||||
@@ -165,6 +176,7 @@ pub struct Link {
|
||||
pub snr: Option<f64>,
|
||||
/// Link quality indicator in `[0.0, 1.0]`.
|
||||
pub q: Option<f64>,
|
||||
track_phy_stats: bool,
|
||||
|
||||
pub has_channel: bool,
|
||||
|
||||
@@ -216,6 +228,7 @@ impl Link {
|
||||
let link = Self {
|
||||
link_id,
|
||||
state: LinkState::Pending,
|
||||
teardown_reason: None,
|
||||
is_initiator: true,
|
||||
mode: DEFAULT_MODE,
|
||||
ephemeral_keys: Some(ephemeral_keys),
|
||||
@@ -231,7 +244,7 @@ impl Link {
|
||||
stale_since: None,
|
||||
keepalive: KeepaliveState::new(true),
|
||||
mtu: rns_wire::constants::MTU as u32,
|
||||
mdu: rns_wire::constants::ENCRYPTED_MDU,
|
||||
mdu: rns_wire::constants::LINK_MDU,
|
||||
resource_strategy: ResourceStrategy::default(),
|
||||
pending_requests: Vec::new(),
|
||||
incoming_resources: Vec::new(),
|
||||
@@ -252,6 +265,7 @@ impl Link {
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
track_phy_stats: false,
|
||||
has_channel: false,
|
||||
packet_callback: None,
|
||||
resource_callback: None,
|
||||
@@ -476,6 +490,7 @@ impl Link {
|
||||
let link = Self {
|
||||
link_id,
|
||||
state: LinkState::Handshake,
|
||||
teardown_reason: None,
|
||||
is_initiator: false,
|
||||
mode: request.signalling.mode,
|
||||
ephemeral_keys: Some(responder_keys),
|
||||
@@ -490,7 +505,7 @@ impl Link {
|
||||
stale_since: None,
|
||||
keepalive: KeepaliveState::new(false),
|
||||
mtu: request.signalling.mtu.min(rns_wire::constants::MTU as u32),
|
||||
mdu: rns_wire::constants::ENCRYPTED_MDU,
|
||||
mdu: rns_wire::constants::LINK_MDU,
|
||||
resource_strategy: ResourceStrategy::default(),
|
||||
pending_requests: Vec::new(),
|
||||
incoming_resources: Vec::new(),
|
||||
@@ -512,6 +527,7 @@ impl Link {
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
track_phy_stats: false,
|
||||
has_channel: false,
|
||||
packet_callback: None,
|
||||
resource_callback: None,
|
||||
@@ -700,11 +716,31 @@ impl Link {
|
||||
path: &str,
|
||||
data: Option<&[u8]>,
|
||||
timeout: Duration,
|
||||
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
|
||||
let (packed, request_id) = self.prepare_request(path, data, timeout)?;
|
||||
match self.encrypt(&packed) {
|
||||
Ok(encrypted) => Ok((encrypted, request_id)),
|
||||
Err(error) => {
|
||||
self.discard_pending_request(&request_id);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the plaintext MsgPack request body and register its receipt.
|
||||
///
|
||||
/// Packet-sized callers encrypt the returned body directly. Bodies larger
|
||||
/// than the Link MDU are passed to Resource with the returned request ID.
|
||||
pub fn prepare_request(
|
||||
&mut self,
|
||||
path: &str,
|
||||
data: Option<&[u8]>,
|
||||
timeout: Duration,
|
||||
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
|
||||
let data_value = data
|
||||
.map(msgpack_value_from_bytes_or_binary)
|
||||
.unwrap_or(rmpv::Value::Nil);
|
||||
self.request_value(path, data_value, timeout)
|
||||
self.prepare_request_value(path, data_value, timeout)
|
||||
}
|
||||
|
||||
/// Build a REQUEST payload with a MsgPack string body.
|
||||
@@ -717,10 +753,18 @@ impl Link {
|
||||
data: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
|
||||
self.request_value(path, rmpv::Value::String(data.into()), timeout)
|
||||
let (packed, request_id) =
|
||||
self.prepare_request_value(path, rmpv::Value::String(data.into()), timeout)?;
|
||||
match self.encrypt(&packed) {
|
||||
Ok(encrypted) => Ok((encrypted, request_id)),
|
||||
Err(error) => {
|
||||
self.discard_pending_request(&request_id);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request_value(
|
||||
fn prepare_request_value(
|
||||
&mut self,
|
||||
path: &str,
|
||||
data_value: rmpv::Value,
|
||||
@@ -745,8 +789,6 @@ impl Link {
|
||||
rmpv::encode::write_value(&mut packed, &array)
|
||||
.map_err(|_| LinkCryptoError::EncryptionFailed)?;
|
||||
|
||||
let encrypted = self.encrypt(&packed)?;
|
||||
|
||||
// request_id is a truncated SHA-256 of the plaintext, so both sides derive
|
||||
// the same ID without exchanging it.
|
||||
let request_id = truncated_hash(&packed);
|
||||
@@ -756,7 +798,53 @@ impl Link {
|
||||
let receipt = RequestReceipt::new(receipt_id, self.link_id, timeout);
|
||||
self.pending_requests.push(receipt);
|
||||
|
||||
Ok((encrypted, request_id))
|
||||
Ok((packed, request_id))
|
||||
}
|
||||
|
||||
/// Suspend a request's response timeout while its body is sent by Resource.
|
||||
pub fn mark_request_resource_sending(&mut self, request_id: &[u8; 16]) -> bool {
|
||||
let Some(receipt) = self
|
||||
.pending_requests
|
||||
.iter_mut()
|
||||
.find(|receipt| receipt.request_id[..16] == request_id[..])
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
receipt.mark_resource_sending();
|
||||
true
|
||||
}
|
||||
|
||||
/// Start a Resource-backed request's response timeout after send proof.
|
||||
pub fn mark_request_resource_sent(&mut self, request_id: &[u8; 16]) -> bool {
|
||||
let Some(receipt) = self
|
||||
.pending_requests
|
||||
.iter_mut()
|
||||
.find(|receipt| receipt.request_id[..16] == request_id[..])
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
receipt.mark_resource_sent();
|
||||
true
|
||||
}
|
||||
|
||||
/// Fail and remove a pending request by its truncated request ID.
|
||||
pub fn fail_pending_request(&mut self, request_id: &[u8; 16]) -> bool {
|
||||
let Some(receipt) = self
|
||||
.pending_requests
|
||||
.iter_mut()
|
||||
.find(|receipt| receipt.request_id[..16] == request_id[..])
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
receipt.fail();
|
||||
self.pending_requests
|
||||
.retain(|receipt| receipt.request_id[..16] != request_id[..]);
|
||||
true
|
||||
}
|
||||
|
||||
fn discard_pending_request(&mut self, request_id: &[u8; 16]) {
|
||||
self.pending_requests
|
||||
.retain(|receipt| receipt.request_id[..16] != request_id[..]);
|
||||
}
|
||||
|
||||
/// Replace the initial request id with the packet-hash id used by
|
||||
@@ -785,9 +873,17 @@ impl Link {
|
||||
encrypted_data: &[u8],
|
||||
) -> Result<ParsedRequestData, LinkCryptoError> {
|
||||
let plaintext = self.decrypt(encrypted_data)?;
|
||||
Self::parse_request(&plaintext)
|
||||
}
|
||||
|
||||
/// Parse an already-decrypted Link request.
|
||||
///
|
||||
/// Packet requests use [`Self::handle_request`]. Request Resources are
|
||||
/// decrypted by the Resource transfer before reaching the Link runtime,
|
||||
/// so they use this parser directly.
|
||||
pub fn parse_request(plaintext: &[u8]) -> Result<ParsedRequestData, LinkCryptoError> {
|
||||
// request_id = SHA-256(packed_request)[:16]
|
||||
let request_id = truncated_hash(&plaintext);
|
||||
let request_id = truncated_hash(plaintext);
|
||||
|
||||
// Unpack msgpack array: [timestamp, path_hash, data]
|
||||
let value = rmpv::decode::read_value(&mut &plaintext[..])
|
||||
@@ -861,6 +957,16 @@ impl Link {
|
||||
pub fn handle_response_plaintext(
|
||||
&mut self,
|
||||
plaintext: &[u8],
|
||||
) -> Result<([u8; 16], Vec<u8>), LinkCryptoError> {
|
||||
let (request_id, response_data) = Self::parse_response_plaintext(plaintext)?;
|
||||
self.deliver_response_data(&request_id, response_data.clone());
|
||||
Ok((request_id, response_data))
|
||||
}
|
||||
|
||||
/// Parse plaintext MsgPack `[request_id, response_data]` without mutating
|
||||
/// pending request state.
|
||||
pub fn parse_response_plaintext(
|
||||
plaintext: &[u8],
|
||||
) -> Result<([u8; 16], Vec<u8>), LinkCryptoError> {
|
||||
let value = rmpv::decode::read_value(&mut &plaintext[..])
|
||||
.map_err(|_| LinkCryptoError::DecryptionFailed)?;
|
||||
@@ -881,18 +987,23 @@ impl Link {
|
||||
|
||||
let response_data = msgpack_value_to_bytes(&array[1])?;
|
||||
|
||||
if let Some(receipt) = self
|
||||
Ok((request_id, response_data))
|
||||
}
|
||||
|
||||
/// Deliver already-decoded response bytes to a pending request.
|
||||
pub fn deliver_response_data(&mut self, request_id: &[u8; 16], response_data: Vec<u8>) -> bool {
|
||||
let Some(receipt) = self
|
||||
.pending_requests
|
||||
.iter_mut()
|
||||
.find(|r| r.request_id[..16] == request_id[..])
|
||||
{
|
||||
receipt.receive_response(response_data.clone());
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
receipt.receive_response(response_data);
|
||||
|
||||
self.pending_requests
|
||||
.retain(|r| r.state == RequestState::Sent);
|
||||
|
||||
Ok((request_id, response_data))
|
||||
.retain(|receipt| receipt.request_id[..16] != request_id[..]);
|
||||
true
|
||||
}
|
||||
|
||||
/// Update RTT from an LRRTT packet (context 0xFE) received after handshake.
|
||||
@@ -1060,11 +1171,23 @@ impl Link {
|
||||
self.keepalive.record_outbound();
|
||||
}
|
||||
|
||||
/// Count an outbound keepalive beat (Python counts them too, Packet.py:291)
|
||||
/// without touching `last_outbound` — that would defer `is_stale` forever.
|
||||
/// Count an outbound keepalive beat and retain its send time.
|
||||
///
|
||||
/// Stale detection deliberately ignores local outbound activity, while the
|
||||
/// retained timestamp prevents redundant keepalive traffic.
|
||||
pub fn record_tx_keepalive(&mut self, bytes: usize) {
|
||||
self.tx_bytes += bytes as u64;
|
||||
self.tx_count += 1;
|
||||
self.keepalive.record_keepalive_outbound();
|
||||
}
|
||||
|
||||
/// Whether this responder should answer a keepalive request.
|
||||
///
|
||||
/// Recent outbound traffic already proves the responder can transmit, so
|
||||
/// an immediate extra reply would only duplicate that traffic.
|
||||
pub fn should_respond_to_keepalive(&self) -> bool {
|
||||
self.keepalive
|
||||
.should_respond_to_keepalive_at(Instant::now())
|
||||
}
|
||||
|
||||
/// `bytes` is the link payload after the context byte (Link.py:929).
|
||||
@@ -1078,9 +1201,28 @@ impl Link {
|
||||
(self.tx_bytes, self.rx_bytes, self.tx_count, self.rx_count)
|
||||
}
|
||||
|
||||
/// Merge PHY measurements from the receiving interface; `None` values leave
|
||||
/// the current reading intact.
|
||||
/// Enable or disable per-packet physical-layer measurement tracking.
|
||||
pub fn track_phy_stats(&mut self, track: bool) {
|
||||
self.track_phy_stats = track;
|
||||
}
|
||||
|
||||
pub fn phy_stats_tracking_enabled(&self) -> bool {
|
||||
self.track_phy_stats
|
||||
}
|
||||
|
||||
/// Merge measurements when tracking is enabled.
|
||||
pub fn update_phy_stats(&mut self, rssi: Option<f64>, snr: Option<f64>, q: Option<f64>) {
|
||||
if !self.track_phy_stats {
|
||||
return;
|
||||
}
|
||||
self.update_phy_stats_force(rssi, snr, q);
|
||||
}
|
||||
|
||||
/// Merge measurements regardless of the tracking gate.
|
||||
///
|
||||
/// Responder Links use this to retain the establishment packet's
|
||||
/// measurements, matching Python's forced initial update.
|
||||
pub fn update_phy_stats_force(&mut self, rssi: Option<f64>, snr: Option<f64>, q: Option<f64>) {
|
||||
if rssi.is_some() {
|
||||
self.rssi = rssi;
|
||||
}
|
||||
@@ -1094,7 +1236,32 @@ impl Link {
|
||||
|
||||
/// Current PHY measurements as `(rssi, snr, q)`.
|
||||
pub fn phy_stats(&self) -> (Option<f64>, Option<f64>, Option<f64>) {
|
||||
(self.rssi, self.snr, self.q)
|
||||
let stats = self.phy_stats_snapshot();
|
||||
(stats.rssi, stats.snr, stats.q)
|
||||
}
|
||||
|
||||
pub fn phy_stats_snapshot(&self) -> LinkPhyStats {
|
||||
if self.track_phy_stats {
|
||||
LinkPhyStats {
|
||||
rssi: self.rssi,
|
||||
snr: self.snr,
|
||||
q: self.q,
|
||||
}
|
||||
} else {
|
||||
LinkPhyStats::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_rssi(&self) -> Option<f64> {
|
||||
self.track_phy_stats.then_some(self.rssi).flatten()
|
||||
}
|
||||
|
||||
pub fn get_snr(&self) -> Option<f64> {
|
||||
self.track_phy_stats.then_some(self.snr).flatten()
|
||||
}
|
||||
|
||||
pub fn get_q(&self) -> Option<f64> {
|
||||
self.track_phy_stats.then_some(self.q).flatten()
|
||||
}
|
||||
|
||||
/// Clone of the session keys, for handing to a Channel or Resource.
|
||||
@@ -1117,9 +1284,15 @@ impl Link {
|
||||
),
|
||||
)]
|
||||
pub fn tick(&mut self) -> LinkAction {
|
||||
let now = Instant::now();
|
||||
for receipt in &mut self.pending_requests {
|
||||
receipt.check_timeout();
|
||||
}
|
||||
self.pending_requests.retain(|receipt| !receipt.concluded());
|
||||
|
||||
match self.state {
|
||||
LinkState::Pending | LinkState::Handshake => {
|
||||
if self.request_time.elapsed() > self.establishment_timeout {
|
||||
if now.saturating_duration_since(self.request_time) > self.establishment_timeout {
|
||||
self.close(CloseReason::Timeout);
|
||||
return LinkAction::Closed(CloseReason::Timeout);
|
||||
}
|
||||
@@ -1128,13 +1301,13 @@ impl Link {
|
||||
LinkState::Active => {
|
||||
// Emit any pending keepalive before checking staleness so a final
|
||||
// beat goes out on the same tick the link transitions to STALE.
|
||||
if self.keepalive.should_send_keepalive() {
|
||||
self.keepalive.mark_keepalive_sent();
|
||||
if self.keepalive.should_send_keepalive_at(now) {
|
||||
self.keepalive.mark_keepalive_sent_at(now);
|
||||
return LinkAction::SendKeepalive;
|
||||
}
|
||||
if self.keepalive.is_stale() {
|
||||
if self.keepalive.is_stale_at(now) {
|
||||
self.state = LinkState::Stale;
|
||||
self.stale_since = Some(Instant::now());
|
||||
self.stale_since = Some(now);
|
||||
tracing::debug!(link_id = ?self.link_id, "link state -> Stale");
|
||||
return LinkAction::TransitionedToStale;
|
||||
}
|
||||
@@ -1146,7 +1319,7 @@ impl Link {
|
||||
let rtt = self.rtt.unwrap_or(Duration::from_secs(1));
|
||||
let grace = self.keepalive.stale_grace_timeout(rtt);
|
||||
if let Some(stale_since) = self.stale_since {
|
||||
if stale_since.elapsed() >= grace {
|
||||
if now.saturating_duration_since(stale_since) >= grace {
|
||||
let teardown_data = self.encrypt(&self.link_id).unwrap_or_default();
|
||||
self.close(CloseReason::Timeout);
|
||||
return LinkAction::SendTeardownAndClose(teardown_data);
|
||||
@@ -1198,6 +1371,11 @@ impl Link {
|
||||
|
||||
fn close(&mut self, reason: CloseReason) {
|
||||
tracing::debug!(link_id = ?self.link_id, ?reason, "link state -> Closed");
|
||||
self.teardown_reason = Some(reason);
|
||||
for receipt in &mut self.pending_requests {
|
||||
receipt.fail();
|
||||
}
|
||||
self.pending_requests.clear();
|
||||
self.state = LinkState::Closed;
|
||||
self.purge_keys();
|
||||
}
|
||||
@@ -1337,6 +1515,31 @@ impl Link {
|
||||
self.establishment_rate.map(|rate| rate * 8.0)
|
||||
}
|
||||
|
||||
/// Negotiated MTU for an active Link.
|
||||
pub fn get_mtu(&self) -> Option<u32> {
|
||||
(self.state == LinkState::Active).then_some(self.mtu)
|
||||
}
|
||||
|
||||
/// Negotiated encrypted-payload MDU for an active Link.
|
||||
pub fn get_mdu(&self) -> Option<usize> {
|
||||
(self.state == LinkState::Active).then_some(self.mdu)
|
||||
}
|
||||
|
||||
/// Negotiated Link mode.
|
||||
pub const fn get_mode(&self) -> u8 {
|
||||
self.mode
|
||||
}
|
||||
|
||||
/// Duration since activation, or `None` before the Link is established.
|
||||
pub fn age(&self) -> Option<Duration> {
|
||||
self.activated_at.map(|activated| activated.elapsed())
|
||||
}
|
||||
|
||||
/// Python-compatible Link age in seconds.
|
||||
pub fn get_age(&self) -> Option<f64> {
|
||||
self.age().map(|age| age.as_secs_f64())
|
||||
}
|
||||
|
||||
/// Expected in-flight rate in bits/sec for an active link; `None` until the
|
||||
/// first resource transfer completes.
|
||||
pub fn get_expected_rate(&self) -> Option<f64> {
|
||||
@@ -1512,11 +1715,19 @@ mod tests {
|
||||
|
||||
let teardown_data = initiator.teardown(CloseReason::InitiatorClosed);
|
||||
assert_eq!(initiator.state, LinkState::Closed);
|
||||
assert_eq!(
|
||||
initiator.teardown_reason,
|
||||
Some(CloseReason::InitiatorClosed)
|
||||
);
|
||||
assert!(teardown_data.is_some());
|
||||
|
||||
let accepted = responder.receive_teardown(&teardown_data.unwrap());
|
||||
assert!(accepted);
|
||||
assert_eq!(responder.state, LinkState::Closed);
|
||||
assert_eq!(
|
||||
responder.teardown_reason,
|
||||
Some(CloseReason::DestinationClosed)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1816,6 +2027,29 @@ mod tests {
|
||||
assert!((initiator_rate_bps - initiator_rate_bytes * 8.0).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_link_metric_accessors_gate_negotiated_sizes_and_report_age() {
|
||||
let (mut link, _) = Link::new_initiator([0xA4; 16], 1);
|
||||
assert_eq!(link.get_mtu(), None);
|
||||
assert_eq!(link.get_mdu(), None);
|
||||
assert_eq!(link.get_age(), None);
|
||||
assert_eq!(link.get_mode(), link.mode);
|
||||
|
||||
link.state = LinkState::Active;
|
||||
link.activated_at = Instant::now().checked_sub(Duration::from_millis(10));
|
||||
assert_eq!(link.get_mtu(), Some(link.mtu));
|
||||
assert_eq!(link.get_mdu(), Some(link.mdu));
|
||||
assert!(
|
||||
link.age()
|
||||
.is_some_and(|age| age >= Duration::from_millis(10))
|
||||
);
|
||||
assert!(link.get_age().is_some_and(|age| age >= 0.01));
|
||||
|
||||
link.state = LinkState::Stale;
|
||||
assert_eq!(link.get_mtu(), None);
|
||||
assert_eq!(link.get_mdu(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expected_rate_computed_on_resource_concluded() {
|
||||
let dest_hash = [0xAA; 16];
|
||||
@@ -2115,6 +2349,72 @@ mod tests {
|
||||
assert!(initiator.pending_requests.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_plaintext_request_resource_payload() {
|
||||
let (mut initiator, responder, _) = make_active_link();
|
||||
|
||||
let (encrypted, request_id) = initiator
|
||||
.request(
|
||||
"resource.path",
|
||||
Some(b"resource request data"),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.unwrap();
|
||||
let plaintext = responder.decrypt(&encrypted).unwrap();
|
||||
|
||||
let (parsed_id, path_hash, _timestamp, data) = Link::parse_request(&plaintext).unwrap();
|
||||
assert_eq!(parsed_id, request_id);
|
||||
assert_eq!(path_hash, truncated_hash(b"resource.path"));
|
||||
assert_eq!(data, b"resource request data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tick_expires_pending_request_and_fires_callback() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let (mut initiator, _responder, _) = make_active_link();
|
||||
initiator
|
||||
.request("test.timeout", None, Duration::ZERO)
|
||||
.unwrap();
|
||||
|
||||
let fired = Arc::new(AtomicBool::new(false));
|
||||
let callback_fired = fired.clone();
|
||||
initiator.pending_requests[0].set_failed_callback(move |_| {
|
||||
callback_fired.store(true, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
initiator.tick();
|
||||
|
||||
assert!(fired.load(Ordering::SeqCst));
|
||||
assert!(
|
||||
initiator.pending_requests.is_empty(),
|
||||
"owning runtime tick must reap concluded request receipts"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_close_fails_pending_request() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let (mut initiator, _responder, _) = make_active_link();
|
||||
initiator
|
||||
.request("test.close", None, Duration::from_secs(30))
|
||||
.unwrap();
|
||||
|
||||
let fired = Arc::new(AtomicBool::new(false));
|
||||
let callback_fired = fired.clone();
|
||||
initiator.pending_requests[0].set_failed_callback(move |_| {
|
||||
callback_fired.store(true, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
initiator.mark_closed(CloseReason::DestinationClosed);
|
||||
|
||||
assert!(fired.load(Ordering::SeqCst));
|
||||
assert!(initiator.pending_requests.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_request_response_preserves_msgpack_object_bodies() {
|
||||
use rmpv::Value;
|
||||
@@ -2253,11 +2553,10 @@ mod tests {
|
||||
assert_eq!(rx_c, 1);
|
||||
}
|
||||
|
||||
/// Keepalive beats count into traffic stats (Packet.py:291) but must not
|
||||
/// refresh `last_outbound`, or an initiator pinging a dead peer would
|
||||
/// never go stale.
|
||||
/// Keepalive beats count into traffic stats and refresh the outbound
|
||||
/// keepalive clock. Peer-liveness detection remains inbound-only.
|
||||
#[test]
|
||||
fn test_record_tx_keepalive_counts_without_outbound_refresh() {
|
||||
fn test_record_tx_keepalive_counts_and_refreshes_outbound() {
|
||||
let (mut link, _, _) = make_active_link();
|
||||
assert!(link.keepalive.last_outbound.is_none());
|
||||
|
||||
@@ -2266,7 +2565,8 @@ mod tests {
|
||||
let (tx_b, _, tx_c, _) = link.traffic_stats();
|
||||
assert_eq!(tx_b, 1);
|
||||
assert_eq!(tx_c, 1);
|
||||
assert!(link.keepalive.last_outbound.is_none());
|
||||
assert!(link.keepalive.last_outbound.is_some());
|
||||
assert!(link.keepalive.last_keepalive_sent.is_some());
|
||||
}
|
||||
|
||||
/// Initiator knows expected_hops at creation (Link.py:282); the responder
|
||||
@@ -2288,7 +2588,10 @@ mod tests {
|
||||
let (mut link, _, _) = make_active_link();
|
||||
|
||||
assert_eq!(link.phy_stats(), (None, None, None));
|
||||
link.update_phy_stats(Some(-90.0), Some(5.0), Some(0.5));
|
||||
assert_eq!(link.rssi, None);
|
||||
|
||||
link.track_phy_stats(true);
|
||||
link.update_phy_stats(Some(-80.0), Some(12.5), Some(0.95));
|
||||
assert_eq!(link.rssi, Some(-80.0));
|
||||
assert_eq!(link.snr, Some(12.5));
|
||||
@@ -2298,6 +2601,15 @@ mod tests {
|
||||
link.update_phy_stats(Some(-75.0), None, None);
|
||||
assert_eq!(link.rssi, Some(-75.0));
|
||||
assert_eq!(link.snr, Some(12.5));
|
||||
assert_eq!(link.get_rssi(), Some(-75.0));
|
||||
|
||||
link.track_phy_stats(false);
|
||||
assert_eq!(link.phy_stats(), (None, None, None));
|
||||
assert_eq!(link.get_rssi(), None);
|
||||
|
||||
link.update_phy_stats_force(Some(-60.0), None, None);
|
||||
link.track_phy_stats(true);
|
||||
assert_eq!(link.get_rssi(), Some(-60.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+103
-10
@@ -4,6 +4,11 @@ use std::time::{Duration, Instant};
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RequestState {
|
||||
Sent,
|
||||
/// The request body itself is still being delivered as a Resource.
|
||||
///
|
||||
/// Resource transfer watchdogs own the send timeout in this state. The
|
||||
/// response timeout starts only after the Resource proof arrives.
|
||||
SendingResource,
|
||||
/// Response is arriving as a resource transfer rather than a single packet.
|
||||
Receiving,
|
||||
Delivered,
|
||||
@@ -59,7 +64,10 @@ impl RequestReceipt {
|
||||
|
||||
/// Record a response payload, transition to `Delivered`, and fire the response callback.
|
||||
pub fn deliver(&mut self, response: Vec<u8>) {
|
||||
if self.state == RequestState::Sent || self.state == RequestState::Receiving {
|
||||
if matches!(
|
||||
self.state,
|
||||
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
|
||||
) {
|
||||
self.rtt = Some(self.sent_at.elapsed());
|
||||
self.response = Some(response);
|
||||
self.state = RequestState::Delivered;
|
||||
@@ -72,7 +80,10 @@ impl RequestReceipt {
|
||||
|
||||
/// Transition to `Failed` and fire the failure callback.
|
||||
pub fn fail(&mut self) {
|
||||
if self.state == RequestState::Sent || self.state == RequestState::Receiving {
|
||||
if matches!(
|
||||
self.state,
|
||||
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
|
||||
) {
|
||||
self.state = RequestState::Failed;
|
||||
if let Some(cb) = self.callbacks.failed.take() {
|
||||
cb(self);
|
||||
@@ -81,11 +92,15 @@ impl RequestReceipt {
|
||||
}
|
||||
|
||||
pub fn is_timed_out(&self) -> bool {
|
||||
self.state == RequestState::Sent && self.sent_at.elapsed() > self.timeout
|
||||
matches!(self.state, RequestState::Sent | RequestState::Receiving)
|
||||
&& self.sent_at.elapsed() >= self.timeout
|
||||
}
|
||||
|
||||
pub fn is_pending(&self) -> bool {
|
||||
self.state == RequestState::Sent
|
||||
matches!(
|
||||
self.state,
|
||||
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
|
||||
)
|
||||
}
|
||||
|
||||
/// Store the response payload and advance to `ResponseReceived`.
|
||||
@@ -93,10 +108,20 @@ impl RequestReceipt {
|
||||
/// Distinct from `deliver()`: `receive_response` can fire after `mark_delivered()`
|
||||
/// for protocols that ack then stream the payload.
|
||||
pub fn receive_response(&mut self, data: Vec<u8>) {
|
||||
if self.state == RequestState::Sent || self.state == RequestState::Delivered {
|
||||
if matches!(
|
||||
self.state,
|
||||
RequestState::Sent
|
||||
| RequestState::SendingResource
|
||||
| RequestState::Receiving
|
||||
| RequestState::Delivered
|
||||
) {
|
||||
self.rtt = Some(self.sent_at.elapsed());
|
||||
self.response = Some(data);
|
||||
self.state = RequestState::ResponseReceived;
|
||||
self.progress = 1.0;
|
||||
if let Some(cb) = self.callbacks.response.take() {
|
||||
cb(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,11 +134,30 @@ impl RequestReceipt {
|
||||
|
||||
/// Transition to `Failed` without firing the failure callback.
|
||||
pub fn mark_failed(&mut self) {
|
||||
if self.state == RequestState::Sent {
|
||||
if matches!(
|
||||
self.state,
|
||||
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
|
||||
) {
|
||||
self.state = RequestState::Failed;
|
||||
}
|
||||
}
|
||||
|
||||
/// Suspend the response deadline while the request body is sent as a
|
||||
/// Resource. The Resource transfer has its own watchdog.
|
||||
pub fn mark_resource_sending(&mut self) {
|
||||
if self.state == RequestState::Sent {
|
||||
self.state = RequestState::SendingResource;
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the response deadline after a request Resource is proved.
|
||||
pub fn mark_resource_sent(&mut self) {
|
||||
if self.state == RequestState::SendingResource {
|
||||
self.state = RequestState::Sent;
|
||||
self.sent_at = Instant::now();
|
||||
}
|
||||
}
|
||||
|
||||
/// True once the request has reached a terminal state (delivered, failed, or response received).
|
||||
pub fn concluded(&self) -> bool {
|
||||
matches!(
|
||||
@@ -152,10 +196,7 @@ impl RequestReceipt {
|
||||
/// Expire the request if past its deadline, firing the failure callback. Returns `true` if expired.
|
||||
pub fn check_timeout(&mut self) -> bool {
|
||||
if self.is_timed_out() {
|
||||
self.state = RequestState::Failed;
|
||||
if let Some(cb) = self.callbacks.failed.take() {
|
||||
cb(self);
|
||||
}
|
||||
self.fail();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
@@ -236,6 +277,19 @@ mod tests {
|
||||
assert!(!receipt.is_pending());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_send_suspends_and_restarts_response_timeout() {
|
||||
let mut receipt = RequestReceipt::new([0x12; 32], [0x34; 16], Duration::ZERO);
|
||||
|
||||
receipt.mark_resource_sending();
|
||||
assert_eq!(receipt.state, RequestState::SendingResource);
|
||||
assert!(!receipt.is_timed_out());
|
||||
|
||||
receipt.mark_resource_sent();
|
||||
assert_eq!(receipt.state, RequestState::Sent);
|
||||
assert!(receipt.is_timed_out());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cannot_receive_response_after_fail() {
|
||||
let mut receipt = RequestReceipt::new([0x33; 32], [0x44; 16], Duration::from_secs(10));
|
||||
@@ -245,4 +299,43 @@ mod tests {
|
||||
assert_eq!(receipt.state, RequestState::Failed);
|
||||
assert!(receipt.response.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_receive_response_fires_callback_from_receiving_state() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let fired = Arc::new(AtomicBool::new(false));
|
||||
let callback_fired = fired.clone();
|
||||
let mut receipt = RequestReceipt::new([0x55; 32], [0x66; 16], Duration::from_secs(10));
|
||||
receipt.state = RequestState::Receiving;
|
||||
receipt.set_response_callback(move |receipt| {
|
||||
assert_eq!(receipt.state, RequestState::ResponseReceived);
|
||||
callback_fired.store(true, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
receipt.receive_response(b"resource response".to_vec());
|
||||
|
||||
assert!(fired.load(Ordering::SeqCst));
|
||||
assert_eq!(receipt.get_progress(), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_receiving_request_times_out_and_fires_failure_callback() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let fired = Arc::new(AtomicBool::new(false));
|
||||
let callback_fired = fired.clone();
|
||||
let mut receipt = RequestReceipt::new([0x77; 32], [0x88; 16], Duration::ZERO);
|
||||
receipt.state = RequestState::Receiving;
|
||||
receipt.set_failed_callback(move |receipt| {
|
||||
assert_eq!(receipt.state, RequestState::Failed);
|
||||
callback_fired.store(true, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
assert!(receipt.check_timeout());
|
||||
assert!(fired.load(Ordering::SeqCst));
|
||||
assert!(!receipt.is_pending());
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ name = "rns-protocol"
|
||||
description = "Resource, Channel, and Buffer protocols for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -208,6 +208,10 @@ impl ChannelWindow {
|
||||
/// (subsequent handlers are skipped) or `false` to fall through.
|
||||
pub type MessageCallback = Box<dyn Fn(u16, &[u8]) -> bool + Send>;
|
||||
|
||||
/// Opaque token for removing one registered message handler.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct HandlerId(u64);
|
||||
|
||||
/// Sequenced, reliable message pipe over a Reticulum link.
|
||||
///
|
||||
/// The channel is passive: the owning runtime calls `send`/`receive`/
|
||||
@@ -221,12 +225,13 @@ pub struct Channel {
|
||||
rx_ring: VecDeque<Envelope>,
|
||||
pub window: ChannelWindow,
|
||||
pub active: bool,
|
||||
initial_rtt: f64,
|
||||
current_rtt: f64,
|
||||
/// When non-empty, only these types are accepted on `receive`.
|
||||
registered_types: Vec<u16>,
|
||||
/// Called in registration order on each delivered message; the first
|
||||
/// handler that returns `true` stops the chain.
|
||||
message_handlers: Vec<MessageCallback>,
|
||||
message_handlers: Vec<(HandlerId, MessageCallback)>,
|
||||
next_handler_id: u64,
|
||||
}
|
||||
|
||||
impl Channel {
|
||||
@@ -238,9 +243,10 @@ impl Channel {
|
||||
rx_ring: VecDeque::new(),
|
||||
window: ChannelWindow::new(rtt),
|
||||
active: true,
|
||||
initial_rtt: rtt,
|
||||
current_rtt: rtt,
|
||||
registered_types: Vec::new(),
|
||||
message_handlers: Vec::new(),
|
||||
next_handler_id: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,9 +271,26 @@ impl Channel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Append `handler` to the end of the callback chain.
|
||||
pub fn add_message_handler(&mut self, handler: MessageCallback) {
|
||||
self.message_handlers.push(handler);
|
||||
/// Append `handler` to the end of the callback chain and return its token.
|
||||
pub fn add_message_handler(&mut self, handler: MessageCallback) -> HandlerId {
|
||||
let id = HandlerId(self.next_handler_id);
|
||||
self.next_handler_id = self.next_handler_id.wrapping_add(1);
|
||||
self.message_handlers.push((id, handler));
|
||||
id
|
||||
}
|
||||
|
||||
/// Remove exactly one previously registered handler.
|
||||
pub fn remove_message_handler(&mut self, id: HandlerId) -> bool {
|
||||
let Some(index) = self
|
||||
.message_handlers
|
||||
.iter()
|
||||
.position(|(candidate, _)| *candidate == id)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let (_id, handler) = self.message_handlers.remove(index);
|
||||
drop(handler);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn clear_message_handlers(&mut self) {
|
||||
@@ -275,19 +298,24 @@ impl Channel {
|
||||
}
|
||||
|
||||
fn run_callbacks(&self, msg_type: u16, payload: &[u8]) -> bool {
|
||||
for handler in &self.message_handlers {
|
||||
if handler(msg_type, payload) {
|
||||
for (_, handler) in &self.message_handlers {
|
||||
// Application callbacks must not prevent the channel from
|
||||
// advancing its receive sequence or starve handlers registered
|
||||
// after them. The process panic hook still reports the failure;
|
||||
// this boundary only isolates unwinding builds.
|
||||
let consumed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
handler(msg_type, payload)
|
||||
}))
|
||||
.unwrap_or(false);
|
||||
if consumed {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Empty registration list means "accept anything", matching the
|
||||
/// permissive behaviour of the Python reference before type filters were
|
||||
/// added.
|
||||
fn is_type_registered(&self, msg_type: u16) -> bool {
|
||||
self.registered_types.is_empty() || self.registered_types.contains(&msg_type)
|
||||
self.registered_types.contains(&msg_type)
|
||||
}
|
||||
|
||||
/// True when the channel has window headroom to accept a new outbound message.
|
||||
@@ -303,6 +331,11 @@ impl Channel {
|
||||
outstanding < self.window.window
|
||||
}
|
||||
|
||||
/// True when every outbound envelope has been acknowledged and removed.
|
||||
pub fn is_drained(&self) -> bool {
|
||||
self.tx_ring.is_empty()
|
||||
}
|
||||
|
||||
/// Pack `msg`, push it onto the TX ring, and return the raw envelope for
|
||||
/// the transport to send. Fails when the channel is closed or its window
|
||||
/// is already saturated.
|
||||
@@ -312,6 +345,14 @@ impl Channel {
|
||||
|
||||
/// As [`Self::send`], but also returns the assigned sequence number.
|
||||
pub fn send_tracked(&mut self, msg: &dyn MessageBase) -> Result<(u16, Vec<u8>), ChannelError> {
|
||||
self.send_tracked_with_max_envelope(msg, None)
|
||||
}
|
||||
|
||||
fn send_tracked_with_max_envelope(
|
||||
&mut self,
|
||||
msg: &dyn MessageBase,
|
||||
max_envelope_size: Option<usize>,
|
||||
) -> Result<(u16, Vec<u8>), ChannelError> {
|
||||
if !self.active {
|
||||
return Err(ChannelError::ChannelClosed);
|
||||
}
|
||||
@@ -320,9 +361,16 @@ impl Channel {
|
||||
}
|
||||
|
||||
let seq = self.next_tx_sequence;
|
||||
self.next_tx_sequence = ((self.next_tx_sequence as u32 + 1) % SEQ_MODULUS) as u16;
|
||||
|
||||
let mut envelope = Envelope::pack(msg, seq);
|
||||
if let Some(max) = max_envelope_size {
|
||||
if envelope.raw.len() > max {
|
||||
return Err(ChannelError::MessageTooLarge {
|
||||
actual: envelope.raw.len(),
|
||||
max,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.next_tx_sequence = ((self.next_tx_sequence as u32 + 1) % SEQ_MODULUS) as u16;
|
||||
envelope.state = MessageState::Sent;
|
||||
envelope.tries = 1;
|
||||
envelope.last_sent = Some(Instant::now());
|
||||
@@ -397,6 +445,9 @@ impl Channel {
|
||||
/// legitimate. Out-of-range or duplicate sequence numbers are silently
|
||||
/// dropped; registered callbacks fire in order on each delivered message.
|
||||
pub fn receive(&mut self, raw: &[u8]) -> Result<Vec<(u16, Vec<u8>)>, ChannelError> {
|
||||
if !self.active {
|
||||
return Err(ChannelError::ChannelClosed);
|
||||
}
|
||||
let envelope = Envelope::unpack(raw).map_err(|_| ChannelError::InvalidEnvelope)?;
|
||||
|
||||
if !self.is_type_registered(envelope.msg_type) {
|
||||
@@ -477,10 +528,10 @@ impl Channel {
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Retransmit timeout: `1.5^(tries - 1) * max(rtt * 2.5, MIN_TIMEOUT_BASE)
|
||||
/// * (outstanding + 1.5)` seconds, using the RTT captured at construction.
|
||||
/// Retransmit timeout uses the Python-compatible exponential backoff,
|
||||
/// based on the latest Link RTT supplied by the owning runtime.
|
||||
pub fn compute_timeout(&self, tries: usize) -> f64 {
|
||||
let rtt = self.initial_rtt;
|
||||
let rtt = self.current_rtt;
|
||||
let backoff = 1.5_f64.powi(tries.saturating_sub(1) as i32);
|
||||
let base = (rtt * 2.5).max(MIN_TIMEOUT_BASE);
|
||||
let outstanding = self.outstanding_count() as f64 + 1.5;
|
||||
@@ -491,6 +542,13 @@ impl Channel {
|
||||
Duration::from_secs_f64(self.compute_timeout(tries).max(MIN_TIMEOUT_BASE))
|
||||
}
|
||||
|
||||
/// Update the live Link RTT used by subsequent retransmit deadlines.
|
||||
pub fn update_rtt(&mut self, rtt: f64) {
|
||||
if rtt.is_finite() && rtt >= 0.0 {
|
||||
self.current_rtt = rtt;
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark the channel inactive and drop every buffered envelope and
|
||||
/// handler. Idempotent.
|
||||
pub fn shutdown(&mut self) {
|
||||
@@ -522,6 +580,8 @@ pub enum ChannelError {
|
||||
UnknownMessageType(u16),
|
||||
#[error("invalid message type: 0x{0:04X} (reserved for system use)")]
|
||||
InvalidMessageType(u16),
|
||||
#[error("packed channel message is {actual} bytes; Link MDU is {max}")]
|
||||
MessageTooLarge { actual: usize, max: usize },
|
||||
}
|
||||
|
||||
/// A [`Channel`] paired with its link ID and (optionally) link session keys,
|
||||
@@ -530,6 +590,7 @@ pub enum ChannelError {
|
||||
pub struct LinkChannel {
|
||||
channel: Channel,
|
||||
link_id: [u8; 16],
|
||||
link_mdu: usize,
|
||||
session_keys: Option<rns_link::key_derivation::LinkKeys>,
|
||||
outbound_packet_hashes: HashMap<[u8; 32], u16>,
|
||||
}
|
||||
@@ -543,9 +604,15 @@ pub struct PreparedChannelData {
|
||||
impl LinkChannel {
|
||||
/// Plain-text channel (no transport-side encryption).
|
||||
pub fn new(link_id: [u8; 16], rtt: f64) -> Self {
|
||||
Self::new_with_mdu(link_id, rtt, rns_wire::constants::LINK_MDU)
|
||||
}
|
||||
|
||||
/// Plain-text channel with an explicit Link MDU.
|
||||
pub fn new_with_mdu(link_id: [u8; 16], rtt: f64, link_mdu: usize) -> Self {
|
||||
Self {
|
||||
channel: Channel::new(rtt),
|
||||
link_id,
|
||||
link_mdu,
|
||||
session_keys: None,
|
||||
outbound_packet_hashes: HashMap::new(),
|
||||
}
|
||||
@@ -557,10 +624,21 @@ impl LinkChannel {
|
||||
link_id: [u8; 16],
|
||||
rtt: f64,
|
||||
keys: rns_link::key_derivation::LinkKeys,
|
||||
) -> Self {
|
||||
Self::new_encrypted_with_mdu(link_id, rtt, rns_wire::constants::LINK_MDU, keys)
|
||||
}
|
||||
|
||||
/// Encrypted channel with an explicit Link MDU.
|
||||
pub fn new_encrypted_with_mdu(
|
||||
link_id: [u8; 16],
|
||||
rtt: f64,
|
||||
link_mdu: usize,
|
||||
keys: rns_link::key_derivation::LinkKeys,
|
||||
) -> Self {
|
||||
Self {
|
||||
channel: Channel::new(rtt),
|
||||
link_id,
|
||||
link_mdu,
|
||||
session_keys: Some(keys),
|
||||
outbound_packet_hashes: HashMap::new(),
|
||||
}
|
||||
@@ -578,7 +656,9 @@ impl LinkChannel {
|
||||
&mut self,
|
||||
msg: &dyn MessageBase,
|
||||
) -> Result<PreparedChannelData, ChannelError> {
|
||||
let (sequence, raw) = self.channel.send_tracked(msg)?;
|
||||
let (sequence, raw) = self
|
||||
.channel
|
||||
.send_tracked_with_max_envelope(msg, Some(self.link_mdu))?;
|
||||
if let Some(ref keys) = self.session_keys {
|
||||
let data = rns_link::encryption::link_encrypt(keys, &raw)
|
||||
.map_err(|_| ChannelError::ChannelClosed)?;
|
||||
@@ -604,6 +684,7 @@ impl LinkChannel {
|
||||
}
|
||||
|
||||
pub fn delivered(&mut self, sequence: u16, rtt: f64) {
|
||||
self.channel.update_rtt(rtt);
|
||||
self.channel.delivered(sequence, rtt);
|
||||
}
|
||||
|
||||
@@ -613,6 +694,8 @@ impl LinkChannel {
|
||||
|
||||
pub fn delivered_by_packet_hash(&mut self, packet_hash: &[u8; 32], rtt: f64) -> Option<u16> {
|
||||
let sequence = self.outbound_packet_hashes.remove(packet_hash)?;
|
||||
self.outbound_packet_hashes
|
||||
.retain(|_, tracked_sequence| *tracked_sequence != sequence);
|
||||
self.delivered(sequence, rtt);
|
||||
Some(sequence)
|
||||
}
|
||||
@@ -621,12 +704,42 @@ impl LinkChannel {
|
||||
self.channel.is_ready_to_send()
|
||||
}
|
||||
|
||||
pub fn is_drained(&self) -> bool {
|
||||
self.channel.is_drained()
|
||||
}
|
||||
|
||||
/// Maximum payload bytes available to one channel message.
|
||||
pub fn mdu(&self) -> usize {
|
||||
Channel::channel_mdu(self.link_mdu)
|
||||
}
|
||||
|
||||
pub fn register_message_type(&mut self, msg_type: u16) -> Result<(), ChannelError> {
|
||||
self.channel.register_message_type(msg_type)
|
||||
}
|
||||
|
||||
pub fn register_system_type(&mut self, msg_type: u16) {
|
||||
self.channel.register_system_type(msg_type);
|
||||
}
|
||||
|
||||
pub fn add_message_handler(&mut self, handler: MessageCallback) -> HandlerId {
|
||||
self.channel.add_message_handler(handler)
|
||||
}
|
||||
|
||||
pub fn remove_message_handler(&mut self, id: HandlerId) -> bool {
|
||||
self.channel.remove_message_handler(id)
|
||||
}
|
||||
|
||||
pub fn clear_message_handlers(&mut self) {
|
||||
self.channel.clear_message_handlers();
|
||||
}
|
||||
|
||||
pub fn link_id(&self) -> &[u8; 16] {
|
||||
&self.link_id
|
||||
}
|
||||
|
||||
pub fn shutdown(&mut self) {
|
||||
self.channel.shutdown();
|
||||
self.outbound_packet_hashes.clear();
|
||||
}
|
||||
|
||||
pub fn is_active(&self) -> bool {
|
||||
@@ -657,6 +770,10 @@ impl LinkChannel {
|
||||
pub fn next_timeout_duration(&self) -> Option<Duration> {
|
||||
self.channel.next_timeout_duration()
|
||||
}
|
||||
|
||||
pub fn update_rtt(&mut self, rtt: f64) {
|
||||
self.channel.update_rtt(rtt);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -731,6 +848,7 @@ mod tests {
|
||||
fn test_channel_send_receive() {
|
||||
let mut tx_channel = Channel::new(0.1);
|
||||
let mut rx_channel = Channel::new(0.1);
|
||||
rx_channel.register_message_type(0x0001).unwrap();
|
||||
|
||||
let msg = TestMessage::new(b"hello");
|
||||
let raw = tx_channel.send(&msg).unwrap();
|
||||
@@ -745,6 +863,7 @@ mod tests {
|
||||
fn test_channel_ordering() {
|
||||
let mut tx = Channel::new(0.1);
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
|
||||
let msg1 = TestMessage::new(b"first");
|
||||
let msg2 = TestMessage::new(b"second");
|
||||
@@ -776,6 +895,7 @@ mod tests {
|
||||
fn test_channel_flow_control() {
|
||||
let mut ch = Channel::new(0.1);
|
||||
assert!(ch.is_ready_to_send());
|
||||
assert!(ch.is_drained());
|
||||
|
||||
let msg = TestMessage::new(b"a");
|
||||
// `WINDOW_INITIAL` = 2 slots, so two sends saturate the window.
|
||||
@@ -783,9 +903,13 @@ mod tests {
|
||||
ch.send(&msg).unwrap();
|
||||
|
||||
assert!(!ch.is_ready_to_send());
|
||||
assert!(!ch.is_drained());
|
||||
|
||||
ch.delivered(0, 0.1);
|
||||
assert!(ch.is_ready_to_send());
|
||||
assert!(!ch.is_drained());
|
||||
ch.delivered(1, 0.1);
|
||||
assert!(ch.is_drained());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -808,6 +932,7 @@ mod tests {
|
||||
fn test_duplicate_rejection() {
|
||||
let mut tx = Channel::new(0.1);
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
|
||||
let msg = TestMessage::new(b"once");
|
||||
let raw = tx.send(&msg).unwrap();
|
||||
@@ -907,6 +1032,10 @@ mod tests {
|
||||
ch.shutdown();
|
||||
assert!(!ch.active);
|
||||
assert!(ch.send(&msg).is_err());
|
||||
assert!(matches!(
|
||||
ch.receive(&Envelope::pack(&msg, 0).raw),
|
||||
Err(ChannelError::ChannelClosed)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -973,8 +1102,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_registered_types_allows_all() {
|
||||
// With an empty registry the channel must not filter inbound frames.
|
||||
fn test_no_registered_types_rejects_all() {
|
||||
// Python requires every inbound user or system type to be registered.
|
||||
let mut ch = Channel::new(0.1);
|
||||
|
||||
let mut raw = Vec::new();
|
||||
@@ -984,7 +1113,10 @@ mod tests {
|
||||
raw.extend_from_slice(b"test");
|
||||
|
||||
let result = ch.receive(&raw);
|
||||
assert!(result.is_ok());
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(ChannelError::UnknownMessageType(0x1234))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1031,6 +1163,7 @@ mod tests {
|
||||
let raw = ch.send(&msg).unwrap();
|
||||
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
let counter2 = counter.clone();
|
||||
let c4 = counter2.clone();
|
||||
rx.add_message_handler(Box::new(move |_msg_type, _payload| {
|
||||
@@ -1052,11 +1185,76 @@ mod tests {
|
||||
assert_eq!(counter2.load(Ordering::SeqCst), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panicking_handler_does_not_block_delivery_or_later_handlers() {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
let mut tx = Channel::new(0.1);
|
||||
let raw = tx.send(&TestMessage::new(b"isolated")).unwrap();
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
rx.add_message_handler(Box::new(|_, _| panic!("consumer failed")));
|
||||
|
||||
let later_handler_ran = Arc::new(AtomicBool::new(false));
|
||||
let observed = later_handler_ran.clone();
|
||||
rx.add_message_handler(Box::new(move |_, _| {
|
||||
observed.store(true, Ordering::SeqCst);
|
||||
false
|
||||
}));
|
||||
|
||||
let delivered = rx.receive(&raw).unwrap();
|
||||
assert_eq!(delivered, vec![(0x0001, b"isolated".to_vec())]);
|
||||
assert!(later_handler_ran.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_remove_message_handler_removes_only_its_token() {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU32, Ordering},
|
||||
};
|
||||
|
||||
let mut tx = Channel::new(0.1);
|
||||
let raw = tx.send(&TestMessage::new(b"handler tokens")).unwrap();
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
let counter = Arc::new(AtomicU32::new(0));
|
||||
|
||||
let first_counter = counter.clone();
|
||||
let first = rx.add_message_handler(Box::new(move |_, _| {
|
||||
first_counter.fetch_add(1, Ordering::SeqCst);
|
||||
false
|
||||
}));
|
||||
let second_counter = counter.clone();
|
||||
let _second = rx.add_message_handler(Box::new(move |_, _| {
|
||||
second_counter.fetch_add(10, Ordering::SeqCst);
|
||||
false
|
||||
}));
|
||||
|
||||
assert!(rx.remove_message_handler(first));
|
||||
assert!(!rx.remove_message_handler(first));
|
||||
rx.receive(&raw).unwrap();
|
||||
assert_eq!(counter.load(Ordering::SeqCst), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_live_rtt_updates_retransmit_timeout() {
|
||||
let mut channel = Channel::new(0.1);
|
||||
channel.send(&TestMessage::new(b"rtt")).unwrap();
|
||||
let initial = channel.compute_timeout(1);
|
||||
channel.update_rtt(1.0);
|
||||
assert!(channel.compute_timeout(1) > initial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_channel_send_receive() {
|
||||
let link_id = [0xAA; 16];
|
||||
let mut tx_lc = LinkChannel::new(link_id, 0.1);
|
||||
let mut rx_lc = LinkChannel::new(link_id, 0.1);
|
||||
rx_lc.register_message_type(0x0001).unwrap();
|
||||
|
||||
assert_eq!(*tx_lc.link_id(), link_id);
|
||||
assert!(tx_lc.is_active());
|
||||
@@ -1076,6 +1274,7 @@ mod tests {
|
||||
let link_id = [0xBB; 16];
|
||||
let mut tx_lc = LinkChannel::new(link_id, 0.1);
|
||||
let mut rx_lc = LinkChannel::new(link_id, 0.1);
|
||||
rx_lc.register_message_type(0x0001).unwrap();
|
||||
|
||||
// Send two messages
|
||||
let msg1 = TestMessage::new(b"first");
|
||||
@@ -1095,6 +1294,7 @@ mod tests {
|
||||
tx_lc.delivered(0, 0.1);
|
||||
tx_lc.delivered(1, 0.1);
|
||||
assert_eq!(tx_lc.outstanding_count(), 0);
|
||||
assert!(tx_lc.is_drained());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1123,6 +1323,44 @@ mod tests {
|
||||
assert!(resend.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_channel_delivery_clears_retransmission_hashes_for_sequence() {
|
||||
let mut channel = LinkChannel::new([0xDF; 16], 0.1);
|
||||
channel
|
||||
.prepare_send_tracked(&TestMessage::new(b"tracked"))
|
||||
.unwrap();
|
||||
let first_hash = [1u8; 32];
|
||||
let retry_hash = [2u8; 32];
|
||||
channel.track_outbound_packet_hash(first_hash, 0);
|
||||
channel.track_outbound_packet_hash(retry_hash, 0);
|
||||
|
||||
assert_eq!(channel.delivered_by_packet_hash(&retry_hash, 0.1), Some(0));
|
||||
assert!(channel.outbound_packet_hashes.is_empty());
|
||||
assert_eq!(channel.delivered_by_packet_hash(&first_hash, 0.1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_channel_enforces_message_mdu_without_consuming_sequence() {
|
||||
let link_id = [0xDE; 16];
|
||||
let mut channel = LinkChannel::new_with_mdu(link_id, 0.1, 32);
|
||||
assert_eq!(channel.mdu(), 32 - ENVELOPE_HEADER_SIZE);
|
||||
|
||||
let oversized = TestMessage::new(&vec![0u8; channel.mdu() + 1]);
|
||||
assert!(matches!(
|
||||
channel.prepare_send_tracked(&oversized),
|
||||
Err(ChannelError::MessageTooLarge {
|
||||
actual: 33,
|
||||
max: 32
|
||||
})
|
||||
));
|
||||
assert_eq!(channel.outstanding_count(), 0);
|
||||
|
||||
let prepared = channel
|
||||
.prepare_send_tracked(&TestMessage::new(b"fits"))
|
||||
.unwrap();
|
||||
assert_eq!(prepared.sequence, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encrypted_link_channel_roundtrip() {
|
||||
use rns_crypto::x25519::X25519PrivateKey;
|
||||
@@ -1140,6 +1378,7 @@ mod tests {
|
||||
|
||||
let mut tx_lc = LinkChannel::new_encrypted(link_id, 0.1, keys_a);
|
||||
let mut rx_lc = LinkChannel::new_encrypted(link_id, 0.1, keys_b);
|
||||
rx_lc.register_message_type(0x0001).unwrap();
|
||||
|
||||
let msg = TestMessage::new(b"encrypted hello");
|
||||
let raw = tx_lc.prepare_send(&msg).unwrap();
|
||||
|
||||
@@ -564,6 +564,10 @@ impl InboundResource {
|
||||
initial_map_hashes: Vec<[u8; MAPHASH_LEN]>,
|
||||
link_sdu: Option<usize>,
|
||||
) -> Result<Self, ResourceError> {
|
||||
if total_parts == 0 {
|
||||
return Err(ResourceError::InvalidAdvertisement);
|
||||
}
|
||||
|
||||
// `total_size` is post-encryption: max plaintext + random_hash +
|
||||
// TOKEN_OVERHEAD + worst-case PKCS7 pad.
|
||||
const MAX_AES_BLOCK_PAD: usize = 16;
|
||||
@@ -807,6 +811,17 @@ pub struct MultiSegmentOutbound {
|
||||
pub data_size: usize,
|
||||
}
|
||||
|
||||
fn required_segment_count(data_size: usize, metadata_wire_size: usize) -> usize {
|
||||
if data_size == 0 {
|
||||
return 1;
|
||||
}
|
||||
let first_payload_size = MAX_EFFICIENT_SIZE.saturating_sub(metadata_wire_size);
|
||||
let first_len = data_size.min(first_payload_size);
|
||||
1 + data_size
|
||||
.saturating_sub(first_len)
|
||||
.div_ceil(MAX_EFFICIENT_SIZE)
|
||||
}
|
||||
|
||||
impl MultiSegmentOutbound {
|
||||
/// Split `data` into `MAX_EFFICIENT_SIZE`-sized chunks, each wrapped in
|
||||
/// its own `OutboundResource` with `flags.split = true` and the correct
|
||||
@@ -854,9 +869,13 @@ impl MultiSegmentOutbound {
|
||||
if metadata_wire_size > MAX_EFFICIENT_SIZE {
|
||||
return Err(ResourceError::MetadataTooLarge);
|
||||
}
|
||||
let planned_segments = required_segment_count(data.len(), metadata_wire_size);
|
||||
if planned_segments > MAX_SEGMENTS {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
|
||||
let first_payload_max = MAX_EFFICIENT_SIZE - metadata_wire_size;
|
||||
let mut chunk_specs: Vec<(Vec<u8>, Option<Vec<u8>>)> = Vec::new();
|
||||
let mut chunk_specs: Vec<(Vec<u8>, Option<Vec<u8>>)> = Vec::with_capacity(planned_segments);
|
||||
|
||||
if data.is_empty() {
|
||||
chunk_specs.push((Vec::new(), metadata.clone()));
|
||||
@@ -873,6 +892,7 @@ impl MultiSegmentOutbound {
|
||||
}
|
||||
|
||||
let total_segments = chunk_specs.len();
|
||||
debug_assert_eq!(total_segments, planned_segments);
|
||||
let mut segments = Vec::with_capacity(total_segments);
|
||||
|
||||
for (i, (chunk, segment_metadata)) in chunk_specs.into_iter().enumerate() {
|
||||
@@ -1391,6 +1411,34 @@ impl OutboundTransfer {
|
||||
TransferAction::None
|
||||
}
|
||||
|
||||
/// Sender-side advertisement watchdog for request-driven runtimes.
|
||||
///
|
||||
/// An outbound transfer remains `Advertised` until the receiver's first
|
||||
/// `RESOURCE_REQ` arrives. If that advertisement is lost, resend it up to
|
||||
/// the Python-compatible retry limit instead of leaving the transfer
|
||||
/// dormant forever.
|
||||
pub fn check_timeout(&mut self) -> TransferAction {
|
||||
if self.resource.state != ResourceState::Advertised {
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
let timeout = Duration::from_secs_f64(
|
||||
self.rtt.as_secs_f64() * rns_link::constants::TRAFFIC_TIMEOUT_FACTOR + PROCESSING_GRACE,
|
||||
);
|
||||
if self.started_at.elapsed() <= timeout {
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
if self.retries < MAX_ADV_RETRIES {
|
||||
self.retries += 1;
|
||||
self.started_at = Instant::now();
|
||||
TransferAction::SendAdvertisement(self.create_advertisement())
|
||||
} else {
|
||||
self.resource.state = ResourceState::Failed;
|
||||
TransferAction::Failed("resource advertisement timed out".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume a hashmap-update frame from the receiver.
|
||||
///
|
||||
/// Wire layout:
|
||||
@@ -1551,8 +1599,7 @@ impl OutboundTransfer {
|
||||
// The collision guard widens the search window so out-of-order
|
||||
// part requests don't fall outside the scanned range when the
|
||||
// receiver's consecutive height lags ours.
|
||||
let guard_size =
|
||||
crate::resource_adv::collision_guard_size(rns_wire::constants::ENCRYPTED_MDU);
|
||||
let guard_size = crate::resource_adv::collision_guard_size(rns_wire::constants::LINK_MDU);
|
||||
let search_start = self.receiver_min_consecutive_height;
|
||||
let search_end = (search_start + guard_size).min(self.resource.num_parts());
|
||||
|
||||
@@ -1599,7 +1646,7 @@ impl OutboundTransfer {
|
||||
};
|
||||
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
|
||||
// Python cancels if an exhausted request cursor is not aligned to
|
||||
// a hashmap segment boundary.
|
||||
@@ -1695,7 +1742,7 @@ impl OutboundTransfer {
|
||||
self.resource.random_hash.to_vec(),
|
||||
self.resource.flags,
|
||||
&self.resource.map_hashes,
|
||||
rns_wire::constants::ENCRYPTED_MDU,
|
||||
rns_wire::constants::LINK_MDU,
|
||||
);
|
||||
// `ResourceAdvertisement::new` defaults to single-segment metadata
|
||||
// (`segment_index = 1`, `total_segments = 1`, `original_hash =
|
||||
@@ -2144,23 +2191,25 @@ impl InboundTransfer {
|
||||
return self.cancel();
|
||||
}
|
||||
|
||||
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
let Some(segment_start) = segment.checked_mul(hashmap_max_len) else {
|
||||
return self.cancel();
|
||||
};
|
||||
if segment_start >= self.resource.total_parts {
|
||||
return self.cancel();
|
||||
}
|
||||
|
||||
self.resource.state = ResourceState::Transferring;
|
||||
self.last_activity = Instant::now();
|
||||
self.retries_left = MAX_RETRIES;
|
||||
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
|
||||
// Parse hashes from the hashmap data and insert into our map_hashes.
|
||||
// `segment` is wire-supplied: indices are bounded by total_parts
|
||||
// (Python preallocates hashmap to total_parts, so out-of-range
|
||||
// writes are impossible there) — anything beyond is hostile.
|
||||
let hashes_count = hashmap_data.len() / MAPHASH_LEN;
|
||||
for i in 0..hashes_count {
|
||||
let idx = match segment
|
||||
.checked_mul(hashmap_max_len)
|
||||
.and_then(|base| base.checked_add(i))
|
||||
{
|
||||
let idx = match segment_start.checked_add(i) {
|
||||
Some(idx) if idx < self.resource.total_parts => idx,
|
||||
_ => break,
|
||||
};
|
||||
@@ -2772,6 +2821,47 @@ mod tests {
|
||||
assert!(matches!(action, TransferAction::SendPart(0, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_outbound_advertisement_watchdog_retries() {
|
||||
let mut transfer = OutboundTransfer::new(
|
||||
b"retry advertisement".to_vec(),
|
||||
false,
|
||||
Duration::from_millis(1),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
transfer.tick(),
|
||||
TransferAction::SendAdvertisement(_)
|
||||
));
|
||||
|
||||
transfer.started_at = Instant::now() - Duration::from_secs(60);
|
||||
assert!(matches!(
|
||||
transfer.check_timeout(),
|
||||
TransferAction::SendAdvertisement(_)
|
||||
));
|
||||
assert_eq!(transfer.retries, 1);
|
||||
assert_eq!(transfer.resource.state, ResourceState::Advertised);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_outbound_advertisement_watchdog_fails_after_retry_limit() {
|
||||
let mut transfer = OutboundTransfer::new(
|
||||
b"failed advertisement".to_vec(),
|
||||
false,
|
||||
Duration::from_millis(1),
|
||||
)
|
||||
.unwrap();
|
||||
transfer.tick();
|
||||
transfer.retries = MAX_ADV_RETRIES;
|
||||
transfer.started_at = Instant::now() - Duration::from_secs(60);
|
||||
|
||||
assert!(matches!(
|
||||
transfer.check_timeout(),
|
||||
TransferAction::Failed(_)
|
||||
));
|
||||
assert_eq!(transfer.resource.state, ResourceState::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_outbound_transfer_hmu_handling() {
|
||||
let data = b"small data".to_vec();
|
||||
@@ -2847,6 +2937,17 @@ mod tests {
|
||||
);
|
||||
assert!(matches!(result, Err(ResourceError::TooLarge)));
|
||||
|
||||
let result = InboundResource::new(
|
||||
0,
|
||||
1024,
|
||||
1000,
|
||||
[0xAA; RANDOM_HASH_SIZE],
|
||||
[0xBB; 32],
|
||||
ResourceFlags::default(),
|
||||
Vec::new(),
|
||||
);
|
||||
assert!(matches!(result, Err(ResourceError::InvalidAdvertisement)));
|
||||
|
||||
// Same bound at the InboundResource layer directly.
|
||||
let result = InboundResource::new(
|
||||
usize::MAX,
|
||||
@@ -3287,6 +3388,17 @@ mod tests {
|
||||
assert!(MultiSegmentOutbound::new(data, false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multi_segment_plan_caps_metadata_induced_extra_segment() {
|
||||
let bounded_payload = MAX_EFFICIENT_SIZE * MAX_SEGMENTS;
|
||||
assert_eq!(required_segment_count(bounded_payload, 0), MAX_SEGMENTS);
|
||||
assert_eq!(required_segment_count(bounded_payload, 4), MAX_SEGMENTS + 1);
|
||||
assert_eq!(
|
||||
required_segment_count(MAX_RESOURCE_SIZE, 0),
|
||||
MAX_SEGMENTS + 1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multi_segment_cancel_all_fans_out() {
|
||||
// Python parity: head-cancel must tear down every follow-on segment.
|
||||
@@ -3954,7 +4066,7 @@ mod tests {
|
||||
let mut sender =
|
||||
OutboundTransfer::new(data.clone(), false, Duration::from_millis(100)).unwrap();
|
||||
assert!(
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU) > 1,
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU) > 1,
|
||||
"test requires a multi-entry hashmap segment"
|
||||
);
|
||||
|
||||
@@ -4183,8 +4295,7 @@ mod tests {
|
||||
assert_eq!(inbound.hashmap_height, initial_height);
|
||||
|
||||
// Build hashmap data for segment 0 with additional hashes
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
let mut hashmap_bytes = Vec::new();
|
||||
let end = outbound.map_hashes.len().min(hashmap_max_len);
|
||||
for i in 0..end {
|
||||
@@ -4268,39 +4379,40 @@ mod tests {
|
||||
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
|
||||
let total_parts = outbound.num_parts();
|
||||
|
||||
let mut inbound = InboundTransfer::from_advertisement(
|
||||
total_parts,
|
||||
outbound.total_size,
|
||||
data.len(),
|
||||
outbound.random_hash,
|
||||
outbound.resource_hash,
|
||||
ResourceFlags {
|
||||
compressed: false,
|
||||
..Default::default()
|
||||
},
|
||||
outbound.map_hashes[..2].to_vec(),
|
||||
Duration::from_millis(100),
|
||||
)
|
||||
.unwrap();
|
||||
for segment in [1_000_000, usize::MAX] {
|
||||
let mut inbound = InboundTransfer::from_advertisement(
|
||||
total_parts,
|
||||
outbound.total_size,
|
||||
data.len(),
|
||||
outbound.random_hash,
|
||||
outbound.resource_hash,
|
||||
ResourceFlags {
|
||||
compressed: false,
|
||||
..Default::default()
|
||||
},
|
||||
outbound.map_hashes[..2].to_vec(),
|
||||
Duration::from_millis(100),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Hostile segment index: would previously push ~segment*74 zero
|
||||
// entries into map_hashes. Must be ignored without growth or panic.
|
||||
inbound.waiting_for_hmu = true;
|
||||
inbound.hashmap_update(1_000_000, &outbound.map_hashes[0]);
|
||||
assert_eq!(inbound.resource.map_hashes.len(), 2);
|
||||
|
||||
// Overflowing segment*hashmap_max_len must not panic either.
|
||||
inbound.waiting_for_hmu = true;
|
||||
inbound.hashmap_update(usize::MAX, &outbound.map_hashes[0]);
|
||||
assert_eq!(inbound.resource.map_hashes.len(), 2);
|
||||
// Hostile and overflowing segment indices must neither grow the
|
||||
// hashmap nor refresh the watchdog indefinitely.
|
||||
inbound.waiting_for_hmu = true;
|
||||
let action = inbound.hashmap_update(segment, &outbound.map_hashes[0]);
|
||||
assert!(matches!(
|
||||
action,
|
||||
TransferAction::SendCancel(CancelType::Rcl, _)
|
||||
));
|
||||
assert_eq!(inbound.resource.map_hashes.len(), 2);
|
||||
assert_eq!(inbound.resource.state, ResourceState::Failed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hashmap_update_second_segment_bounded_by_total_parts() {
|
||||
// Resource large enough that its hashmap spans >1 segment: segment 1
|
||||
// writes land, but never past total_parts even if overfull.
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
let data = vec![0xCD; (hashmap_max_len + 12) * SDU];
|
||||
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
|
||||
let total_parts = outbound.num_parts();
|
||||
@@ -4508,8 +4620,7 @@ mod tests {
|
||||
let mut request_data = Vec::new();
|
||||
request_data.push(HASHMAP_IS_EXHAUSTED);
|
||||
// last_map_hash -- use the hash at hashmap_max_len boundary
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
let boundary_idx = hashmap_max_len.min(sender.resource.num_parts()) - 1;
|
||||
request_data.extend_from_slice(&sender.resource.map_hashes[boundary_idx]);
|
||||
request_data.extend_from_slice(&sender.resource.resource_hash);
|
||||
|
||||
@@ -289,8 +289,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_default_link_mdu_matches_python_hashmap_capacity() {
|
||||
assert_eq!(rns_wire::constants::ENCRYPTED_MDU, 431);
|
||||
assert_eq!(hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU), 74);
|
||||
assert_eq!(rns_wire::constants::LINK_MDU, 431);
|
||||
assert_eq!(hashmap_max_len(rns_wire::constants::LINK_MDU), 74);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -64,10 +64,10 @@ impl LocalKeyBackend for HardwareBackend {
|
||||
|
||||
fn lock(&self) {
|
||||
let (reply, rx) = mpsc::channel();
|
||||
if let Ok(tx) = self.cmd_tx.lock()
|
||||
&& tx.send(Cmd::Lock { reply }).is_ok()
|
||||
{
|
||||
let _ = rx.recv();
|
||||
if let Ok(tx) = self.cmd_tx.lock() {
|
||||
if tx.send(Cmd::Lock { reply }).is_ok() {
|
||||
let _ = rx.recv();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-runtime"
|
||||
description = "Core runtime, config parsing, and lifecycle for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
@@ -32,3 +33,6 @@ serde = { workspace = true }
|
||||
subtle = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
nix = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -0,0 +1,28 @@
|
||||
# Reticulum runtime examples
|
||||
|
||||
These examples mirror the application-facing subjects in the upstream Python
|
||||
Reticulum examples while using explicit Rust runtime ownership.
|
||||
|
||||
Most networked examples have `server` and `client` modes:
|
||||
|
||||
```console
|
||||
cargo run -p rns-runtime --example link -- server
|
||||
cargo run -p rns-runtime --example link -- client <destination-hash> "hello"
|
||||
```
|
||||
|
||||
Pass `--config <directory>` to either mode to select a Reticulum config
|
||||
directory. Servers print their destination hash and announce once at startup.
|
||||
|
||||
The `ratchets` example is a local composition recipe because ratchet files and
|
||||
identity files are application-owned secrets:
|
||||
|
||||
```console
|
||||
cargo run -p rns-runtime --example ratchets -- identity.key ratchets.bin
|
||||
```
|
||||
|
||||
Use private, access-controlled paths for both files in a real application.
|
||||
|
||||
Python's `ExampleInterface.py` demonstrates runtime-loaded Python classes.
|
||||
Rust instead integrates third-party interfaces at compile time through
|
||||
`rns_interface::InterfaceHandle` and the runtime's interface factory. This is
|
||||
an intentional ownership and type-safety difference, not a wire-protocol gap.
|
||||
@@ -0,0 +1,66 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
|
||||
const ASPECT: &str = "example_utilities.announcesample.fruits";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut subscription = runtime
|
||||
.handle
|
||||
.subscribe_announces(Some(ASPECT.to_string()), false)
|
||||
.await?;
|
||||
let destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"Announce destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
println!("Press enter to announce with app data; Ctrl-C stops");
|
||||
|
||||
let mut lines = BufReader::new(tokio::io::stdin()).lines();
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
announce = subscription.recv() => {
|
||||
let Some(announce) = announce else { break };
|
||||
println!(
|
||||
"Observed {} app_data={}",
|
||||
hex::encode(announce.destination_hash),
|
||||
announce
|
||||
.app_data
|
||||
.as_deref()
|
||||
.map(String::from_utf8_lossy)
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
line = lines.next_line() => {
|
||||
if line?.is_none() {
|
||||
break;
|
||||
}
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions {
|
||||
app_data: Some(b"Peach".to_vec()),
|
||||
..DestinationAnnounceOptions::default()
|
||||
})
|
||||
.await?;
|
||||
println!("Announced {}", hex::encode(destination.handle.destination_hash()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
subscription.close().await?;
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.broadcast";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
let message = args
|
||||
.positional
|
||||
.first()
|
||||
.map_or("Hello Reticulum", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let destination = Destination::new(None, Direction::Out, DestType::Plain, ASPECT)?;
|
||||
|
||||
let sent = runtime
|
||||
.handle
|
||||
.send_to(
|
||||
&destination,
|
||||
message.as_bytes(),
|
||||
SendOptions {
|
||||
create_receipt: false,
|
||||
..SendOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
println!(
|
||||
"Broadcast {} to {}",
|
||||
hex::encode(sent.packet_hash),
|
||||
hex::encode(destination.hash)
|
||||
);
|
||||
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_protocol::channel_message::{MessageBase, SMT_STREAM_DATA};
|
||||
use rns_protocol::stream_data::StreamDataMessage;
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
const ASPECT: &str = "example_utilities.bufferexample";
|
||||
const STREAM_ID: u16 = 0;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination("Buffer destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
message = destination.events.channel_messages.recv() => {
|
||||
let Some(message) = message else { break };
|
||||
if message.msg_type != SMT_STREAM_DATA {
|
||||
continue;
|
||||
}
|
||||
let mut frame = StreamDataMessage::new(0, Vec::new(), false);
|
||||
frame.unpack(&message.payload)?;
|
||||
if frame.eof {
|
||||
destination
|
||||
.handle
|
||||
.send_channel(
|
||||
message.link_id,
|
||||
SMT_STREAM_DATA,
|
||||
StreamDataMessage::new(frame.stream_id, Vec::new(), true).pack(),
|
||||
)
|
||||
.await?;
|
||||
continue;
|
||||
}
|
||||
|
||||
let text = String::from_utf8_lossy(&frame.data);
|
||||
println!("Received over Buffer: {text}");
|
||||
let reply = StreamDataMessage::new(
|
||||
frame.stream_id,
|
||||
format!("Received: {text}").into_bytes(),
|
||||
false,
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.send_channel(message.link_id, SMT_STREAM_DATA, reply.pack())
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Hello Buffer", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, false, "buffer-example").await?;
|
||||
let mut buffer = session
|
||||
.handle
|
||||
.channel()
|
||||
.create_bidirectional_buffer(STREAM_ID, STREAM_ID)
|
||||
.await?;
|
||||
|
||||
buffer.write_all(message.as_bytes()).await?;
|
||||
buffer.flush().await?;
|
||||
let expected_len = "Received: ".len() + message.len();
|
||||
let mut reply = vec![0; expected_len];
|
||||
tokio::time::timeout(Duration::from_secs(30), buffer.read_exact(&mut reply)).await??;
|
||||
println!("Reply: {}", String::from_utf8_lossy(&reply));
|
||||
buffer.shutdown().await?;
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.channelexample";
|
||||
const STRING_MESSAGE: u16 = 0x0101;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination("Channel destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
message = destination.events.channel_messages.recv() => {
|
||||
let Some(message) = message else { break };
|
||||
if message.msg_type == STRING_MESSAGE {
|
||||
println!(
|
||||
"Received on {}: {}",
|
||||
hex::encode(message.link_id),
|
||||
String::from_utf8_lossy(&message.payload),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.send_channel(message.link_id, STRING_MESSAGE, message.payload)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Hello Channel", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, false, "channel-example").await?;
|
||||
let channel = session.handle.channel();
|
||||
channel.register_message_type(STRING_MESSAGE).await?;
|
||||
|
||||
let (reply_tx, mut reply_rx) = tokio::sync::mpsc::channel(1);
|
||||
let handler = channel
|
||||
.add_message_handler(move |msg_type, payload| {
|
||||
if msg_type != STRING_MESSAGE {
|
||||
return false;
|
||||
}
|
||||
let _ = reply_tx.try_send(payload.to_vec());
|
||||
true
|
||||
})
|
||||
.await?;
|
||||
channel.send_raw(STRING_MESSAGE, message.as_bytes()).await?;
|
||||
|
||||
let reply = tokio::time::timeout(Duration::from_secs(30), reply_rx.recv())
|
||||
.await?
|
||||
.ok_or("Channel closed before the echo arrived")?;
|
||||
println!("Reply: {}", String::from_utf8_lossy(&reply));
|
||||
|
||||
channel.remove_message_handler(handler).await?;
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.echo";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions {
|
||||
proof_strategy: ProofStrategy::ProveAll,
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
print_destination("Echo destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
packet = destination.events.packets.recv() => {
|
||||
let Some(packet) = packet else { break };
|
||||
println!("Proved {} bytes: {}", packet.data.len(), String::from_utf8_lossy(&packet.data));
|
||||
}
|
||||
}
|
||||
}
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args.positional.get(2).map_or("Hello echo", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let destination =
|
||||
recall_outbound_destination(&runtime.handle, destination_hash, ASPECT).await?;
|
||||
let sent = runtime
|
||||
.handle
|
||||
.send_to(&destination, message.as_bytes(), SendOptions::default())
|
||||
.await?;
|
||||
let receipt = sent.receipt.ok_or("echo send did not create a receipt")?;
|
||||
let rtt = receipt.delivered().await?;
|
||||
println!("Delivered in {:.3} ms", rtt.as_secs_f64() * 1000.0);
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
mod support;
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.filetransfer.server";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let output_path = args.require(1, "new output file")?.to_string();
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions {
|
||||
resource_strategy: ResourceStrategy::AcceptAll,
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"File-transfer destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
println!("The first completed transfer will be written to {output_path}");
|
||||
|
||||
let completed = tokio::select! {
|
||||
_ = runtime.shutdown.wait() => None,
|
||||
completed = destination.events.resource_completions.recv() => completed,
|
||||
};
|
||||
if let Some(completed) = completed {
|
||||
let mut output = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&output_path)?;
|
||||
output.write_all(&completed.data)?;
|
||||
output.sync_all()?;
|
||||
println!(
|
||||
"Wrote {} bytes to {} without replacing an existing file",
|
||||
completed.data.len(),
|
||||
output_path,
|
||||
);
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let input_path = Path::new(args.require(2, "input file")?);
|
||||
let input = File::open(input_path)?;
|
||||
let file_name = input_path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("resource")
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(
|
||||
&runtime.handle,
|
||||
destination_hash,
|
||||
false,
|
||||
"filetransfer-example",
|
||||
)
|
||||
.await?;
|
||||
let transfer = session
|
||||
.handle
|
||||
.send_resource(
|
||||
input,
|
||||
ResourceOptions {
|
||||
auto_compress: false,
|
||||
metadata: Some(file_name),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut progress = transfer.progress();
|
||||
let concluded = transfer.concluded();
|
||||
tokio::pin!(concluded);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
result = &mut concluded => {
|
||||
let receipt = result?;
|
||||
println!(
|
||||
"Transferred {} bytes as {}",
|
||||
receipt.data_size,
|
||||
hex::encode(receipt.resource_id),
|
||||
);
|
||||
break;
|
||||
}
|
||||
changed = progress.changed() => {
|
||||
changed?;
|
||||
println!("Progress: {:.1}%", *progress.borrow() * 100.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.identifyexample";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"Identification destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
established = destination.events.links_established.recv() => {
|
||||
let Some(link_id) = established else { break };
|
||||
println!("Link {} established", hex::encode(link_id));
|
||||
}
|
||||
identified = destination.events.links_identified.recv() => {
|
||||
let Some((link_id, identity_hash)) = identified else { break };
|
||||
println!(
|
||||
"Link {} identified as {}",
|
||||
hex::encode(link_id),
|
||||
hex::encode(identity_hash),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, true, "identify-example").await?;
|
||||
println!(
|
||||
"Established and identified Link {}",
|
||||
hex::encode(session.handle.link_id())
|
||||
);
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.linkexample";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination("Link destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
packet = destination.events.link_packets.recv() => {
|
||||
let Some((data, link_id)) = packet else { break };
|
||||
println!("Received on {}: {}", hex::encode(link_id), String::from_utf8_lossy(&data));
|
||||
destination
|
||||
.handle
|
||||
.send_link_packet(link_id, data)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args.positional.get(2).map_or("Hello Link", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut session = connect(&runtime.handle, destination_hash, false, "link-example").await?;
|
||||
session
|
||||
.handle
|
||||
.send_packet(message.as_bytes().to_vec())
|
||||
.await?;
|
||||
|
||||
let reply = tokio::time::timeout(Duration::from_secs(30), async {
|
||||
while let Some(event) = session.events.recv().await {
|
||||
if let LinkSessionEvent::Packet { data, .. } = event {
|
||||
return Some(data);
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.await?
|
||||
.ok_or("Link closed before the echo arrived")?;
|
||||
println!("Reply: {}", String::from_utf8_lossy(&reply));
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.minimalsample";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions {
|
||||
proof_strategy: ProofStrategy::ProveAll,
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
print_destination("Minimal destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
println!("Announced; waiting for packets (Ctrl-C to stop)");
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
packet = destination.events.packets.recv() => {
|
||||
let Some(packet) = packet else { break };
|
||||
println!("Received: {}", String::from_utf8_lossy(&packet.data));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
mod support;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.ratchet.echo.request";
|
||||
|
||||
fn load_or_create_identity(path: &Path) -> ExampleResult<Identity> {
|
||||
if path.exists() {
|
||||
return Ok(Identity::from_file(path)?);
|
||||
}
|
||||
let identity = Identity::new();
|
||||
identity.to_file(path)?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn load_or_create_ring(path: &Path, identity: &Identity) -> ExampleResult<PersistentRatchetRing> {
|
||||
let mut ring = PersistentRatchetRing::open(path, identity)?;
|
||||
ring.ensure_current(identity)?;
|
||||
Ok(ring)
|
||||
}
|
||||
|
||||
fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
let identity_path = Path::new(args.require(0, "identity file")?);
|
||||
let ratchet_path = Path::new(args.require(1, "ratchet file")?);
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Forward-secret message", String::as_str);
|
||||
|
||||
let identity = load_or_create_identity(identity_path)?;
|
||||
let ring = load_or_create_ring(ratchet_path, &identity)?;
|
||||
let ratchet = ring
|
||||
.current_public_key()
|
||||
.ok_or("ratchet ring has no current key")?;
|
||||
|
||||
let mut inbound = Destination::new(Some(&identity), Direction::In, DestType::Single, ASPECT)?;
|
||||
inbound.enable_ratchets(true);
|
||||
inbound.set_local_ratchet(ratchet);
|
||||
let announce = inbound.announce_packet(
|
||||
&identity,
|
||||
Some(b"ratchet example"),
|
||||
inbound.get_ratchet_for_announce().as_ref(),
|
||||
false,
|
||||
None,
|
||||
0.0,
|
||||
)?;
|
||||
|
||||
let remote_identity = Identity::from_public_key(&identity.get_public_key())?;
|
||||
let mut outbound = Destination::new(
|
||||
Some(&remote_identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
ASPECT,
|
||||
)?;
|
||||
outbound.set_remote_ratchet(ratchet);
|
||||
let ciphertext = outbound.encrypt(
|
||||
message.as_bytes(),
|
||||
&remote_identity,
|
||||
outbound.remote_ratchet_pub.as_ref(),
|
||||
)?;
|
||||
let plaintext =
|
||||
inbound.decrypt_with_ratchets(&ciphertext, &identity, Some(ring.private_keys()))?;
|
||||
|
||||
println!("Destination: {}", hex::encode(inbound.hash));
|
||||
println!("Retained ratchets: {}", ring.len());
|
||||
println!("Signed announce: {} bytes", announce.len());
|
||||
println!("Decrypted: {}", String::from_utf8_lossy(&plaintext));
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.requestexample";
|
||||
const REQUEST_PATH: &str = "/echo";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
destination
|
||||
.handle
|
||||
.register_request_handler(
|
||||
REQUEST_PATH,
|
||||
AllowPolicy::AllowAll,
|
||||
Vec::new(),
|
||||
true,
|
||||
|request| {
|
||||
println!(
|
||||
"{} requested {} bytes on {}",
|
||||
hex::encode(request.link_id),
|
||||
request.data.len(),
|
||||
request.path,
|
||||
);
|
||||
RequestOutcome::Reply(request.data)
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
print_destination("Request destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
runtime.shutdown.wait().await;
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Hello request", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, false, "request-example").await?;
|
||||
let response = session
|
||||
.handle
|
||||
.request(
|
||||
REQUEST_PATH,
|
||||
message.as_bytes(),
|
||||
Some(Duration::from_secs(30)),
|
||||
)
|
||||
.await?;
|
||||
println!(
|
||||
"Response in {:.3} ms: {}",
|
||||
response.response_time.as_secs_f64() * 1000.0,
|
||||
String::from_utf8_lossy(&response.data),
|
||||
);
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.resourceexample";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions {
|
||||
resource_strategy: ResourceStrategy::AcceptAll,
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"Resource destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
completed = destination.events.resource_completions.recv() => {
|
||||
let Some(completed) = completed else { break };
|
||||
println!(
|
||||
"Received {} bytes on {} as {}",
|
||||
completed.data.len(),
|
||||
hex::encode(completed.link_id),
|
||||
hex::encode(completed.resource_hash),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Hello Resource", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, false, "resource-example").await?;
|
||||
let transfer = session
|
||||
.handle
|
||||
.send_resource_bytes(
|
||||
message.as_bytes().to_vec(),
|
||||
ResourceOptions {
|
||||
auto_compress: true,
|
||||
metadata: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut progress = transfer.progress();
|
||||
let concluded = transfer.concluded();
|
||||
tokio::pin!(concluded);
|
||||
|
||||
let receipt = loop {
|
||||
tokio::select! {
|
||||
result = &mut concluded => break result?,
|
||||
changed = progress.changed() => {
|
||||
changed?;
|
||||
println!("Progress: {:.1}%", *progress.borrow() * 100.0);
|
||||
}
|
||||
}
|
||||
};
|
||||
println!(
|
||||
"Resource {} completed ({} bytes)",
|
||||
hex::encode(receipt.resource_id),
|
||||
receipt.data_size,
|
||||
);
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.speedtest";
|
||||
const DEFAULT_BYTES: usize = 2 * 1024 * 1024;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"Speed-test destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
let mut total = 0usize;
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
packet = destination.events.link_packets.recv() => {
|
||||
let Some((data, _)) = packet else { break };
|
||||
total = total.saturating_add(data.len());
|
||||
if total >= DEFAULT_BYTES {
|
||||
let elapsed = started.elapsed().as_secs_f64();
|
||||
println!(
|
||||
"Received {total} bytes at {:.2} Mbit/s",
|
||||
(total as f64 * 8.0) / elapsed / 1_000_000.0,
|
||||
);
|
||||
total = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let total_bytes = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map(|value| value.parse::<usize>())
|
||||
.transpose()?
|
||||
.unwrap_or(DEFAULT_BYTES);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(
|
||||
&runtime.handle,
|
||||
destination_hash,
|
||||
false,
|
||||
"speedtest-example",
|
||||
)
|
||||
.await?;
|
||||
let chunk = vec![0xAA; session.handle.mdu()];
|
||||
let started = Instant::now();
|
||||
let mut sent = 0usize;
|
||||
|
||||
while sent < total_bytes {
|
||||
let count = (total_bytes - sent).min(chunk.len());
|
||||
session.handle.send_packet(chunk[..count].to_vec()).await?;
|
||||
sent += count;
|
||||
}
|
||||
let elapsed = started.elapsed().as_secs_f64();
|
||||
println!(
|
||||
"Queued {sent} bytes in {:.3}s ({:.2} Mbit/s)",
|
||||
elapsed,
|
||||
(sent as f64 * 8.0) / elapsed / 1_000_000.0,
|
||||
);
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_runtime::lifecycle::install_signal_handlers;
|
||||
use rns_runtime::prelude::*;
|
||||
|
||||
pub type ExampleResult<T = ()> = Result<T, Box<dyn Error + Send + Sync>>;
|
||||
|
||||
pub struct ExampleArgs {
|
||||
pub config_dir: Option<String>,
|
||||
pub positional: Vec<String>,
|
||||
}
|
||||
|
||||
impl ExampleArgs {
|
||||
pub fn parse() -> ExampleResult<Self> {
|
||||
let mut config_dir = None;
|
||||
let mut positional = Vec::new();
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
if arg == "--config" {
|
||||
config_dir = Some(args.next().ok_or("--config requires a directory")?);
|
||||
} else {
|
||||
positional.push(arg);
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
config_dir,
|
||||
positional,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn require(&self, index: usize, label: &str) -> ExampleResult<&str> {
|
||||
self.positional
|
||||
.get(index)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| format!("missing {label}").into())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ExampleRuntime {
|
||||
pub handle: ReticulumHandle,
|
||||
pub shutdown: ShutdownSignal,
|
||||
}
|
||||
|
||||
impl ExampleRuntime {
|
||||
pub async fn start(config_dir: Option<&str>) -> ExampleResult<Self> {
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signals = install_signal_handlers(shutdown.clone());
|
||||
let handle = init(
|
||||
config_dir,
|
||||
None,
|
||||
shutdown.clone(),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
)
|
||||
.await?;
|
||||
Ok(Self { handle, shutdown })
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
self.handle.shutdown_and_wait().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_destination_hash(value: &str) -> ExampleResult<[u8; 16]> {
|
||||
let bytes = hex::decode(value)?;
|
||||
bytes
|
||||
.try_into()
|
||||
.map_err(|_| "destination hash must contain exactly 32 hexadecimal characters".into())
|
||||
}
|
||||
|
||||
pub async fn recall_outbound_destination(
|
||||
runtime: &ReticulumHandle,
|
||||
destination_hash: [u8; 16],
|
||||
app_name: &str,
|
||||
) -> ExampleResult<Destination> {
|
||||
let recalled = match runtime.recall(destination_hash).await? {
|
||||
Some(recalled) => recalled,
|
||||
None => {
|
||||
runtime
|
||||
.await_path(destination_hash, Duration::from_secs(15))
|
||||
.await?;
|
||||
runtime
|
||||
.recall(destination_hash)
|
||||
.await?
|
||||
.ok_or("destination identity was not learned from its announce")?
|
||||
}
|
||||
};
|
||||
let destination = Destination::new(
|
||||
Some(&recalled.identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
app_name,
|
||||
)?;
|
||||
if destination.hash != destination_hash {
|
||||
return Err(format!(
|
||||
"destination {} does not match application aspect {app_name}",
|
||||
hex::encode(destination_hash)
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(destination)
|
||||
}
|
||||
|
||||
pub async fn connect(
|
||||
runtime: &ReticulumHandle,
|
||||
destination_hash: [u8; 16],
|
||||
identify: bool,
|
||||
label: &str,
|
||||
) -> ExampleResult<LinkSession> {
|
||||
let options = LinkConnectOptions {
|
||||
identify,
|
||||
client_label: label.to_string(),
|
||||
..LinkConnectOptions::default()
|
||||
};
|
||||
Ok(runtime
|
||||
.connect_link(destination_hash, Identity::new(), options)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn register_single(
|
||||
runtime: &ReticulumHandle,
|
||||
identity: Identity,
|
||||
app_name: &str,
|
||||
options: DestinationRuntimeOptions,
|
||||
) -> ExampleResult<RegisteredDestination> {
|
||||
Ok(runtime
|
||||
.register_destination(identity, app_name.to_string(), options)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub fn print_destination(label: &str, hash: [u8; 16]) {
|
||||
println!("{label}: {}", hex::encode(hash));
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
//! Async byte streams carried by a reliable Reticulum Link channel.
|
||||
//!
|
||||
//! The protocol framing and compression live in `rns-protocol`; this module
|
||||
//! wires them to the actor-owned [`LinkSessionChannelHandle`] and presents
|
||||
//! Tokio [`AsyncRead`] / [`AsyncWrite`] implementations.
|
||||
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
use std::task::{Context, Poll, Waker};
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_protocol::buffer::{MAX_CHUNK_LEN, StreamReader, StreamWriter};
|
||||
use rns_protocol::channel::ChannelError;
|
||||
use rns_protocol::channel_message::{MessageBase, SMT_STREAM_DATA};
|
||||
use rns_protocol::stream_data::{STREAM_ID_MAX, StreamDataMessage};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
|
||||
use crate::link_session::{LinkSessionChannelError, LinkSessionChannelHandle};
|
||||
|
||||
/// Maximum unread data retained by the default channel Buffer reader.
|
||||
pub const DEFAULT_READER_CAPACITY: usize = 1024 * 1024;
|
||||
|
||||
/// Maximum time an orderly writer shutdown waits for channel headroom.
|
||||
pub const DEFAULT_CLOSE_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
const CHANNEL_RETRY_INTERVAL: Duration = Duration::from_millis(10);
|
||||
const STREAM_HEADER_LEN: usize = 2;
|
||||
|
||||
type IoFuture = Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'static>>;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LinkSessionBufferError {
|
||||
#[error("stream id {0} exceeds the 14-bit Buffer stream-id range")]
|
||||
InvalidStreamId(u16),
|
||||
#[error("reader capacity must be greater than zero")]
|
||||
InvalidReaderCapacity,
|
||||
#[error("channel MDU {0} is too small for a Buffer frame")]
|
||||
ChannelMduTooSmall(usize),
|
||||
#[error(transparent)]
|
||||
Channel(#[from] LinkSessionChannelError),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum ReaderFailure {
|
||||
InvalidFrame,
|
||||
CapacityExceeded,
|
||||
}
|
||||
|
||||
impl ReaderFailure {
|
||||
fn into_io_error(self) -> io::Error {
|
||||
match self {
|
||||
Self::InvalidFrame => {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "invalid channel Buffer frame")
|
||||
}
|
||||
Self::CapacityExceeded => io::Error::new(
|
||||
io::ErrorKind::OutOfMemory,
|
||||
"channel Buffer reader capacity exceeded",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ReaderState {
|
||||
stream_id: u16,
|
||||
reader: StreamReader,
|
||||
capacity: usize,
|
||||
failure: Option<ReaderFailure>,
|
||||
closed: bool,
|
||||
waker: Option<Waker>,
|
||||
}
|
||||
|
||||
impl ReaderState {
|
||||
fn wake(&mut self) -> Option<Waker> {
|
||||
self.waker.take()
|
||||
}
|
||||
|
||||
fn remember_waker(&mut self, waker: &Waker) {
|
||||
if self
|
||||
.waker
|
||||
.as_ref()
|
||||
.is_none_or(|current| !current.will_wake(waker))
|
||||
{
|
||||
self.waker = Some(waker.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read half of a channel-backed Reticulum Buffer stream.
|
||||
///
|
||||
/// Dropping the reader performs best-effort handler deregistration. Call
|
||||
/// [`Self::close`] when deterministic deregistration is required.
|
||||
pub struct LinkSessionBufferReader {
|
||||
channel: LinkSessionChannelHandle,
|
||||
handler_id: Option<rns_protocol::channel::HandlerId>,
|
||||
state: Arc<Mutex<ReaderState>>,
|
||||
}
|
||||
|
||||
impl LinkSessionBufferReader {
|
||||
pub fn stream_id(&self) -> u16 {
|
||||
self.state.lock().map(|state| state.stream_id).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn available(&self) -> usize {
|
||||
self.state
|
||||
.lock()
|
||||
.map(|state| state.reader.available())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn is_eof(&self) -> bool {
|
||||
self.state
|
||||
.lock()
|
||||
.map(|state| state.reader.is_eof() || state.closed)
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub async fn close(&mut self) -> Result<(), LinkSessionBufferError> {
|
||||
mark_reader_closed(&self.state);
|
||||
if let Some(handler_id) = self.handler_id.take() {
|
||||
let _ = self.channel.remove_message_handler(handler_id).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for LinkSessionBufferReader {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buffer: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
let mut state = match self.state.lock() {
|
||||
Ok(state) => state,
|
||||
Err(_) => {
|
||||
return Poll::Ready(Err(io::Error::other(
|
||||
"channel Buffer reader state is poisoned",
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(failure) = state.failure {
|
||||
return Poll::Ready(Err(failure.into_io_error()));
|
||||
}
|
||||
|
||||
if buffer.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
if let Some(data) = state.reader.read(buffer.remaining()) {
|
||||
buffer.put_slice(&data);
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
if state.closed || state.reader.is_done() {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
state.remember_waker(cx.waker());
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LinkSessionBufferReader {
|
||||
fn drop(&mut self) {
|
||||
mark_reader_closed(&self.state);
|
||||
if let Some(handler_id) = self.handler_id.take() {
|
||||
self.channel.try_remove_message_handler(handler_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum WriterState {
|
||||
Open,
|
||||
Sending { accepted: usize, future: IoFuture },
|
||||
Closing { future: IoFuture },
|
||||
Closed,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// Write half of a channel-backed Reticulum Buffer stream.
|
||||
///
|
||||
/// Writes are split and compressed by the protocol layer. Shutdown queues EOF
|
||||
/// only after all earlier writer frames have entered the reliable channel
|
||||
/// sequence and the channel has headroom for EOF.
|
||||
pub struct LinkSessionBufferWriter {
|
||||
channel: LinkSessionChannelHandle,
|
||||
writer: StreamWriter,
|
||||
state: WriterState,
|
||||
close_timeout: Duration,
|
||||
}
|
||||
|
||||
impl LinkSessionBufferWriter {
|
||||
pub fn with_close_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.close_timeout = timeout;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
matches!(self.state, WriterState::Closed)
|
||||
}
|
||||
|
||||
fn start_write(&mut self, data: &[u8]) -> io::Result<usize> {
|
||||
let accepted = data.len().min(MAX_CHUNK_LEN);
|
||||
let messages = self
|
||||
.writer
|
||||
.write(&data[..accepted])
|
||||
.map_err(io::Error::other)?;
|
||||
self.state = WriterState::Sending {
|
||||
accepted,
|
||||
future: send_messages(self.channel.clone(), messages),
|
||||
};
|
||||
Ok(accepted)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for LinkSessionBufferWriter {
|
||||
fn poll_write(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buffer: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
let this = self.get_mut();
|
||||
loop {
|
||||
match &mut this.state {
|
||||
WriterState::Open => {
|
||||
if buffer.is_empty() {
|
||||
return Poll::Ready(Ok(0));
|
||||
}
|
||||
if let Err(error) = this.start_write(buffer) {
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
}
|
||||
WriterState::Sending { accepted, future } => {
|
||||
let accepted = *accepted;
|
||||
match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = WriterState::Open;
|
||||
return Poll::Ready(Ok(accepted));
|
||||
}
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
WriterState::Closing { .. } | WriterState::Closed => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
"channel Buffer writer is closed",
|
||||
)));
|
||||
}
|
||||
WriterState::Failed(message) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
message.clone(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
let this = self.get_mut();
|
||||
loop {
|
||||
match &mut this.state {
|
||||
WriterState::Sending { future, .. } => match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => this.state = WriterState::Open,
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
},
|
||||
WriterState::Open | WriterState::Closed => return Poll::Ready(Ok(())),
|
||||
WriterState::Closing { future } => match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = WriterState::Closed;
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
},
|
||||
WriterState::Failed(message) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
message.clone(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
let this = self.get_mut();
|
||||
loop {
|
||||
match &mut this.state {
|
||||
WriterState::Sending { future, .. } => match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => this.state = WriterState::Open,
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
},
|
||||
WriterState::Open => {
|
||||
let eof = this.writer.close_simple();
|
||||
this.state = WriterState::Closing {
|
||||
future: drain_then_send_eof(this.channel.clone(), eof, this.close_timeout),
|
||||
};
|
||||
}
|
||||
WriterState::Closing { future } => match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = WriterState::Closed;
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
},
|
||||
WriterState::Closed => return Poll::Ready(Ok(())),
|
||||
WriterState::Failed(message) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
message.clone(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bidirectional channel Buffer with independent receive and send stream IDs.
|
||||
pub struct LinkSessionBuffer {
|
||||
reader: LinkSessionBufferReader,
|
||||
writer: LinkSessionBufferWriter,
|
||||
}
|
||||
|
||||
impl LinkSessionBuffer {
|
||||
pub fn reader(&self) -> &LinkSessionBufferReader {
|
||||
&self.reader
|
||||
}
|
||||
|
||||
pub fn writer(&self) -> &LinkSessionBufferWriter {
|
||||
&self.writer
|
||||
}
|
||||
|
||||
pub async fn close_reader(&mut self) -> Result<(), LinkSessionBufferError> {
|
||||
self.reader.close().await
|
||||
}
|
||||
|
||||
pub fn into_split(self) -> (LinkSessionBufferReader, LinkSessionBufferWriter) {
|
||||
(self.reader, self.writer)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for LinkSessionBuffer {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buffer: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().reader).poll_read(cx, buffer)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for LinkSessionBuffer {
|
||||
fn poll_write(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buffer: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.get_mut().writer).poll_write(cx, buffer)
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().writer).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().writer).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl LinkSessionChannelHandle {
|
||||
pub async fn create_reader(
|
||||
&self,
|
||||
stream_id: u16,
|
||||
) -> Result<LinkSessionBufferReader, LinkSessionBufferError> {
|
||||
self.create_reader_with_capacity(stream_id, DEFAULT_READER_CAPACITY)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_reader_with_capacity(
|
||||
&self,
|
||||
stream_id: u16,
|
||||
capacity: usize,
|
||||
) -> Result<LinkSessionBufferReader, LinkSessionBufferError> {
|
||||
validate_stream_id(stream_id)?;
|
||||
if capacity == 0 {
|
||||
return Err(LinkSessionBufferError::InvalidReaderCapacity);
|
||||
}
|
||||
|
||||
self.register_system_type(SMT_STREAM_DATA).await?;
|
||||
let state = Arc::new(Mutex::new(ReaderState {
|
||||
stream_id,
|
||||
reader: StreamReader::new(stream_id),
|
||||
capacity,
|
||||
failure: None,
|
||||
closed: false,
|
||||
waker: None,
|
||||
}));
|
||||
let weak_state = Arc::downgrade(&state);
|
||||
let handler_id = self
|
||||
.add_message_handler(move |msg_type, payload| {
|
||||
handle_stream_message(&weak_state, stream_id, msg_type, payload)
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(LinkSessionBufferReader {
|
||||
channel: self.clone(),
|
||||
handler_id: Some(handler_id),
|
||||
state,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_writer(
|
||||
&self,
|
||||
stream_id: u16,
|
||||
) -> Result<LinkSessionBufferWriter, LinkSessionBufferError> {
|
||||
validate_stream_id(stream_id)?;
|
||||
let max_data_len = self.mdu().saturating_sub(STREAM_HEADER_LEN);
|
||||
if max_data_len == 0 {
|
||||
return Err(LinkSessionBufferError::ChannelMduTooSmall(self.mdu()));
|
||||
}
|
||||
Ok(LinkSessionBufferWriter {
|
||||
channel: self.clone(),
|
||||
writer: StreamWriter::new(stream_id, max_data_len),
|
||||
state: WriterState::Open,
|
||||
close_timeout: DEFAULT_CLOSE_TIMEOUT,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn create_bidirectional_buffer(
|
||||
&self,
|
||||
receive_stream_id: u16,
|
||||
send_stream_id: u16,
|
||||
) -> Result<LinkSessionBuffer, LinkSessionBufferError> {
|
||||
validate_stream_id(receive_stream_id)?;
|
||||
validate_stream_id(send_stream_id)?;
|
||||
let reader = self.create_reader(receive_stream_id).await?;
|
||||
let writer = self.create_writer(send_stream_id)?;
|
||||
Ok(LinkSessionBuffer { reader, writer })
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_stream_id(stream_id: u16) -> Result<(), LinkSessionBufferError> {
|
||||
if stream_id > STREAM_ID_MAX {
|
||||
return Err(LinkSessionBufferError::InvalidStreamId(stream_id));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mark_reader_closed(state: &Arc<Mutex<ReaderState>>) {
|
||||
let wake = state.lock().ok().and_then(|mut state| {
|
||||
state.closed = true;
|
||||
state.wake()
|
||||
});
|
||||
if let Some(waker) = wake {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_stream_message(
|
||||
weak_state: &Weak<Mutex<ReaderState>>,
|
||||
stream_id: u16,
|
||||
msg_type: u16,
|
||||
payload: &[u8],
|
||||
) -> bool {
|
||||
if msg_type != SMT_STREAM_DATA || payload.len() < STREAM_HEADER_LEN {
|
||||
return false;
|
||||
}
|
||||
let encoded_stream_id = u16::from_be_bytes([payload[0], payload[1]]) & STREAM_ID_MAX;
|
||||
if encoded_stream_id != stream_id {
|
||||
return false;
|
||||
}
|
||||
let Some(state) = weak_state.upgrade() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let mut message = StreamDataMessage::new(0, Vec::new(), false);
|
||||
let decoded = message.unpack(payload);
|
||||
let wake = match state.lock() {
|
||||
Ok(mut state) => {
|
||||
if state.closed {
|
||||
return false;
|
||||
}
|
||||
if state.failure.is_some() {
|
||||
return true;
|
||||
} else if decoded.is_err() {
|
||||
state.failure = Some(ReaderFailure::InvalidFrame);
|
||||
} else if message.data.len() > state.capacity.saturating_sub(state.reader.available()) {
|
||||
state.failure = Some(ReaderFailure::CapacityExceeded);
|
||||
} else {
|
||||
state.reader.feed(&message);
|
||||
}
|
||||
state.wake()
|
||||
}
|
||||
Err(_) => return true,
|
||||
};
|
||||
if let Some(waker) = wake {
|
||||
waker.wake();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn send_messages(channel: LinkSessionChannelHandle, messages: Vec<StreamDataMessage>) -> IoFuture {
|
||||
Box::pin(async move {
|
||||
for message in messages {
|
||||
let msg_type = message.msg_type();
|
||||
let payload = message.pack();
|
||||
loop {
|
||||
match channel.send_raw(msg_type, payload.clone()).await {
|
||||
Ok(_) => break,
|
||||
Err(LinkSessionChannelError::Channel(ChannelError::NotReady)) => {
|
||||
tokio::time::sleep(CHANNEL_RETRY_INTERVAL).await;
|
||||
}
|
||||
Err(error) => return Err(io::Error::other(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn drain_then_send_eof(
|
||||
channel: LinkSessionChannelHandle,
|
||||
eof: StreamDataMessage,
|
||||
close_timeout: Duration,
|
||||
) -> IoFuture {
|
||||
Box::pin(async move {
|
||||
tokio::time::timeout(close_timeout, send_messages(channel, vec![eof]))
|
||||
.await
|
||||
.map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"timed out draining channel Buffer writer",
|
||||
)
|
||||
})?
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn reader_state(stream_id: u16, capacity: usize) -> Arc<Mutex<ReaderState>> {
|
||||
Arc::new(Mutex::new(ReaderState {
|
||||
stream_id,
|
||||
reader: StreamReader::new(stream_id),
|
||||
capacity,
|
||||
failure: None,
|
||||
closed: false,
|
||||
waker: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_routes_only_the_matching_stream() {
|
||||
let state = reader_state(7, 128);
|
||||
let weak = Arc::downgrade(&state);
|
||||
|
||||
let wrong = StreamDataMessage::new(8, b"wrong".to_vec(), false).pack();
|
||||
assert!(!handle_stream_message(&weak, 7, SMT_STREAM_DATA, &wrong));
|
||||
assert_eq!(state.lock().unwrap().reader.available(), 0);
|
||||
|
||||
let matching = StreamDataMessage::new(7, b"hello".to_vec(), true).pack();
|
||||
assert!(handle_stream_message(&weak, 7, SMT_STREAM_DATA, &matching));
|
||||
let mut state = state.lock().unwrap();
|
||||
assert_eq!(state.reader.read_all().unwrap(), b"hello");
|
||||
assert!(state.reader.is_done());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_fails_closed_at_reader_capacity() {
|
||||
let state = reader_state(1, 4);
|
||||
let weak = Arc::downgrade(&state);
|
||||
let oversized = StreamDataMessage::new(1, b"12345".to_vec(), false).pack();
|
||||
|
||||
assert!(handle_stream_message(&weak, 1, SMT_STREAM_DATA, &oversized));
|
||||
let state = state.lock().unwrap();
|
||||
assert!(matches!(
|
||||
state.failure,
|
||||
Some(ReaderFailure::CapacityExceeded)
|
||||
));
|
||||
assert_eq!(state.reader.available(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_reports_invalid_compressed_payload() {
|
||||
let state = reader_state(2, 128);
|
||||
let weak = Arc::downgrade(&state);
|
||||
let mut malformed = (0x4000_u16 | 2).to_be_bytes().to_vec();
|
||||
malformed.extend_from_slice(b"not bzip2");
|
||||
|
||||
assert!(handle_stream_message(&weak, 2, SMT_STREAM_DATA, &malformed));
|
||||
assert!(matches!(
|
||||
state.lock().unwrap().failure,
|
||||
Some(ReaderFailure::InvalidFrame)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_the_full_stream_id_range() {
|
||||
assert!(validate_stream_id(STREAM_ID_MAX).is_ok());
|
||||
assert!(matches!(
|
||||
validate_stream_id(STREAM_ID_MAX + 1),
|
||||
Err(LinkSessionBufferError::InvalidStreamId(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,706 @@
|
||||
//! App-facing ownership for an inbound SINGLE destination.
|
||||
//!
|
||||
//! Python binds Destination construction, transport registration, Link
|
||||
//! handling, and callbacks to process-global state. This facade keeps those
|
||||
//! responsibilities explicit: one registration owns one responder
|
||||
//! [`LinkManager`], exposes bounded event receivers, and deregisters when
|
||||
//! closed.
|
||||
|
||||
use rns_identity::destination::{
|
||||
AllowPolicy, DestType, Destination, DestinationError, Direction, ProofStrategy,
|
||||
};
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_link::link::{CloseReason, ResourceStrategy};
|
||||
use rns_protocol::channel_message::{ChannelMessageError, MessageBase};
|
||||
use rns_transport::messages::TransportMessage;
|
||||
use std::path::PathBuf;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::link_manager::{
|
||||
ChannelSendError, ChannelSendReceipt, DestinationAnnounceOptions, DestinationControlError,
|
||||
DestinationRequest, LinkChannelMessage, LinkManager, LinkManagerCommand, LinkPacketProof,
|
||||
LinkPacketSendReceipt, LinkPayloadSendReceipt, LinkResourceEvent, LinkResourceProof,
|
||||
LinkResourceSendReceipt, LinkSendError, RequestOutcome, ResourceCompletion,
|
||||
};
|
||||
|
||||
const DEFAULT_EVENT_CAPACITY: usize = 128;
|
||||
const COMMAND_CAPACITY: usize = 256;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DestinationRuntimeOptions {
|
||||
pub proof_strategy: ProofStrategy,
|
||||
pub accepts_links: bool,
|
||||
pub resource_strategy: ResourceStrategy,
|
||||
pub event_capacity: usize,
|
||||
}
|
||||
|
||||
impl Default for DestinationRuntimeOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
proof_strategy: ProofStrategy::ProveNone,
|
||||
accepts_links: true,
|
||||
resource_strategy: ResourceStrategy::AcceptNone,
|
||||
event_capacity: DEFAULT_EVENT_CAPACITY,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistent forward-secrecy settings for a live inbound destination.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DestinationRatchetOptions {
|
||||
/// Signed Python-compatible ratchet-ring file.
|
||||
pub path: PathBuf,
|
||||
/// Reject packets encrypted only to the base identity key.
|
||||
pub enforce: bool,
|
||||
}
|
||||
|
||||
impl DestinationRatchetOptions {
|
||||
/// Use `path` with ratchet enforcement disabled.
|
||||
pub fn new(path: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
path: path.into(),
|
||||
enforce: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DestinationPacket {
|
||||
pub data: Vec<u8>,
|
||||
pub raw: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Bounded event receivers owned by one registered destination.
|
||||
pub struct DestinationEvents {
|
||||
pub packets: mpsc::Receiver<DestinationPacket>,
|
||||
pub links_established: mpsc::Receiver<[u8; 16]>,
|
||||
pub links_identified: mpsc::Receiver<([u8; 16], [u8; 16])>,
|
||||
pub link_packets: mpsc::Receiver<(Vec<u8>, [u8; 16])>,
|
||||
pub link_packet_proofs: mpsc::Receiver<LinkPacketProof>,
|
||||
pub resource_completions: mpsc::Receiver<ResourceCompletion>,
|
||||
pub resource_proofs: mpsc::Receiver<LinkResourceProof>,
|
||||
pub resource_events: mpsc::Receiver<LinkResourceEvent>,
|
||||
pub channel_messages: mpsc::Receiver<LinkChannelMessage>,
|
||||
pub links_closed: mpsc::Receiver<[u8; 16]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DestinationRuntimeError {
|
||||
#[error(transparent)]
|
||||
Destination(#[from] DestinationError),
|
||||
#[error(transparent)]
|
||||
Control(#[from] DestinationControlError),
|
||||
#[error(transparent)]
|
||||
LinkSend(#[from] LinkSendError),
|
||||
#[error(transparent)]
|
||||
ChannelSend(#[from] ChannelSendError),
|
||||
#[error("destination event capacity must be greater than zero")]
|
||||
InvalidEventCapacity,
|
||||
#[error("destination manager is no longer available")]
|
||||
ManagerUnavailable,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DestinationHandle {
|
||||
destination_hash: [u8; 16],
|
||||
app_name: String,
|
||||
command_tx: mpsc::Sender<LinkManagerCommand>,
|
||||
}
|
||||
|
||||
impl DestinationHandle {
|
||||
pub fn destination_hash(&self) -> [u8; 16] {
|
||||
self.destination_hash
|
||||
}
|
||||
|
||||
pub fn app_name(&self) -> &str {
|
||||
&self.app_name
|
||||
}
|
||||
|
||||
pub async fn announce(
|
||||
&self,
|
||||
options: DestinationAnnounceOptions,
|
||||
) -> Result<(), DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::AnnounceWith {
|
||||
options,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_accepts_links(&self, accepts: bool) -> Result<(), DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SetAcceptsLinks {
|
||||
accepts,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn register_request_handler<F>(
|
||||
&self,
|
||||
path: impl Into<String>,
|
||||
allow: AllowPolicy,
|
||||
allowed_list: Vec<[u8; 16]>,
|
||||
auto_compress: bool,
|
||||
handler: F,
|
||||
) -> Result<bool, DestinationRuntimeError>
|
||||
where
|
||||
F: Fn(DestinationRequest) -> RequestOutcome + Send + 'static,
|
||||
{
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::RegisterRequestHandler {
|
||||
path: path.into(),
|
||||
allow,
|
||||
allowed_list,
|
||||
auto_compress,
|
||||
handler: Box::new(handler),
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
|
||||
}
|
||||
|
||||
pub async fn deregister_request_handler(
|
||||
&self,
|
||||
path: impl Into<String>,
|
||||
) -> Result<bool, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::DeregisterRequestHandler {
|
||||
path: path.into(),
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
|
||||
}
|
||||
|
||||
pub async fn send_link_packet(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
payload: impl Into<Vec<u8>>,
|
||||
) -> Result<LinkPacketSendReceipt, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SendLinkPacket {
|
||||
link_id,
|
||||
payload: payload.into(),
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
Ok(result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
|
||||
}
|
||||
|
||||
pub async fn send_link_resource(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
payload: impl Into<Vec<u8>>,
|
||||
auto_compress: bool,
|
||||
) -> Result<LinkResourceSendReceipt, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SendLinkResource {
|
||||
link_id,
|
||||
payload: payload.into(),
|
||||
auto_compress,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
Ok(result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
|
||||
}
|
||||
|
||||
pub async fn send_link_payload(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
payload: impl Into<Vec<u8>>,
|
||||
auto_compress: bool,
|
||||
) -> Result<LinkPayloadSendReceipt, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SendLinkPayload {
|
||||
link_id,
|
||||
payload: payload.into(),
|
||||
auto_compress,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
Ok(result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
|
||||
}
|
||||
|
||||
pub async fn send_channel(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
msg_type: u16,
|
||||
payload: impl Into<Vec<u8>>,
|
||||
) -> Result<ChannelSendReceipt, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SendChannelMessage {
|
||||
link_id,
|
||||
message: Box::new(RawChannelMessage {
|
||||
msg_type,
|
||||
payload: payload.into(),
|
||||
}),
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
Ok(result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
|
||||
}
|
||||
|
||||
pub async fn close_link(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
reason: CloseReason,
|
||||
send_teardown: bool,
|
||||
) -> Result<(), DestinationRuntimeError> {
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::CloseLink {
|
||||
link_id,
|
||||
reason,
|
||||
send_teardown,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
|
||||
}
|
||||
|
||||
pub async fn shutdown(&self) -> Result<(), DestinationRuntimeError> {
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::Shutdown)
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns one live inbound destination and its responder Link manager.
|
||||
pub struct RegisteredDestination {
|
||||
pub handle: DestinationHandle,
|
||||
pub events: DestinationEvents,
|
||||
stopped_rx: Option<oneshot::Receiver<()>>,
|
||||
}
|
||||
|
||||
impl RegisteredDestination {
|
||||
pub async fn register(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
identity: Identity,
|
||||
app_name: impl Into<String>,
|
||||
options: DestinationRuntimeOptions,
|
||||
) -> Result<Self, DestinationRuntimeError> {
|
||||
Self::register_inner(transport_tx, identity, app_name, options, None).await
|
||||
}
|
||||
|
||||
/// Register a live destination whose announce rotation and inbound
|
||||
/// decryption are backed by one verified persistent ratchet ring.
|
||||
pub async fn register_ratcheted(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
identity: Identity,
|
||||
app_name: impl Into<String>,
|
||||
options: DestinationRuntimeOptions,
|
||||
ratchet_options: DestinationRatchetOptions,
|
||||
) -> Result<Self, DestinationRuntimeError> {
|
||||
Self::register_inner(
|
||||
transport_tx,
|
||||
identity,
|
||||
app_name,
|
||||
options,
|
||||
Some(ratchet_options),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn register_inner(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
identity: Identity,
|
||||
app_name: impl Into<String>,
|
||||
options: DestinationRuntimeOptions,
|
||||
ratchet_options: Option<DestinationRatchetOptions>,
|
||||
) -> Result<Self, DestinationRuntimeError> {
|
||||
if options.event_capacity == 0 {
|
||||
return Err(DestinationRuntimeError::InvalidEventCapacity);
|
||||
}
|
||||
let app_name = app_name.into();
|
||||
let destination =
|
||||
Destination::new(Some(&identity), Direction::In, DestType::Single, &app_name)?;
|
||||
let destination_hash = destination.hash;
|
||||
let (delivery_tx, delivery_rx) = mpsc::channel(options.event_capacity);
|
||||
|
||||
let mut manager = LinkManager::with_destination(
|
||||
transport_tx.clone(),
|
||||
delivery_rx,
|
||||
&identity,
|
||||
&app_name,
|
||||
identity.get_signing_key(),
|
||||
);
|
||||
if let Some(ratchet_options) = ratchet_options {
|
||||
manager.enable_persistent_ratchets(ratchet_options.path, ratchet_options.enforce)?;
|
||||
}
|
||||
manager.set_resource_strategy(options.resource_strategy);
|
||||
manager.set_use_implicit_proof(true);
|
||||
let owned_destination = manager
|
||||
.destination_mut()
|
||||
.ok_or(DestinationControlError::DestinationUnavailable)?;
|
||||
owned_destination.set_proof_strategy(options.proof_strategy);
|
||||
owned_destination.set_accepts_links(options.accepts_links);
|
||||
|
||||
transport_tx
|
||||
.send(TransportMessage::RegisterDestination {
|
||||
hash: destination_hash,
|
||||
app_name: app_name.clone(),
|
||||
delivery_tx: Some(delivery_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
|
||||
let capacity = options.event_capacity;
|
||||
let (packet_tx, packets) = mpsc::channel(capacity);
|
||||
owned_destination.set_packet_callback(Box::new(move |data, raw| {
|
||||
let _ = packet_tx.try_send(DestinationPacket {
|
||||
data: data.to_vec(),
|
||||
raw: raw.to_vec(),
|
||||
});
|
||||
}));
|
||||
|
||||
let (links_established_tx, links_established) = mpsc::channel(capacity);
|
||||
let (links_identified_tx, links_identified) = mpsc::channel(capacity);
|
||||
let (link_packets_tx, link_packets) = mpsc::channel(capacity);
|
||||
let (link_packet_proofs_tx, link_packet_proofs) = mpsc::channel(capacity);
|
||||
let (resource_completions_tx, resource_completions) = mpsc::channel(capacity);
|
||||
let (resource_proofs_tx, resource_proofs) = mpsc::channel(capacity);
|
||||
let (resource_events_tx, resource_events) = mpsc::channel(capacity);
|
||||
let (channel_messages_tx, channel_messages) = mpsc::channel(capacity);
|
||||
let (links_closed_tx, links_closed) = mpsc::channel(capacity);
|
||||
manager.set_link_established_channel(links_established_tx);
|
||||
manager.set_link_identified_channel(links_identified_tx);
|
||||
manager.set_link_packet_channel(link_packets_tx);
|
||||
manager.set_link_packet_proof_channel(link_packet_proofs_tx);
|
||||
manager.set_resource_completion_channel(resource_completions_tx);
|
||||
manager.set_outbound_resource_proof_channel(resource_proofs_tx);
|
||||
manager.set_resource_event_channel(resource_events_tx);
|
||||
manager.set_channel_message_channel(channel_messages_tx);
|
||||
manager.set_link_closed_channel(links_closed_tx);
|
||||
|
||||
let (command_tx, command_rx) = mpsc::channel(COMMAND_CAPACITY);
|
||||
let (stopped_tx, stopped_rx) = oneshot::channel();
|
||||
let manager_transport_tx = transport_tx;
|
||||
tokio::spawn(async move {
|
||||
manager.run_with_commands(command_rx).await;
|
||||
let _ = manager_transport_tx
|
||||
.send(TransportMessage::DeregisterDestination {
|
||||
hash: destination_hash,
|
||||
})
|
||||
.await;
|
||||
let _ = stopped_tx.send(());
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
handle: DestinationHandle {
|
||||
destination_hash,
|
||||
app_name,
|
||||
command_tx,
|
||||
},
|
||||
events: DestinationEvents {
|
||||
packets,
|
||||
links_established,
|
||||
links_identified,
|
||||
link_packets,
|
||||
link_packet_proofs,
|
||||
resource_completions,
|
||||
resource_proofs,
|
||||
resource_events,
|
||||
channel_messages,
|
||||
links_closed,
|
||||
},
|
||||
stopped_rx: Some(stopped_rx),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn close(mut self) -> Result<(), DestinationRuntimeError> {
|
||||
self.handle.shutdown().await?;
|
||||
if let Some(stopped_rx) = self.stopped_rx.take() {
|
||||
stopped_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RegisteredDestination {
|
||||
fn drop(&mut self) {
|
||||
let command = LinkManagerCommand::Shutdown;
|
||||
match self.handle.command_tx.try_send(command) {
|
||||
Ok(()) | Err(mpsc::error::TrySendError::Closed(_)) => {}
|
||||
Err(mpsc::error::TrySendError::Full(command)) => {
|
||||
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
|
||||
let command_tx = self.handle.command_tx.clone();
|
||||
runtime.spawn(async move {
|
||||
let _ = command_tx.send(command).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RawChannelMessage {
|
||||
msg_type: u16,
|
||||
payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl MessageBase for RawChannelMessage {
|
||||
fn msg_type(&self) -> u16 {
|
||||
self.msg_type
|
||||
}
|
||||
|
||||
fn pack(&self) -> Vec<u8> {
|
||||
self.payload.clone()
|
||||
}
|
||||
|
||||
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
|
||||
self.payload = raw.to_vec();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rns_transport::messages::TransportMessage;
|
||||
|
||||
#[tokio::test]
|
||||
async fn registration_announces_and_deregisters_exact_destination() {
|
||||
let identity = Identity::new();
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(16);
|
||||
let registration = RegisteredDestination::register(
|
||||
transport_tx,
|
||||
identity,
|
||||
"example.runtime",
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let destination_hash = registration.handle.destination_hash();
|
||||
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::RegisterDestination { hash, .. }) if hash == destination_hash
|
||||
));
|
||||
registration
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions {
|
||||
app_data: Some(b"hello".to_vec()),
|
||||
..DestinationAnnounceOptions::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::Outbound(_)) | Some(TransportMessage::OutboundAttached { .. })
|
||||
));
|
||||
|
||||
registration.close().await.unwrap();
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::DeregisterDestination { hash }) if hash == destination_hash
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ratcheted_registration_advertises_and_decrypts_owned_ring() {
|
||||
let identity = Identity::new();
|
||||
let app_name = "example.runtime.ratcheted";
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("reticulum_runtime_ratchets_{}", identity.hexhash()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let ratchet_path = dir.join("ratchets");
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(16);
|
||||
|
||||
let mut registration = RegisteredDestination::register_ratcheted(
|
||||
transport_tx,
|
||||
identity.clone(),
|
||||
app_name,
|
||||
DestinationRuntimeOptions::default(),
|
||||
DestinationRatchetOptions {
|
||||
path: ratchet_path.clone(),
|
||||
enforce: true,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let destination_hash = registration.handle.destination_hash();
|
||||
let delivery_tx = match transport_rx.recv().await.unwrap() {
|
||||
TransportMessage::RegisterDestination {
|
||||
hash,
|
||||
delivery_tx: Some(delivery_tx),
|
||||
..
|
||||
} => {
|
||||
assert_eq!(hash, destination_hash);
|
||||
delivery_tx
|
||||
}
|
||||
other => panic!("expected destination registration, got {other:?}"),
|
||||
};
|
||||
|
||||
registration
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let announce_raw = match transport_rx.recv().await.unwrap() {
|
||||
TransportMessage::Outbound(request) => request.raw,
|
||||
TransportMessage::OutboundAttached { request, .. } => request.raw,
|
||||
other => panic!("expected ratcheted announce, got {other:?}"),
|
||||
};
|
||||
let (announce_header, _) = rns_wire::header::PacketHeader::unpack(&announce_raw).unwrap();
|
||||
assert_eq!(
|
||||
announce_header.flags.packet_type,
|
||||
rns_wire::flags::PacketType::Announce
|
||||
);
|
||||
assert!(announce_header.flags.context_flag);
|
||||
|
||||
let ratchet = rns_identity::ratchet::RatchetRing::load_verified(&ratchet_path, &identity)
|
||||
.unwrap()
|
||||
.ring()
|
||||
.current_public_key()
|
||||
.unwrap();
|
||||
let mut wrong_ratchet = ratchet;
|
||||
wrong_ratchet[0] ^= 0xFF;
|
||||
assert!(matches!(
|
||||
registration
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions {
|
||||
ratchet: Some(wrong_ratchet),
|
||||
..DestinationAnnounceOptions::default()
|
||||
})
|
||||
.await,
|
||||
Err(DestinationRuntimeError::Control(
|
||||
DestinationControlError::ManagedRatchetMismatch
|
||||
))
|
||||
));
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"a mismatched managed ratchet must not be advertised"
|
||||
);
|
||||
|
||||
let public_identity = Identity::from_public_key(&identity.get_public_key()).unwrap();
|
||||
let mut outbound = Destination::new(
|
||||
Some(&public_identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
app_name,
|
||||
)
|
||||
.unwrap();
|
||||
outbound.set_remote_ratchet(ratchet);
|
||||
let ciphertext = outbound
|
||||
.encrypt(
|
||||
b"forward secret",
|
||||
&public_identity,
|
||||
outbound.remote_ratchet_pub.as_ref(),
|
||||
)
|
||||
.unwrap();
|
||||
let packet = rns_wire::packet::Packet::new(
|
||||
rns_wire::header::PacketHeader {
|
||||
flags: rns_wire::flags::PacketFlags {
|
||||
header_type: rns_wire::flags::HeaderType::Header1,
|
||||
context_flag: false,
|
||||
transport_type: rns_wire::flags::TransportType::Broadcast,
|
||||
destination_type: rns_wire::flags::DestinationType::Single,
|
||||
packet_type: rns_wire::flags::PacketType::Data,
|
||||
},
|
||||
hops: 0,
|
||||
transport_id: None,
|
||||
destination_hash,
|
||||
context: rns_wire::context::PacketContext::None,
|
||||
},
|
||||
ciphertext,
|
||||
)
|
||||
.unwrap();
|
||||
delivery_tx
|
||||
.send(
|
||||
rns_transport::link_messages::DestinationEvent::InboundPacket {
|
||||
raw: bytes::Bytes::from(packet.raw),
|
||||
interface_id: 1,
|
||||
metrics: rns_transport::link_messages::PacketMetrics::default(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let delivered = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
registration.events.packets.recv(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(delivered.data, b"forward secret");
|
||||
|
||||
registration.close().await.unwrap();
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::DeregisterDestination { hash }) if hash == destination_hash
|
||||
));
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_ratchet_setup_does_not_leak_transport_registration() {
|
||||
let identity = Identity::new();
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"reticulum_runtime_missing_ratchets_{}",
|
||||
identity.hexhash()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let ratchet_path = root.join("missing").join("ratchets");
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(4);
|
||||
|
||||
let result = RegisteredDestination::register_ratcheted(
|
||||
transport_tx,
|
||||
identity,
|
||||
"example.runtime.ratchet-failure",
|
||||
DestinationRuntimeOptions::default(),
|
||||
DestinationRatchetOptions::new(ratchet_path),
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(DestinationRuntimeError::Control(
|
||||
DestinationControlError::RatchetPersistence(_)
|
||||
))
|
||||
));
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"failed local setup must not register a destination with transport"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Mirrors `Reticulum._synthesize_interface` in the Python reference but
|
||||
//! rejects external-program interfaces.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config::ConfigSection;
|
||||
use rns_interface::tcp::{TcpClientConfig, TcpServerConfig};
|
||||
use rns_interface::traits::InterfaceMode;
|
||||
@@ -114,6 +116,43 @@ pub struct RNodeInterfaceConfig {
|
||||
pub id_callsign: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
impl RNodeInterfaceConfig {
|
||||
/// Convert runtime configuration into the lower driver type while
|
||||
/// preserving signed-value and RF-range validation.
|
||||
pub(crate) fn to_rnode_config(
|
||||
&self,
|
||||
) -> Result<rns_interface::rnode::RNodeConfig, InterfaceFactoryError> {
|
||||
let tx_power =
|
||||
u8::try_from(self.tx_power).map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{}.txpower", self.name),
|
||||
message: format!("{} is outside 0..=37 dBm", self.tx_power),
|
||||
})?;
|
||||
let mut config = rns_interface::rnode::RNodeConfig::new(&self.name, &self.port);
|
||||
config.frequency = self.frequency;
|
||||
config.bandwidth = self.bandwidth;
|
||||
config.spreading_factor = self.spreading_factor;
|
||||
config.coding_rate = self.coding_rate;
|
||||
config.tx_power = tx_power;
|
||||
config.mode = self.mode;
|
||||
config.flow_control = self.flow_control;
|
||||
config.st_alock = self.st_alock;
|
||||
config.lt_alock = self.lt_alock;
|
||||
config.id_interval = self.id_interval;
|
||||
config.id_callsign = self
|
||||
.id_callsign
|
||||
.as_ref()
|
||||
.map(|callsign| callsign.as_bytes().to_vec());
|
||||
config
|
||||
.validate()
|
||||
.map_err(|error| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{}.{}", self.name, error.field().as_str()),
|
||||
message: error.to_string(),
|
||||
})?;
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
|
||||
/// LoRa RNode reached over Bluetooth LE.
|
||||
#[cfg(feature = "ble")]
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -237,6 +276,14 @@ pub struct BackboneInterfaceConfig {
|
||||
pub max_reconnect_tries: Option<usize>,
|
||||
/// Parsed for Python config compatibility; advisory only.
|
||||
pub i2p_tunneled: bool,
|
||||
/// Listener-only fast-flap blocking switch. Python default: enabled.
|
||||
pub block_fast_flapping: bool,
|
||||
/// Listener-only short-connection threshold. Python default: 20 seconds.
|
||||
pub fast_flapping_threshold: Duration,
|
||||
/// Listener-only tolerated short-connection count. Python default: 5.
|
||||
pub fast_flapping_grace: u64,
|
||||
/// Listener-only block time. Configured in minutes; Python default: 720.
|
||||
pub fast_flapping_block_time: Duration,
|
||||
}
|
||||
|
||||
fn parse_interface_mode(s: &str) -> Option<InterfaceMode> {
|
||||
@@ -274,6 +321,92 @@ fn parse_port_opt(
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn parse_bool_strict(
|
||||
name: &str,
|
||||
field: &str,
|
||||
section: &ConfigSection,
|
||||
default: bool,
|
||||
) -> Result<bool, InterfaceFactoryError> {
|
||||
if !section.has(field) {
|
||||
return Ok(default);
|
||||
}
|
||||
section
|
||||
.get_bool(field)
|
||||
.ok_or_else(|| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: "expected a boolean value".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_uint_strict(
|
||||
name: &str,
|
||||
field: &str,
|
||||
section: &ConfigSection,
|
||||
default: u64,
|
||||
) -> Result<u64, InterfaceFactoryError> {
|
||||
if !section.has(field) {
|
||||
return Ok(default);
|
||||
}
|
||||
let raw = section
|
||||
.get(field)
|
||||
.ok_or_else(|| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: "expected a non-negative integer".to_string(),
|
||||
})?;
|
||||
raw.parse::<u64>()
|
||||
.map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is not a non-negative integer"),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_duration_strict(
|
||||
name: &str,
|
||||
field: &str,
|
||||
section: &ConfigSection,
|
||||
unit_seconds: f64,
|
||||
default: Duration,
|
||||
) -> Result<Duration, InterfaceFactoryError> {
|
||||
if !section.has(field) {
|
||||
return Ok(default);
|
||||
}
|
||||
let raw = section
|
||||
.get(field)
|
||||
.ok_or_else(|| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: "expected a finite non-negative number".to_string(),
|
||||
})?;
|
||||
let value = raw
|
||||
.parse::<f64>()
|
||||
.map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is not a number"),
|
||||
})?;
|
||||
if !value.is_finite() {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is not finite"),
|
||||
});
|
||||
}
|
||||
if value < 0.0 {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' must not be negative"),
|
||||
});
|
||||
}
|
||||
let seconds = value * unit_seconds;
|
||||
if !seconds.is_finite() {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is too large"),
|
||||
});
|
||||
}
|
||||
Duration::try_from_secs_f64(seconds).map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("'{raw}' is outside the supported duration range"),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn synthesize_interface(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -651,11 +784,11 @@ fn synthesize_rnode(
|
||||
.to_string();
|
||||
|
||||
let (frequency, bandwidth, spreading_factor, coding_rate, tx_power) =
|
||||
require_rnode_radio_params(name, section)?;
|
||||
require_generic_rnode_radio_params(name, section)?;
|
||||
|
||||
let (flow_control, st_alock, lt_alock) = parse_rnode_airtime(name, section)?;
|
||||
let (flow_control, st_alock, lt_alock) = parse_generic_rnode_airtime(name, section)?;
|
||||
|
||||
Ok(InterfaceConfig::RNode(RNodeInterfaceConfig {
|
||||
let config = RNodeInterfaceConfig {
|
||||
name: name.to_string(),
|
||||
port,
|
||||
frequency,
|
||||
@@ -669,14 +802,205 @@ fn synthesize_rnode(
|
||||
lt_alock,
|
||||
id_interval: section.get_uint("id_interval"),
|
||||
id_callsign: section.get("id_callsign").map(|s| s.to_string()),
|
||||
}))
|
||||
};
|
||||
// Report invalid user configuration here with its exact section field.
|
||||
// The lower driver repeats this check before any endpoint I/O so manually
|
||||
// constructed runtime configurations receive the same protection.
|
||||
config.to_rnode_config()?;
|
||||
Ok(InterfaceConfig::RNode(config))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn require_generic_rnode_radio_params(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
) -> Result<(u32, u32, u8, u8, i8), InterfaceFactoryError> {
|
||||
let (frequency_key, frequency) =
|
||||
parse_required_rnode_unsigned::<u32>(name, section, &["frequency"])?;
|
||||
let frequency = validate_parsed_rnode_integer(
|
||||
name,
|
||||
&frequency_key,
|
||||
frequency,
|
||||
i64::from(rns_interface::rnode::RNODE_FREQUENCY_MIN_HZ),
|
||||
i64::from(rns_interface::rnode::RNODE_FREQUENCY_MAX_HZ),
|
||||
)?;
|
||||
let (bandwidth_key, bandwidth) =
|
||||
parse_required_rnode_unsigned::<u32>(name, section, &["bandwidth"])?;
|
||||
let bandwidth = validate_parsed_rnode_integer(
|
||||
name,
|
||||
&bandwidth_key,
|
||||
bandwidth,
|
||||
i64::from(rns_interface::rnode::RNODE_BANDWIDTH_MIN_HZ),
|
||||
i64::from(rns_interface::rnode::RNODE_BANDWIDTH_MAX_HZ),
|
||||
)?;
|
||||
let (spreading_factor_key, spreading_factor) = parse_required_rnode_unsigned::<u8>(
|
||||
name,
|
||||
section,
|
||||
&["spreadingfactor", "spreading_factor"],
|
||||
)?;
|
||||
let spreading_factor = validate_parsed_rnode_integer(
|
||||
name,
|
||||
&spreading_factor_key,
|
||||
spreading_factor,
|
||||
i64::from(rns_interface::rnode::RNODE_SPREADING_FACTOR_MIN),
|
||||
i64::from(rns_interface::rnode::RNODE_SPREADING_FACTOR_MAX),
|
||||
)?;
|
||||
let (coding_rate_key, coding_rate) =
|
||||
parse_required_rnode_unsigned::<u8>(name, section, &["codingrate", "coding_rate"])?;
|
||||
let coding_rate = validate_parsed_rnode_integer(
|
||||
name,
|
||||
&coding_rate_key,
|
||||
coding_rate,
|
||||
i64::from(rns_interface::rnode::RNODE_CODING_RATE_MIN),
|
||||
i64::from(rns_interface::rnode::RNODE_CODING_RATE_MAX),
|
||||
)?;
|
||||
let (tx_power_key, tx_power) =
|
||||
parse_required_rnode_signed::<i8>(name, section, &["txpower", "tx_power"])?;
|
||||
let tx_power = validate_parsed_rnode_integer(
|
||||
name,
|
||||
&tx_power_key,
|
||||
tx_power,
|
||||
i64::from(rns_interface::rnode::RNODE_TX_POWER_MIN_DBM),
|
||||
i64::from(rns_interface::rnode::RNODE_TX_POWER_MAX_DBM),
|
||||
)?;
|
||||
Ok((
|
||||
frequency,
|
||||
bandwidth,
|
||||
spreading_factor,
|
||||
coding_rate,
|
||||
tx_power,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn required_rnode_scalar<'a>(
|
||||
name: &str,
|
||||
section: &'a ConfigSection,
|
||||
keys: &[&str],
|
||||
) -> Result<(String, &'a str), InterfaceFactoryError> {
|
||||
for key in keys {
|
||||
if let Some(value) = section.get(key) {
|
||||
return Ok(((*key).to_string(), value));
|
||||
}
|
||||
}
|
||||
Err(InterfaceFactoryError::MissingField {
|
||||
name: name.to_string(),
|
||||
field: keys[0].to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn parse_required_rnode_unsigned<T>(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
keys: &[&str],
|
||||
) -> Result<(String, T), InterfaceFactoryError>
|
||||
where
|
||||
T: TryFrom<u64>,
|
||||
{
|
||||
let (key, raw) = required_rnode_scalar(name, section, keys)?;
|
||||
let parsed = raw
|
||||
.parse::<u64>()
|
||||
.map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{key}"),
|
||||
message: format!("'{raw}' is not a valid unsigned integer"),
|
||||
})?;
|
||||
let value = T::try_from(parsed).map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{key}"),
|
||||
message: format!("{parsed} cannot be represented by this field"),
|
||||
})?;
|
||||
Ok((key, value))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn parse_required_rnode_signed<T>(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
keys: &[&str],
|
||||
) -> Result<(String, T), InterfaceFactoryError>
|
||||
where
|
||||
T: TryFrom<i64>,
|
||||
{
|
||||
let (key, raw) = required_rnode_scalar(name, section, keys)?;
|
||||
let parsed = raw
|
||||
.parse::<i64>()
|
||||
.map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{key}"),
|
||||
message: format!("'{raw}' is not a valid signed integer"),
|
||||
})?;
|
||||
let value = T::try_from(parsed).map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{key}"),
|
||||
message: format!("{parsed} cannot be represented by this field"),
|
||||
})?;
|
||||
Ok((key, value))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn validate_parsed_rnode_integer<T>(
|
||||
name: &str,
|
||||
key: &str,
|
||||
value: T,
|
||||
minimum: i64,
|
||||
maximum: i64,
|
||||
) -> Result<T, InterfaceFactoryError>
|
||||
where
|
||||
T: Copy + Into<i64>,
|
||||
{
|
||||
let comparable = value.into();
|
||||
if comparable < minimum || comparable > maximum {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{key}"),
|
||||
message: format!("{comparable} is outside {minimum}..={maximum}"),
|
||||
});
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn parse_generic_rnode_airtime(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
) -> Result<(bool, Option<f32>, Option<f32>), InterfaceFactoryError> {
|
||||
let flow_control = section.get_bool("flow_control").unwrap_or(false);
|
||||
let st_alock =
|
||||
parse_generic_rnode_airtime_value(name, section, &["airtime_limit_short", "st_alock"])?;
|
||||
let lt_alock =
|
||||
parse_generic_rnode_airtime_value(name, section, &["airtime_limit_long", "lt_alock"])?;
|
||||
Ok((flow_control, st_alock, lt_alock))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn parse_generic_rnode_airtime_value(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
keys: &[&str],
|
||||
) -> Result<Option<f32>, InterfaceFactoryError> {
|
||||
let Some((key, raw)) = keys
|
||||
.iter()
|
||||
.find_map(|key| section.get(key).map(|value| (*key, value)))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let value = raw
|
||||
.parse::<f64>()
|
||||
.map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{key}"),
|
||||
message: format!("'{raw}' is not a valid percentage"),
|
||||
})?;
|
||||
if !value.is_finite() || !(0.0..=100.0).contains(&value) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{key}"),
|
||||
message: format!("{value} must be finite and within 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
Ok(Some(value as f32))
|
||||
}
|
||||
|
||||
/// Radio parameters are deliberately required: Python errors when they are
|
||||
/// absent (RNodeInterface validation fails on the 0 fallbacks), and silently
|
||||
/// inventing RF parameters — especially TX power — risks misconfigured
|
||||
/// transmissions. Documented in fix-registry (final sweep decision items).
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))]
|
||||
#[cfg(any(feature = "serial", feature = "ble"))]
|
||||
fn require_rnode_radio_params(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -715,7 +1039,7 @@ fn require_rnode_radio_params(
|
||||
/// Shared RNode airtime/flow-control parsing. Python `RNodeInterface.py:156-160`:
|
||||
/// `flow_control` defaults off, `airtime_limit_short`/`airtime_limit_long` are
|
||||
/// duty-cycle percentages validated to 0..=100.
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))]
|
||||
#[cfg(feature = "ble")]
|
||||
fn parse_rnode_airtime(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -729,21 +1053,21 @@ fn parse_rnode_airtime(
|
||||
.get_float("airtime_limit_long")
|
||||
.or_else(|| section.get_float("lt_alock"))
|
||||
.map(|v| v as f32);
|
||||
if let Some(v) = st_alock
|
||||
&& !(0.0..=100.0).contains(&v)
|
||||
{
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_short"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
if let Some(v) = st_alock {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_short"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(v) = lt_alock
|
||||
&& !(0.0..=100.0).contains(&v)
|
||||
{
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_long"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
if let Some(v) = lt_alock {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_long"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok((flow_control, st_alock, lt_alock))
|
||||
}
|
||||
@@ -1133,6 +1457,32 @@ fn synthesize_backbone(
|
||||
let connect_timeout = section.get_uint("connect_timeout").unwrap_or(5);
|
||||
let max_reconnect_tries = section.get_uint("max_reconnect_tries").map(|v| v as usize);
|
||||
let i2p_tunneled = section.get_bool("i2p_tunneled").unwrap_or(false);
|
||||
let block_fast_flapping = parse_bool_strict(
|
||||
name,
|
||||
"block_fast_flapping",
|
||||
section,
|
||||
rns_interface::backbone::BLOCK_FAST_FLAPPING,
|
||||
)?;
|
||||
let fast_flapping_threshold = parse_duration_strict(
|
||||
name,
|
||||
"fast_flapping_threshold",
|
||||
section,
|
||||
1.0,
|
||||
rns_interface::backbone::FAST_FLAPPING_THRESHOLD,
|
||||
)?;
|
||||
let fast_flapping_grace = parse_uint_strict(
|
||||
name,
|
||||
"fast_flapping_grace",
|
||||
section,
|
||||
rns_interface::backbone::FAST_FLAPPING_GRACE,
|
||||
)?;
|
||||
let fast_flapping_block_time = parse_duration_strict(
|
||||
name,
|
||||
"fast_flapping_block_time",
|
||||
section,
|
||||
60.0,
|
||||
rns_interface::backbone::FAST_FLAPPING_BLOCK_TIME,
|
||||
)?;
|
||||
|
||||
Ok(InterfaceConfig::Backbone(BackboneInterfaceConfig {
|
||||
name: name.to_string(),
|
||||
@@ -1145,6 +1495,10 @@ fn synthesize_backbone(
|
||||
connect_timeout,
|
||||
max_reconnect_tries,
|
||||
i2p_tunneled,
|
||||
block_fast_flapping,
|
||||
fast_flapping_threshold,
|
||||
fast_flapping_grace,
|
||||
fast_flapping_block_time,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1894,6 +2248,180 @@ mod tests {
|
||||
section.set("txpower", "17");
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn complete_rnode_section() -> ConfigSection {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "tcp://rnode.local");
|
||||
section.set("frequency", "868000000");
|
||||
set_rnode_radio_params(&mut section);
|
||||
section
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn complete_rnode_alias_section() -> ConfigSection {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "tcp://rnode.local");
|
||||
section.set("frequency", "868000000");
|
||||
section.set("bandwidth", "125000");
|
||||
section.set("spreading_factor", "7");
|
||||
section.set("coding_rate", "5");
|
||||
section.set("tx_power", "17");
|
||||
section
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn assert_invalid_rnode_field(section: &ConfigSection, expected_field: &str) {
|
||||
match synthesize_interface("rnode_invalid", section) {
|
||||
Err(InterfaceFactoryError::InvalidValue { field, .. }) => {
|
||||
assert_eq!(field, format!("rnode_invalid.{expected_field}"));
|
||||
}
|
||||
other => panic!("expected InvalidValue for {expected_field}, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_accepts_all_inclusive_rf_boundaries() {
|
||||
let mut section = complete_rnode_section();
|
||||
section.set("frequency", "137000000");
|
||||
section.set("bandwidth", "7800");
|
||||
section.set("spreadingfactor", "5");
|
||||
section.set("codingrate", "5");
|
||||
section.set("txpower", "0");
|
||||
section.set("airtime_limit_short", "0");
|
||||
section.set("airtime_limit_long", "0");
|
||||
assert!(synthesize_interface("rnode_min", §ion).is_ok());
|
||||
|
||||
section.set("frequency", "3000000000");
|
||||
section.set("bandwidth", "1625000");
|
||||
section.set("spreadingfactor", "12");
|
||||
section.set("codingrate", "8");
|
||||
section.set("txpower", "37");
|
||||
section.set("airtime_limit_short", "100");
|
||||
section.set("airtime_limit_long", "100");
|
||||
assert!(synthesize_interface("rnode_max", §ion).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_rejects_every_just_outside_boundary() {
|
||||
for (field, value) in [
|
||||
("frequency", "136999999"),
|
||||
("frequency", "3000000001"),
|
||||
("bandwidth", "7799"),
|
||||
("bandwidth", "1625001"),
|
||||
("spreadingfactor", "4"),
|
||||
("spreadingfactor", "13"),
|
||||
("codingrate", "4"),
|
||||
("codingrate", "9"),
|
||||
("txpower", "-1"),
|
||||
("txpower", "38"),
|
||||
("airtime_limit_short", "-0.0001"),
|
||||
("airtime_limit_short", "100.0001"),
|
||||
("airtime_limit_long", "-0.0001"),
|
||||
("airtime_limit_long", "100.0001"),
|
||||
] {
|
||||
let mut section = complete_rnode_section();
|
||||
section.set(field, value);
|
||||
assert_invalid_rnode_field(§ion, field);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_rejects_integer_narrowing_and_negative_unsigned_values() {
|
||||
for (field, value) in [
|
||||
("frequency", "4294967296"),
|
||||
("frequency", "-1"),
|
||||
("bandwidth", "4294967296"),
|
||||
("bandwidth", "-1"),
|
||||
("spreadingfactor", "256"),
|
||||
("spreadingfactor", "-1"),
|
||||
("codingrate", "256"),
|
||||
("codingrate", "-1"),
|
||||
("txpower", "128"),
|
||||
("txpower", "-129"),
|
||||
("txpower", "18446744073709551616"),
|
||||
] {
|
||||
let mut section = complete_rnode_section();
|
||||
section.set(field, value);
|
||||
assert_invalid_rnode_field(§ion, field);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_rejects_non_finite_airtime() {
|
||||
for field in ["airtime_limit_short", "airtime_limit_long"] {
|
||||
for value in ["NaN", "inf", "-inf"] {
|
||||
let mut section = complete_rnode_section();
|
||||
section.set(field, value);
|
||||
assert_invalid_rnode_field(§ion, field);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_reports_airtime_alias_that_was_supplied() {
|
||||
for (field, value) in [("st_alock", "-1"), ("lt_alock", "inf")] {
|
||||
let mut section = complete_rnode_section();
|
||||
section.set(field, value);
|
||||
assert_invalid_rnode_field(§ion, field);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_reports_rf_alias_that_was_supplied() {
|
||||
assert!(synthesize_interface("rnode_aliases", &complete_rnode_alias_section()).is_ok());
|
||||
|
||||
for (field, value) in [
|
||||
("spreading_factor", "13"),
|
||||
("coding_rate", "9"),
|
||||
("tx_power", "-1"),
|
||||
] {
|
||||
let mut section = complete_rnode_alias_section();
|
||||
section.set(field, value);
|
||||
assert_invalid_rnode_field(§ion, field);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_error_does_not_repeat_field_name() {
|
||||
let mut section = complete_rnode_section();
|
||||
section.set("frequency", "136999999");
|
||||
match synthesize_interface("rnode_invalid", §ion) {
|
||||
Err(InterfaceFactoryError::InvalidValue { field, message }) => {
|
||||
assert_eq!(field, "rnode_invalid.frequency");
|
||||
assert!(!message.contains("frequency"), "{message}");
|
||||
}
|
||||
other => panic!("expected InvalidValue, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_manual_runtime_rnode_config_cannot_wrap_negative_tx_power() {
|
||||
let mut config = match synthesize_interface("rnode_manual", &complete_rnode_section())
|
||||
.expect("valid baseline")
|
||||
{
|
||||
InterfaceConfig::RNode(config) => config,
|
||||
other => panic!("expected RNode, got {other:?}"),
|
||||
};
|
||||
config.tx_power = -1;
|
||||
|
||||
match config.to_rnode_config() {
|
||||
Err(InterfaceFactoryError::InvalidValue { field, .. }) => {
|
||||
assert_eq!(field, "rnode_manual.txpower");
|
||||
}
|
||||
other => panic!("expected InvalidValue, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python parity: all radio params required — no invented defaults.
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
@@ -2284,11 +2812,68 @@ mod tests {
|
||||
assert_eq!(c.connect_timeout, 5);
|
||||
assert!(c.max_reconnect_tries.is_none());
|
||||
assert!(!c.i2p_tunneled);
|
||||
assert!(c.block_fast_flapping);
|
||||
assert_eq!(c.fast_flapping_threshold, Duration::from_secs(20));
|
||||
assert_eq!(c.fast_flapping_grace, 5);
|
||||
assert_eq!(c.fast_flapping_block_time, Duration::from_secs(720 * 60));
|
||||
}
|
||||
_ => panic!("expected Backbone"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_synthesize_backbone_fast_flap_overrides_allow_fractions() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "BackboneInterface");
|
||||
section.set("listen_on", "0.0.0.0");
|
||||
section.set("port", "4242");
|
||||
section.set("block_fast_flapping", "no");
|
||||
section.set("fast_flapping_threshold", "1.25");
|
||||
section.set("fast_flapping_grace", "9");
|
||||
section.set("fast_flapping_block_time", "0.5");
|
||||
|
||||
let config = synthesize_interface("backbone_flap_overrides", §ion).unwrap();
|
||||
match config {
|
||||
InterfaceConfig::Backbone(c) => {
|
||||
assert!(!c.block_fast_flapping);
|
||||
assert_eq!(c.fast_flapping_threshold, Duration::from_millis(1250));
|
||||
assert_eq!(c.fast_flapping_grace, 9);
|
||||
assert_eq!(c.fast_flapping_block_time, Duration::from_secs(30));
|
||||
}
|
||||
_ => panic!("expected Backbone"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_synthesize_backbone_rejects_invalid_fast_flap_values() {
|
||||
for (field, value) in [
|
||||
("block_fast_flapping", "sometimes"),
|
||||
("fast_flapping_threshold", "not-a-number"),
|
||||
("fast_flapping_threshold", "NaN"),
|
||||
("fast_flapping_threshold", "-0.1"),
|
||||
("fast_flapping_threshold", "1e30"),
|
||||
("fast_flapping_grace", "-1"),
|
||||
("fast_flapping_grace", "1.5"),
|
||||
("fast_flapping_grace", "18446744073709551616"),
|
||||
("fast_flapping_block_time", "inf"),
|
||||
("fast_flapping_block_time", "-1"),
|
||||
("fast_flapping_block_time", "1e307"),
|
||||
] {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "BackboneInterface");
|
||||
section.set("listen_on", "0.0.0.0");
|
||||
section.set("port", "4242");
|
||||
section.set(field, value);
|
||||
|
||||
match synthesize_interface("backbone_invalid_flap", §ion) {
|
||||
Err(InterfaceFactoryError::InvalidValue {
|
||||
field: error_field, ..
|
||||
}) => assert_eq!(error_field, format!("backbone_invalid_flap.{field}")),
|
||||
other => panic!("expected InvalidValue for {field}={value}, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_synthesize_backbone_connect_timeout() {
|
||||
let mut section = ConfigSection::new();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,19 +1,63 @@
|
||||
//! Reticulum runtime: config, lifecycle, RPC, and the [`reticulum::ReticulumHandle`]
|
||||
//! that user code holds. Python reference: `RNS/Reticulum.py`.
|
||||
|
||||
pub mod buffer_stream;
|
||||
pub mod config;
|
||||
pub mod constants;
|
||||
pub mod destination_runtime;
|
||||
pub mod interface_factory;
|
||||
mod interface_registry;
|
||||
pub mod jobs;
|
||||
pub mod lifecycle;
|
||||
pub mod link_client;
|
||||
pub mod link_manager;
|
||||
pub mod link_session;
|
||||
pub mod platform;
|
||||
pub mod probe;
|
||||
pub mod remote_management;
|
||||
pub mod remote_management_schema;
|
||||
pub mod resource_source;
|
||||
pub mod reticulum;
|
||||
pub mod rncp;
|
||||
pub mod rnsh;
|
||||
pub mod rpc;
|
||||
pub mod rpc_server;
|
||||
|
||||
/// Common application-facing types for Reticulum programs.
|
||||
///
|
||||
/// This is additive convenience; module-qualified paths remain supported.
|
||||
pub mod prelude {
|
||||
pub use crate::destination_runtime::{
|
||||
DestinationEvents, DestinationHandle, DestinationPacket, DestinationRatchetOptions,
|
||||
DestinationRuntimeError, DestinationRuntimeOptions, RegisteredDestination,
|
||||
};
|
||||
pub use crate::lifecycle::ShutdownSignal;
|
||||
pub use crate::link_manager::{DestinationAnnounceOptions, DestinationRequest, RequestOutcome};
|
||||
pub use crate::link_session::{
|
||||
LinkSession, LinkSessionChannelError, LinkSessionChannelHandle, LinkSessionCloseReason,
|
||||
LinkSessionError, LinkSessionEvent, LinkSessionHandle, LinkSessionResourceError,
|
||||
LinkSessionResourceOffer, LinkSessionResponse,
|
||||
};
|
||||
pub use crate::resource_source::{ResourceOptions, ResourceSource};
|
||||
pub use crate::reticulum::{
|
||||
AnnounceSubscription, ControlError, InitOptions, InterfaceStats, LinkConnectError,
|
||||
LinkConnectOptions, OutboundPacket, PacketReceiptHandle, PacketReceiptStatus,
|
||||
RNodeReadinessError, RNodeRuntimeLookupError, RNodeRuntimeObserver, RNodeRuntimeSpawnError,
|
||||
RecalledDestination, ReceiptError, ReticulumError, ReticulumHandle, SendError, SendOptions,
|
||||
SendResult, SpawnedRNodeRuntime, StartupRNodeRuntime, init, init_with_options,
|
||||
init_with_options_and_rnode_startup_options,
|
||||
};
|
||||
pub use rns_identity::destination::{
|
||||
AllowPolicy, DestType, Destination, DestinationPacketError, DestinationPacketOptions,
|
||||
Direction, PackedDestinationPacket, ProofStrategy,
|
||||
};
|
||||
pub use rns_identity::identity::Identity;
|
||||
pub use rns_identity::ratchet::PersistentRatchetRing;
|
||||
pub use rns_interface::rnode::{
|
||||
RNodeCapabilityAdmissionError, RNodeCapabilityState, RNodeConfigurationState,
|
||||
RNodeDetectionState, RNodeFirmwareCompatibility, RNodeObservedRadioState,
|
||||
RNodeRuntimePhase, RNodeRuntimeReason, RNodeRuntimeSnapshot, RNodeSpawnError,
|
||||
RNodeStartupOptions, RNodeTransmitFlowState, RNodeTransportClass,
|
||||
};
|
||||
pub use rns_link::link::{CloseReason, ResourceStrategy};
|
||||
}
|
||||
@@ -32,10 +32,15 @@ impl ShutdownSignal {
|
||||
}
|
||||
|
||||
pub async fn wait(&self) {
|
||||
if self.is_triggered() {
|
||||
return;
|
||||
loop {
|
||||
let notified = self.notify.notified();
|
||||
tokio::pin!(notified);
|
||||
notified.as_mut().enable();
|
||||
if self.is_triggered() {
|
||||
return;
|
||||
}
|
||||
notified.await;
|
||||
}
|
||||
self.notify.notified().await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,33 +80,50 @@ impl Default for ExitHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Install a Ctrl-C (SIGINT) handler that trips `shutdown`. Returned receiver
|
||||
/// yields once on signal for await-based callers.
|
||||
/// Install process-signal handlers that trip `shutdown`. On Unix this covers
|
||||
/// both SIGINT and SIGTERM; other platforms use the runtime's Ctrl-C handler.
|
||||
/// The returned receiver yields once on the first signal for await-based
|
||||
/// callers.
|
||||
///
|
||||
/// On unix the OS-level registration happens synchronously in this call — a
|
||||
/// handler registered inside a spawned task only takes effect once that task
|
||||
/// is first polled, leaving a window where SIGINT kills the process via the
|
||||
/// is first polled, leaving a window where a signal kills the process via the
|
||||
/// default disposition.
|
||||
pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> {
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
let shutdown_clone = shutdown.clone();
|
||||
|
||||
#[cfg(unix)]
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()) {
|
||||
Ok(mut sigint) => {
|
||||
tokio::spawn(async move {
|
||||
sigint.recv().await;
|
||||
signal_shutdown(shutdown_clone, tx).await;
|
||||
});
|
||||
{
|
||||
let shutdown_clone = shutdown.clone();
|
||||
let tx_clone = tx.clone();
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()) {
|
||||
Ok(mut sigint) => {
|
||||
tokio::spawn(async move {
|
||||
sigint.recv().await;
|
||||
signal_shutdown(shutdown_clone, tx_clone, "SIGINT");
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "SIGINT registration failed; falling back to ctrl_c");
|
||||
spawn_ctrl_c_handler(shutdown.clone(), tx.clone());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "SIGINT registration failed; falling back to ctrl_c");
|
||||
spawn_ctrl_c_handler(shutdown_clone, tx);
|
||||
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
||||
Ok(mut sigterm) => {
|
||||
tokio::spawn(async move {
|
||||
sigterm.recv().await;
|
||||
signal_shutdown(shutdown, tx, "SIGTERM");
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "SIGTERM registration failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
spawn_ctrl_c_handler(shutdown_clone, tx);
|
||||
spawn_ctrl_c_handler(shutdown, tx);
|
||||
|
||||
rx
|
||||
}
|
||||
@@ -109,14 +131,14 @@ pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> {
|
||||
fn spawn_ctrl_c_handler(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) {
|
||||
tokio::spawn(async move {
|
||||
tokio::signal::ctrl_c().await.ok();
|
||||
signal_shutdown(shutdown, tx).await;
|
||||
signal_shutdown(shutdown, tx, "Ctrl-C");
|
||||
});
|
||||
}
|
||||
|
||||
async fn signal_shutdown(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) {
|
||||
tracing::info!("received shutdown signal");
|
||||
fn signal_shutdown(shutdown: ShutdownSignal, tx: mpsc::Sender<()>, signal: &'static str) {
|
||||
tracing::info!(signal, "received shutdown signal");
|
||||
shutdown.trigger();
|
||||
let _ = tx.send(()).await;
|
||||
let _ = tx.try_send(());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -171,4 +193,13 @@ mod tests {
|
||||
signal.wait().await;
|
||||
assert!(signal.is_triggered());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_shutdown_wait_after_trigger() {
|
||||
let signal = ShutdownSignal::new();
|
||||
signal.trigger();
|
||||
tokio::time::timeout(std::time::Duration::from_millis(50), signal.wait())
|
||||
.await
|
||||
.expect("pre-triggered shutdown wait must return");
|
||||
}
|
||||
}
|
||||
+4520
-527
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -85,7 +85,9 @@ pub async fn spawn_probe_responder(
|
||||
tokio::spawn(async move {
|
||||
while let Some(event) = event_rx.recv().await {
|
||||
let (raw, interface_id) = match event {
|
||||
DestinationEvent::InboundPacket { raw, interface_id } => (raw, interface_id),
|
||||
DestinationEvent::InboundPacket {
|
||||
raw, interface_id, ..
|
||||
} => (raw, interface_id),
|
||||
DestinationEvent::AnnounceRequested(request) => {
|
||||
let raw = match destination.announce_packet(
|
||||
identity.as_ref(),
|
||||
@@ -135,6 +137,9 @@ pub async fn spawn_probe_responder(
|
||||
if header.flags.packet_type != PacketType::Data {
|
||||
continue;
|
||||
}
|
||||
if !destination.should_prove(&raw) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (full_hash, trunc_hash) = packet_hash_pair(&raw, header.flags.header_type);
|
||||
let proof_payload = match identity.prove(&full_hash, implicit) {
|
||||
@@ -366,6 +371,8 @@ pub async fn probe_once(
|
||||
.send(TransportMessage::RegisterReceipt {
|
||||
truncated_hash: trunc_hash,
|
||||
full_hash,
|
||||
destination_hash: dest_hash,
|
||||
destination_public_key: pubkey,
|
||||
msg_id: msg_id.clone(),
|
||||
timeout: Some(proof_wait + Duration::from_secs(1)),
|
||||
})
|
||||
@@ -596,6 +603,7 @@ mod tests {
|
||||
.send(DestinationEvent::InboundPacket {
|
||||
raw: bytes::Bytes::from(raw),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -729,6 +737,7 @@ mod tests {
|
||||
.send(DestinationEvent::InboundPacket {
|
||||
raw: bytes::Bytes::from(raw),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -266,6 +266,7 @@ fn interface_stats_from_rpc(e: InterfaceStatRpcEntry) -> schema::InterfaceStats
|
||||
txs: e.tx_rate,
|
||||
announce_queue: e.announce_queue,
|
||||
clients: e.clients,
|
||||
blocked_ips: e.blocked_ips,
|
||||
ifac_signature: None,
|
||||
ifac_size,
|
||||
ifac_netname: None,
|
||||
@@ -350,6 +351,7 @@ mod tests {
|
||||
txs: 0,
|
||||
announce_queue: None,
|
||||
clients: None,
|
||||
blocked_ips: None,
|
||||
ifac_signature: None,
|
||||
ifac_size: None,
|
||||
ifac_netname: None,
|
||||
@@ -376,9 +378,67 @@ mod tests {
|
||||
.any(|(k, _)| k.as_str() == Some("interfaces"));
|
||||
assert!(has_interfaces, "stats dict has 'interfaces' key");
|
||||
|
||||
let interface_map = stats_map
|
||||
.iter()
|
||||
.find(|(key, _)| key.as_str() == Some("interfaces"))
|
||||
.and_then(|(_, value)| value.as_array())
|
||||
.and_then(|interfaces| interfaces.first())
|
||||
.and_then(rmpv::Value::as_map)
|
||||
.expect("first interface is a map");
|
||||
assert!(
|
||||
!interface_map
|
||||
.iter()
|
||||
.any(|(key, _)| key.as_str() == Some("blocked_ips")),
|
||||
"absent aggregate count is omitted"
|
||||
);
|
||||
assert_eq!(arr[1].as_u64(), Some(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_response_serializes_only_aggregate_blocked_ip_count() {
|
||||
let stats = schema::InterfaceStats {
|
||||
name: "Backbone".to_string(),
|
||||
short_name: "Backbone".to_string(),
|
||||
hash: None,
|
||||
type_: "Interface".to_string(),
|
||||
rxb: 0,
|
||||
txb: 0,
|
||||
incoming_announce_frequency: 0.0,
|
||||
outgoing_announce_frequency: 0.0,
|
||||
incoming_pr_frequency: 0.0,
|
||||
outgoing_pr_frequency: 0.0,
|
||||
held_announces: 0,
|
||||
burst_active: false,
|
||||
burst_activated: 0.0,
|
||||
pr_burst_active: false,
|
||||
pr_burst_activated: 0.0,
|
||||
status: true,
|
||||
mode: 0x01,
|
||||
bitrate: Some(1_000_000),
|
||||
rxs: 0,
|
||||
txs: 0,
|
||||
announce_queue: None,
|
||||
clients: Some(2),
|
||||
blocked_ips: Some(3),
|
||||
ifac_signature: None,
|
||||
ifac_size: None,
|
||||
ifac_netname: None,
|
||||
};
|
||||
let encoded = rmp_serde::to_vec_named(&stats).unwrap();
|
||||
let decoded: rmpv::Value = rmp_serde::from_slice(&encoded).unwrap();
|
||||
let map = decoded.as_map().expect("interface stats are a map");
|
||||
assert_eq!(
|
||||
map.iter()
|
||||
.find(|(key, _)| key.as_str() == Some("blocked_ips"))
|
||||
.and_then(|(_, value)| value.as_u64()),
|
||||
Some(3)
|
||||
);
|
||||
assert!(
|
||||
!map.iter()
|
||||
.any(|(key, _)| key.as_str() == Some("blocked_ip_list"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_response_is_list_of_dicts() {
|
||||
let entry = schema::PathEntry {
|
||||
@@ -484,6 +544,7 @@ mod tests {
|
||||
pr_burst_active: true,
|
||||
pr_burst_activated: 1_700_000_002.0,
|
||||
clients: None,
|
||||
blocked_ips: Some(3),
|
||||
announce_rate_target: None,
|
||||
announce_rate_grace: None,
|
||||
announce_rate_penalty: None,
|
||||
@@ -611,6 +672,16 @@ mod tests {
|
||||
.1
|
||||
.as_bool();
|
||||
assert_eq!(pr_burst_active, Some(true));
|
||||
let blocked_ips = iface_map
|
||||
.iter()
|
||||
.find(|(key, _)| key.as_str() == Some("blocked_ips"))
|
||||
.and_then(|(_, value)| value.as_u64());
|
||||
assert_eq!(blocked_ips, Some(3));
|
||||
assert!(
|
||||
!iface_map
|
||||
.iter()
|
||||
.any(|(key, _)| key.as_str() == Some("blocked_ip_list"))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
|
||||
@@ -53,6 +53,8 @@ pub struct InterfaceStats {
|
||||
pub announce_queue: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub clients: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub blocked_ips: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")]
|
||||
pub ifac_signature: Option<Vec<u8>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
//! Bounded-memory sources for Link Resource transfers.
|
||||
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_link::key_derivation::LinkKeys;
|
||||
use rns_protocol::resource::{
|
||||
MAX_EFFICIENT_SIZE, MAX_RESOURCE_SIZE, MAX_SEGMENTS, OutboundResource, OutboundTransfer,
|
||||
ResourceError,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// Seekable source accepted by the high-level Resource API.
|
||||
pub trait ResourceSource: Read + Seek + Send {}
|
||||
|
||||
impl<T> ResourceSource for T where T: Read + Seek + Send {}
|
||||
|
||||
/// Sender options shared by byte and streaming Resource sources.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ResourceOptions {
|
||||
pub auto_compress: bool,
|
||||
pub metadata: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ResourceSourceError {
|
||||
#[error("resource source I/O failed: {0}")]
|
||||
Io(#[from] io::Error),
|
||||
#[error("resource source exceeds the supported {MAX_RESOURCE_SIZE}-byte limit")]
|
||||
TooLarge,
|
||||
#[error("resource metadata leaves no valid bounded segment plan")]
|
||||
TooManySegments,
|
||||
#[error("resource preparation failed: {0}")]
|
||||
Protocol(#[from] ResourceError),
|
||||
}
|
||||
|
||||
pub(crate) struct PreparedResourceSegment {
|
||||
pub transfer: OutboundTransfer,
|
||||
pub logical_hash: [u8; 32],
|
||||
pub segment_index: usize,
|
||||
pub total_segments: usize,
|
||||
pub data_size: usize,
|
||||
pub segment_data_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) enum ResourcePurpose {
|
||||
#[default]
|
||||
Ordinary,
|
||||
Request([u8; 16]),
|
||||
}
|
||||
|
||||
impl ResourcePurpose {
|
||||
fn apply(self, resource: &mut OutboundResource) {
|
||||
if let Self::Request(request_id) = self {
|
||||
resource.flags.is_request = true;
|
||||
resource.request_id = Some(request_id.to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum PreparedResourceSource {
|
||||
Single {
|
||||
data: Option<Vec<u8>>,
|
||||
options: ResourceOptions,
|
||||
purpose: ResourcePurpose,
|
||||
},
|
||||
Split {
|
||||
source: Box<dyn ResourceSource>,
|
||||
options: ResourceOptions,
|
||||
purpose: ResourcePurpose,
|
||||
data_size: usize,
|
||||
metadata_wire_size: usize,
|
||||
original_hash: [u8; 32],
|
||||
total_segments: usize,
|
||||
next_segment: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl PreparedResourceSource {
|
||||
pub(crate) fn prepare<S>(
|
||||
source: S,
|
||||
options: ResourceOptions,
|
||||
) -> Result<Self, ResourceSourceError>
|
||||
where
|
||||
S: ResourceSource + 'static,
|
||||
{
|
||||
Self::prepare_with_purpose(source, options, ResourcePurpose::Ordinary)
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_request<S>(
|
||||
source: S,
|
||||
request_id: [u8; 16],
|
||||
) -> Result<Self, ResourceSourceError>
|
||||
where
|
||||
S: ResourceSource + 'static,
|
||||
{
|
||||
Self::prepare_with_purpose(
|
||||
source,
|
||||
ResourceOptions::default(),
|
||||
ResourcePurpose::Request(request_id),
|
||||
)
|
||||
}
|
||||
|
||||
fn prepare_with_purpose<S>(
|
||||
mut source: S,
|
||||
options: ResourceOptions,
|
||||
purpose: ResourcePurpose,
|
||||
) -> Result<Self, ResourceSourceError>
|
||||
where
|
||||
S: ResourceSource + 'static,
|
||||
{
|
||||
let data_size = source.seek(SeekFrom::End(0))?;
|
||||
if data_size > MAX_RESOURCE_SIZE as u64 {
|
||||
return Err(ResourceSourceError::TooLarge);
|
||||
}
|
||||
source.seek(SeekFrom::Start(0))?;
|
||||
let data_size = data_size as usize;
|
||||
let metadata_wire_size = options
|
||||
.metadata
|
||||
.as_ref()
|
||||
.map(|metadata| 3usize.saturating_add(metadata.len()))
|
||||
.unwrap_or(0);
|
||||
|
||||
if metadata_wire_size.saturating_add(data_size) <= MAX_EFFICIENT_SIZE {
|
||||
let mut data = Vec::with_capacity(data_size);
|
||||
source.read_to_end(&mut data)?;
|
||||
return Ok(Self::Single {
|
||||
data: Some(data),
|
||||
options,
|
||||
purpose,
|
||||
});
|
||||
}
|
||||
|
||||
if metadata_wire_size > MAX_EFFICIENT_SIZE {
|
||||
return Err(ResourceSourceError::Protocol(
|
||||
ResourceError::MetadataTooLarge,
|
||||
));
|
||||
}
|
||||
let first_payload_size = MAX_EFFICIENT_SIZE - metadata_wire_size;
|
||||
let first_len = data_size.min(first_payload_size);
|
||||
let remaining = data_size.saturating_sub(first_len);
|
||||
let total_segments = 1 + remaining.div_ceil(MAX_EFFICIENT_SIZE);
|
||||
if total_segments > MAX_SEGMENTS {
|
||||
return Err(ResourceSourceError::TooManySegments);
|
||||
}
|
||||
|
||||
let random_hash: [u8; 4] = rns_crypto::random::random_bytes(4)
|
||||
.try_into()
|
||||
.expect("fixed random-hash length");
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let read = source.read(&mut buffer)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..read]);
|
||||
}
|
||||
hasher.update(random_hash);
|
||||
let original_hash = hasher.finalize().into();
|
||||
source.seek(SeekFrom::Start(0))?;
|
||||
|
||||
Ok(Self::Split {
|
||||
source: Box::new(source),
|
||||
options,
|
||||
purpose,
|
||||
data_size,
|
||||
metadata_wire_size,
|
||||
original_hash,
|
||||
total_segments,
|
||||
next_segment: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn next_segment(
|
||||
&mut self,
|
||||
keys: &LinkKeys,
|
||||
rtt: Duration,
|
||||
) -> Result<Option<PreparedResourceSegment>, ResourceSourceError> {
|
||||
let encrypt = |plaintext: &[u8]| {
|
||||
rns_link::encryption::link_encrypt(keys, plaintext)
|
||||
.unwrap_or_else(|_| plaintext.to_vec())
|
||||
};
|
||||
|
||||
match self {
|
||||
Self::Single {
|
||||
data,
|
||||
options,
|
||||
purpose,
|
||||
} => {
|
||||
let Some(data) = data.take() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let data_size = data.len();
|
||||
let resource = OutboundResource::with_options(
|
||||
data,
|
||||
options.auto_compress,
|
||||
options.metadata.take(),
|
||||
None,
|
||||
Some(&encrypt),
|
||||
)?;
|
||||
let mut resource = resource;
|
||||
purpose.apply(&mut resource);
|
||||
let logical_hash = resource.resource_hash;
|
||||
Ok(Some(PreparedResourceSegment {
|
||||
transfer: OutboundTransfer::from_prebuilt(resource, rtt),
|
||||
logical_hash,
|
||||
segment_index: 1,
|
||||
total_segments: 1,
|
||||
data_size,
|
||||
segment_data_size: data_size,
|
||||
}))
|
||||
}
|
||||
Self::Split {
|
||||
source,
|
||||
options,
|
||||
purpose,
|
||||
data_size,
|
||||
metadata_wire_size,
|
||||
original_hash,
|
||||
total_segments,
|
||||
next_segment,
|
||||
} => {
|
||||
if *next_segment >= *total_segments {
|
||||
return Ok(None);
|
||||
}
|
||||
let segment_index = *next_segment + 1;
|
||||
let metadata = if segment_index == 1 {
|
||||
options.metadata.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let segment_metadata_wire_size = metadata
|
||||
.as_ref()
|
||||
.map(|value| 3usize.saturating_add(value.len()))
|
||||
.unwrap_or(0);
|
||||
let payload_limit = if segment_index == 1 {
|
||||
MAX_EFFICIENT_SIZE - segment_metadata_wire_size
|
||||
} else {
|
||||
MAX_EFFICIENT_SIZE
|
||||
};
|
||||
let mut data = vec![0u8; payload_limit];
|
||||
let mut filled = 0;
|
||||
while filled < data.len() {
|
||||
let read = source.read(&mut data[filled..])?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
filled += read;
|
||||
}
|
||||
data.truncate(filled);
|
||||
|
||||
let mut resource = OutboundResource::with_options(
|
||||
data,
|
||||
options.auto_compress,
|
||||
metadata,
|
||||
None,
|
||||
Some(&encrypt),
|
||||
)?;
|
||||
purpose.apply(&mut resource);
|
||||
resource.flags.split = true;
|
||||
resource.segment_index = segment_index;
|
||||
resource.total_segments = *total_segments;
|
||||
resource.original_hash = Some(*original_hash);
|
||||
resource.advertisement_data_size = data_size.saturating_add(*metadata_wire_size);
|
||||
let segment_data_size = resource.data.len();
|
||||
*next_segment += 1;
|
||||
|
||||
Ok(Some(PreparedResourceSegment {
|
||||
transfer: OutboundTransfer::from_prebuilt(resource, rtt),
|
||||
logical_hash: *original_hash,
|
||||
segment_index,
|
||||
total_segments: *total_segments,
|
||||
data_size: *data_size,
|
||||
segment_data_size,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Cursor;
|
||||
|
||||
use rns_crypto::x25519::X25519PrivateKey;
|
||||
use rns_link::constants::MODE_AES256_CBC;
|
||||
use rns_link::key_derivation::LinkKeys;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn test_keys() -> LinkKeys {
|
||||
let local = X25519PrivateKey::generate();
|
||||
let remote = X25519PrivateKey::generate();
|
||||
LinkKeys::derive(&local, &remote.public_key(), &[0xA5; 16], MODE_AES256_CBC).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_source_prepares_one_segment() {
|
||||
let mut prepared = PreparedResourceSource::prepare(
|
||||
Cursor::new(b"small resource".to_vec()),
|
||||
ResourceOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let segment = prepared
|
||||
.next_segment(&test_keys(), Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(segment.total_segments, 1);
|
||||
assert_eq!(segment.segment_index, 1);
|
||||
assert_eq!(segment.data_size, b"small resource".len());
|
||||
assert_eq!(
|
||||
segment.logical_hash,
|
||||
segment.transfer.resource.resource_hash
|
||||
);
|
||||
assert!(
|
||||
prepared
|
||||
.next_segment(&test_keys(), Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_source_is_read_one_segment_at_a_time() {
|
||||
let data = vec![0x5A; MAX_EFFICIENT_SIZE + 17];
|
||||
let mut prepared =
|
||||
PreparedResourceSource::prepare(Cursor::new(data.clone()), ResourceOptions::default())
|
||||
.unwrap();
|
||||
let keys = test_keys();
|
||||
let first = prepared
|
||||
.next_segment(&keys, Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let second = prepared
|
||||
.next_segment(&keys, Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(first.total_segments, 2);
|
||||
assert_eq!(second.total_segments, 2);
|
||||
assert_eq!(first.logical_hash, second.logical_hash);
|
||||
assert_eq!(first.transfer.resource.segment_index, 1);
|
||||
assert_eq!(second.transfer.resource.segment_index, 2);
|
||||
assert_eq!(second.transfer.resource.data.len(), 17);
|
||||
assert_eq!(first.data_size, data.len());
|
||||
assert!(
|
||||
prepared
|
||||
.next_segment(&keys, Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_source_marks_every_segment_with_request_id() {
|
||||
let request_id = [0x42; 16];
|
||||
let data = vec![0xA5; MAX_EFFICIENT_SIZE + 17];
|
||||
let mut prepared =
|
||||
PreparedResourceSource::prepare_request(Cursor::new(data), request_id).unwrap();
|
||||
let keys = test_keys();
|
||||
|
||||
for expected_segment in 1..=2 {
|
||||
let segment = prepared
|
||||
.next_segment(&keys, Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(segment.segment_index, expected_segment);
|
||||
assert!(segment.transfer.resource.flags.is_request);
|
||||
assert!(!segment.transfer.resource.flags.is_response);
|
||||
assert_eq!(
|
||||
segment.transfer.resource.request_id.as_deref(),
|
||||
Some(request_id.as_slice())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+7745
-401
File diff suppressed because it is too large.
Load diff
@@ -23,9 +23,9 @@ use rns_link::link::{CloseReason, Link};
|
||||
use rns_protocol::channel::{ChannelError, LinkChannel};
|
||||
use rns_protocol::channel_message::MessageBase;
|
||||
use rns_protocol::rnsh::{
|
||||
CommandExitedMessage, ErrorMessage, ExecuteCommandMessage, NoopMessage, PROTOCOL_VERSION,
|
||||
RnshMessage, RnshStreamDataMessage, STREAM_ID_STDERR, STREAM_ID_STDIN, STREAM_ID_STDOUT,
|
||||
VersionInfoMessage, WindowSizeMessage,
|
||||
CommandExitedMessage, ErrorMessage, ExecuteCommandMessage, MESSAGE_TYPES, NoopMessage,
|
||||
PROTOCOL_VERSION, RnshMessage, RnshStreamDataMessage, STREAM_ID_STDERR, STREAM_ID_STDIN,
|
||||
STREAM_ID_STDOUT, VersionInfoMessage, WindowSizeMessage,
|
||||
};
|
||||
use rns_transport::link_messages::DestinationEvent;
|
||||
use rns_transport::messages::{
|
||||
@@ -171,6 +171,9 @@ async fn run_rnsh_listener_inner(
|
||||
RNSH_APP_NAME,
|
||||
Some(signing_key),
|
||||
);
|
||||
for msg_type in MESSAGE_TYPES {
|
||||
link_mgr.register_channel_message_type(msg_type)?;
|
||||
}
|
||||
|
||||
let announce_tx = transport_tx.clone();
|
||||
let announce_packet = build_announce_packet(&cfg.identity, RNSH_APP_NAME)?;
|
||||
@@ -191,17 +194,6 @@ async fn run_rnsh_listener_inner(
|
||||
link_mgr.set_link_identified_channel(identified_tx);
|
||||
link_mgr.set_link_closed_channel(closed_tx);
|
||||
|
||||
// Defense in depth: in authenticated mode, reject unallowed identities
|
||||
// synchronously at the link layer (as rncp does), so the manager tears the
|
||||
// link down at identify time in addition to the handler-level allow-check
|
||||
// below. allow_all installs no gate.
|
||||
if !cfg.allow_all {
|
||||
let allowed = listener_allowed_identities(&cfg);
|
||||
link_mgr.set_link_identity_gate(move |_link_id, identity_hash| {
|
||||
allowed.contains(&identity_hash)
|
||||
});
|
||||
}
|
||||
|
||||
let manager_task = tokio::spawn(async move {
|
||||
link_mgr.run_with_commands(command_rx).await;
|
||||
});
|
||||
@@ -259,11 +251,11 @@ async fn run_rnsh_listener_inner(
|
||||
link_id,
|
||||
ErrorMessage::new(Some("Identity is not allowed.".into()), true, None),
|
||||
).await?;
|
||||
let _ = command_tx.send(LinkManagerCommand::CloseLink {
|
||||
link_id,
|
||||
reason: CloseReason::DestinationClosed,
|
||||
send_teardown: true,
|
||||
}).await;
|
||||
// Keep the already-closed session around just long enough
|
||||
// for the peer to receive the protocol-level denial. The
|
||||
// channel-message gate drops every subsequent message, so
|
||||
// this grace period cannot advance or run the session.
|
||||
close_link_after_error(command_tx.clone(), link_id);
|
||||
}
|
||||
}
|
||||
maybe_closed = closed_rx.recv() => {
|
||||
@@ -405,7 +397,9 @@ pub async fn rnsh_client_execute(
|
||||
let session_keys = link
|
||||
.session_keys()
|
||||
.ok_or_else(|| RnshError::LinkCrypto("no session keys".into()))?;
|
||||
let mut channel = LinkChannel::new_encrypted(link_id, link.rtt_secs(), session_keys);
|
||||
let mut channel =
|
||||
LinkChannel::new_encrypted_with_mdu(link_id, link.rtt_secs(), link.mdu, session_keys);
|
||||
register_rnsh_message_types(&mut channel)?;
|
||||
link.mark_channel_created();
|
||||
let mut pending_messages = VecDeque::new();
|
||||
let mut stdout = Vec::new();
|
||||
@@ -515,6 +509,13 @@ pub async fn rnsh_client_execute(
|
||||
})
|
||||
}
|
||||
|
||||
fn register_rnsh_message_types(channel: &mut LinkChannel) -> Result<(), ChannelError> {
|
||||
for msg_type in MESSAGE_TYPES {
|
||||
channel.register_message_type(msg_type)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pending_has_remote_terminal(pending_messages: &VecDeque<RnshMessage>) -> bool {
|
||||
pending_messages.iter().any(|message| {
|
||||
matches!(
|
||||
@@ -1555,6 +1556,7 @@ async fn resend_timed_out_client_channel_messages(
|
||||
link: &mut Link,
|
||||
channel: &mut LinkChannel,
|
||||
) -> Result<(), RnshError> {
|
||||
channel.update_rtt(link.rtt_secs());
|
||||
for sequence in channel.timed_out_sequences() {
|
||||
let Some(data) = channel.timeout(sequence)? else {
|
||||
continue;
|
||||
@@ -1997,6 +1999,21 @@ mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[test]
|
||||
fn rnsh_channel_registration_accepts_every_protocol_type() {
|
||||
let mut channel = LinkChannel::new([0xA2; 16], 0.1);
|
||||
register_rnsh_message_types(&mut channel).unwrap();
|
||||
|
||||
for (sequence, msg_type) in MESSAGE_TYPES.into_iter().enumerate() {
|
||||
let mut envelope = Vec::with_capacity(6);
|
||||
envelope.extend_from_slice(&msg_type.to_be_bytes());
|
||||
envelope.extend_from_slice(&(sequence as u16).to_be_bytes());
|
||||
envelope.extend_from_slice(&0u16.to_be_bytes());
|
||||
let received = channel.receive_data(&envelope).unwrap();
|
||||
assert_eq!(received, vec![(msg_type, Vec::new())]);
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_ack_manager(
|
||||
mut rx: mpsc::Receiver<LinkManagerCommand>,
|
||||
messages: Arc<Mutex<Vec<RnshMessage>>>,
|
||||
|
||||
@@ -171,6 +171,8 @@ pub struct InterfaceStatEntry {
|
||||
#[serde(default)]
|
||||
pub pr_burst_activated: f64,
|
||||
pub clients: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blocked_ips: Option<u64>,
|
||||
pub announce_rate_target: Option<f64>,
|
||||
pub announce_rate_grace: Option<u32>,
|
||||
pub announce_rate_penalty: Option<f64>,
|
||||
@@ -513,7 +515,7 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
|
||||
let interfaces = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
py_dict(vec![
|
||||
let mut fields = vec![
|
||||
("id", PyValue::Int(i128::from(e.id))),
|
||||
("name", PyValue::String(e.name.clone())),
|
||||
("short_name", PyValue::String(e.name.clone())),
|
||||
@@ -564,7 +566,11 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
|
||||
.unwrap_or(PyValue::None),
|
||||
),
|
||||
("tx_drops", PyValue::Int(i128::from(e.tx_drops))),
|
||||
])
|
||||
];
|
||||
if let Some(blocked_ips) = e.blocked_ips {
|
||||
fields.push(("blocked_ips", PyValue::Int(i128::from(blocked_ips))));
|
||||
}
|
||||
py_dict(fields)
|
||||
})
|
||||
.collect();
|
||||
let rxb = entries.iter().map(|e| e.rx_bytes).sum::<u64>();
|
||||
@@ -670,6 +676,10 @@ fn py_value_to_response_for_request(
|
||||
value: &PyValue,
|
||||
request: &RpcRequest,
|
||||
) -> Result<RpcResponse, RpcError> {
|
||||
if matches!(value, PyValue::Dict(entries) if dict_get(entries, "error").is_some()) {
|
||||
return py_value_to_response(value);
|
||||
}
|
||||
|
||||
match request {
|
||||
RpcRequest::GetPathTable { .. } => Ok(RpcResponse::PathTable(parse_path_table(value)?)),
|
||||
RpcRequest::GetInterfaceStats => {
|
||||
@@ -836,6 +846,10 @@ fn parse_interface_stats(value: &PyValue) -> Result<Vec<InterfaceStatEntry>, Rpc
|
||||
Some(PyValue::None) | None => None,
|
||||
Some(value) => py_u64(value),
|
||||
},
|
||||
blocked_ips: match dict_get(m, "blocked_ips") {
|
||||
Some(PyValue::None) | None => None,
|
||||
Some(value) => py_u64(value),
|
||||
},
|
||||
announce_rate_target: dict_get(m, "announce_rate_target").and_then(py_f64),
|
||||
announce_rate_grace: dict_get(m, "announce_rate_grace").and_then(py_u32),
|
||||
announce_rate_penalty: dict_get(m, "announce_rate_penalty").and_then(py_f64),
|
||||
@@ -1684,6 +1698,19 @@ pub enum RpcError {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn contains_string_key(value: &PyValue, expected: &str) -> bool {
|
||||
match value {
|
||||
PyValue::List(values) => values
|
||||
.iter()
|
||||
.any(|value| contains_string_key(value, expected)),
|
||||
PyValue::Dict(entries) => entries.iter().any(|(key, value)| {
|
||||
matches!(key, PyDictKey::String(key) if key == expected)
|
||||
|| contains_string_key(value, expected)
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_request_roundtrip() {
|
||||
let req = RpcRequest::GetPathTable { max_hops: Some(8) };
|
||||
@@ -1752,6 +1779,7 @@ mod tests {
|
||||
pr_burst_active: true,
|
||||
pr_burst_activated: 1_700_000_002.0,
|
||||
clients: Some(4),
|
||||
blocked_ips: Some(2),
|
||||
announce_rate_target: Some(3600.0),
|
||||
announce_rate_grace: Some(5),
|
||||
announce_rate_penalty: Some(30.0),
|
||||
@@ -1777,6 +1805,7 @@ mod tests {
|
||||
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);
|
||||
assert_eq!(entry.blocked_ips, Some(2));
|
||||
}
|
||||
_ => panic!("wrong variant"),
|
||||
}
|
||||
@@ -1806,11 +1835,69 @@ mod tests {
|
||||
assert_eq!(entry.burst_activated, 0.0);
|
||||
assert!(!entry.pr_burst_active);
|
||||
assert_eq!(entry.pr_burst_activated, 0.0);
|
||||
assert_eq!(entry.blocked_ips, None);
|
||||
assert_eq!(entry.mtu, 0, "Python stats omit MTU");
|
||||
}
|
||||
_ => panic!("wrong variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_specific_decoder_preserves_rpc_errors() {
|
||||
let encoded = encode_response(&RpcResponse::Error("transport unavailable".to_string()))
|
||||
.expect("encode RPC error");
|
||||
for request in [
|
||||
RpcRequest::GetPathTable { max_hops: None },
|
||||
RpcRequest::DropPath {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
] {
|
||||
assert!(matches!(
|
||||
decode_response_for_request(&encoded, &request),
|
||||
Ok(RpcResponse::Error(message)) if message == "transport unavailable"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_stats_omit_absent_blocked_ip_count() {
|
||||
let mut entry = interface_stat_entry();
|
||||
entry.blocked_ips = None;
|
||||
let encoded = encode_response(&RpcResponse::InterfaceStats(vec![entry])).unwrap();
|
||||
let raw = decode_umsgpack(&encoded).unwrap();
|
||||
assert!(!contains_string_key(&raw, "blocked_ips"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_stats_ignore_blocked_ip_lists_and_never_reencode_them() {
|
||||
let upstream = py_dict(vec![(
|
||||
"interfaces",
|
||||
PyValue::List(vec![py_dict(vec![
|
||||
("name", PyValue::String("Backbone".to_string())),
|
||||
("rxb", PyValue::Int(1)),
|
||||
("txb", PyValue::Int(2)),
|
||||
("status", PyValue::Bool(true)),
|
||||
("blocked_ips", PyValue::Int(3)),
|
||||
(
|
||||
"blocked_ip_list",
|
||||
PyValue::List(vec![PyValue::String("192.0.2.1".to_string())]),
|
||||
),
|
||||
])]),
|
||||
)]);
|
||||
let encoded = encode_umsgpack(&upstream).unwrap();
|
||||
let decoded =
|
||||
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap();
|
||||
let RpcResponse::InterfaceStats(entries) = &decoded else {
|
||||
panic!("unexpected interface stats response");
|
||||
};
|
||||
assert_eq!(entries[0].blocked_ips, Some(3));
|
||||
|
||||
let reencoded = encode_response(&decoded).unwrap();
|
||||
let raw = decode_umsgpack(&reencoded).unwrap();
|
||||
assert!(contains_string_key(&raw, "blocked_ips"));
|
||||
assert!(!contains_string_key(&raw, "blocked_ip_list"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_python_blackhole_dict_response_shape() {
|
||||
let identity_hash = vec![0x42; 16];
|
||||
|
||||
@@ -220,16 +220,56 @@ async fn handle_rpc_client(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const TRANSPORT_QUERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum TransportQueryFailure {
|
||||
SendTimedOut,
|
||||
ChannelClosed,
|
||||
ResponseTimedOut,
|
||||
ResponseClosed,
|
||||
}
|
||||
|
||||
impl TransportQueryFailure {
|
||||
fn description(self) -> &'static str {
|
||||
match self {
|
||||
Self::SendTimedOut => "request enqueue timed out",
|
||||
Self::ChannelClosed => "query channel is closed",
|
||||
Self::ResponseTimedOut => "response timed out",
|
||||
Self::ResponseClosed => "response channel closed without an answer",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn transport_failure_response(
|
||||
operation: &'static str,
|
||||
failure: TransportQueryFailure,
|
||||
) -> RpcResponse {
|
||||
RpcResponse::Error(format!(
|
||||
"transport actor failed {operation}: {}",
|
||||
failure.description()
|
||||
))
|
||||
}
|
||||
|
||||
fn unexpected_transport_response(operation: &'static str) -> RpcResponse {
|
||||
RpcResponse::Error(format!(
|
||||
"transport actor returned an unexpected response to {operation}"
|
||||
))
|
||||
}
|
||||
|
||||
fn invalid_request_hash(kind: &'static str) -> RpcResponse {
|
||||
RpcResponse::Error(format!("invalid {kind} hash in RPC request"))
|
||||
}
|
||||
|
||||
/// 5 s cap so a wedged actor can't hold a client open indefinitely.
|
||||
async fn query_transport(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
query: rns_transport::messages::TransportQuery,
|
||||
) -> Option<rns_transport::messages::TransportQueryResponse> {
|
||||
) -> Result<rns_transport::messages::TransportQueryResponse, TransportQueryFailure> {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
let budget = std::time::Duration::from_secs(5);
|
||||
let started = std::time::Instant::now();
|
||||
match tokio::time::timeout(
|
||||
budget,
|
||||
TRANSPORT_QUERY_BUDGET,
|
||||
transport_tx.send(TransportMessage::Rpc {
|
||||
query,
|
||||
response_tx: tx,
|
||||
@@ -238,45 +278,57 @@ async fn query_transport(
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(_)) => return None,
|
||||
Err(_) => return None,
|
||||
Ok(Err(_)) => return Err(TransportQueryFailure::ChannelClosed),
|
||||
Err(_) => return Err(TransportQueryFailure::SendTimedOut),
|
||||
}
|
||||
let remaining = TRANSPORT_QUERY_BUDGET
|
||||
.checked_sub(started.elapsed())
|
||||
.ok_or(TransportQueryFailure::ResponseTimedOut)?;
|
||||
match tokio::time::timeout(remaining, rx).await {
|
||||
Ok(Ok(response)) => Ok(response),
|
||||
Ok(Err(_)) => Err(TransportQueryFailure::ResponseClosed),
|
||||
Err(_) => Err(TransportQueryFailure::ResponseTimedOut),
|
||||
}
|
||||
let remaining = budget.checked_sub(started.elapsed())?;
|
||||
tokio::time::timeout(remaining, rx)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|r| r.ok())
|
||||
}
|
||||
|
||||
async fn request_path(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
destination_hash: [u8; 16],
|
||||
timeout_secs: Option<f64>,
|
||||
) -> bool {
|
||||
) -> Result<bool, TransportQueryFailure> {
|
||||
let wait = std::time::Duration::from_secs_f64(timeout_secs.unwrap_or(5.0).max(0.1));
|
||||
if transport_tx
|
||||
.send(TransportMessage::RequestPath { destination_hash })
|
||||
.await
|
||||
.is_err()
|
||||
match tokio::time::timeout(
|
||||
TRANSPORT_QUERY_BUDGET,
|
||||
transport_tx.send(TransportMessage::RequestPath { destination_hash }),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return false;
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(_)) => return Err(TransportQueryFailure::ChannelClosed),
|
||||
Err(_) => return Err(TransportQueryFailure::SendTimedOut),
|
||||
}
|
||||
|
||||
let (reply, rx) = tokio::sync::oneshot::channel();
|
||||
if transport_tx
|
||||
.send(TransportMessage::AwaitPath {
|
||||
match tokio::time::timeout(
|
||||
TRANSPORT_QUERY_BUDGET,
|
||||
transport_tx.send(TransportMessage::AwaitPath {
|
||||
dest: destination_hash,
|
||||
reply,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return false;
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(_)) => return Err(TransportQueryFailure::ChannelClosed),
|
||||
Err(_) => return Err(TransportQueryFailure::SendTimedOut),
|
||||
}
|
||||
|
||||
match tokio::time::timeout(wait, rx).await {
|
||||
Ok(Ok(found)) => found,
|
||||
_ => false,
|
||||
Ok(Ok(found)) => Ok(found),
|
||||
Ok(Err(_)) => Err(TransportQueryFailure::ResponseClosed),
|
||||
// This is the caller-selected path-discovery deadline, so an intact
|
||||
// actor that simply did not discover a path reports `false`.
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,10 +338,19 @@ async fn process_rpc_request(
|
||||
) -> RpcResponse {
|
||||
use rns_transport::messages::{TransportQuery, TransportQueryResponse};
|
||||
|
||||
macro_rules! authoritative_query {
|
||||
($query:expr, $operation:literal) => {
|
||||
match query_transport(transport_tx, $query).await {
|
||||
Ok(response) => response,
|
||||
Err(failure) => return transport_failure_response($operation, failure),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
match request {
|
||||
RpcRequest::GetPathTable { max_hops } => {
|
||||
match query_transport(transport_tx, TransportQuery::GetPathTable).await {
|
||||
Some(TransportQueryResponse::PathTable(entries)) => {
|
||||
match authoritative_query!(TransportQuery::GetPathTable, "path table query") {
|
||||
TransportQueryResponse::PathTable(entries) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.filter(|e| max_hops.is_none_or(|max| e.hops <= max))
|
||||
@@ -304,12 +365,12 @@ async fn process_rpc_request(
|
||||
.collect();
|
||||
RpcResponse::PathTable(rpc_entries)
|
||||
}
|
||||
_ => RpcResponse::PathTable(Vec::new()),
|
||||
_ => unexpected_transport_response("path table query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetInterfaceStats => {
|
||||
match query_transport(transport_tx, TransportQuery::GetInterfaceStats).await {
|
||||
Some(TransportQueryResponse::InterfaceStats(entries)) => {
|
||||
match authoritative_query!(TransportQuery::GetInterfaceStats, "interface stats query") {
|
||||
TransportQueryResponse::InterfaceStats(entries) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.map(|e| rpc::InterfaceStatEntry {
|
||||
@@ -335,6 +396,7 @@ async fn process_rpc_request(
|
||||
pr_burst_active: e.pr_burst_active,
|
||||
pr_burst_activated: e.pr_burst_activated,
|
||||
clients: e.clients,
|
||||
blocked_ips: e.blocked_ips,
|
||||
announce_rate_target: e.announce_rate_target,
|
||||
announce_rate_grace: e.announce_rate_grace,
|
||||
announce_rate_penalty: e.announce_rate_penalty,
|
||||
@@ -345,14 +407,12 @@ async fn process_rpc_request(
|
||||
.collect();
|
||||
RpcResponse::InterfaceStats(rpc_entries)
|
||||
}
|
||||
_ => RpcResponse::Error(
|
||||
"transport actor did not answer interface stats query".to_string(),
|
||||
),
|
||||
_ => unexpected_transport_response("interface stats query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetRateTable => {
|
||||
match query_transport(transport_tx, TransportQuery::GetRateTable).await {
|
||||
Some(TransportQueryResponse::RateTable(entries)) => {
|
||||
match authoritative_query!(TransportQuery::GetRateTable, "rate table query") {
|
||||
TransportQueryResponse::RateTable(entries) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.map(|e| rpc::RateTableEntry {
|
||||
@@ -366,266 +426,266 @@ async fn process_rpc_request(
|
||||
.collect();
|
||||
RpcResponse::RateTable(rpc_entries)
|
||||
}
|
||||
_ => RpcResponse::RateTable(Vec::new()),
|
||||
_ => unexpected_transport_response("rate table query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetLinkCount => {
|
||||
match query_transport(transport_tx, TransportQuery::GetLinkCount).await {
|
||||
Some(TransportQueryResponse::IntResult(n)) => RpcResponse::IntResult(n),
|
||||
_ => RpcResponse::IntResult(0),
|
||||
match authoritative_query!(TransportQuery::GetLinkCount, "link count query") {
|
||||
TransportQueryResponse::IntResult(n) => RpcResponse::IntResult(n),
|
||||
_ => unexpected_transport_response("link count query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetNextHopIfName { destination_hash } => {
|
||||
let dest = hash_to_array(&destination_hash);
|
||||
match dest {
|
||||
Some(d) => {
|
||||
match query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::GetNextHopIfName { dest: d },
|
||||
)
|
||||
.await
|
||||
{
|
||||
Some(TransportQueryResponse::StringResult(s)) => {
|
||||
RpcResponse::StringResult(s)
|
||||
}
|
||||
_ => RpcResponse::StringResult(None),
|
||||
}
|
||||
}
|
||||
None => RpcResponse::StringResult(None),
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::GetNextHopIfName { dest },
|
||||
"next-hop interface query"
|
||||
) {
|
||||
TransportQueryResponse::StringResult(name) => RpcResponse::StringResult(name),
|
||||
_ => unexpected_transport_response("next-hop interface query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetNextHop { destination_hash } => {
|
||||
let dest = hash_to_array(&destination_hash);
|
||||
match dest {
|
||||
Some(d) => {
|
||||
match query_transport(transport_tx, TransportQuery::GetNextHop { dest: d })
|
||||
.await
|
||||
{
|
||||
Some(TransportQueryResponse::HashResult(h)) => {
|
||||
RpcResponse::HashResult(h.map(|a| a.to_vec()))
|
||||
}
|
||||
_ => RpcResponse::HashResult(None),
|
||||
}
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(TransportQuery::GetNextHop { dest }, "next-hop query") {
|
||||
TransportQueryResponse::HashResult(hash) => {
|
||||
RpcResponse::HashResult(hash.map(|hash| hash.to_vec()))
|
||||
}
|
||||
None => RpcResponse::HashResult(None),
|
||||
_ => unexpected_transport_response("next-hop query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash,
|
||||
timeout_secs,
|
||||
} => match hash_to_array(&destination_hash) {
|
||||
Some(dest) => {
|
||||
RpcResponse::BoolResult(request_path(transport_tx, dest, timeout_secs).await)
|
||||
} => {
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match request_path(transport_tx, dest, timeout_secs).await {
|
||||
Ok(found) => RpcResponse::BoolResult(found),
|
||||
Err(failure) => transport_failure_response("path request", failure),
|
||||
}
|
||||
None => RpcResponse::BoolResult(false),
|
||||
},
|
||||
}
|
||||
RpcRequest::DropPath { destination_hash } => {
|
||||
let dest = hash_to_array(&destination_hash);
|
||||
if let Some(d) = dest {
|
||||
let _ = query_transport(transport_tx, TransportQuery::DropPath { dest: d }).await;
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(TransportQuery::DropPath { dest }, "path drop") {
|
||||
TransportQueryResponse::Ok => RpcResponse::Ok,
|
||||
_ => unexpected_transport_response("path drop"),
|
||||
}
|
||||
RpcResponse::Ok
|
||||
}
|
||||
RpcRequest::DropPathTable => {
|
||||
if let Some(TransportQueryResponse::IntResult(n)) =
|
||||
query_transport(transport_tx, TransportQuery::DropPathTable).await
|
||||
{
|
||||
return RpcResponse::IntResult(n);
|
||||
match authoritative_query!(TransportQuery::DropPathTable, "path table drop") {
|
||||
TransportQueryResponse::IntResult(n) => RpcResponse::IntResult(n),
|
||||
_ => unexpected_transport_response("path table drop"),
|
||||
}
|
||||
RpcResponse::IntResult(0)
|
||||
}
|
||||
RpcRequest::DropRecentAnnounces => {
|
||||
if let Some(TransportQueryResponse::IntResult(n)) =
|
||||
query_transport(transport_tx, TransportQuery::DropRecentAnnounces).await
|
||||
match authoritative_query!(TransportQuery::DropRecentAnnounces, "recent announces drop")
|
||||
{
|
||||
return RpcResponse::IntResult(n);
|
||||
TransportQueryResponse::IntResult(n) => RpcResponse::IntResult(n),
|
||||
_ => unexpected_transport_response("recent announces drop"),
|
||||
}
|
||||
RpcResponse::IntResult(0)
|
||||
}
|
||||
RpcRequest::DropAnnounceQueues => {
|
||||
let _ = query_transport(transport_tx, TransportQuery::DropAnnounceQueues).await;
|
||||
RpcResponse::Ok
|
||||
}
|
||||
RpcRequest::GetBlackholedIdentities => {
|
||||
match query_transport(transport_tx, TransportQuery::GetBlackholedIdentities).await {
|
||||
Some(TransportQueryResponse::BlackholeList(entries)) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.map(|e| rpc::BlackholeEntry {
|
||||
identity_hash: e.identity_hash.to_vec(),
|
||||
source: e.source.map(|source| source.to_vec()),
|
||||
// Wire compat: `until` is absolute expiry (created + ttl);
|
||||
// permanent entries report `None`.
|
||||
until: e.ttl.map(|t| e.created + t),
|
||||
reason: Some(
|
||||
e.reason_label
|
||||
.unwrap_or_else(|| e.reason.as_str().to_string()),
|
||||
),
|
||||
})
|
||||
.collect();
|
||||
RpcResponse::BlackholeList(rpc_entries)
|
||||
}
|
||||
_ => RpcResponse::BlackholeList(Vec::new()),
|
||||
match authoritative_query!(TransportQuery::DropAnnounceQueues, "announce queue drop") {
|
||||
TransportQueryResponse::Ok => RpcResponse::Ok,
|
||||
_ => unexpected_transport_response("announce queue drop"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetBlackholedIdentities => match authoritative_query!(
|
||||
TransportQuery::GetBlackholedIdentities,
|
||||
"blackholed identity query"
|
||||
) {
|
||||
TransportQueryResponse::BlackholeList(entries) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.map(|e| rpc::BlackholeEntry {
|
||||
identity_hash: e.identity_hash.to_vec(),
|
||||
source: e.source.map(|source| source.to_vec()),
|
||||
// Wire compat: `until` is absolute expiry (created + ttl);
|
||||
// permanent entries report `None`.
|
||||
until: e.ttl.map(|t| e.created + t),
|
||||
reason: Some(
|
||||
e.reason_label
|
||||
.unwrap_or_else(|| e.reason.as_str().to_string()),
|
||||
),
|
||||
})
|
||||
.collect();
|
||||
RpcResponse::BlackholeList(rpc_entries)
|
||||
}
|
||||
_ => unexpected_transport_response("blackholed identity query"),
|
||||
},
|
||||
RpcRequest::IsBlackholed { identity_hash } => {
|
||||
if let Some(hash) = hash_to_array(&identity_hash) {
|
||||
if let Some(TransportQueryResponse::BoolResult(v)) =
|
||||
query_transport(transport_tx, TransportQuery::IsBlackholed { hash }).await
|
||||
{
|
||||
return RpcResponse::BoolResult(v);
|
||||
}
|
||||
let Some(hash) = hash_to_array(&identity_hash) else {
|
||||
return invalid_request_hash("identity");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::IsBlackholed { hash },
|
||||
"blackhole status query"
|
||||
) {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("blackhole status query"),
|
||||
}
|
||||
RpcResponse::BoolResult(false)
|
||||
}
|
||||
RpcRequest::BlackholeIdentity {
|
||||
identity_hash,
|
||||
until,
|
||||
reason,
|
||||
} => {
|
||||
if let Some(h) = hash_to_array(&identity_hash) {
|
||||
// `until` (absolute unix ts) → relative TTL; past timestamps
|
||||
// clamp to ~0 so the entry expires on the next maintenance tick.
|
||||
let ttl = until.map(|u| {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
(u - now).max(0.001)
|
||||
});
|
||||
let reason_enum = reason
|
||||
.as_deref()
|
||||
.map(rns_transport::blackhole::BlackholeReason::parse)
|
||||
.unwrap_or_default();
|
||||
let _ = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::BlackholeIdentity {
|
||||
hash: h,
|
||||
ttl,
|
||||
reason: reason_enum,
|
||||
reason_label: reason,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let Some(hash) = hash_to_array(&identity_hash) else {
|
||||
return invalid_request_hash("identity");
|
||||
};
|
||||
// `until` (absolute unix ts) → relative TTL; past timestamps
|
||||
// clamp to ~0 so the entry expires on the next maintenance tick.
|
||||
let ttl = until.map(|until| {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
(until - now).max(0.001)
|
||||
});
|
||||
let reason_enum = reason
|
||||
.as_deref()
|
||||
.map(rns_transport::blackhole::BlackholeReason::parse)
|
||||
.unwrap_or_default();
|
||||
match authoritative_query!(
|
||||
TransportQuery::BlackholeIdentity {
|
||||
hash,
|
||||
ttl,
|
||||
reason: reason_enum,
|
||||
reason_label: reason,
|
||||
},
|
||||
"identity blackhole"
|
||||
) {
|
||||
TransportQueryResponse::Ok => RpcResponse::Ok,
|
||||
_ => unexpected_transport_response("identity blackhole"),
|
||||
}
|
||||
RpcResponse::Ok
|
||||
}
|
||||
RpcRequest::UnblackholeIdentity { identity_hash } => {
|
||||
if let Some(h) = hash_to_array(&identity_hash) {
|
||||
let _ = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::UnblackholeIdentity { hash: h },
|
||||
)
|
||||
.await;
|
||||
let Some(hash) = hash_to_array(&identity_hash) else {
|
||||
return invalid_request_hash("identity");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::UnblackholeIdentity { hash },
|
||||
"identity unblackhole"
|
||||
) {
|
||||
// Python's mutation response is success-shaped even when the
|
||||
// identity was not present; the typed actor result proves the
|
||||
// mutation was authoritatively processed.
|
||||
TransportQueryResponse::BoolResult(_) => RpcResponse::Ok,
|
||||
_ => unexpected_transport_response("identity unblackhole"),
|
||||
}
|
||||
RpcResponse::Ok
|
||||
}
|
||||
RpcRequest::GetFirstHopTimeout { destination_hash } => {
|
||||
let dest = hash_to_array(&destination_hash);
|
||||
match dest {
|
||||
Some(d) => {
|
||||
match query_transport(transport_tx, TransportQuery::FirstHopTimeout { dest: d })
|
||||
.await
|
||||
{
|
||||
Some(TransportQueryResponse::FloatResult(v)) => RpcResponse::FloatResult(v),
|
||||
_ => RpcResponse::FloatResult(None),
|
||||
}
|
||||
}
|
||||
None => RpcResponse::FloatResult(None),
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::FirstHopTimeout { dest },
|
||||
"first-hop timeout query"
|
||||
) {
|
||||
TransportQueryResponse::FloatResult(value) => RpcResponse::FloatResult(value),
|
||||
_ => unexpected_transport_response("first-hop timeout query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetPacketRssi { packet_hash } => {
|
||||
if let Some(hash) = packet_hash_to_array(&packet_hash) {
|
||||
if let Some(TransportQueryResponse::FloatResult(v)) = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::GetPacketRssi { packet_hash: hash },
|
||||
)
|
||||
.await
|
||||
{
|
||||
return RpcResponse::FloatResult(v);
|
||||
}
|
||||
let Some(packet_hash) = packet_hash_to_array(&packet_hash) else {
|
||||
return invalid_request_hash("packet");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::GetPacketRssi { packet_hash },
|
||||
"packet RSSI query"
|
||||
) {
|
||||
TransportQueryResponse::FloatResult(value) => RpcResponse::FloatResult(value),
|
||||
_ => unexpected_transport_response("packet RSSI query"),
|
||||
}
|
||||
RpcResponse::FloatResult(None)
|
||||
}
|
||||
RpcRequest::GetPacketSnr { packet_hash } => {
|
||||
if let Some(hash) = packet_hash_to_array(&packet_hash) {
|
||||
if let Some(TransportQueryResponse::FloatResult(v)) = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::GetPacketSnr { packet_hash: hash },
|
||||
)
|
||||
.await
|
||||
{
|
||||
return RpcResponse::FloatResult(v);
|
||||
}
|
||||
let Some(packet_hash) = packet_hash_to_array(&packet_hash) else {
|
||||
return invalid_request_hash("packet");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::GetPacketSnr { packet_hash },
|
||||
"packet SNR query"
|
||||
) {
|
||||
TransportQueryResponse::FloatResult(value) => RpcResponse::FloatResult(value),
|
||||
_ => unexpected_transport_response("packet SNR query"),
|
||||
}
|
||||
RpcResponse::FloatResult(None)
|
||||
}
|
||||
RpcRequest::GetPacketQ { packet_hash } => {
|
||||
if let Some(hash) = packet_hash_to_array(&packet_hash) {
|
||||
if let Some(TransportQueryResponse::FloatResult(v)) = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::GetPacketQ { packet_hash: hash },
|
||||
)
|
||||
.await
|
||||
{
|
||||
return RpcResponse::FloatResult(v);
|
||||
}
|
||||
let Some(packet_hash) = packet_hash_to_array(&packet_hash) else {
|
||||
return invalid_request_hash("packet");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::GetPacketQ { packet_hash },
|
||||
"packet quality query"
|
||||
) {
|
||||
TransportQueryResponse::FloatResult(value) => RpcResponse::FloatResult(value),
|
||||
_ => unexpected_transport_response("packet quality query"),
|
||||
}
|
||||
RpcResponse::FloatResult(None)
|
||||
}
|
||||
RpcRequest::DropAllVia { transport_hash } => {
|
||||
if let Some(next_hop) = hash_to_array(&transport_hash) {
|
||||
if let Some(TransportQueryResponse::IntResult(n)) =
|
||||
query_transport(transport_tx, TransportQuery::DropAllVia { next_hop }).await
|
||||
{
|
||||
return RpcResponse::IntResult(n);
|
||||
}
|
||||
let Some(next_hop) = hash_to_array(&transport_hash) else {
|
||||
return invalid_request_hash("transport");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::DropAllVia { next_hop },
|
||||
"drop all via transport"
|
||||
) {
|
||||
TransportQueryResponse::IntResult(count) => RpcResponse::IntResult(count),
|
||||
_ => unexpected_transport_response("drop all via transport"),
|
||||
}
|
||||
RpcResponse::IntResult(0)
|
||||
}
|
||||
RpcRequest::UseDestination { destination_hash } => {
|
||||
if let Some(dest) = hash_to_array(&destination_hash) {
|
||||
if let Some(TransportQueryResponse::BoolResult(v)) =
|
||||
query_transport(transport_tx, TransportQuery::UseDestination { dest }).await
|
||||
{
|
||||
return RpcResponse::BoolResult(v);
|
||||
}
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(TransportQuery::UseDestination { dest }, "destination use") {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("destination use"),
|
||||
}
|
||||
RpcResponse::BoolResult(false)
|
||||
}
|
||||
RpcRequest::RetainDestination { destination_hash } => {
|
||||
if let Some(dest) = hash_to_array(&destination_hash) {
|
||||
if let Some(TransportQueryResponse::BoolResult(v)) =
|
||||
query_transport(transport_tx, TransportQuery::RetainDestination { dest }).await
|
||||
{
|
||||
return RpcResponse::BoolResult(v);
|
||||
}
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::RetainDestination { dest },
|
||||
"destination retention"
|
||||
) {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("destination retention"),
|
||||
}
|
||||
RpcResponse::BoolResult(false)
|
||||
}
|
||||
RpcRequest::RetainIdentity { identity_hash } => {
|
||||
if let Some(identity_hash) = hash_to_array(&identity_hash) {
|
||||
if let Some(TransportQueryResponse::BoolResult(v)) = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::RetainIdentity { identity_hash },
|
||||
)
|
||||
.await
|
||||
{
|
||||
return RpcResponse::BoolResult(v);
|
||||
}
|
||||
let Some(identity_hash) = hash_to_array(&identity_hash) else {
|
||||
return invalid_request_hash("identity");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::RetainIdentity { identity_hash },
|
||||
"identity retention"
|
||||
) {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("identity retention"),
|
||||
}
|
||||
RpcResponse::BoolResult(false)
|
||||
}
|
||||
RpcRequest::UnretainDestination { destination_hash } => {
|
||||
if let Some(dest) = hash_to_array(&destination_hash) {
|
||||
if let Some(TransportQueryResponse::BoolResult(v)) =
|
||||
query_transport(transport_tx, TransportQuery::UnretainDestination { dest })
|
||||
.await
|
||||
{
|
||||
return RpcResponse::BoolResult(v);
|
||||
}
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::UnretainDestination { dest },
|
||||
"destination release"
|
||||
) {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("destination release"),
|
||||
}
|
||||
RpcResponse::BoolResult(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -654,6 +714,70 @@ fn packet_hash_to_array(hash: &[u8]) -> Option<[u8; 32]> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn all_rpc_requests() -> Vec<RpcRequest> {
|
||||
vec![
|
||||
RpcRequest::GetPathTable { max_hops: Some(5) },
|
||||
RpcRequest::GetInterfaceStats,
|
||||
RpcRequest::GetRateTable,
|
||||
RpcRequest::GetNextHopIfName {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetNextHop {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash: vec![0; 16],
|
||||
timeout_secs: Some(0.01),
|
||||
},
|
||||
RpcRequest::GetFirstHopTimeout {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetLinkCount,
|
||||
RpcRequest::GetPacketRssi {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetPacketSnr {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetPacketQ {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetBlackholedIdentities,
|
||||
RpcRequest::IsBlackholed {
|
||||
identity_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropPath {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropAllVia {
|
||||
transport_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropPathTable,
|
||||
RpcRequest::DropRecentAnnounces,
|
||||
RpcRequest::DropAnnounceQueues,
|
||||
RpcRequest::BlackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
until: Some(99999.0),
|
||||
reason: Some("test".to_string()),
|
||||
},
|
||||
RpcRequest::UnblackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::UseDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RetainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RetainIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::UnretainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rpc_server_bind_and_shutdown() {
|
||||
let shutdown = ShutdownSignal::new();
|
||||
@@ -753,6 +877,81 @@ mod tests {
|
||||
shutdown.trigger();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_listener_returns_errors_when_transport_actor_is_closed() {
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
drop(rx);
|
||||
let rpc_key = b"closed_actor_key".to_vec();
|
||||
let port = spawn_test_rpc_server(rpc_key.clone(), tx, shutdown.clone()).await;
|
||||
|
||||
for request in all_rpc_requests() {
|
||||
let response = rpc_client_request(port, &rpc_key, request).await;
|
||||
assert!(
|
||||
matches!(response, RpcResponse::Error(_)),
|
||||
"closed transport actor must produce an RPC error, got {response:?}"
|
||||
);
|
||||
}
|
||||
|
||||
shutdown.trigger();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transport_query_reports_closed_send_and_response_channels() {
|
||||
let (closed_tx, closed_rx) = mpsc::channel(1);
|
||||
drop(closed_rx);
|
||||
assert!(matches!(
|
||||
query_transport(
|
||||
&closed_tx,
|
||||
rns_transport::messages::TransportQuery::GetLinkCount
|
||||
)
|
||||
.await,
|
||||
Err(TransportQueryFailure::ChannelClosed)
|
||||
));
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let responder = tokio::spawn(async move {
|
||||
let Some(TransportMessage::Rpc { response_tx, .. }) = rx.recv().await else {
|
||||
panic!("expected transport RPC query");
|
||||
};
|
||||
drop(response_tx);
|
||||
});
|
||||
assert!(matches!(
|
||||
query_transport(&tx, rns_transport::messages::TransportQuery::GetLinkCount).await,
|
||||
Err(TransportQueryFailure::ResponseClosed)
|
||||
));
|
||||
responder.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn transport_query_reports_enqueue_and_response_timeouts() {
|
||||
let (full_tx, full_rx) = mpsc::channel(1);
|
||||
full_tx.send(TransportMessage::Shutdown).await.unwrap();
|
||||
assert!(matches!(
|
||||
query_transport(
|
||||
&full_tx,
|
||||
rns_transport::messages::TransportQuery::GetLinkCount
|
||||
)
|
||||
.await,
|
||||
Err(TransportQueryFailure::SendTimedOut)
|
||||
));
|
||||
drop(full_rx);
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let responder = tokio::spawn(async move {
|
||||
let Some(TransportMessage::Rpc { response_tx, .. }) = rx.recv().await else {
|
||||
panic!("expected transport RPC query");
|
||||
};
|
||||
let _response_tx = response_tx;
|
||||
std::future::pending::<()>().await;
|
||||
});
|
||||
assert!(matches!(
|
||||
query_transport(&tx, rns_transport::messages::TransportQuery::GetLinkCount).await,
|
||||
Err(TransportQueryFailure::ResponseTimedOut)
|
||||
));
|
||||
responder.abort();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_rpc_server_accepts_python_multiprocessing_client() {
|
||||
if std::process::Command::new("python3")
|
||||
@@ -907,66 +1106,7 @@ listener.close()
|
||||
let (actor, tx) = rns_transport::actor::TransportActor::new();
|
||||
tokio::spawn(actor.run());
|
||||
|
||||
let requests = vec![
|
||||
RpcRequest::GetPathTable { max_hops: Some(5) },
|
||||
RpcRequest::GetInterfaceStats,
|
||||
RpcRequest::GetRateTable,
|
||||
RpcRequest::GetNextHopIfName {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetNextHop {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash: vec![0; 16],
|
||||
timeout_secs: Some(0.01),
|
||||
},
|
||||
RpcRequest::GetFirstHopTimeout {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetLinkCount,
|
||||
RpcRequest::GetPacketRssi {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetPacketSnr {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetPacketQ {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetBlackholedIdentities,
|
||||
RpcRequest::IsBlackholed {
|
||||
identity_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropPath {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropAllVia {
|
||||
transport_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropPathTable,
|
||||
RpcRequest::DropRecentAnnounces,
|
||||
RpcRequest::DropAnnounceQueues,
|
||||
RpcRequest::BlackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
until: Some(99999.0),
|
||||
reason: Some("test".to_string()),
|
||||
},
|
||||
RpcRequest::UnblackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::UseDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RetainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::UnretainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
];
|
||||
|
||||
for req in requests {
|
||||
for req in all_rpc_requests() {
|
||||
let resp = process_rpc_request(req, &tx).await;
|
||||
assert!(
|
||||
!matches!(resp, RpcResponse::Error(_)),
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-tools"
|
||||
description = "Rust CLI utilities for Reticulum (rnsd-rs, rnstatus-rs, etc.)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
autobins = false
|
||||
|
||||
|
||||
@@ -859,6 +859,26 @@ async fn announce_destination(identity: &Identity, aspects: &str, args: &Args) -
|
||||
println!("Created destination {aspects}");
|
||||
println!("Announcing destination {}", pretty_hash(&destination.hash));
|
||||
|
||||
// Destination construction is intentionally side-effect free in the Rust
|
||||
// implementation. Register this short-lived destination explicitly so
|
||||
// the transport recognises its announce as locally originated and allows
|
||||
// it through the announce egress gates.
|
||||
let dest_hash = destination.hash;
|
||||
if handle
|
||||
.transport_tx
|
||||
.send(TransportMessage::RegisterDestination {
|
||||
hash: dest_hash,
|
||||
app_name: aspects.to_string(),
|
||||
delivery_tx: None,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
eprintln!("An error occurred while attempting to register the announce destination");
|
||||
shutdown.trigger();
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
|
||||
let raw = match destination.announce_packet(identity, None, None, false, None, now_epoch()) {
|
||||
Ok(raw) => raw,
|
||||
Err(e) => {
|
||||
@@ -867,14 +887,19 @@ async fn announce_destination(identity: &Identity, aspects: &str, args: &Args) -
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let dest_hash = destination.hash;
|
||||
let _ = handle
|
||||
if handle
|
||||
.transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: raw.into(),
|
||||
destination_hash: dest_hash,
|
||||
}))
|
||||
.await;
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
eprintln!("An error occurred while attempting to queue the announce");
|
||||
shutdown.trigger();
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
shutdown.trigger();
|
||||
ExitCode::SUCCESS
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,8 @@
|
||||
//! RNode platform, product and firmware model tables.
|
||||
//! RNode platform, product and firmware model metadata.
|
||||
//!
|
||||
//! Radio families and numeric operating limits belong to
|
||||
//! `rns_interface::rnode_capabilities`; this tool-local table contains only
|
||||
//! metadata needed to plan firmware operations.
|
||||
|
||||
pub const PLATFORM_AVR: u8 = 0x90;
|
||||
pub const PLATFORM_ESP32: u8 = 0x80;
|
||||
@@ -32,439 +36,61 @@ pub const MODEL_B9_TCXO: u8 = 0x09;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ModelInfo {
|
||||
pub model: u8,
|
||||
pub min_frequency: u32,
|
||||
pub max_frequency: u32,
|
||||
pub max_tx_power: u8,
|
||||
pub band_label: &'static str,
|
||||
pub firmware_filename: Option<&'static str>,
|
||||
pub radio: &'static str,
|
||||
}
|
||||
|
||||
pub const MODELS: &[ModelInfo] = &[
|
||||
model(
|
||||
0xA4,
|
||||
410000000,
|
||||
525000000,
|
||||
14,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware.hex"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xA9,
|
||||
820000000,
|
||||
1020000000,
|
||||
17,
|
||||
"820 - 1020 MHz",
|
||||
Some("rnode_firmware.hex"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xA1,
|
||||
410000000,
|
||||
525000000,
|
||||
22,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware_t3s3.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xA6,
|
||||
820000000,
|
||||
1020000000,
|
||||
22,
|
||||
"820 - 960 MHz",
|
||||
Some("rnode_firmware_t3s3.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xA5,
|
||||
410000000,
|
||||
525000000,
|
||||
17,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware_t3s3_sx127x.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xAA,
|
||||
820000000,
|
||||
1020000000,
|
||||
17,
|
||||
"820 - 960 MHz",
|
||||
Some("rnode_firmware_t3s3_sx127x.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xAC,
|
||||
2400000000,
|
||||
2500000000,
|
||||
20,
|
||||
"2.4 - 2.5 GHz",
|
||||
Some("rnode_firmware_t3s3_sx1280_pa.zip"),
|
||||
"SX1280",
|
||||
),
|
||||
model(
|
||||
0xA2,
|
||||
410000000,
|
||||
525000000,
|
||||
17,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware_ng21.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xA7,
|
||||
820000000,
|
||||
1020000000,
|
||||
17,
|
||||
"820 - 1020 MHz",
|
||||
Some("rnode_firmware_ng21.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xA3,
|
||||
410000000,
|
||||
525000000,
|
||||
17,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware_ng20.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xA8,
|
||||
820000000,
|
||||
1020000000,
|
||||
17,
|
||||
"820 - 1020 MHz",
|
||||
Some("rnode_firmware_ng20.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xB3,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_lora32v20.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xB8,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_lora32v20.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xB4,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_lora32v21.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xB9,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_lora32v21.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
MODEL_B4_TCXO,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_lora32v21_tcxo.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
MODEL_B9_TCXO,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_lora32v21_tcxo.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xBA,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_lora32v10.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xBB,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_lora32v10.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xC4,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_heltec32v2.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xC9,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_heltec32v2.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xC5,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_heltec32v3.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xCA,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_heltec32v3.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xC8,
|
||||
860000000,
|
||||
930000000,
|
||||
28,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_heltec32v4pa.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xC6,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_heltec_t114.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xC7,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_heltec_t114.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xE4,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_tbeam.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xE9,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_tbeam.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xD4,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_tdeck.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xD9,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_tdeck.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xDB,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_tbeam_supreme.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xDC,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_tbeam_supreme.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xE3,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_tbeam_sx1262.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xE8,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_tbeam_sx1262.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x11,
|
||||
430000000,
|
||||
510000000,
|
||||
22,
|
||||
"430 - 510 MHz",
|
||||
Some("rnode_firmware_rak4631.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x12,
|
||||
779000000,
|
||||
928000000,
|
||||
22,
|
||||
"779 - 928 MHz",
|
||||
Some("rnode_firmware_rak4631.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x13,
|
||||
430000000,
|
||||
510000000,
|
||||
22,
|
||||
"430 - 510 MHz",
|
||||
Some("rnode_firmware_rak4631_sx1280.zip"),
|
||||
"SX1262 + SX1280",
|
||||
),
|
||||
model(
|
||||
0x14,
|
||||
779000000,
|
||||
928000000,
|
||||
22,
|
||||
"779 - 928 MHz",
|
||||
Some("rnode_firmware_rak4631_sx1280.zip"),
|
||||
"SX1262 + SX1280",
|
||||
),
|
||||
model(
|
||||
0x16,
|
||||
779000000,
|
||||
928000000,
|
||||
22,
|
||||
"430 - 510 Mhz",
|
||||
Some("rnode_firmware_techo.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x17,
|
||||
779000000,
|
||||
928000000,
|
||||
22,
|
||||
"779 - 928 Mhz",
|
||||
Some("rnode_firmware_techo.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x21,
|
||||
820000000,
|
||||
960000000,
|
||||
22,
|
||||
"820 - 960 MHz",
|
||||
Some("rnode_firmware_opencom_xl.zip"),
|
||||
"SX1262 + SX1280",
|
||||
),
|
||||
model(
|
||||
0xDE,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_xiao_esp32s3.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xDD,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_xiao_esp32s3.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xFE,
|
||||
100000000,
|
||||
1100000000,
|
||||
17,
|
||||
"(Band capabilities unknown)",
|
||||
None,
|
||||
"Unknown",
|
||||
),
|
||||
model(
|
||||
0xFF,
|
||||
100000000,
|
||||
1100000000,
|
||||
14,
|
||||
"(Band capabilities unknown)",
|
||||
None,
|
||||
"Unknown",
|
||||
),
|
||||
model(0xA4, Some("rnode_firmware.hex")),
|
||||
model(0xA9, Some("rnode_firmware.hex")),
|
||||
model(0xA1, Some("rnode_firmware_t3s3.zip")),
|
||||
model(0xA6, Some("rnode_firmware_t3s3.zip")),
|
||||
model(0xA5, Some("rnode_firmware_t3s3_sx127x.zip")),
|
||||
model(0xAA, Some("rnode_firmware_t3s3_sx127x.zip")),
|
||||
model(0xAC, Some("rnode_firmware_t3s3_sx1280_pa.zip")),
|
||||
model(0xA2, Some("rnode_firmware_ng21.zip")),
|
||||
model(0xA7, Some("rnode_firmware_ng21.zip")),
|
||||
model(0xA3, Some("rnode_firmware_ng20.zip")),
|
||||
model(0xA8, Some("rnode_firmware_ng20.zip")),
|
||||
model(0xB3, Some("rnode_firmware_lora32v20.zip")),
|
||||
model(0xB8, Some("rnode_firmware_lora32v20.zip")),
|
||||
model(0xB4, Some("rnode_firmware_lora32v21.zip")),
|
||||
model(0xB9, Some("rnode_firmware_lora32v21.zip")),
|
||||
model(MODEL_B4_TCXO, Some("rnode_firmware_lora32v21_tcxo.zip")),
|
||||
model(MODEL_B9_TCXO, Some("rnode_firmware_lora32v21_tcxo.zip")),
|
||||
model(0xBA, Some("rnode_firmware_lora32v10.zip")),
|
||||
model(0xBB, Some("rnode_firmware_lora32v10.zip")),
|
||||
model(0xC4, Some("rnode_firmware_heltec32v2.zip")),
|
||||
model(0xC9, Some("rnode_firmware_heltec32v2.zip")),
|
||||
model(0xC5, Some("rnode_firmware_heltec32v3.zip")),
|
||||
model(0xCA, Some("rnode_firmware_heltec32v3.zip")),
|
||||
model(0xC8, Some("rnode_firmware_heltec32v4pa.zip")),
|
||||
model(0xC6, Some("rnode_firmware_heltec_t114.zip")),
|
||||
model(0xC7, Some("rnode_firmware_heltec_t114.zip")),
|
||||
model(0xE4, Some("rnode_firmware_tbeam.zip")),
|
||||
model(0xE9, Some("rnode_firmware_tbeam.zip")),
|
||||
model(0xD4, Some("rnode_firmware_tdeck.zip")),
|
||||
model(0xD9, Some("rnode_firmware_tdeck.zip")),
|
||||
model(0xDB, Some("rnode_firmware_tbeam_supreme.zip")),
|
||||
model(0xDC, Some("rnode_firmware_tbeam_supreme.zip")),
|
||||
model(0xE3, Some("rnode_firmware_tbeam_sx1262.zip")),
|
||||
model(0xE8, Some("rnode_firmware_tbeam_sx1262.zip")),
|
||||
model(0x11, Some("rnode_firmware_rak4631.zip")),
|
||||
model(0x12, Some("rnode_firmware_rak4631.zip")),
|
||||
model(0x13, Some("rnode_firmware_rak4631_sx1280.zip")),
|
||||
model(0x14, Some("rnode_firmware_rak4631_sx1280.zip")),
|
||||
model(0x16, Some("rnode_firmware_techo.zip")),
|
||||
model(0x17, Some("rnode_firmware_techo.zip")),
|
||||
model(0x21, Some("rnode_firmware_opencom_xl.zip")),
|
||||
model(0xDE, Some("rnode_firmware_xiao_esp32s3.zip")),
|
||||
model(0xDD, Some("rnode_firmware_xiao_esp32s3.zip")),
|
||||
model(0xFE, None),
|
||||
model(0xFF, None),
|
||||
];
|
||||
|
||||
const fn model(
|
||||
model: u8,
|
||||
min_frequency: u32,
|
||||
max_frequency: u32,
|
||||
max_tx_power: u8,
|
||||
band_label: &'static str,
|
||||
firmware_filename: Option<&'static str>,
|
||||
radio: &'static str,
|
||||
) -> ModelInfo {
|
||||
const fn model(model: u8, firmware_filename: Option<&'static str>) -> ModelInfo {
|
||||
ModelInfo {
|
||||
model,
|
||||
min_frequency,
|
||||
max_frequency,
|
||||
max_tx_power,
|
||||
band_label,
|
||||
firmware_filename,
|
||||
radio,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,28 +106,6 @@ pub fn normalize_eeprom_model(model: u8) -> u8 {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn product_name(product: u8) -> Option<&'static str> {
|
||||
Some(match product {
|
||||
PRODUCT_RNODE => "RNode",
|
||||
PRODUCT_HMBRW => "Hombrew RNode",
|
||||
PRODUCT_TBEAM => "LilyGO T-Beam",
|
||||
PRODUCT_TBEAM_S_V1 => "LilyGO T-Beam Supreme",
|
||||
PRODUCT_TDECK => "LilyGO T-Deck",
|
||||
PRODUCT_T32_10 => "LilyGO LoRa32 v1.0",
|
||||
PRODUCT_T32_20 => "LilyGO LoRa32 v2.0",
|
||||
PRODUCT_T32_21 => "LilyGO LoRa32 v2.1",
|
||||
PRODUCT_H32_V2 => "Heltec LoRa32 v2",
|
||||
PRODUCT_H32_V3 => "Heltec LoRa32 v3",
|
||||
PRODUCT_H32_V4 => "Heltec LoRa32 v4",
|
||||
PRODUCT_TECHO => "LilyGO T-Echo",
|
||||
PRODUCT_RAK4631 => "RAK4631",
|
||||
PRODUCT_OPENCOM_XL => "openCom XL",
|
||||
PRODUCT_HELTEC_T114 => "Heltec Mesh Node T114",
|
||||
PRODUCT_XIAO_S3 => "Seeed XIAO ESP32S3 Wio-SX1262",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn platform_name(platform: u8) -> Option<&'static str> {
|
||||
Some(match platform {
|
||||
PLATFORM_AVR => "AVR",
|
||||
@@ -526,7 +130,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn model_table_matches_upstream_shape() {
|
||||
fn model_table_retains_only_firmware_planning_metadata() {
|
||||
assert_eq!(MODELS.len(), 45);
|
||||
assert_eq!(
|
||||
model_info(0xA4).unwrap().firmware_filename,
|
||||
@@ -537,7 +141,7 @@ mod tests {
|
||||
Some("rnode_firmware_t3s3_sx1280_pa.zip")
|
||||
);
|
||||
assert_eq!(model_info(0xFE).unwrap().firmware_filename, None);
|
||||
assert_eq!(model_info(0xFF).unwrap().max_tx_power, 14);
|
||||
assert_eq!(model_info(0xFF).unwrap().firmware_filename, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -548,8 +152,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_match_upstream_spellings() {
|
||||
assert_eq!(product_name(PRODUCT_HMBRW), Some("Hombrew RNode"));
|
||||
fn platform_and_mcu_names_match_upstream_spellings() {
|
||||
assert_eq!(platform_name(PLATFORM_ESP32), Some("ESP32"));
|
||||
assert_eq!(mcu_name(MCU_NRF52), Some("Nordic Semiconductor nRF52840"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
//! Side-effect-free command planning for the bounded `rnodeconf` slice.
|
||||
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use rns_interface::{rnode, rnode_admin};
|
||||
|
||||
use super::{Args, frame};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DevicePlan {
|
||||
pub mutation: Option<MutationPlan>,
|
||||
pub read_only: Vec<rnode_admin::AdminFrame>,
|
||||
pub show_psk: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MutationPlan {
|
||||
Tnc(rnode::RNodeRadioSettings),
|
||||
Normal,
|
||||
}
|
||||
|
||||
impl DevicePlan {
|
||||
pub fn build(args: &Args) -> Result<Self, String> {
|
||||
validate_conflicts(args)?;
|
||||
validate_wifi_inputs(args)?;
|
||||
|
||||
if args.show_psk && !args.config {
|
||||
return Err("--show-psk requires --config".to_string());
|
||||
}
|
||||
|
||||
let radio = plan_radio(args)?;
|
||||
reject_unverified_mutations(args)?;
|
||||
|
||||
let mutation = if args.normal {
|
||||
Some(MutationPlan::Normal)
|
||||
} else {
|
||||
radio.map(MutationPlan::Tnc)
|
||||
};
|
||||
|
||||
let mut read_only = Vec::new();
|
||||
if args.info {
|
||||
read_only.extend(rnode_admin::detect_sequence());
|
||||
read_only.push(rnode_admin::eeprom_read_frame());
|
||||
}
|
||||
if args.config {
|
||||
read_only.push(frame(rnode::CMD_CFG_READ, &[0]));
|
||||
}
|
||||
if args.eeprom_dump || args.eeprom_backup {
|
||||
read_only.push(rnode_admin::eeprom_read_frame());
|
||||
}
|
||||
if args.get_target_firmware_hash {
|
||||
read_only.push(frame(rnode::CMD_HASHES, &[1]));
|
||||
}
|
||||
if args.get_firmware_hash {
|
||||
read_only.push(frame(rnode::CMD_HASHES, &[2]));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
mutation,
|
||||
read_only,
|
||||
show_psk: args.show_psk,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.mutation.is_none() && self.read_only.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_conflicts(args: &Args) -> Result<(), String> {
|
||||
if args.normal && args.tnc {
|
||||
return Err("--normal conflicts with --tnc".to_string());
|
||||
}
|
||||
|
||||
let bluetooth_flags = [args.bluetooth_on, args.bluetooth_off, args.bluetooth_pair]
|
||||
.into_iter()
|
||||
.filter(|enabled| *enabled)
|
||||
.count();
|
||||
if bluetooth_flags > 1 {
|
||||
return Err(
|
||||
"--bluetooth-on, --bluetooth-off and --bluetooth-pair are mutually exclusive"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
if args.ia_enable && args.ia_disable {
|
||||
return Err("--ia-enable conflicts with --ia-disable".to_string());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn plan_radio(args: &Args) -> Result<Option<rnode::RNodeRadioSettings>, String> {
|
||||
let fields = [
|
||||
args.freq.is_some(),
|
||||
args.bandwidth.is_some(),
|
||||
args.spreading_factor.is_some(),
|
||||
args.coding_rate.is_some(),
|
||||
args.tx_power.is_some(),
|
||||
];
|
||||
let any = fields.iter().any(|present| *present);
|
||||
let all = fields.iter().all(|present| *present);
|
||||
|
||||
if any && !args.tnc {
|
||||
return Err("RF settings are only allowed as a complete --tnc tuple".to_string());
|
||||
}
|
||||
if args.tnc && !all {
|
||||
return Err(
|
||||
"--tnc requires --freq, --bw, --sf, --cr and --txp as a complete tuple".to_string(),
|
||||
);
|
||||
}
|
||||
if !args.tnc {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let settings = rnode::RNodeRadioSettings::new(
|
||||
args.freq.expect("tuple completeness checked"),
|
||||
args.bandwidth.expect("tuple completeness checked"),
|
||||
args.spreading_factor.expect("tuple completeness checked"),
|
||||
args.coding_rate.expect("tuple completeness checked"),
|
||||
args.tx_power.expect("tuple completeness checked"),
|
||||
);
|
||||
settings
|
||||
.validate()
|
||||
.map_err(|error| format!("invalid {}: {error}", error.field()))?;
|
||||
Ok(Some(settings))
|
||||
}
|
||||
|
||||
fn validate_wifi_inputs(args: &Args) -> Result<(), String> {
|
||||
if let Some(mode) = args.wifi.as_deref() {
|
||||
match mode.to_ascii_lowercase().as_str() {
|
||||
"off" | "none" | "station" | "sta" | "ap" | "accesspoint" | "access_point" => {}
|
||||
_ => return Err("WiFi mode must be OFF, AP or STATION".to_string()),
|
||||
}
|
||||
}
|
||||
if let Some(channel) = args.channel {
|
||||
if !(1..=14).contains(&channel) {
|
||||
return Err("WiFi channel must be in 1..=14".to_string());
|
||||
}
|
||||
}
|
||||
if let Some(ssid) = args.ssid.as_deref() {
|
||||
if !ssid.eq_ignore_ascii_case("none") && ssid.len() > 32 {
|
||||
return Err("WiFi SSID must be at most 32 bytes".to_string());
|
||||
}
|
||||
}
|
||||
if let Some(psk) = args.psk.as_deref() {
|
||||
if !psk.eq_ignore_ascii_case("none") && !(8..=32).contains(&psk.len()) {
|
||||
return Err("WiFi PSK must be 8 to 32 bytes, or NONE".to_string());
|
||||
}
|
||||
}
|
||||
for (name, value) in [
|
||||
("IP address", args.ip.as_deref()),
|
||||
("netmask", args.nm.as_deref()),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
if !value.eq_ignore_ascii_case("none") {
|
||||
value
|
||||
.parse::<Ipv4Addr>()
|
||||
.map_err(|error| format!("invalid WiFi {name} {value}: {error}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reject_unverified_mutations(args: &Args) -> Result<(), String> {
|
||||
let bluetooth = args.bluetooth_on || args.bluetooth_off || args.bluetooth_pair;
|
||||
let wifi = args.wifi.is_some()
|
||||
|| args.channel.is_some()
|
||||
|| args.ssid.is_some()
|
||||
|| args.psk.is_some()
|
||||
|| args.ip.is_some()
|
||||
|| args.nm.is_some();
|
||||
let display = args.display.is_some()
|
||||
|| args.timeout.is_some()
|
||||
|| args.rotation.is_some()
|
||||
|| args.display_addr.is_some()
|
||||
|| args.recondition_display
|
||||
|| args.neopixel.is_some();
|
||||
let interference_avoidance = args.ia_enable || args.ia_disable;
|
||||
|
||||
let mut unsupported = Vec::new();
|
||||
if bluetooth {
|
||||
unsupported.push("Bluetooth");
|
||||
}
|
||||
if wifi {
|
||||
unsupported.push("WiFi");
|
||||
}
|
||||
if display {
|
||||
unsupported.push("display");
|
||||
}
|
||||
if interference_avoidance {
|
||||
unsupported.push("interference-avoidance");
|
||||
}
|
||||
if unsupported.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"{} mutations are not yet safely supported",
|
||||
unsupported.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use clap::Parser;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn plan(args: &[&str]) -> Result<DevicePlan, String> {
|
||||
let args = Args::parse_from(std::iter::once("rnodeconf").chain(args.iter().copied()));
|
||||
DevicePlan::build(&args)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planner_builds_typed_tnc_and_preserves_radio_order() {
|
||||
let plan = plan(&[
|
||||
"--tnc",
|
||||
"--freq",
|
||||
"868000000",
|
||||
"--bw",
|
||||
"125000",
|
||||
"--sf",
|
||||
"7",
|
||||
"--cr",
|
||||
"5",
|
||||
"--txp",
|
||||
"14",
|
||||
"fake",
|
||||
])
|
||||
.unwrap();
|
||||
let MutationPlan::Tnc(settings) = plan.mutation.unwrap() else {
|
||||
panic!("expected TNC plan");
|
||||
};
|
||||
let frames =
|
||||
rnode_admin::decode_frames(&rnode::build_radio_configuration_sequence(&settings));
|
||||
assert_eq!(
|
||||
frames.iter().map(|frame| frame.command).collect::<Vec<_>>(),
|
||||
vec![
|
||||
rnode::CMD_RADIO_STATE,
|
||||
rnode::CMD_FREQUENCY,
|
||||
rnode::CMD_BANDWIDTH,
|
||||
rnode::CMD_SF,
|
||||
rnode::CMD_CR,
|
||||
rnode::CMD_TXPOWER,
|
||||
rnode::CMD_RADIO_STATE,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planner_rejects_conflicts_and_incomplete_or_detached_rf_tuples() {
|
||||
assert!(plan(&["--normal", "--tnc", "fake"]).is_err());
|
||||
assert!(plan(&["--bluetooth-on", "--bluetooth-off", "fake"]).is_err());
|
||||
assert!(plan(&["--ia-enable", "--ia-disable", "fake"]).is_err());
|
||||
assert!(plan(&["--tnc", "--freq", "868000000", "fake"]).is_err());
|
||||
assert!(plan(&["--freq", "868000000", "fake"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planner_rejects_generic_ranges_before_a_session_can_be_opened() {
|
||||
let result = plan(&[
|
||||
"--tnc",
|
||||
"--freq",
|
||||
"136999999",
|
||||
"--bw",
|
||||
"125000",
|
||||
"--sf",
|
||||
"7",
|
||||
"--cr",
|
||||
"5",
|
||||
"--txp",
|
||||
"14",
|
||||
"fake",
|
||||
]);
|
||||
assert!(result.unwrap_err().contains("invalid frequency"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_wifi_is_rejected_before_unsupported_mutation_gate() {
|
||||
assert!(
|
||||
plan(&["--wifi", "bogus", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("WiFi mode")
|
||||
);
|
||||
assert!(
|
||||
plan(&["--channel", "0", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("channel")
|
||||
);
|
||||
assert!(
|
||||
plan(&["--ip", "999.1.1.1", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("IP address")
|
||||
);
|
||||
assert!(
|
||||
plan(&["--psk", "short", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("PSK")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unacknowledged_mutation_families_fail_closed() {
|
||||
for args in [
|
||||
&["--bluetooth-on", "fake"][..],
|
||||
&["--wifi", "off", "fake"][..],
|
||||
&["--display", "10", "fake"][..],
|
||||
&["--ia-enable", "fake"][..],
|
||||
] {
|
||||
assert!(plan(args).unwrap_err().contains("not yet safely supported"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_psk_is_only_a_config_output_permission() {
|
||||
assert!(
|
||||
plan(&["--show-psk", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("requires --config")
|
||||
);
|
||||
let plan = plan(&["--config", "--show-psk", "fake"]).unwrap();
|
||||
assert_eq!(plan.read_only.len(), 1);
|
||||
assert_eq!(plan.read_only[0].command, rnode::CMD_CFG_READ);
|
||||
assert!(
|
||||
plan.read_only
|
||||
.iter()
|
||||
.all(|frame| frame.command != rnode::CMD_WIFI_PSK)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Framing and deadline ownership for staged RNode administration sessions.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::io::{Read, Write};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use rns_interface::{kiss, rnode_admin};
|
||||
|
||||
/// Small transaction surface used by the mutation executor and deterministic
|
||||
/// tests. Implementations must preserve inbound framing state between calls.
|
||||
pub trait FrameSession {
|
||||
fn send(&mut self, frame: &rnode_admin::AdminFrame) -> Result<(), String>;
|
||||
|
||||
/// Return the next complete frame, or `None` once `deadline` expires.
|
||||
fn receive_until(
|
||||
&mut self,
|
||||
deadline: Instant,
|
||||
) -> Result<Option<rnode_admin::AdminFrame>, String>;
|
||||
}
|
||||
|
||||
pub struct SerialFrameSession {
|
||||
port: Box<dyn serialport::SerialPort>,
|
||||
inbox: FrameInbox,
|
||||
}
|
||||
|
||||
impl SerialFrameSession {
|
||||
pub fn new(port: Box<dyn serialport::SerialPort>) -> Self {
|
||||
Self {
|
||||
port,
|
||||
inbox: FrameInbox::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FrameSession for SerialFrameSession {
|
||||
fn send(&mut self, frame: &rnode_admin::AdminFrame) -> Result<(), String> {
|
||||
let encoded = rnode_admin::encode_frame(frame.command, &frame.payload);
|
||||
self.port
|
||||
.write_all(&encoded)
|
||||
.map_err(|error| format!("serial write failed: {error}"))?;
|
||||
self.port
|
||||
.flush()
|
||||
.map_err(|error| format!("serial flush failed: {error}"))
|
||||
}
|
||||
|
||||
fn receive_until(
|
||||
&mut self,
|
||||
deadline: Instant,
|
||||
) -> Result<Option<rnode_admin::AdminFrame>, String> {
|
||||
if let Some(frame) = self.inbox.pop() {
|
||||
return Ok(Some(frame));
|
||||
}
|
||||
|
||||
let mut buffer = [0u8; 512];
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
return Ok(None);
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(now);
|
||||
let read_timeout = remaining.min(Duration::from_millis(100));
|
||||
self.port
|
||||
.set_timeout(read_timeout)
|
||||
.map_err(|error| format!("could not set serial read timeout: {error}"))?;
|
||||
|
||||
match self.port.read(&mut buffer) {
|
||||
Ok(0) => {}
|
||||
Ok(count) => {
|
||||
self.inbox.feed(&buffer[..count]);
|
||||
if let Some(frame) = self.inbox.pop() {
|
||||
return Ok(Some(frame));
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
Err(error) => return Err(format!("serial read failed: {error}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FrameInbox {
|
||||
deframer: kiss::RawKissDeframer,
|
||||
frames: VecDeque<rnode_admin::AdminFrame>,
|
||||
}
|
||||
|
||||
impl FrameInbox {
|
||||
fn feed(&mut self, bytes: &[u8]) {
|
||||
self.frames.extend(
|
||||
self.deframer
|
||||
.feed(bytes)
|
||||
.into_iter()
|
||||
.map(|(command, payload)| rnode_admin::AdminFrame { command, payload }),
|
||||
);
|
||||
}
|
||||
|
||||
fn pop(&mut self) -> Option<rnode_admin::AdminFrame> {
|
||||
self.frames.pop_front()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rns_interface::{kiss, rnode};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn one_deframer_survives_fragmented_and_escaped_input_across_stages() {
|
||||
let first =
|
||||
rnode_admin::encode_frame(rnode::CMD_CFG_READ, &[0x11, kiss::FEND, 0x22, kiss::FESC]);
|
||||
let second = rnode_admin::encode_frame(rnode::CMD_FREQUENCY, &868_000_000u32.to_be_bytes());
|
||||
let split = first.len() - 2;
|
||||
let mut inbox = FrameInbox::default();
|
||||
|
||||
inbox.feed(&first[..3]);
|
||||
assert!(inbox.pop().is_none());
|
||||
inbox.feed(&first[3..split]);
|
||||
assert!(inbox.pop().is_none());
|
||||
inbox.feed(&first[split..]);
|
||||
assert_eq!(
|
||||
inbox.pop(),
|
||||
Some(rnode_admin::AdminFrame {
|
||||
command: rnode::CMD_CFG_READ,
|
||||
payload: vec![0x11, kiss::FEND, 0x22, kiss::FESC],
|
||||
})
|
||||
);
|
||||
|
||||
for chunk in second.chunks(2) {
|
||||
inbox.feed(chunk);
|
||||
}
|
||||
assert_eq!(inbox.pop(), rnode_admin::decode_frames(&second).pop());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inbox_queues_multiple_frames_without_reframing_between_reads() {
|
||||
let mut wire = rnode_admin::encode_frame(rnode::CMD_READY, &[1]);
|
||||
wire.extend(rnode_admin::encode_frame(rnode::CMD_RADIO_STATE, &[1]));
|
||||
let mut inbox = FrameInbox::default();
|
||||
inbox.feed(&wire);
|
||||
|
||||
assert_eq!(inbox.pop().unwrap().command, rnode::CMD_READY);
|
||||
assert_eq!(inbox.pop().unwrap().command, rnode::CMD_RADIO_STATE);
|
||||
assert!(inbox.pop().is_none());
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,7 @@ struct Args {
|
||||
#[arg(short = 'q', long, action = clap::ArgAction::Count)]
|
||||
quiet: u8,
|
||||
|
||||
/// Run as service and log to <configdir>/logfile.
|
||||
/// Run as service and log to `<configdir>/logfile`.
|
||||
#[arg(short = 's', long)]
|
||||
service: bool,
|
||||
|
||||
@@ -209,6 +209,7 @@ pub(crate) async fn main() {
|
||||
}
|
||||
|
||||
shutdown.wait().await;
|
||||
handle.shutdown_and_wait().await;
|
||||
tracing::info!("rnsd-rs shutting down");
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
@@ -528,6 +528,9 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
if let Some(clients) = entry.clients {
|
||||
println!(" Clients : {clients}");
|
||||
}
|
||||
if let Some(blocked) = blocked_count_text(entry.blocked_ips) {
|
||||
println!(" Blocked : {blocked}");
|
||||
}
|
||||
if entry.ifac_size > 0 {
|
||||
println!(" IFAC : {} bits", entry.ifac_size * 8);
|
||||
}
|
||||
@@ -616,7 +619,7 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
print!(",");
|
||||
}
|
||||
print!(
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"blocked_ips\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
|
||||
json_str(&e.name),
|
||||
e.online,
|
||||
json_str(&e.mode),
|
||||
@@ -640,6 +643,7 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
e.pr_burst_active,
|
||||
e.pr_burst_activated,
|
||||
opt_u64_json(e.clients),
|
||||
opt_u64_json(e.blocked_ips),
|
||||
opt_f64_json(e.announce_rate_target),
|
||||
opt_u32_json(e.announce_rate_grace),
|
||||
opt_f64_json(e.announce_rate_penalty),
|
||||
@@ -1037,6 +1041,7 @@ struct RemoteInterface {
|
||||
pr_burst_active: bool,
|
||||
pr_burst_activated: f64,
|
||||
clients: Option<u64>,
|
||||
blocked_ips: Option<u64>,
|
||||
announce_rate_target: Option<f64>,
|
||||
announce_rate_grace: Option<u32>,
|
||||
announce_rate_penalty: Option<f64>,
|
||||
@@ -1137,7 +1142,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
print!(",");
|
||||
}
|
||||
print!(
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"blocked_ips\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
|
||||
json_str(&iface.name),
|
||||
iface.online,
|
||||
iface.mode,
|
||||
@@ -1160,6 +1165,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
iface.pr_burst_active,
|
||||
iface.pr_burst_activated,
|
||||
opt_u64_json(iface.clients),
|
||||
opt_u64_json(iface.blocked_ips),
|
||||
opt_f64_json(iface.announce_rate_target),
|
||||
opt_u32_json(iface.announce_rate_grace),
|
||||
opt_f64_json(iface.announce_rate_penalty),
|
||||
@@ -1189,6 +1195,9 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
if let Some(clients) = iface.clients {
|
||||
println!(" Clients : {clients}");
|
||||
}
|
||||
if let Some(blocked) = blocked_count_text(iface.blocked_ips) {
|
||||
println!(" Blocked : {blocked}");
|
||||
}
|
||||
if args.announce_stats {
|
||||
if let Some(queued) = iface.announce_queue {
|
||||
if queued > 0 {
|
||||
@@ -1284,6 +1293,7 @@ fn remote_interface_from_map(m: &[(rmpv::Value, rmpv::Value)]) -> RemoteInterfac
|
||||
pr_burst_active: map_bool(m, "pr_burst_active").unwrap_or(false),
|
||||
pr_burst_activated: map_f64_or_u64(m, "pr_burst_activated").unwrap_or(0.0),
|
||||
clients: map_u64(m, "clients"),
|
||||
blocked_ips: map_u64(m, "blocked_ips"),
|
||||
announce_rate_target: map_f64_or_u64(m, "announce_rate_target"),
|
||||
announce_rate_grace: map_u64(m, "announce_rate_grace")
|
||||
.map(|v| v.min(u32::MAX as u64) as u32),
|
||||
@@ -1397,6 +1407,12 @@ fn opt_u64_json(value: Option<u64>) -> String {
|
||||
.unwrap_or_else(|| "null".to_string())
|
||||
}
|
||||
|
||||
fn blocked_count_text(blocked_ips: Option<u64>) -> Option<String> {
|
||||
let count = blocked_ips.filter(|count| *count > 0)?;
|
||||
let noun = if count == 1 { "IP" } else { "IPs" };
|
||||
Some(format!("{count} {noun}"))
|
||||
}
|
||||
|
||||
fn opt_u32_json(value: Option<u32>) -> String {
|
||||
value
|
||||
.map(|v| v.to_string())
|
||||
@@ -1501,6 +1517,7 @@ mod tests {
|
||||
0.0
|
||||
},
|
||||
clients: None,
|
||||
blocked_ips: None,
|
||||
announce_rate_target: None,
|
||||
announce_rate_grace: None,
|
||||
announce_rate_penalty: None,
|
||||
@@ -1566,6 +1583,33 @@ mod tests {
|
||||
assert_eq!(iface.burst_activated, 0.0);
|
||||
assert!(!iface.pr_burst_active);
|
||||
assert_eq!(iface.pr_burst_activated, 0.0);
|
||||
assert_eq!(iface.blocked_ips, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_status_parser_accepts_only_scalar_blocked_count() {
|
||||
let iface = remote_interface_from_map(&[
|
||||
(rmpv::Value::from("name"), rmpv::Value::from("BackboneIf")),
|
||||
(rmpv::Value::from("blocked_ips"), rmpv::Value::from(2)),
|
||||
(
|
||||
rmpv::Value::from("blocked_ip_list"),
|
||||
rmpv::Value::Array(vec![
|
||||
rmpv::Value::from("198.51.100.2"),
|
||||
rmpv::Value::from("203.0.113.7"),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
|
||||
assert_eq!(iface.blocked_ips, Some(2));
|
||||
assert_eq!(blocked_count_text(iface.blocked_ips), Some("2 IPs".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_count_text_omits_empty_counts_and_pluralizes() {
|
||||
assert_eq!(blocked_count_text(None), None);
|
||||
assert_eq!(blocked_count_text(Some(0)), None);
|
||||
assert_eq!(blocked_count_text(Some(1)), Some("1 IP".into()));
|
||||
assert_eq!(blocked_count_text(Some(2)), Some("2 IPs".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -42,10 +42,13 @@ impl Drop for TempDir {
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn write_config(tmp: &TempDir) {
|
||||
fn write_config(tmp: &TempDir, enable_transport: bool) {
|
||||
let enable_transport = if enable_transport { "Yes" } else { "No" };
|
||||
fs::write(
|
||||
tmp.path().join("config"),
|
||||
"[reticulum]\nshare_instance = No\nenable_transport = No\n\n[interfaces]\n",
|
||||
format!(
|
||||
"[reticulum]\nshare_instance = No\nenable_transport = {enable_transport}\n\n[interfaces]\n"
|
||||
),
|
||||
)
|
||||
.expect("write config");
|
||||
}
|
||||
@@ -62,13 +65,18 @@ fn wait_until_running(child: &mut Child, settle: Duration) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Sends SIGINT after a settle period and asserts a clean exit. Retries once
|
||||
/// Sends a process signal after a settle period and asserts a clean exit. Retries once
|
||||
/// with a longer settle if the child died from the raw signal (exit by signal
|
||||
/// 2): under full-workspace load the child can still be booting when the
|
||||
/// first SIGINT lands, before its handler is registered. A real handler
|
||||
/// number): under full-workspace load the child can still be booting when the
|
||||
/// first signal lands, before its handler is registered. A real handler
|
||||
/// regression fails both attempts.
|
||||
#[cfg(unix)]
|
||||
fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) {
|
||||
fn assert_signal_exits(
|
||||
spawn: impl Fn() -> Child,
|
||||
name: &str,
|
||||
signal_name: &str,
|
||||
signal_number: i32,
|
||||
) {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
let settles = [Duration::from_secs(3), Duration::from_secs(8)];
|
||||
@@ -78,7 +86,7 @@ fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) {
|
||||
if !wait_until_running(&mut child, settle) {
|
||||
let output = child.wait_with_output().expect("collect child output");
|
||||
panic!(
|
||||
"{name} exited before SIGINT\nstatus: {}\nstdout:\n{}\nstderr:\n{}",
|
||||
"{name} exited before {signal_name}\nstatus: {}\nstdout:\n{}\nstderr:\n{}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
@@ -86,11 +94,11 @@ fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) {
|
||||
}
|
||||
|
||||
let status = Command::new("kill")
|
||||
.arg("-INT")
|
||||
.arg(format!("-{signal_name}"))
|
||||
.arg(child.id().to_string())
|
||||
.status()
|
||||
.expect("send SIGINT");
|
||||
assert!(status.success(), "kill -INT failed with {status}");
|
||||
.unwrap_or_else(|_| panic!("send {signal_name}"));
|
||||
assert!(status.success(), "kill -{signal_name} failed with {status}");
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let exit_status = loop {
|
||||
@@ -105,14 +113,14 @@ fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) {
|
||||
|
||||
match exit_status {
|
||||
Some(status) if status.success() => return,
|
||||
Some(status) if attempt < last_attempt && status.signal() == Some(2) => {
|
||||
Some(status) if attempt < last_attempt && status.signal() == Some(signal_number) => {
|
||||
let _ = child.wait_with_output();
|
||||
continue;
|
||||
}
|
||||
Some(status) => {
|
||||
let output = child.wait_with_output().expect("collect child output");
|
||||
panic!(
|
||||
"{name} exited unsuccessfully after SIGINT: {status}\nstdout:\n{}\nstderr:\n{}",
|
||||
"{name} exited unsuccessfully after {signal_name}: {status}\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
@@ -123,7 +131,7 @@ fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) {
|
||||
.wait_with_output()
|
||||
.expect("collect killed child output");
|
||||
panic!(
|
||||
"{name} did not exit after SIGINT\nstdout:\n{}\nstderr:\n{}",
|
||||
"{name} did not exit after {signal_name}\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
@@ -137,8 +145,8 @@ fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) {
|
||||
#[test]
|
||||
fn rncp_listener_exits_on_sigint() {
|
||||
let tmp = TempDir::new("rncp-sigint");
|
||||
write_config(&tmp);
|
||||
assert_sigint_exits(
|
||||
write_config(&tmp, false);
|
||||
assert_signal_exits(
|
||||
|| {
|
||||
Command::new(env!("CARGO_BIN_EXE_rncp-rs"))
|
||||
.arg("--config")
|
||||
@@ -152,6 +160,8 @@ fn rncp_listener_exits_on_sigint() {
|
||||
.expect("spawn rncp-rs listener")
|
||||
},
|
||||
"rncp-rs",
|
||||
"INT",
|
||||
2,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -159,8 +169,8 @@ fn rncp_listener_exits_on_sigint() {
|
||||
#[test]
|
||||
fn rnsh_listener_exits_on_sigint() {
|
||||
let tmp = TempDir::new("rnsh-sigint");
|
||||
write_config(&tmp);
|
||||
assert_sigint_exits(
|
||||
write_config(&tmp, false);
|
||||
assert_signal_exits(
|
||||
|| {
|
||||
Command::new(env!("CARGO_BIN_EXE_rnsh-rs"))
|
||||
.arg("--config")
|
||||
@@ -173,5 +183,32 @@ fn rnsh_listener_exits_on_sigint() {
|
||||
.expect("spawn rnsh-rs listener")
|
||||
},
|
||||
"rnsh-rs",
|
||||
"INT",
|
||||
2,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rnsd_flushes_state_and_exits_on_sigterm() {
|
||||
let tmp = TempDir::new("rnsd-sigterm");
|
||||
write_config(&tmp, true);
|
||||
assert_signal_exits(
|
||||
|| {
|
||||
Command::new(env!("CARGO_BIN_EXE_rnsd-rs"))
|
||||
.arg("--config")
|
||||
.arg(tmp.path())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn rnsd-rs")
|
||||
},
|
||||
"rnsd-rs",
|
||||
"TERM",
|
||||
15,
|
||||
);
|
||||
assert!(
|
||||
tmp.path().join("storage/packet_hashlist.raw").is_file(),
|
||||
"orderly SIGTERM shutdown must flush transport state"
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ name = "rns-transport"
|
||||
description = "Transport and routing engine for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
|
||||
@@ -28,6 +28,12 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else if crate::ifac::has_ifac_flag(&packet.raw) {
|
||||
trace!(
|
||||
interface_id = packet.interface_id,
|
||||
"IFAC packet received on clear interface, dropping packet"
|
||||
);
|
||||
return;
|
||||
} else {
|
||||
packet.raw.clone()
|
||||
}
|
||||
@@ -66,14 +72,12 @@ impl TransportActor {
|
||||
// repeat (keepalives, resource transfer frames, channel traffic) and
|
||||
// must bypass the check.
|
||||
let pkt_hash = rns_wire::hash::packet_hash(&raw, parsed.flags.header_type);
|
||||
self.record_packet_metrics(
|
||||
pkt_hash,
|
||||
PacketMetrics {
|
||||
rssi: packet.rssi,
|
||||
snr: packet.snr,
|
||||
q: packet.q,
|
||||
},
|
||||
);
|
||||
let packet_metrics = PacketMetrics {
|
||||
rssi: packet.rssi,
|
||||
snr: packet.snr,
|
||||
q: packet.q,
|
||||
};
|
||||
self.record_packet_metrics(pkt_hash, packet_metrics);
|
||||
let skip_hashlist = matches!(
|
||||
parsed.context,
|
||||
rns_wire::context::PacketContext::Keepalive
|
||||
@@ -119,13 +123,13 @@ impl TransportActor {
|
||||
self.process_announce(&raw, &parsed, data_offset, packet.interface_id);
|
||||
}
|
||||
rns_wire::flags::PacketType::LinkRequest => {
|
||||
self.process_link_request(&raw, &parsed, packet.interface_id);
|
||||
self.process_link_request(&raw, &parsed, packet.interface_id, packet_metrics);
|
||||
}
|
||||
rns_wire::flags::PacketType::Proof => {
|
||||
self.process_proof(&raw, &parsed, packet.interface_id);
|
||||
self.process_proof(&raw, &parsed, packet.interface_id, packet_metrics);
|
||||
}
|
||||
rns_wire::flags::PacketType::Data => {
|
||||
self.process_data(&raw, &parsed, packet.interface_id);
|
||||
self.process_data(&raw, &parsed, packet.interface_id, packet_metrics);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -581,7 +585,7 @@ impl TransportActor {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let _ = registration
|
||||
let send_result = registration
|
||||
.tx
|
||||
.try_send(crate::messages::AnnounceHandlerEvent {
|
||||
destination_hash: header.destination_hash,
|
||||
@@ -594,7 +598,17 @@ impl TransportActor {
|
||||
ratchet: announce_ratchet,
|
||||
name_hash: announce_name_hash,
|
||||
});
|
||||
if matches!(
|
||||
send_result,
|
||||
Err(tokio::sync::mpsc::error::TrySendError::Full(_))
|
||||
) {
|
||||
registration
|
||||
.dropped_events
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
self.announce_handlers
|
||||
.retain(|registration| !registration.tx.is_closed());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,6 +633,7 @@ impl TransportActor {
|
||||
raw: &bytes::Bytes,
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
interface_id: InterfaceId,
|
||||
metrics: PacketMetrics,
|
||||
) {
|
||||
let from_local_client = self.is_local_client_interface(interface_id);
|
||||
let for_local_client = self
|
||||
@@ -727,7 +742,7 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
tracing::debug!(
|
||||
dest = %hex::encode(header.destination_hash),
|
||||
is_local = self.local_destinations.contains(&header.destination_hash),
|
||||
has_channel = self.destination_channels.contains_key(&header.destination_hash),
|
||||
@@ -739,6 +754,7 @@ impl TransportActor {
|
||||
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw: raw.clone(),
|
||||
interface_id,
|
||||
metrics,
|
||||
}) {
|
||||
self.channel_drops += 1;
|
||||
warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e,
|
||||
@@ -780,6 +796,7 @@ impl TransportActor {
|
||||
raw: &bytes::Bytes,
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
interface_id: InterfaceId,
|
||||
metrics: PacketMetrics,
|
||||
) {
|
||||
let from_local_client = self.is_local_client_interface(interface_id);
|
||||
let for_local_client = self
|
||||
@@ -807,6 +824,7 @@ impl TransportActor {
|
||||
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::LinkRequest {
|
||||
raw: raw.clone(),
|
||||
interface_id,
|
||||
metrics,
|
||||
}) {
|
||||
self.channel_drops += 1;
|
||||
error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e,
|
||||
@@ -985,6 +1003,7 @@ impl TransportActor {
|
||||
raw: &bytes::Bytes,
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
_interface_id: InterfaceId,
|
||||
metrics: PacketMetrics,
|
||||
) {
|
||||
let from_local_client = self.is_local_client_interface(_interface_id);
|
||||
let for_local_client_link =
|
||||
@@ -1000,12 +1019,56 @@ impl TransportActor {
|
||||
.is_some_and(|entry| self.is_local_client_interface(entry.receiving_interface));
|
||||
|
||||
if header.context != rns_wire::context::PacketContext::Lrproof
|
||||
&& let Some(receipt) = self.receipt_table.get_mut(&header.destination_hash)
|
||||
&& self.receipt_table.contains_key(&header.destination_hash)
|
||||
{
|
||||
let rtt = receipt
|
||||
.get_rtt()
|
||||
.or_else(|| Some(receipt.sent_at.elapsed()));
|
||||
receipt.deliver();
|
||||
let payload_offset = header.size();
|
||||
let Some(proof) = raw.get(payload_offset..) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Python PacketReceipt retains the destination identity used for
|
||||
// the send and validates every explicit or implicit proof against
|
||||
// it. If registration preceded outbound binding, fill the key from
|
||||
// the validated announce cache before attempting verification.
|
||||
let destination_hash = self
|
||||
.receipt_table
|
||||
.get(&header.destination_hash)
|
||||
.and_then(|receipt| receipt.destination_hash);
|
||||
let recalled_public_key = destination_hash.and_then(|destination_hash| {
|
||||
self.recent_announces
|
||||
.get(&destination_hash)
|
||||
.and_then(|announce| announce.public_key)
|
||||
});
|
||||
let (validated, rtt) = {
|
||||
let receipt = self
|
||||
.receipt_table
|
||||
.get_mut(&header.destination_hash)
|
||||
.expect("receipt existence checked above");
|
||||
if receipt.destination_public_key.is_none() {
|
||||
if let Some(destination_hash) = receipt.destination_hash {
|
||||
receipt.set_destination_identity(destination_hash, recalled_public_key);
|
||||
}
|
||||
}
|
||||
let validated = receipt.validate_proof_from_destination(proof);
|
||||
(validated, receipt.get_rtt())
|
||||
};
|
||||
|
||||
if !validated {
|
||||
warn!(
|
||||
trunc = %hex::encode(header.destination_hash),
|
||||
proof_len = proof.len(),
|
||||
identity_known = recalled_public_key.is_some(),
|
||||
"invalid delivery proof rejected"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(status_tx) = self.receipt_updates.remove(&header.destination_hash) {
|
||||
let update = rtt.map_or(crate::messages::ReceiptUpdate::Failed, |rtt| {
|
||||
crate::messages::ReceiptUpdate::Delivered { rtt }
|
||||
});
|
||||
status_tx.send_replace(update);
|
||||
}
|
||||
|
||||
if let Some(msg_id) = self.receipt_msg_ids.remove(&header.destination_hash) {
|
||||
debug!(
|
||||
@@ -1119,6 +1182,7 @@ impl TransportActor {
|
||||
tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw: raw.clone(),
|
||||
interface_id: _interface_id,
|
||||
metrics,
|
||||
});
|
||||
if let Err(e) = delivered {
|
||||
self.channel_drops += 1;
|
||||
@@ -1193,6 +1257,7 @@ impl TransportActor {
|
||||
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw: raw.clone(),
|
||||
interface_id: _interface_id,
|
||||
metrics,
|
||||
}) {
|
||||
self.channel_drops += 1;
|
||||
error!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e,
|
||||
|
||||
@@ -131,15 +131,41 @@ impl TransportActor {
|
||||
}
|
||||
|
||||
if now - self.last_receipts_check >= RECEIPTS_CHECK_INTERVAL {
|
||||
for receipt in self.receipt_table.values_mut() {
|
||||
if receipt.status == ReceiptStatus::Sent && receipt.is_timed_out() {
|
||||
let mut concluded = Vec::new();
|
||||
for (key, receipt) in &mut self.receipt_table {
|
||||
let timed_out = receipt.status == ReceiptStatus::Sent && receipt.is_timed_out();
|
||||
if timed_out {
|
||||
receipt.fail();
|
||||
}
|
||||
if receipt.status != ReceiptStatus::Sent {
|
||||
let update = if timed_out {
|
||||
crate::messages::ReceiptUpdate::TimedOut
|
||||
} else {
|
||||
match receipt.status {
|
||||
ReceiptStatus::Delivered => receipt
|
||||
.get_rtt()
|
||||
.map_or(crate::messages::ReceiptUpdate::Failed, |rtt| {
|
||||
crate::messages::ReceiptUpdate::Delivered { rtt }
|
||||
}),
|
||||
ReceiptStatus::Culled => crate::messages::ReceiptUpdate::Culled,
|
||||
ReceiptStatus::Failed | ReceiptStatus::Receiving => {
|
||||
crate::messages::ReceiptUpdate::Failed
|
||||
}
|
||||
ReceiptStatus::Sent => continue,
|
||||
}
|
||||
};
|
||||
concluded.push((*key, update));
|
||||
}
|
||||
}
|
||||
// Only in-flight (Sent) receipts are worth keeping; concluded
|
||||
// ones (Delivered/Failed/Culled) were already signalled out.
|
||||
self.receipt_table
|
||||
.retain(|_, r| r.status == ReceiptStatus::Sent);
|
||||
for (key, update) in concluded {
|
||||
self.receipt_table.remove(&key);
|
||||
self.receipt_msg_ids.remove(&key);
|
||||
if let Some(status_tx) = self.receipt_updates.remove(&key) {
|
||||
status_tx.send_replace(update);
|
||||
}
|
||||
}
|
||||
let excess = self.receipt_table.len().saturating_sub(MAX_RECEIPTS);
|
||||
if excess > 0 {
|
||||
// Cull the oldest in one sorted pass — a min-scan per
|
||||
@@ -154,6 +180,10 @@ impl TransportActor {
|
||||
if let Some(mut receipt) = self.receipt_table.remove(&key) {
|
||||
receipt.cull();
|
||||
}
|
||||
self.receipt_msg_ids.remove(&key);
|
||||
if let Some(status_tx) = self.receipt_updates.remove(&key) {
|
||||
status_tx.send_replace(crate::messages::ReceiptUpdate::Culled);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.last_receipts_check = now;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -15,11 +15,19 @@ macro_rules! pr_log {
|
||||
|
||||
impl TransportActor {
|
||||
pub(super) fn on_outbound(&mut self, request: crate::messages::OutboundRequest) {
|
||||
let _ = self.on_outbound_with_receipt_policy(request, true);
|
||||
}
|
||||
|
||||
pub(super) fn on_outbound_with_receipt_policy(
|
||||
&mut self,
|
||||
request: crate::messages::OutboundRequest,
|
||||
create_receipt: bool,
|
||||
) -> bool {
|
||||
self.traffic.record_tx(0, request.raw.len() as u64); // interface 0 = local
|
||||
|
||||
let parsed = match rns_wire::header::PacketHeader::unpack(&request.raw) {
|
||||
Ok((header, _)) => header,
|
||||
Err(_) => return,
|
||||
Err(_) => return false,
|
||||
};
|
||||
|
||||
// Seed the dedup set with our own packet hash so echoes looped back
|
||||
@@ -30,25 +38,42 @@ impl TransportActor {
|
||||
// Generate a general-purpose receipt for every outbound Data packet to a
|
||||
// non-Plain destination so callers can observe delivery / timeout.
|
||||
// Link- and resource-level contexts manage their own receipts.
|
||||
if parsed.flags.packet_type == rns_wire::flags::PacketType::Data
|
||||
if create_receipt
|
||||
&& parsed.flags.packet_type == rns_wire::flags::PacketType::Data
|
||||
&& parsed.flags.destination_type != rns_wire::flags::DestinationType::Plain
|
||||
{
|
||||
let trunc_hash =
|
||||
rns_wire::hash::truncated_packet_hash(&request.raw, parsed.flags.header_type);
|
||||
if let std::collections::hash_map::Entry::Vacant(e) =
|
||||
self.receipt_table.entry(trunc_hash)
|
||||
{
|
||||
let full_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type);
|
||||
let receipt = PacketReceipt::new(
|
||||
full_hash,
|
||||
trunc_hash,
|
||||
Some(std::time::Duration::from_secs(180)),
|
||||
);
|
||||
e.insert(receipt);
|
||||
trace!(
|
||||
trunc = hex::encode(trunc_hash),
|
||||
"generated receipt for outbound packet"
|
||||
);
|
||||
let destination_public_key = self
|
||||
.recent_announces
|
||||
.get(&request.destination_hash)
|
||||
.and_then(|announce| announce.public_key);
|
||||
match self.receipt_table.entry(trunc_hash) {
|
||||
std::collections::hash_map::Entry::Vacant(entry) => {
|
||||
let full_hash =
|
||||
rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type);
|
||||
let mut receipt = PacketReceipt::new(
|
||||
full_hash,
|
||||
trunc_hash,
|
||||
Some(std::time::Duration::from_secs(180)),
|
||||
);
|
||||
receipt
|
||||
.set_destination_identity(request.destination_hash, destination_public_key);
|
||||
entry.insert(receipt);
|
||||
trace!(
|
||||
trunc = hex::encode(trunc_hash),
|
||||
"generated receipt for outbound packet"
|
||||
);
|
||||
}
|
||||
std::collections::hash_map::Entry::Occupied(mut entry) => {
|
||||
// Explicit receipt registration may arrive before the
|
||||
// outbound packet (for example rnprobe). Complete its
|
||||
// destination binding here without discarding its timeout
|
||||
// or application message id.
|
||||
entry
|
||||
.get_mut()
|
||||
.set_destination_identity(request.destination_hash, destination_public_key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,13 +86,17 @@ impl TransportActor {
|
||||
);
|
||||
|
||||
if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce {
|
||||
let has_outbound_interface = self
|
||||
.interfaces
|
||||
.values()
|
||||
.any(|interface| interface.direction.outbound);
|
||||
self.broadcast_local_announce_on_interfaces(&request.raw, None);
|
||||
return;
|
||||
return has_outbound_interface;
|
||||
}
|
||||
|
||||
match parsed.flags.destination_type {
|
||||
rns_wire::flags::DestinationType::Plain | rns_wire::flags::DestinationType::Group => {
|
||||
self.broadcast_on_interfaces(&request.raw, None);
|
||||
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_live(&request.destination_hash) {
|
||||
@@ -95,7 +124,7 @@ impl TransportActor {
|
||||
// Transport nodes only forward Header2 packets whose transport_id
|
||||
// matches their identity — Python hubs silently drop Header1 —
|
||||
// so every directed send through a relay must be wrapped.
|
||||
if let Some(next_hop) = path_next_hop {
|
||||
let sent = if let Some(next_hop) = path_next_hop {
|
||||
if parsed.flags.header_type == rns_wire::flags::HeaderType::Header1 {
|
||||
let new_flags = rns_wire::flags::PacketFlags {
|
||||
header_type: rns_wire::flags::HeaderType::Header2,
|
||||
@@ -123,25 +152,29 @@ impl TransportActor {
|
||||
transport_id = %hex::encode(next_hop),
|
||||
"outbound: wrapped Header1 -> Header2 for transport"
|
||||
);
|
||||
self.send_to_interface(target_interface, &new_raw);
|
||||
self.send_to_interface(target_interface, &new_raw)
|
||||
} else if apply_delta {
|
||||
let mangled = self.mangle_hops(&request.raw, &parsed, false);
|
||||
self.send_to_interface(target_interface, &mangled);
|
||||
self.send_to_interface(target_interface, &mangled)
|
||||
} else {
|
||||
self.send_to_interface(target_interface, &request.raw);
|
||||
self.send_to_interface(target_interface, &request.raw)
|
||||
}
|
||||
} else if apply_delta {
|
||||
let mangled = self.mangle_hops(&request.raw, &parsed, false);
|
||||
self.send_to_interface(target_interface, &mangled);
|
||||
self.send_to_interface(target_interface, &mangled)
|
||||
} else {
|
||||
self.send_to_interface(target_interface, &request.raw);
|
||||
}
|
||||
self.send_to_interface(target_interface, &request.raw)
|
||||
};
|
||||
|
||||
// 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_live_mut(&request.destination_hash) {
|
||||
path.touch();
|
||||
if sent {
|
||||
if let Some(path) = self.path_table.get_live_mut(&request.destination_hash)
|
||||
{
|
||||
path.touch();
|
||||
}
|
||||
}
|
||||
sent
|
||||
} else {
|
||||
let iface_names: Vec<&str> = self
|
||||
.interfaces
|
||||
@@ -154,10 +187,11 @@ impl TransportActor {
|
||||
broadcast_to = ?iface_names,
|
||||
"outbound: no path, broadcasting"
|
||||
);
|
||||
self.broadcast_on_interfaces(&request.raw, None);
|
||||
let sent = self.broadcast_on_interfaces(&request.raw, None);
|
||||
if parsed.flags.packet_type != rns_wire::flags::PacketType::Proof {
|
||||
self.on_automatic_path_request(request.destination_hash);
|
||||
}
|
||||
sent
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,7 +201,7 @@ impl TransportActor {
|
||||
&mut self,
|
||||
request: crate::messages::OutboundRequest,
|
||||
interface_id: InterfaceId,
|
||||
) {
|
||||
) -> bool {
|
||||
self.traffic.record_tx(0, request.raw.len() as u64);
|
||||
|
||||
if let Ok((parsed, _)) = rns_wire::header::PacketHeader::unpack(&request.raw) {
|
||||
@@ -175,20 +209,23 @@ impl TransportActor {
|
||||
self.packet_hashlist.insert(pkt_hash);
|
||||
// Python's outbound applies should_apply_delta on attached-
|
||||
// interface sends too (Transport.py:1342-1345).
|
||||
if self.should_apply_delta(&parsed, interface_id) {
|
||||
let sent = if self.should_apply_delta(&parsed, interface_id) {
|
||||
let transport_insert = parsed.flags.packet_type
|
||||
== rns_wire::flags::PacketType::Announce
|
||||
&& parsed.flags.header_type == rns_wire::flags::HeaderType::Header1;
|
||||
let mangled = self.mangle_hops(&request.raw, &parsed, transport_insert);
|
||||
self.send_to_interface(interface_id, &mangled);
|
||||
self.send_to_interface(interface_id, &mangled)
|
||||
} else {
|
||||
self.send_to_interface(interface_id, &request.raw);
|
||||
}
|
||||
if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce {
|
||||
self.send_to_interface(interface_id, &request.raw)
|
||||
};
|
||||
if sent && parsed.flags.packet_type == rns_wire::flags::PacketType::Announce {
|
||||
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
|
||||
entry.ingress.sent_announce();
|
||||
}
|
||||
}
|
||||
sent
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -649,6 +686,34 @@ impl TransportActor {
|
||||
self.broadcast_path_request(destination_hash);
|
||||
}
|
||||
|
||||
pub(super) fn on_path_request_with_options(
|
||||
&mut self,
|
||||
destination_hash: [u8; 16],
|
||||
options: crate::messages::PathRequestOptions,
|
||||
) {
|
||||
let request_tag = options
|
||||
.tag
|
||||
.unwrap_or_else(|| rns_crypto::random::random_bytes(16));
|
||||
if let Some(interface_id) = options.on_interface {
|
||||
self.send_path_request(
|
||||
destination_hash,
|
||||
interface_id,
|
||||
Some(&request_tag),
|
||||
options.recursive,
|
||||
);
|
||||
} else {
|
||||
// Python only applies recursive announce-cap gating when an
|
||||
// interface is explicitly attached.
|
||||
self.forward_path_request(destination_hash, None, Some(&request_tag), false);
|
||||
}
|
||||
debug!(
|
||||
dest = hex::encode(destination_hash),
|
||||
interface = ?options.on_interface,
|
||||
recursive = options.recursive,
|
||||
"explicit path request sent"
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn on_automatic_path_request(&mut self, destination_hash: [u8; 16]) {
|
||||
if self.path_table.has_path(&destination_hash) {
|
||||
return;
|
||||
|
||||
@@ -27,24 +27,26 @@ fn recent_announce_from_cached_packet(
|
||||
name_hash: [0u8; 10],
|
||||
};
|
||||
|
||||
if let Ok((header, offset)) = rns_wire::header::PacketHeader::unpack(&raw_packet)
|
||||
&& header.flags.packet_type == rns_wire::flags::PacketType::Announce
|
||||
&& header.destination_hash == dest_hash
|
||||
&& raw_packet.len() >= offset
|
||||
{
|
||||
recent.packet_hash = Some(rns_wire::hash::packet_hash(
|
||||
&raw_packet,
|
||||
header.flags.header_type,
|
||||
));
|
||||
recent.is_path_response = header.context == rns_wire::context::PacketContext::PathResponse;
|
||||
if let Ok(announce) = rns_identity::announce::AnnounceData::unpack(
|
||||
&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;
|
||||
if let Ok((header, offset)) = rns_wire::header::PacketHeader::unpack(&raw_packet) {
|
||||
if header.flags.packet_type == rns_wire::flags::PacketType::Announce
|
||||
&& header.destination_hash == dest_hash
|
||||
&& raw_packet.len() >= offset
|
||||
{
|
||||
recent.packet_hash = Some(rns_wire::hash::packet_hash(
|
||||
&raw_packet,
|
||||
header.flags.header_type,
|
||||
));
|
||||
recent.is_path_response =
|
||||
header.context == rns_wire::context::PacketContext::PathResponse;
|
||||
if let Ok(announce) = rns_identity::announce::AnnounceData::unpack(
|
||||
&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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,11 +60,10 @@ fn python_announce_cache_index(
|
||||
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());
|
||||
if let Some(name) = entry.file_name().to_str() {
|
||||
if name.len() == 64 && name.as_bytes().iter().all(u8::is_ascii_hexdigit) {
|
||||
names.insert(name.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(names)
|
||||
@@ -284,18 +285,31 @@ impl TransportActor {
|
||||
self.routing_save_in_flight
|
||||
.store(true, std::sync::atomic::Ordering::Release);
|
||||
let snapshot = self.routing_snapshot();
|
||||
let generation = self
|
||||
.routing_save_generation
|
||||
.fetch_add(1, std::sync::atomic::Ordering::AcqRel)
|
||||
.wrapping_add(1);
|
||||
let latest_generation = self.routing_save_generation.clone();
|
||||
let write_lock = self.routing_save_lock.clone();
|
||||
let in_flight = self.routing_save_in_flight.clone();
|
||||
let write = move || {
|
||||
let _guard = write_lock
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if latest_generation.load(std::sync::atomic::Ordering::Acquire) == generation {
|
||||
write_routing_snapshot(&dir, &snapshot);
|
||||
} else {
|
||||
trace!(generation, "skipping superseded routing-state snapshot");
|
||||
}
|
||||
in_flight.store(false, std::sync::atomic::Ordering::Release);
|
||||
};
|
||||
match tokio::runtime::Handle::try_current() {
|
||||
Ok(handle) => {
|
||||
handle.spawn_blocking(move || {
|
||||
write_routing_snapshot(&dir, &snapshot);
|
||||
in_flight.store(false, std::sync::atomic::Ordering::Release);
|
||||
});
|
||||
handle.spawn_blocking(write);
|
||||
}
|
||||
Err(_) => {
|
||||
// No runtime (tests, exotic embedders): write inline.
|
||||
write_routing_snapshot(&dir, &snapshot);
|
||||
in_flight.store(false, std::sync::atomic::Ordering::Release);
|
||||
write();
|
||||
}
|
||||
}
|
||||
self.state_dirty = false;
|
||||
@@ -381,26 +395,35 @@ impl TransportActor {
|
||||
true
|
||||
}
|
||||
|
||||
/// Wait (bounded) for an in-flight async save so a synchronous save
|
||||
/// can't race it on the shared `<file>.tmp` paths.
|
||||
pub(super) fn wait_for_routing_save(&self) {
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
|
||||
/// Wait (bounded) for an older asynchronous hashlist snapshot before a
|
||||
/// synchronous flush takes its newer snapshot. Without this ordering, an
|
||||
/// already-queued background writer could replace the shutdown file with
|
||||
/// stale state after the synchronous write completed.
|
||||
pub(super) fn wait_for_hashlist_save(&self) -> bool {
|
||||
self.wait_for_hashlist_save_until(
|
||||
std::time::Instant::now() + std::time::Duration::from_secs(15),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn wait_for_hashlist_save_until(&self, deadline: std::time::Instant) -> bool {
|
||||
while self
|
||||
.routing_save_in_flight
|
||||
.hashlist_save_in_flight
|
||||
.load(std::sync::atomic::Ordering::Acquire)
|
||||
{
|
||||
if std::time::Instant::now() >= deadline {
|
||||
tracing::warn!("in-flight routing-state save did not finish before sync save");
|
||||
break;
|
||||
tracing::warn!("in-flight hashlist save did not finish before sync save");
|
||||
return false;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Flush the small/critical routing-state files: path_table,
|
||||
/// announce_cache, blackhole_table, tunnel_table. Hashlist is excluded —
|
||||
/// it can be multiple MB and is rebuildable from in-flight traffic, so
|
||||
/// we save it only on shutdown / falling-edge via `save_state`.
|
||||
/// it can be multiple MB and is rebuildable from in-flight traffic, so it
|
||||
/// is persisted independently on the scheduled `PersistData` command,
|
||||
/// background falling edges, and shutdown.
|
||||
/// Synchronous: used by shutdown / falling-edge / RPC-forced saves where
|
||||
/// completion must be guaranteed before proceeding.
|
||||
pub(super) fn save_routing_state(&mut self) {
|
||||
@@ -411,9 +434,14 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
|
||||
self.wait_for_routing_save();
|
||||
if let Some(dir) = self.storage_dir.clone() {
|
||||
let snapshot = self.routing_snapshot();
|
||||
self.routing_save_generation
|
||||
.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
|
||||
let _guard = self
|
||||
.routing_save_lock
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
write_routing_snapshot(&dir, &snapshot);
|
||||
}
|
||||
self.state_dirty = false;
|
||||
@@ -426,17 +454,20 @@ 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 {
|
||||
if !self.owns_persistent_hashlist() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(ref dir) = self.storage_dir {
|
||||
let hashlist_path = dir.join("packet_hashlist");
|
||||
if let Err(e) = crate::persistence::save_hashlist(&self.packet_hashlist, &hashlist_path)
|
||||
{
|
||||
if !self.wait_for_hashlist_save() {
|
||||
return;
|
||||
}
|
||||
let hashlist_path = dir.join("packet_hashlist.raw");
|
||||
let hashes = self.packet_hashlist.current_hashes();
|
||||
if let Err(e) = crate::persistence::save_raw_hashes(&hashes, &hashlist_path) {
|
||||
trace!("failed to save hashlist: {}", e);
|
||||
} else {
|
||||
info!(entries = self.packet_hashlist.len(), "flushed hashlist");
|
||||
info!(entries = hashes.len(), "flushed hashlist");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -447,7 +478,7 @@ impl TransportActor {
|
||||
/// file on macOS) stalls routing + control queries for seconds.
|
||||
pub(super) fn save_state_async(&mut self) {
|
||||
self.save_routing_state_async();
|
||||
if self.shared_instance_client_mode {
|
||||
if !self.owns_persistent_hashlist() {
|
||||
return;
|
||||
}
|
||||
let Some(dir) = self.storage_dir.clone() else {
|
||||
@@ -462,12 +493,12 @@ impl TransportActor {
|
||||
}
|
||||
self.hashlist_save_in_flight
|
||||
.store(true, std::sync::atomic::Ordering::Release);
|
||||
let hashlist = self.packet_hashlist.clone();
|
||||
let hashes = self.packet_hashlist.current_hashes();
|
||||
let in_flight = self.hashlist_save_in_flight.clone();
|
||||
let entries = hashlist.len();
|
||||
let entries = hashes.len();
|
||||
let write = move || {
|
||||
let hashlist_path = dir.join("packet_hashlist");
|
||||
if let Err(e) = crate::persistence::save_hashlist(&hashlist, &hashlist_path) {
|
||||
let hashlist_path = dir.join("packet_hashlist.raw");
|
||||
if let Err(e) = crate::persistence::save_raw_hashes(&hashes, &hashlist_path) {
|
||||
trace!("failed to save hashlist: {}", e);
|
||||
} else {
|
||||
info!(entries, "flushed hashlist");
|
||||
@@ -486,6 +517,98 @@ impl TransportActor {
|
||||
self.save_state();
|
||||
}
|
||||
|
||||
fn owns_persistent_hashlist(&self) -> bool {
|
||||
self.is_transport_enabled && !self.shared_instance_client_mode
|
||||
}
|
||||
|
||||
/// Restore the canonical packet hashlist once both storage and the
|
||||
/// actor's transport authority are known. Shared-instance clients and
|
||||
/// non-transport leaves must never load or overwrite the authoritative
|
||||
/// transport node's deduplication state.
|
||||
pub(super) fn maybe_load_hashlist(&mut self) {
|
||||
if self.hashlist_load_attempted || !self.owns_persistent_hashlist() {
|
||||
return;
|
||||
}
|
||||
let Some(dir) = self.storage_dir.clone() else {
|
||||
return;
|
||||
};
|
||||
self.hashlist_load_attempted = true;
|
||||
|
||||
let raw_path = dir.join("packet_hashlist.raw");
|
||||
if raw_path.exists() {
|
||||
match crate::persistence::load_hashlist_raw(&raw_path) {
|
||||
Ok(loaded) => {
|
||||
let count = loaded.hashes.len();
|
||||
if loaded.partial_tail_bytes > 0 {
|
||||
tracing::warn!(
|
||||
path = %raw_path.display(),
|
||||
ignored_bytes = loaded.partial_tail_bytes,
|
||||
"ignored partial packet hash at end of canonical hashlist"
|
||||
);
|
||||
}
|
||||
if loaded.duplicate_count > 0 {
|
||||
debug!(
|
||||
duplicates = loaded.duplicate_count,
|
||||
"deduplicated canonical packet hashlist"
|
||||
);
|
||||
}
|
||||
self.packet_hashlist.load_from(loaded.hashes);
|
||||
debug!(count, "loaded canonical packet hashlist from disk");
|
||||
}
|
||||
Err(e) => {
|
||||
// The canonical file is authoritative when present. Do
|
||||
// not mask damage by silently falling back to stale
|
||||
// legacy state.
|
||||
tracing::warn!(
|
||||
path = %raw_path.display(),
|
||||
error = %e,
|
||||
"failed to load canonical packet hashlist"
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let legacy_paths = [dir.join("packet_hashlist"), dir.join("hashlist.msgpack")];
|
||||
for legacy_path in legacy_paths {
|
||||
if !legacy_path.exists() {
|
||||
continue;
|
||||
}
|
||||
match crate::persistence::load_hashlist_legacy(&legacy_path) {
|
||||
Ok(hashes) => {
|
||||
let count = hashes.len();
|
||||
self.packet_hashlist.load_from(hashes.clone());
|
||||
match crate::persistence::save_raw_hashes(&hashes, &raw_path) {
|
||||
Ok(()) => {
|
||||
info!(
|
||||
source = %legacy_path.display(),
|
||||
destination = %raw_path.display(),
|
||||
count,
|
||||
"migrated legacy packet hashlist"
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
source = %legacy_path.display(),
|
||||
destination = %raw_path.display(),
|
||||
error = %e,
|
||||
"loaded legacy packet hashlist but failed canonical migration"
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
path = %legacy_path.display(),
|
||||
error = %e,
|
||||
"failed to load legacy packet hashlist"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore on-disk transport state. Entries can't bind to a concrete
|
||||
/// `interface_id` until the matching interface re-registers, so they're
|
||||
/// staged in `pending_path_entries` / `pending_tunnel_entries` and
|
||||
@@ -497,30 +620,6 @@ impl TransportActor {
|
||||
};
|
||||
let now_ts = now();
|
||||
|
||||
// packet_hashlist — Python-compatible canonical shape. Fall back to
|
||||
// the old Rust sidecar so existing local development state still loads.
|
||||
let hashlist_path = dir.join("packet_hashlist");
|
||||
let legacy_hashlist_path = dir.join("hashlist.msgpack");
|
||||
let hashlist_path = if hashlist_path.exists() {
|
||||
Some(hashlist_path)
|
||||
} else if legacy_hashlist_path.exists() {
|
||||
Some(legacy_hashlist_path)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(hashlist_path) = hashlist_path {
|
||||
match crate::persistence::load_hashlist(&hashlist_path) {
|
||||
Ok(hashes) => {
|
||||
let count = hashes.len();
|
||||
self.packet_hashlist.load_from(hashes);
|
||||
debug!(count, "loaded packet hashlist from disk");
|
||||
}
|
||||
Err(e) => {
|
||||
trace!("failed to load packet hashlist: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Python destination_table — canonical interop shape. Defer interface
|
||||
// hash remap until matching interfaces register.
|
||||
let destination_table_path = dir.join("destination_table");
|
||||
@@ -1351,6 +1450,18 @@ mod async_save_tests {
|
||||
fn dirty_actor(dir: &std::path::Path) -> TransportActor {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
actor.storage_dir = Some(dir.to_path_buf());
|
||||
let (interface_tx, _interface_rx) = tokio::sync::mpsc::channel(1);
|
||||
actor.interfaces.insert(
|
||||
7,
|
||||
crate::messages::InterfaceEntry::new(
|
||||
"persisted-test-interface".to_string(),
|
||||
crate::constants::InterfaceMode::Gateway,
|
||||
crate::constants::InterfaceDirection::bidirectional(),
|
||||
1_000_000,
|
||||
rns_wire::constants::MTU as u32,
|
||||
interface_tx,
|
||||
),
|
||||
);
|
||||
actor.path_table.insert(
|
||||
[0x11; 16],
|
||||
crate::path_table::PathEntry {
|
||||
@@ -1421,22 +1532,23 @@ mod async_save_tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The synchronous path (shutdown / falling edge) waits for an in-flight
|
||||
/// async save before writing, then completes inline.
|
||||
/// The synchronous path (shutdown / falling edge) serializes behind an
|
||||
/// in-flight publication, then completes inline.
|
||||
#[test]
|
||||
fn sync_save_waits_for_in_flight_then_writes() {
|
||||
let dir = temp_storage();
|
||||
let mut actor = dirty_actor(&dir);
|
||||
|
||||
let flag = actor.routing_save_in_flight.clone();
|
||||
flag.store(true, std::sync::atomic::Ordering::Release);
|
||||
let release = std::thread::spawn({
|
||||
let flag = flag.clone();
|
||||
move || {
|
||||
std::thread::sleep(std::time::Duration::from_millis(150));
|
||||
flag.store(false, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
let write_lock = actor.routing_save_lock.clone();
|
||||
let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
|
||||
let release = std::thread::spawn(move || {
|
||||
let _guard = write_lock
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
acquired_tx.send(()).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(150));
|
||||
});
|
||||
acquired_rx.recv().unwrap();
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
actor.save_routing_state();
|
||||
@@ -1444,10 +1556,78 @@ mod async_save_tests {
|
||||
|
||||
assert!(
|
||||
started.elapsed() >= std::time::Duration::from_millis(140),
|
||||
"sync save must wait out the in-flight writer"
|
||||
"sync save must serialize behind the active writer"
|
||||
);
|
||||
assert!(dir.join("path_table.msgpack").exists());
|
||||
assert!(!actor.state_dirty);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A queued periodic snapshot that loses the generation race must not
|
||||
/// publish after a newer synchronous snapshot.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn superseded_periodic_snapshot_cannot_replace_sync_state() {
|
||||
let dir = temp_storage();
|
||||
let path = dir.join("path_table.msgpack");
|
||||
let mut actor = dirty_actor(&dir);
|
||||
let write_lock = actor.routing_save_lock.clone();
|
||||
let guard = write_lock
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
|
||||
actor.save_routing_state_async();
|
||||
let generation = actor.routing_save_generation.clone();
|
||||
let sync_writer = std::thread::spawn(move || {
|
||||
actor.path_table.insert(
|
||||
[0x44; 16],
|
||||
crate::path_table::PathEntry {
|
||||
timestamp: crate::now_f64(),
|
||||
next_hop: Some([0x55; 16]),
|
||||
hops: 2,
|
||||
expires: crate::now_f64() + 600.0,
|
||||
random_blobs: std::collections::VecDeque::new(),
|
||||
interface_id: 7,
|
||||
packet_hash: Some([0x66; 32]),
|
||||
},
|
||||
);
|
||||
actor.save_routing_state();
|
||||
actor
|
||||
});
|
||||
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while generation.load(std::sync::atomic::Ordering::Acquire) < 2 {
|
||||
assert!(
|
||||
std::time::Instant::now() < deadline,
|
||||
"sync writer did not claim a newer generation"
|
||||
);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
drop(guard);
|
||||
let actor = sync_writer.join().unwrap();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while actor
|
||||
.routing_save_in_flight
|
||||
.load(std::sync::atomic::Ordering::Acquire)
|
||||
{
|
||||
assert!(
|
||||
std::time::Instant::now() < deadline,
|
||||
"superseded periodic writer did not retire"
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
|
||||
let entries = crate::persistence::load_path_table(&path).unwrap();
|
||||
assert_eq!(entries.len(), 2);
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|entry| entry.destination_hash == [0x44; 16])
|
||||
);
|
||||
assert!(
|
||||
!actor
|
||||
.routing_save_in_flight
|
||||
.load(std::sync::atomic::Ordering::Acquire)
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,22 @@ impl TransportActor {
|
||||
.as_ref()
|
||||
.map(|c| c.load(std::sync::atomic::Ordering::Relaxed))
|
||||
.unwrap_or(0);
|
||||
let inspection = entry
|
||||
.inspection
|
||||
.as_ref()
|
||||
.map(|source| {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
source.snapshot()
|
||||
}))
|
||||
.unwrap_or_else(|_| {
|
||||
tracing::warn!(
|
||||
interface_id = iface_id,
|
||||
"interface inspection callback panicked",
|
||||
);
|
||||
InterfaceInspectionSnapshot::default()
|
||||
})
|
||||
})
|
||||
.unwrap_or_default();
|
||||
InterfaceStatRpcEntry {
|
||||
id: iface_id,
|
||||
name: entry.name.clone(),
|
||||
@@ -96,7 +112,8 @@ impl TransportActor {
|
||||
entry.ingress.is_pr_burst_active(),
|
||||
entry.ingress.pr_burst_activated(),
|
||||
),
|
||||
clients: None,
|
||||
clients: inspection.active_clients,
|
||||
blocked_ips: inspection.blocked_ips,
|
||||
announce_rate_target: entry.announce_rate_target,
|
||||
announce_rate_grace: entry.announce_rate_grace,
|
||||
announce_rate_penalty: entry.announce_rate_penalty,
|
||||
@@ -155,6 +172,27 @@ impl TransportActor {
|
||||
});
|
||||
TransportQueryResponse::Announces(entries)
|
||||
}
|
||||
TransportQuery::RecallDestination { dest } => {
|
||||
let recalled = self.recent_announces.get(&dest).and_then(|entry| {
|
||||
Some(RecalledDestinationRpcEntry {
|
||||
dest_hash: entry.dest_hash,
|
||||
public_key: entry.public_key?,
|
||||
app_data: entry.app_data.clone(),
|
||||
ratchet: entry.ratchet,
|
||||
hops: entry.hops,
|
||||
timestamp: entry.timestamp,
|
||||
})
|
||||
});
|
||||
TransportQueryResponse::RecalledDestination(recalled)
|
||||
}
|
||||
TransportQuery::HasPath { dest } => {
|
||||
TransportQueryResponse::BoolResult(self.path_table.has_path(&dest))
|
||||
}
|
||||
TransportQuery::HopsTo { dest } => TransportQueryResponse::IntResult(i64::from(
|
||||
self.path_table
|
||||
.hops_to(&dest)
|
||||
.unwrap_or(crate::constants::PATHFINDER_M),
|
||||
)),
|
||||
TransportQuery::GetNextHop { dest } => {
|
||||
// Python 1.3.8 Transport.py:2685-2688: local destinations
|
||||
// resolve to Transport.identity.hash.
|
||||
@@ -482,6 +520,16 @@ impl TransportActor {
|
||||
.map(|iface| iface.bitrate as f64);
|
||||
TransportQueryResponse::FloatResult(bitrate)
|
||||
}
|
||||
TransportQuery::GetNextHopHardwareMtu { dest } => {
|
||||
let mtu = self
|
||||
.path_table
|
||||
.get_live(&dest)
|
||||
.map(|e| e.interface_id)
|
||||
.or_else(|| self.local_destination_interface_id(&dest))
|
||||
.and_then(|id| self.interfaces.get(&id))
|
||||
.map(|iface| i64::from(iface.mtu));
|
||||
TransportQueryResponse::IntResult(mtu.unwrap_or(-1))
|
||||
}
|
||||
TransportQuery::GetNextHopInterfaceId { dest } => {
|
||||
let id = self
|
||||
.path_table
|
||||
@@ -550,11 +598,11 @@ impl TransportActor {
|
||||
}
|
||||
TransportQuery::ResolveIdentityHash { input } => {
|
||||
// First treat input as a destination hash.
|
||||
if let Some(entry) = self.recent_announces.get(&input)
|
||||
&& let Some(public_key) = entry.public_key
|
||||
{
|
||||
let id_hash = rns_crypto::sha::truncated_hash(&public_key);
|
||||
return TransportQueryResponse::HashResult(Some(id_hash));
|
||||
if let Some(entry) = self.recent_announces.get(&input) {
|
||||
if let Some(public_key) = entry.public_key {
|
||||
let id_hash = rns_crypto::sha::truncated_hash(&public_key);
|
||||
return TransportQueryResponse::HashResult(Some(id_hash));
|
||||
}
|
||||
}
|
||||
// Fall back to treating input as an identity hash already.
|
||||
for entry in self.recent_announces.values() {
|
||||
|
||||
@@ -68,8 +68,10 @@ pub const PATH_REQUEST_RG: f64 = 1.5;
|
||||
/// Minimum interval between path requests (seconds).
|
||||
pub const PATH_REQUEST_MI: f64 = 20.0;
|
||||
|
||||
/// Maximum packet hashes before rotation. Set to 2M with rotation at
|
||||
/// `maxsize/2` so effective history matches Python's 1M-no-rotation window.
|
||||
/// Maximum packet hashes retained across both generations.
|
||||
///
|
||||
/// Python retains roughly one million hashes. Rust deliberately retains up
|
||||
/// to two million for a longer bounded replay window; see RNS-D0056.
|
||||
pub const HASHLIST_MAXSIZE: usize = 2_000_000;
|
||||
|
||||
/// Job loop period (250ms).
|
||||
|
||||
@@ -48,7 +48,7 @@ pub struct DiscoveryInterfaceConfig {
|
||||
pub longitude: f64,
|
||||
pub height: f64,
|
||||
/// Set the `FLAG_ENCRYPTED` bit; caller supplies `encrypt` closure at
|
||||
/// announce time via [`AnnounceRequest::assemble`].
|
||||
/// announce time via [`Announcer::tick`].
|
||||
pub encrypt: bool,
|
||||
/// Set the `FLAG_SIGNED` bit (independent of `encrypt`).
|
||||
pub signed: bool,
|
||||
@@ -106,7 +106,8 @@ struct InterfaceAnnounceState {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AnnounceRequest {
|
||||
pub interface_id: InterfaceId,
|
||||
/// Fully-assembled `app_data` bytes (flags || [encrypted] body).
|
||||
/// Fully assembled `app_data` bytes (flags followed by the optionally
|
||||
/// encrypted body).
|
||||
pub app_data: Vec<u8>,
|
||||
/// Stamp value actually achieved — useful for logging.
|
||||
pub stamp_value: u8,
|
||||
|
||||
@@ -92,10 +92,10 @@ pub fn build_local_manifest(
|
||||
if entry.source.is_some() {
|
||||
continue;
|
||||
}
|
||||
if let Some(set) = verified_ids
|
||||
&& !set.contains(hash.as_bytes())
|
||||
{
|
||||
continue;
|
||||
if let Some(set) = verified_ids {
|
||||
if !set.contains(hash.as_bytes()) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let until = entry.ttl.map(|ttl| entry.created + ttl);
|
||||
let wire_entry = encode_entry_map(until, entry.reason_str(), our_identity_hash);
|
||||
|
||||
@@ -33,9 +33,8 @@ pub const UPDATE_INTERVAL: Duration = Duration::from_secs(60 * 60);
|
||||
/// establishment / request when it lands.
|
||||
pub const SOURCE_TIMEOUT: Duration = Duration::from_secs(25);
|
||||
|
||||
/// Per-process subscriber state. Cheap to clone-on-snapshot via the
|
||||
/// [`SubscriberState::snapshot`] helper; the runtime owner holds the
|
||||
/// authoritative copy.
|
||||
/// Per-process subscriber state. Cheap to clone for inspection; the runtime
|
||||
/// owner holds the authoritative copy.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SubscriberState {
|
||||
/// Unix-seconds timestamp of the most recent successful pull, keyed by
|
||||
|
||||
@@ -23,7 +23,7 @@ pub const ANNOUNCE_JOB_INTERVAL_SECS: u64 = 60;
|
||||
/// Default stamp-value requirement used by both sender (when an interface
|
||||
/// leaves `discovery_stamp_value` unset) and receiver. Matches Python
|
||||
/// `InterfaceAnnouncer.DEFAULT_STAMP_VALUE`.
|
||||
pub const DEFAULT_STAMP_VALUE: u8 = 14;
|
||||
pub const DEFAULT_STAMP_VALUE: u8 = 16;
|
||||
|
||||
/// Rounds used when deriving the stamp workblock. Matches Python
|
||||
/// `InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS`.
|
||||
|
||||
@@ -10,13 +10,16 @@
|
||||
//! 5. upsert into [`DiscoveryStore`] and notify any observer.
|
||||
//!
|
||||
//! Mirrors Python `Discovery.InterfaceAnnounceHandler.received_announce`.
|
||||
//! Runs as a dedicated Tokio task so slow stamp validation does not stall
|
||||
//! the transport actor loop.
|
||||
//! The spawned path uses a bounded blocking-worker set so slow stamp
|
||||
//! validation cannot stall the transport actor or a Tokio runtime worker.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, TryLockError};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::task::{JoinHandle, JoinSet};
|
||||
use tracing::{debug, trace, warn};
|
||||
|
||||
use crate::messages::AnnounceHandlerEvent;
|
||||
@@ -26,6 +29,10 @@ use super::constants::FLAG_ENCRYPTED;
|
||||
use super::stamper::DiscoveryStamper;
|
||||
use super::storage::{DiscoveredInterface, DiscoveryStore};
|
||||
|
||||
const VALID_CACHE_CAPACITY: usize = 2_048;
|
||||
const INVALID_CACHE_CAPACITY: usize = 2_048;
|
||||
const MAX_IN_FLIGHT_EVENTS: usize = 32;
|
||||
|
||||
/// Pluggable decryptor for discovery announces whose flags byte has
|
||||
/// `FLAG_ENCRYPTED` set. The concrete impl wraps the `network_identity`
|
||||
/// (Python `RNS.Identity.decrypt`).
|
||||
@@ -58,8 +65,8 @@ pub struct ReceiverConfig {
|
||||
}
|
||||
|
||||
/// Result of a single announce classification. Returned by
|
||||
/// [`process_event`] so tests can assert on decisions without needing a
|
||||
/// live tokio task.
|
||||
/// [`ReceiverConfig::process_event`] so tests can assert on decisions without
|
||||
/// needing a live tokio task.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Outcome {
|
||||
/// Announce accepted and upserted.
|
||||
@@ -78,6 +85,8 @@ pub enum Reason {
|
||||
EncryptedWithoutKey,
|
||||
/// Decryptor returned `None` (ciphertext not addressed to us).
|
||||
DecryptFailed,
|
||||
/// Another ingress worker is already performing stamp validation.
|
||||
ValidationBusy,
|
||||
/// Stamp did not meet the required value.
|
||||
StampInvalid,
|
||||
/// Info map did not decode.
|
||||
@@ -88,12 +97,171 @@ pub enum Reason {
|
||||
StorageFailed,
|
||||
}
|
||||
|
||||
/// Monotonic, payload-free counters for receiver cache and admission behavior.
|
||||
///
|
||||
/// Values saturate at `u64::MAX`. No announce bytes, hashes, identities, or
|
||||
/// decrypted fields are retained in the metrics.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ReceiverMetrics {
|
||||
valid_cache_hits: AtomicU64,
|
||||
invalid_cache_hits: AtomicU64,
|
||||
validation_busy_drops: AtomicU64,
|
||||
valid_cache_evictions: AtomicU64,
|
||||
invalid_cache_evictions: AtomicU64,
|
||||
}
|
||||
|
||||
/// Point-in-time snapshot of [`ReceiverMetrics`].
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct ReceiverMetricsSnapshot {
|
||||
pub valid_cache_hits: u64,
|
||||
pub invalid_cache_hits: u64,
|
||||
pub validation_busy_drops: u64,
|
||||
pub valid_cache_evictions: u64,
|
||||
pub invalid_cache_evictions: u64,
|
||||
}
|
||||
|
||||
impl ReceiverMetrics {
|
||||
pub fn snapshot(&self) -> ReceiverMetricsSnapshot {
|
||||
ReceiverMetricsSnapshot {
|
||||
valid_cache_hits: self.valid_cache_hits.load(Ordering::Relaxed),
|
||||
invalid_cache_hits: self.invalid_cache_hits.load(Ordering::Relaxed),
|
||||
validation_busy_drops: self.validation_busy_drops.load(Ordering::Relaxed),
|
||||
valid_cache_evictions: self.valid_cache_evictions.load(Ordering::Relaxed),
|
||||
invalid_cache_evictions: self.invalid_cache_evictions.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
fn increment(counter: &AtomicU64) -> u64 {
|
||||
let previous = counter
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
|
||||
Some(value.saturating_add(1))
|
||||
})
|
||||
.unwrap_or(u64::MAX);
|
||||
previous.saturating_add(1)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
struct CacheKey([u8; 32]);
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ValidatedMaterial {
|
||||
info: DiscoveryInfo,
|
||||
stamp: Vec<u8>,
|
||||
stamp_value: u8,
|
||||
}
|
||||
|
||||
enum CacheLookup {
|
||||
Valid(Box<ValidatedMaterial>),
|
||||
Invalid,
|
||||
Miss,
|
||||
}
|
||||
|
||||
struct ValidationCaches {
|
||||
valid: HashMap<CacheKey, ValidatedMaterial>,
|
||||
valid_order: VecDeque<CacheKey>,
|
||||
invalid: HashSet<CacheKey>,
|
||||
invalid_order: VecDeque<CacheKey>,
|
||||
valid_capacity: usize,
|
||||
invalid_capacity: usize,
|
||||
}
|
||||
|
||||
impl ValidationCaches {
|
||||
fn new(valid_capacity: usize, invalid_capacity: usize) -> Self {
|
||||
Self {
|
||||
valid: HashMap::with_capacity(valid_capacity),
|
||||
valid_order: VecDeque::with_capacity(valid_capacity),
|
||||
invalid: HashSet::with_capacity(invalid_capacity),
|
||||
invalid_order: VecDeque::with_capacity(invalid_capacity),
|
||||
valid_capacity,
|
||||
invalid_capacity,
|
||||
}
|
||||
}
|
||||
|
||||
fn lookup(&self, key: &CacheKey) -> CacheLookup {
|
||||
if let Some(material) = self.valid.get(key) {
|
||||
CacheLookup::Valid(Box::new(material.clone()))
|
||||
} else if self.invalid.contains(key) {
|
||||
CacheLookup::Invalid
|
||||
} else {
|
||||
CacheLookup::Miss
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_valid(&mut self, key: CacheKey, material: ValidatedMaterial) -> bool {
|
||||
if let Entry::Occupied(mut entry) = self.valid.entry(key) {
|
||||
entry.insert(material);
|
||||
return false;
|
||||
}
|
||||
|
||||
if self.invalid.remove(&key) {
|
||||
self.invalid_order.retain(|queued| queued != &key);
|
||||
}
|
||||
self.valid.insert(key, material);
|
||||
self.valid_order.push_back(key);
|
||||
self.evict_valid_if_needed()
|
||||
}
|
||||
|
||||
fn insert_invalid(&mut self, key: CacheKey) -> bool {
|
||||
if self.invalid.contains(&key) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if self.valid.remove(&key).is_some() {
|
||||
self.valid_order.retain(|queued| queued != &key);
|
||||
}
|
||||
self.invalid.insert(key);
|
||||
self.invalid_order.push_back(key);
|
||||
self.evict_invalid_if_needed()
|
||||
}
|
||||
|
||||
fn evict_valid_if_needed(&mut self) -> bool {
|
||||
let mut evicted = false;
|
||||
while self.valid.len() > self.valid_capacity {
|
||||
if let Some(oldest) = self.valid_order.pop_front() {
|
||||
evicted |= self.valid.remove(&oldest).is_some();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
evicted
|
||||
}
|
||||
|
||||
fn evict_invalid_if_needed(&mut self) -> bool {
|
||||
let mut evicted = false;
|
||||
while self.invalid.len() > self.invalid_capacity {
|
||||
if let Some(oldest) = self.invalid_order.pop_front() {
|
||||
evicted |= self.invalid.remove(&oldest);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
evicted
|
||||
}
|
||||
}
|
||||
|
||||
struct ReceiverState {
|
||||
config: ReceiverConfig,
|
||||
caches: Mutex<ValidationCaches>,
|
||||
validation_lock: Mutex<()>,
|
||||
persistence_lock: Mutex<()>,
|
||||
metrics: Arc<ReceiverMetrics>,
|
||||
}
|
||||
|
||||
impl ReceiverConfig {
|
||||
/// Classify a single announce event, upsert on accept, emit on observer.
|
||||
///
|
||||
/// Synchronous so unit tests can drive it without a task. Returns an
|
||||
/// [`Outcome`] describing the decision.
|
||||
pub fn process_event(&self, event: &AnnounceHandlerEvent) -> Outcome {
|
||||
self.process_event_inner(event, None)
|
||||
}
|
||||
|
||||
fn process_event_inner(
|
||||
&self,
|
||||
event: &AnnounceHandlerEvent,
|
||||
receiver: Option<&ReceiverState>,
|
||||
) -> Outcome {
|
||||
let Some(raw) = event.app_data.as_ref() else {
|
||||
return Outcome::Rejected(Reason::MissingAppData);
|
||||
};
|
||||
@@ -103,13 +271,41 @@ impl ReceiverConfig {
|
||||
Err(_) => return Outcome::Rejected(Reason::Malformed),
|
||||
};
|
||||
|
||||
let encrypted = flags & FLAG_ENCRYPTED != 0;
|
||||
if encrypted && self.decryptor.is_none() {
|
||||
return Outcome::Rejected(Reason::EncryptedWithoutKey);
|
||||
}
|
||||
|
||||
// Hash the exact wire app_data, including flags and ciphertext. For
|
||||
// encrypted announces, bind the key to this receiver's decryptor
|
||||
// instance so plaintext validated under one network identity cannot
|
||||
// satisfy another identity's cache.
|
||||
let cache_key = receiver.map(|state| {
|
||||
let decryptor = if encrypted {
|
||||
Some(self.decryptor.as_ref().expect("checked above"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
state.cache_key(raw, decryptor)
|
||||
});
|
||||
|
||||
if let (Some(state), Some(key)) = (receiver, cache_key) {
|
||||
match state.cache_lookup(&key) {
|
||||
CacheLookup::Valid(material) => {
|
||||
return self.accept_material(event, *material, receiver);
|
||||
}
|
||||
CacheLookup::Invalid => {
|
||||
return Outcome::Rejected(Reason::StampInvalid);
|
||||
}
|
||||
CacheLookup::Miss => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Decrypt body if FLAG_ENCRYPTED set. We own the bytes once we
|
||||
// decrypt, but keep a borrow when unencrypted.
|
||||
let decrypted: Vec<u8>;
|
||||
let working: &[u8] = if flags & FLAG_ENCRYPTED != 0 {
|
||||
let Some(decryptor) = self.decryptor.as_ref() else {
|
||||
return Outcome::Rejected(Reason::EncryptedWithoutKey);
|
||||
};
|
||||
let working: &[u8] = if encrypted {
|
||||
let decryptor = self.decryptor.as_ref().expect("checked above");
|
||||
match decryptor.decrypt(body) {
|
||||
Some(pt) => {
|
||||
decrypted = pt;
|
||||
@@ -126,19 +322,61 @@ impl ReceiverConfig {
|
||||
Err(_) => return Outcome::Rejected(Reason::Malformed),
|
||||
};
|
||||
|
||||
let material = if let (Some(state), Some(key)) = (receiver, cache_key) {
|
||||
match state.validate_and_cache(key, packed_info, stamp) {
|
||||
Ok(material) => material,
|
||||
Err(reason) => return Outcome::Rejected(reason),
|
||||
}
|
||||
} else {
|
||||
match self.validate_material(packed_info, stamp) {
|
||||
Ok(material) => material,
|
||||
Err(reason) => return Outcome::Rejected(reason),
|
||||
}
|
||||
};
|
||||
|
||||
self.accept_material(event, material, receiver)
|
||||
}
|
||||
|
||||
fn validate_material(
|
||||
&self,
|
||||
packed_info: &[u8],
|
||||
stamp: &[u8],
|
||||
) -> Result<ValidatedMaterial, Reason> {
|
||||
let infohash = rns_crypto::sha::full_hash(packed_info);
|
||||
if !self.stamper.valid(&infohash, stamp, self.required_value) {
|
||||
return Outcome::Rejected(Reason::StampInvalid);
|
||||
return Err(Reason::StampInvalid);
|
||||
}
|
||||
|
||||
let info: DiscoveryInfo = match app_data::decode_info(packed_info) {
|
||||
Ok(i) => i,
|
||||
Err(err) => {
|
||||
trace!(?err, "discovery: info decode failed");
|
||||
return Outcome::Rejected(Reason::DecodeFailed);
|
||||
return Err(Reason::DecodeFailed);
|
||||
}
|
||||
};
|
||||
|
||||
Ok(ValidatedMaterial {
|
||||
info,
|
||||
stamp: stamp.to_vec(),
|
||||
stamp_value: self.stamper.value(&infohash, stamp),
|
||||
})
|
||||
}
|
||||
|
||||
fn accept_material(
|
||||
&self,
|
||||
event: &AnnounceHandlerEvent,
|
||||
material: ValidatedMaterial,
|
||||
receiver: Option<&ReceiverState>,
|
||||
) -> Outcome {
|
||||
// `DiscoveryStore::upsert` uses a deterministic sidecar name. Keep
|
||||
// concurrent cache hits from racing on that file while leaving stamp
|
||||
// validation independent.
|
||||
let _persistence_guard = receiver.map(|state| lock_unpoisoned(&state.persistence_lock));
|
||||
let ValidatedMaterial {
|
||||
info,
|
||||
stamp,
|
||||
stamp_value,
|
||||
} = material;
|
||||
let announced_identity = event.identity_hash.unwrap_or(info.transport_id);
|
||||
if let Some(sources) = self.discovery_sources.as_ref() {
|
||||
if !sources.iter().any(|s| s == &announced_identity) {
|
||||
@@ -146,14 +384,13 @@ impl ReceiverConfig {
|
||||
}
|
||||
}
|
||||
|
||||
let stamp_value = self.stamper.value(&infohash, stamp);
|
||||
let now = now_unix();
|
||||
let record = DiscoveredInterface {
|
||||
info,
|
||||
network_id: announced_identity,
|
||||
hops: event.hops,
|
||||
stamp_value,
|
||||
stamp: stamp.to_vec(),
|
||||
stamp,
|
||||
discovered: now,
|
||||
last_heard: now,
|
||||
heard_count: 0, // overridden by upsert merge
|
||||
@@ -175,31 +412,181 @@ impl ReceiverConfig {
|
||||
}
|
||||
}
|
||||
|
||||
impl ReceiverState {
|
||||
fn new(config: ReceiverConfig, metrics: Arc<ReceiverMetrics>) -> Self {
|
||||
Self {
|
||||
config,
|
||||
caches: Mutex::new(ValidationCaches::new(
|
||||
VALID_CACHE_CAPACITY,
|
||||
INVALID_CACHE_CAPACITY,
|
||||
)),
|
||||
validation_lock: Mutex::new(()),
|
||||
persistence_lock: Mutex::new(()),
|
||||
metrics,
|
||||
}
|
||||
}
|
||||
|
||||
fn process_event(&self, event: &AnnounceHandlerEvent) -> Outcome {
|
||||
self.config.process_event_inner(event, Some(self))
|
||||
}
|
||||
|
||||
fn cache_key(
|
||||
&self,
|
||||
raw_app_data: &[u8],
|
||||
decryptor: Option<&Arc<dyn DiscoveryDecryptor>>,
|
||||
) -> CacheKey {
|
||||
const PLAIN_DOMAIN: &[u8] = b"rns.discovery.cache.plain.v1";
|
||||
const ENCRYPTED_DOMAIN: &[u8] = b"rns.discovery.cache.encrypted.v1";
|
||||
|
||||
let mut key_material = Vec::with_capacity(
|
||||
raw_app_data.len() + ENCRYPTED_DOMAIN.len() + std::mem::size_of::<usize>(),
|
||||
);
|
||||
if let Some(decryptor) = decryptor {
|
||||
key_material.extend_from_slice(ENCRYPTED_DOMAIN);
|
||||
let instance = Arc::as_ptr(decryptor) as *const () as usize;
|
||||
key_material.extend_from_slice(&instance.to_ne_bytes());
|
||||
} else {
|
||||
key_material.extend_from_slice(PLAIN_DOMAIN);
|
||||
}
|
||||
key_material.extend_from_slice(raw_app_data);
|
||||
CacheKey(rns_crypto::sha::full_hash(&key_material))
|
||||
}
|
||||
|
||||
fn cache_lookup(&self, key: &CacheKey) -> CacheLookup {
|
||||
let result = lock_unpoisoned(&self.caches).lookup(key);
|
||||
match result {
|
||||
CacheLookup::Valid(_) => {
|
||||
let hits = ReceiverMetrics::increment(&self.metrics.valid_cache_hits);
|
||||
trace!(hits, "discovery: valid announce cache hit");
|
||||
}
|
||||
CacheLookup::Invalid => {
|
||||
let hits = ReceiverMetrics::increment(&self.metrics.invalid_cache_hits);
|
||||
trace!(hits, "discovery: invalid announce cache hit");
|
||||
}
|
||||
CacheLookup::Miss => {}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn validate_and_cache(
|
||||
&self,
|
||||
key: CacheKey,
|
||||
packed_info: &[u8],
|
||||
stamp: &[u8],
|
||||
) -> Result<ValidatedMaterial, Reason> {
|
||||
let _validation_guard = match self.validation_lock.try_lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(TryLockError::Poisoned(err)) => err.into_inner(),
|
||||
Err(TryLockError::WouldBlock) => {
|
||||
let drops = ReceiverMetrics::increment(&self.metrics.validation_busy_drops);
|
||||
debug!(
|
||||
drops,
|
||||
"discovery: announce dropped while stamp validator is busy"
|
||||
);
|
||||
return Err(Reason::ValidationBusy);
|
||||
}
|
||||
};
|
||||
|
||||
// Another worker may have completed validation between our initial
|
||||
// miss and acquiring the gate.
|
||||
match self.cache_lookup(&key) {
|
||||
CacheLookup::Valid(material) => return Ok(*material),
|
||||
CacheLookup::Invalid => return Err(Reason::StampInvalid),
|
||||
CacheLookup::Miss => {}
|
||||
}
|
||||
|
||||
let infohash = rns_crypto::sha::full_hash(packed_info);
|
||||
if !self
|
||||
.config
|
||||
.stamper
|
||||
.valid(&infohash, stamp, self.config.required_value)
|
||||
{
|
||||
let evicted = lock_unpoisoned(&self.caches).insert_invalid(key);
|
||||
if evicted {
|
||||
ReceiverMetrics::increment(&self.metrics.invalid_cache_evictions);
|
||||
}
|
||||
return Err(Reason::StampInvalid);
|
||||
}
|
||||
|
||||
let info = match app_data::decode_info(packed_info) {
|
||||
Ok(info) => info,
|
||||
Err(err) => {
|
||||
trace!(?err, "discovery: info decode failed");
|
||||
return Err(Reason::DecodeFailed);
|
||||
}
|
||||
};
|
||||
let material = ValidatedMaterial {
|
||||
info,
|
||||
stamp: stamp.to_vec(),
|
||||
stamp_value: self.config.stamper.value(&infohash, stamp),
|
||||
};
|
||||
let evicted = lock_unpoisoned(&self.caches).insert_valid(key, material.clone());
|
||||
if evicted {
|
||||
ReceiverMetrics::increment(&self.metrics.valid_cache_evictions);
|
||||
}
|
||||
Ok(material)
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_unpoisoned<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
mutex.lock().unwrap_or_else(|err| err.into_inner())
|
||||
}
|
||||
|
||||
/// Spawn the receiver task. Returns the sender to register with
|
||||
/// `TransportMessage::RegisterAnnounceHandler { aspect_filter:
|
||||
/// Some("rnstransport.discovery.interface"), callback_tx }` and the
|
||||
/// [`JoinHandle`] for shutdown.
|
||||
pub fn spawn(config: ReceiverConfig) -> (JoinHandle<()>, mpsc::Sender<AnnounceHandlerEvent>) {
|
||||
let (handle, tx, _metrics) = spawn_with_metrics(config);
|
||||
(handle, tx)
|
||||
}
|
||||
|
||||
/// Spawn the receiver and retain a handle to its payload-free operational
|
||||
/// counters.
|
||||
pub fn spawn_with_metrics(
|
||||
config: ReceiverConfig,
|
||||
) -> (
|
||||
JoinHandle<()>,
|
||||
mpsc::Sender<AnnounceHandlerEvent>,
|
||||
Arc<ReceiverMetrics>,
|
||||
) {
|
||||
let (tx, mut rx) = mpsc::channel::<AnnounceHandlerEvent>(128);
|
||||
let metrics = Arc::new(ReceiverMetrics::default());
|
||||
let state = Arc::new(ReceiverState::new(config, metrics.clone()));
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut workers = JoinSet::new();
|
||||
while let Some(event) = rx.recv().await {
|
||||
let outcome = config.process_event(&event);
|
||||
match outcome {
|
||||
Outcome::Accepted => debug!(
|
||||
dest = %hex::encode(event.destination_hash),
|
||||
hops = event.hops,
|
||||
"discovery announce accepted"
|
||||
),
|
||||
Outcome::Rejected(ref reason) => trace!(
|
||||
dest = %hex::encode(event.destination_hash),
|
||||
?reason,
|
||||
"discovery announce rejected"
|
||||
),
|
||||
let worker_state = state.clone();
|
||||
workers.spawn_blocking(move || {
|
||||
let outcome = worker_state.process_event(&event);
|
||||
match outcome {
|
||||
Outcome::Accepted => debug!(
|
||||
dest = %hex::encode(event.destination_hash),
|
||||
hops = event.hops,
|
||||
"discovery announce accepted"
|
||||
),
|
||||
Outcome::Rejected(ref reason) => trace!(
|
||||
dest = %hex::encode(event.destination_hash),
|
||||
?reason,
|
||||
"discovery announce rejected"
|
||||
),
|
||||
}
|
||||
});
|
||||
|
||||
// Keep detached blocking work bounded while still admitting
|
||||
// concurrent callbacks. Stamp validation itself is serialized by
|
||||
// `validation_lock`; cache hits and persistence can proceed in
|
||||
// parallel.
|
||||
if workers.len() >= MAX_IN_FLIGHT_EVENTS {
|
||||
let _ = workers.join_next().await;
|
||||
}
|
||||
while workers.try_join_next().is_some() {}
|
||||
}
|
||||
|
||||
while workers.join_next().await.is_some() {}
|
||||
debug!("discovery receiver task exiting");
|
||||
});
|
||||
(handle, tx)
|
||||
(handle, tx, metrics)
|
||||
}
|
||||
|
||||
fn now_unix() -> u64 {
|
||||
@@ -256,6 +643,50 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
struct CountingStamper {
|
||||
valid_result: bool,
|
||||
value: u8,
|
||||
valid_calls: AtomicU64,
|
||||
value_calls: AtomicU64,
|
||||
}
|
||||
|
||||
impl CountingStamper {
|
||||
fn new(valid_result: bool, value: u8) -> Self {
|
||||
Self {
|
||||
valid_result,
|
||||
value,
|
||||
valid_calls: AtomicU64::new(0),
|
||||
value_calls: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DiscoveryStamper for CountingStamper {
|
||||
fn generate(&self, _ih: &[u8; 32], _tv: u8) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn value(&self, _ih: &[u8; 32], _stamp: &[u8]) -> u8 {
|
||||
self.value_calls.fetch_add(1, Ordering::Relaxed);
|
||||
self.value
|
||||
}
|
||||
|
||||
fn valid(&self, _ih: &[u8; 32], _stamp: &[u8], _required: u8) -> bool {
|
||||
self.valid_calls.fetch_add(1, Ordering::Relaxed);
|
||||
self.valid_result
|
||||
}
|
||||
}
|
||||
|
||||
struct MaskDecryptor {
|
||||
mask: u8,
|
||||
}
|
||||
|
||||
impl DiscoveryDecryptor for MaskDecryptor {
|
||||
fn decrypt(&self, ciphertext: &[u8]) -> Option<Vec<u8>> {
|
||||
Some(ciphertext.iter().map(|byte| byte ^ self.mask).collect())
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_info() -> DiscoveryInfo {
|
||||
DiscoveryInfo {
|
||||
name: "unit-test-iface".into(),
|
||||
@@ -574,6 +1005,132 @@ mod tests {
|
||||
assert_eq!(received.info.name, "unit-test-iface");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_cache_hit_runs_stamper_once() {
|
||||
let dir = tmpdir("valid-cache");
|
||||
let store = Arc::new(DiscoveryStore::open(&dir).unwrap());
|
||||
let stamp = vec![0xAB; STAMP_SIZE];
|
||||
let stamper = Arc::new(CountingStamper::new(true, 20));
|
||||
let (blob, _) = stamped_blob(&sample_info(), &stamp);
|
||||
let metrics = Arc::new(ReceiverMetrics::default());
|
||||
let state = ReceiverState::new(
|
||||
make_cfg(stamper.clone(), store, None, None),
|
||||
metrics.clone(),
|
||||
);
|
||||
let event = event_with(blob);
|
||||
|
||||
assert_eq!(state.process_event(&event), Outcome::Accepted);
|
||||
assert_eq!(state.process_event(&event), Outcome::Accepted);
|
||||
assert_eq!(stamper.valid_calls.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(stamper.value_calls.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(metrics.snapshot().valid_cache_hits, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_cache_hit_runs_stamper_once() {
|
||||
let dir = tmpdir("invalid-cache");
|
||||
let store = Arc::new(DiscoveryStore::open(&dir).unwrap());
|
||||
let stamp = vec![0xAB; STAMP_SIZE];
|
||||
let stamper = Arc::new(CountingStamper::new(false, 0));
|
||||
let (blob, _) = stamped_blob(&sample_info(), &stamp);
|
||||
let metrics = Arc::new(ReceiverMetrics::default());
|
||||
let state = ReceiverState::new(
|
||||
make_cfg(stamper.clone(), store, None, None),
|
||||
metrics.clone(),
|
||||
);
|
||||
let event = event_with(blob);
|
||||
|
||||
assert_eq!(
|
||||
state.process_event(&event),
|
||||
Outcome::Rejected(Reason::StampInvalid)
|
||||
);
|
||||
assert_eq!(
|
||||
state.process_event(&event),
|
||||
Outcome::Rejected(Reason::StampInvalid)
|
||||
);
|
||||
assert_eq!(stamper.valid_calls.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(stamper.value_calls.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(metrics.snapshot().invalid_cache_hits, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_caches_evict_fifo() {
|
||||
assert_eq!(VALID_CACHE_CAPACITY, 2_048);
|
||||
assert_eq!(INVALID_CACHE_CAPACITY, 2_048);
|
||||
|
||||
let material = ValidatedMaterial {
|
||||
info: sample_info(),
|
||||
stamp: vec![0; STAMP_SIZE],
|
||||
stamp_value: 20,
|
||||
};
|
||||
let one = CacheKey([1; 32]);
|
||||
let two = CacheKey([2; 32]);
|
||||
let three = CacheKey([3; 32]);
|
||||
|
||||
let mut valid = ValidationCaches::new(2, 2);
|
||||
assert!(!valid.insert_valid(one, material.clone()));
|
||||
assert!(!valid.insert_valid(two, material.clone()));
|
||||
assert!(matches!(valid.lookup(&one), CacheLookup::Valid(_)));
|
||||
assert!(valid.insert_valid(three, material));
|
||||
assert!(matches!(valid.lookup(&one), CacheLookup::Miss));
|
||||
assert!(matches!(valid.lookup(&two), CacheLookup::Valid(_)));
|
||||
assert!(matches!(valid.lookup(&three), CacheLookup::Valid(_)));
|
||||
|
||||
let mut invalid = ValidationCaches::new(2, 2);
|
||||
assert!(!invalid.insert_invalid(one));
|
||||
assert!(!invalid.insert_invalid(two));
|
||||
assert!(matches!(invalid.lookup(&one), CacheLookup::Invalid));
|
||||
assert!(invalid.insert_invalid(three));
|
||||
assert!(matches!(invalid.lookup(&one), CacheLookup::Miss));
|
||||
assert!(matches!(invalid.lookup(&two), CacheLookup::Invalid));
|
||||
assert!(matches!(invalid.lookup(&three), CacheLookup::Invalid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_validator_drops_without_running_stamper() {
|
||||
let dir = tmpdir("busy-drop");
|
||||
let store = Arc::new(DiscoveryStore::open(&dir).unwrap());
|
||||
let stamp = vec![0xAB; STAMP_SIZE];
|
||||
let stamper = Arc::new(CountingStamper::new(true, 20));
|
||||
let (blob, _) = stamped_blob(&sample_info(), &stamp);
|
||||
let metrics = Arc::new(ReceiverMetrics::default());
|
||||
let state = ReceiverState::new(
|
||||
make_cfg(stamper.clone(), store, None, None),
|
||||
metrics.clone(),
|
||||
);
|
||||
let validation_guard = state.validation_lock.lock().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
state.process_event(&event_with(blob)),
|
||||
Outcome::Rejected(Reason::ValidationBusy)
|
||||
);
|
||||
assert_eq!(stamper.valid_calls.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(metrics.snapshot().validation_busy_drops, 1);
|
||||
drop(validation_guard);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_cache_keys_are_isolated_by_decryptor() {
|
||||
let dir = tmpdir("encrypted-isolation");
|
||||
let store = Arc::new(DiscoveryStore::open(&dir).unwrap());
|
||||
let stamp = vec![0xAB; STAMP_SIZE];
|
||||
let stamper = Arc::new(MockStamper::new(stamp.clone(), 20));
|
||||
let (blob, _) = encrypted_blob(&sample_info(), &stamp);
|
||||
let decryptor_a: Arc<dyn DiscoveryDecryptor> = Arc::new(MaskDecryptor { mask: 0xFF });
|
||||
let decryptor_b: Arc<dyn DiscoveryDecryptor> = Arc::new(MaskDecryptor { mask: 0xFF });
|
||||
let metrics = Arc::new(ReceiverMetrics::default());
|
||||
let state = ReceiverState::new(
|
||||
make_cfg(stamper, store, None, Some(decryptor_a.clone())),
|
||||
metrics,
|
||||
);
|
||||
|
||||
let key_a = state.cache_key(&blob, Some(&decryptor_a));
|
||||
let key_b = state.cache_key(&blob, Some(&decryptor_b));
|
||||
let plain_key = state.cache_key(&blob, None);
|
||||
assert_ne!(key_a, key_b);
|
||||
assert_ne!(key_a, plain_key);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_round_trip() {
|
||||
let dir = tmpdir("spawn");
|
||||
|
||||
@@ -66,7 +66,20 @@ impl PacketHashlist {
|
||||
self.previous.clear();
|
||||
}
|
||||
|
||||
/// All hashes across both generations; used to snapshot for persistence.
|
||||
/// Snapshot the current generation for persistence.
|
||||
///
|
||||
/// The previous generation is deliberately transient. Persisting both
|
||||
/// generations would continually carry already-aged hashes across
|
||||
/// restarts instead of letting the normal rotation window expire them.
|
||||
pub fn current_hashes(&self) -> Vec<[u8; 32]> {
|
||||
self.current.iter().copied().collect()
|
||||
}
|
||||
|
||||
/// Snapshot both in-memory generations.
|
||||
///
|
||||
/// This preserves the pre-1.4 public inspection API. Persistence must use
|
||||
/// [`Self::current_hashes`] so the aged previous generation remains
|
||||
/// transient.
|
||||
pub fn all_hashes(&self) -> Vec<[u8; 32]> {
|
||||
self.current
|
||||
.iter()
|
||||
@@ -75,10 +88,14 @@ impl PacketHashlist {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Rehydrate from a persisted snapshot. Loaded into `previous` so fresh
|
||||
/// packets land in an empty `current` and rotation behaviour is preserved.
|
||||
/// Rehydrate the current generation from a persisted snapshot.
|
||||
///
|
||||
/// This mirrors Reticulum's canonical `packet_hashlist.raw` lifecycle:
|
||||
/// the restored generation remains the one written at the next
|
||||
/// persistence boundary, while the previous generation stays ephemeral.
|
||||
pub fn load_from(&mut self, hashes: Vec<[u8; 32]>) {
|
||||
self.previous = hashes.into_iter().collect();
|
||||
self.current = hashes.into_iter().collect();
|
||||
self.previous.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,4 +152,35 @@ mod tests {
|
||||
hl.clear();
|
||||
assert_eq!(hl.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_snapshot_contains_only_current_generation() {
|
||||
let mut hl = PacketHashlist::new_with_capacity(4);
|
||||
hl.insert([0x01; 32]);
|
||||
hl.insert([0x02; 32]);
|
||||
// The third insertion rotates the first two hashes into `previous`.
|
||||
hl.insert([0x03; 32]);
|
||||
|
||||
assert_eq!(hl.current_hashes(), vec![[0x03; 32]]);
|
||||
let all = hl.all_hashes();
|
||||
assert_eq!(all.len(), 3);
|
||||
assert!(all.contains(&[0x01; 32]));
|
||||
assert!(all.contains(&[0x02; 32]));
|
||||
assert!(all.contains(&[0x03; 32]));
|
||||
assert_eq!(hl.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restored_hashes_populate_current_generation_and_deduplicate() {
|
||||
let mut hl = PacketHashlist::new_with_capacity(10);
|
||||
hl.insert([0x01; 32]);
|
||||
hl.force_rotate();
|
||||
|
||||
hl.load_from(vec![[0xAA; 32], [0xAA; 32], [0xBB; 32]]);
|
||||
|
||||
assert_eq!(hl.len(), 2);
|
||||
assert!(hl.current_hashes().contains(&[0xAA; 32]));
|
||||
assert!(hl.current_hashes().contains(&[0xBB; 32]));
|
||||
assert!(!hl.contains(&[0x01; 32]));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,14 @@ use tokio::sync::oneshot;
|
||||
|
||||
use crate::messages::InterfaceId;
|
||||
|
||||
/// Physical-layer measurements attached to one received packet.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct PacketMetrics {
|
||||
pub rssi: Option<f32>,
|
||||
pub snr: Option<f32>,
|
||||
pub q: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AnnounceRequest {
|
||||
pub app_name: String,
|
||||
@@ -32,10 +40,12 @@ pub enum DestinationEvent {
|
||||
InboundPacket {
|
||||
raw: Bytes,
|
||||
interface_id: InterfaceId,
|
||||
metrics: PacketMetrics,
|
||||
},
|
||||
LinkRequest {
|
||||
raw: Bytes,
|
||||
interface_id: InterfaceId,
|
||||
metrics: PacketMetrics,
|
||||
},
|
||||
LinkEstablished {
|
||||
link_id: [u8; 16],
|
||||
@@ -75,12 +85,14 @@ mod tests {
|
||||
let evt1 = DestinationEvent::InboundPacket {
|
||||
raw: Bytes::from_static(&[1, 2, 3]),
|
||||
interface_id: 42,
|
||||
metrics: PacketMetrics::default(),
|
||||
};
|
||||
assert!(matches!(evt1, DestinationEvent::InboundPacket { .. }));
|
||||
|
||||
let evt2 = DestinationEvent::LinkRequest {
|
||||
raw: Bytes::from_static(&[4, 5, 6]),
|
||||
interface_id: 99,
|
||||
metrics: PacketMetrics::default(),
|
||||
};
|
||||
assert!(matches!(evt2, DestinationEvent::LinkRequest { .. }));
|
||||
|
||||
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user