mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e0d0a6888 | ||
|
|
6c77c9e69d | ||
|
|
27352fd0d4 | ||
|
|
fd973420f2 | ||
|
|
b12f331082 | ||
|
|
04300ecdf4 | ||
|
|
a1b78564e0 | ||
|
|
70b739988b | ||
|
|
140d0aeed4 | ||
|
|
ec61a566d3 | ||
|
|
1285e06cf6 | ||
|
|
bc419b109d | ||
|
|
eee619ef3b | ||
|
|
e47a1d4932 | ||
|
|
07ca72179e | ||
|
|
d24e4e3ce3 | ||
|
|
869322fa80 | ||
|
|
2bce74c74c | ||
|
|
8e58e1b708 | ||
|
|
7a187a7aa0 | ||
|
|
d424c96fa3 | ||
|
|
6547f8370d | ||
|
|
740051c41e | ||
|
|
04db8c9f46 | ||
|
|
9928abed26 |
No files matched your search
+13
-11
@@ -26,14 +26,14 @@ jobs:
|
||||
cache-bin: false
|
||||
- name: Install system deps (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- name: Test (default features)
|
||||
run: cargo test --workspace
|
||||
run: cargo test --workspace --locked
|
||||
- name: Build application examples
|
||||
run: cargo build -p rns-runtime --examples
|
||||
run: cargo build -p rns-runtime --examples --locked
|
||||
- name: Test BLE interface features (Linux/macOS)
|
||||
if: runner.os != 'Windows'
|
||||
run: cargo test -p rns-interface --features ble
|
||||
run: cargo test -p rns-interface --features ble --locked
|
||||
|
||||
lint:
|
||||
name: Lint
|
||||
@@ -45,15 +45,14 @@ jobs:
|
||||
with:
|
||||
components: clippy, rustfmt
|
||||
- name: Install system deps
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- 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
|
||||
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
- name: Check public API documentation
|
||||
env:
|
||||
RUSTDOCFLAGS: "-D warnings"
|
||||
run: cargo doc --workspace --no-deps
|
||||
- run: cargo check --workspace --no-default-features
|
||||
run: cargo doc --workspace --no-deps --locked
|
||||
- run: cargo check --workspace --no-default-features --locked
|
||||
|
||||
msrv:
|
||||
name: Rust 1.85 MSRV
|
||||
@@ -62,9 +61,12 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@1.85.0
|
||||
with:
|
||||
components: clippy
|
||||
- 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
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- name: Clippy (all targets and features)
|
||||
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
@@ -1,5 +1,17 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Forward authenticated non-Link packet delivery proofs from `LinkManager` to
|
||||
owning applications through a lossless completion channel.
|
||||
- Retain and retry destination announcements, including path responses, when
|
||||
the bounded transport ingress is temporarily saturated.
|
||||
- Let one-shot Link clients reuse a validated cached identity when its route is
|
||||
still live, matching Python recall behavior and avoiding redundant path
|
||||
discovery.
|
||||
- Keep completed `rncp` Links alive for Python's receiver-side Resource
|
||||
conclusion callback before sending the authenticated teardown.
|
||||
|
||||
## 1.1.0 - 2026-07-26
|
||||
|
||||
- Added application-facing Destination, announce, receipt, Link, request,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -27,6 +27,124 @@ use rns_transport::messages::TransportMessage;
|
||||
const MIN_TRANSFER_TIMEOUT: Duration = Duration::from_millis(1);
|
||||
const USB_READER_BOUNDARY_POLL_INTERVAL: Duration = Duration::from_millis(1);
|
||||
|
||||
/// Stable identity retained across Android's transient `/dev/bus/usb` names.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct UsbDeviceSelector {
|
||||
pub(crate) legacy_device_name: String,
|
||||
pub(crate) vendor_id: Option<u16>,
|
||||
pub(crate) product_id: Option<u16>,
|
||||
pub(crate) serial_number: Option<String>,
|
||||
}
|
||||
|
||||
/// Permission-safe device facts obtained from one UsbManager enumeration.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct UsbDeviceCandidate {
|
||||
pub(crate) device_name: String,
|
||||
pub(crate) vendor_id: u16,
|
||||
pub(crate) product_id: u16,
|
||||
pub(crate) serial_number: Option<String>,
|
||||
pub(crate) has_permission: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum UsbDeviceResolutionError {
|
||||
NotFound,
|
||||
Ambiguous { matches: usize },
|
||||
PermissionRequired { device_name: String },
|
||||
}
|
||||
|
||||
impl std::fmt::Display for UsbDeviceResolutionError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::NotFound => formatter.write_str("configured Android USB device is not attached"),
|
||||
Self::Ambiguous { matches } => write!(
|
||||
formatter,
|
||||
"configured Android USB selector matches {matches} devices; refusing ambiguous reopen"
|
||||
),
|
||||
Self::PermissionRequired { .. } => {
|
||||
formatter.write_str("Android USB permission is required")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve one physical generation without ever guessing between devices.
|
||||
/// A legacy path may identify the first generation exactly; the returned
|
||||
/// selector learns VID/PID and an accessible serial for later path changes.
|
||||
pub(crate) fn resolve_usb_device(
|
||||
selector: &UsbDeviceSelector,
|
||||
candidates: &[UsbDeviceCandidate],
|
||||
) -> Result<(UsbDeviceCandidate, UsbDeviceSelector), UsbDeviceResolutionError> {
|
||||
let mut matches: Vec<&UsbDeviceCandidate> = match (selector.vendor_id, selector.product_id) {
|
||||
(Some(vendor_id), Some(product_id)) => {
|
||||
let product_matches: Vec<_> = candidates
|
||||
.iter()
|
||||
.filter(|candidate| {
|
||||
candidate.vendor_id == vendor_id && candidate.product_id == product_id
|
||||
})
|
||||
.collect();
|
||||
if let Some(serial) = selector.serial_number.as_ref() {
|
||||
let exact: Vec<_> = product_matches
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|candidate| candidate.serial_number.as_ref() == Some(serial))
|
||||
.collect();
|
||||
if !exact.is_empty() {
|
||||
exact
|
||||
} else {
|
||||
let unreadable: Vec<_> = product_matches
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|candidate| {
|
||||
!candidate.has_permission && candidate.serial_number.is_none()
|
||||
})
|
||||
.collect();
|
||||
match unreadable.as_slice() {
|
||||
[candidate] => {
|
||||
return Err(UsbDeviceResolutionError::PermissionRequired {
|
||||
device_name: candidate.device_name.clone(),
|
||||
});
|
||||
}
|
||||
[] => Vec::new(),
|
||||
candidates => {
|
||||
return Err(UsbDeviceResolutionError::Ambiguous {
|
||||
matches: candidates.len(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
product_matches
|
||||
}
|
||||
}
|
||||
_ => candidates
|
||||
.iter()
|
||||
.filter(|candidate| candidate.device_name == selector.legacy_device_name)
|
||||
.collect(),
|
||||
};
|
||||
if matches.is_empty() {
|
||||
return Err(UsbDeviceResolutionError::NotFound);
|
||||
}
|
||||
if matches.len() != 1 {
|
||||
return Err(UsbDeviceResolutionError::Ambiguous {
|
||||
matches: matches.len(),
|
||||
});
|
||||
}
|
||||
let candidate = matches.pop().expect("one USB match checked").clone();
|
||||
if !candidate.has_permission {
|
||||
return Err(UsbDeviceResolutionError::PermissionRequired {
|
||||
device_name: candidate.device_name,
|
||||
});
|
||||
}
|
||||
let learned = UsbDeviceSelector {
|
||||
legacy_device_name: candidate.device_name.clone(),
|
||||
vendor_id: Some(candidate.vendor_id),
|
||||
product_id: Some(candidate.product_id),
|
||||
serial_number: candidate.serial_number.clone(),
|
||||
};
|
||||
Ok((candidate, learned))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum UsbLeaseKind {
|
||||
@@ -65,7 +183,7 @@ impl<R> UsbLeaseTable<R> {
|
||||
UsbLeaseState::Active => "already active",
|
||||
UsbLeaseState::Quarantined(_) => "permanently quarantined",
|
||||
};
|
||||
return Err(format!("Android USB device {device_name} is {state}"));
|
||||
return Err(format!("Android USB device is {state}"));
|
||||
}
|
||||
self.devices
|
||||
.insert(device_name.to_string(), UsbLeaseState::Opening);
|
||||
@@ -78,15 +196,11 @@ impl<R> UsbLeaseTable<R> {
|
||||
*state = UsbLeaseState::Active;
|
||||
Ok(())
|
||||
}
|
||||
Some(UsbLeaseState::Active) => Err(format!(
|
||||
"Android USB device {device_name} is already active"
|
||||
)),
|
||||
Some(UsbLeaseState::Quarantined(_)) => Err(format!(
|
||||
"Android USB device {device_name} is permanently quarantined"
|
||||
)),
|
||||
None => Err(format!(
|
||||
"Android USB device {device_name} has no opening reservation"
|
||||
)),
|
||||
Some(UsbLeaseState::Active) => Err("Android USB device is already active".into()),
|
||||
Some(UsbLeaseState::Quarantined(_)) => {
|
||||
Err("Android USB device is permanently quarantined".into())
|
||||
}
|
||||
None => Err("Android USB device has no opening reservation".into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,15 +210,13 @@ impl<R> UsbLeaseTable<R> {
|
||||
self.devices.remove(device_name);
|
||||
Ok(())
|
||||
}
|
||||
Some(UsbLeaseState::Active) => Err(format!(
|
||||
"Android USB device {device_name} became active before opening release"
|
||||
)),
|
||||
Some(UsbLeaseState::Quarantined(_)) => Err(format!(
|
||||
"Android USB device {device_name} is permanently quarantined"
|
||||
)),
|
||||
None => Err(format!(
|
||||
"Android USB device {device_name} has no opening reservation"
|
||||
)),
|
||||
Some(UsbLeaseState::Active) => {
|
||||
Err("Android USB device became active before opening release".into())
|
||||
}
|
||||
Some(UsbLeaseState::Quarantined(_)) => {
|
||||
Err("Android USB device is permanently quarantined".into())
|
||||
}
|
||||
None => Err("Android USB device has no opening reservation".into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,15 +226,11 @@ impl<R> UsbLeaseTable<R> {
|
||||
self.devices.remove(device_name);
|
||||
Ok(())
|
||||
}
|
||||
Some(UsbLeaseState::Opening) => Err(format!(
|
||||
"Android USB device {device_name} never became active"
|
||||
)),
|
||||
Some(UsbLeaseState::Quarantined(_)) => Err(format!(
|
||||
"Android USB device {device_name} is permanently quarantined"
|
||||
)),
|
||||
None => Err(format!(
|
||||
"Android USB device {device_name} has no active lease"
|
||||
)),
|
||||
Some(UsbLeaseState::Opening) => Err("Android USB device never became active".into()),
|
||||
Some(UsbLeaseState::Quarantined(_)) => {
|
||||
Err("Android USB device is permanently quarantined".into())
|
||||
}
|
||||
None => Err("Android USB device has no active lease".into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -571,6 +679,18 @@ impl UsbInboundState {
|
||||
projection.publisher.stopped(reason);
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the lifecycle publisher after one physical USB generation ends.
|
||||
///
|
||||
/// Framing and protocol evidence are intentionally generation-local, but
|
||||
/// the privacy-safe observation stream belongs to the stable logical
|
||||
/// interface and must survive an unplug/replug cycle.
|
||||
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
|
||||
pub(crate) fn into_publisher(mut self) -> Option<RNodeSnapshotPublisher> {
|
||||
self.projection
|
||||
.take()
|
||||
.map(|projection| projection.publisher)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
@@ -1191,16 +1311,37 @@ pub(crate) enum UsbTxPumpExit {
|
||||
/// stall writer admission, and a full writer queue cannot stall inbound
|
||||
/// forwarding in the driver task.
|
||||
pub(crate) async fn run_usb_tx_pump(
|
||||
mut application_rx: mpsc::Receiver<Bytes>,
|
||||
application_rx: Arc<tokio::sync::Mutex<mpsc::Receiver<Bytes>>>,
|
||||
writer: UsbWriterHandle,
|
||||
transmitted_bytes: Arc<AtomicU64>,
|
||||
beacon: Option<(Duration, Bytes)>,
|
||||
mut stop: oneshot::Receiver<()>,
|
||||
) -> UsbTxPumpExit {
|
||||
// A fresh physical USB generation borrows the same application queue.
|
||||
// The lock is released when that generation's pump exits, preserving the
|
||||
// stable InterfaceHandle across reconnects without duplicating queues.
|
||||
let mut application_rx = application_rx.lock().await;
|
||||
let mut first_tx: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let payload = tokio::select! {
|
||||
biased;
|
||||
_ = &mut stop => return UsbTxPumpExit::StopRequested,
|
||||
payload = application_rx.recv() => payload,
|
||||
let (payload, station_id) = if let Some((interval, ref callsign)) = beacon {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = &mut stop => return UsbTxPumpExit::StopRequested,
|
||||
payload = application_rx.recv() => (payload, false),
|
||||
_ = tokio::time::sleep(Duration::from_secs(1)) => {
|
||||
if first_tx.is_some_and(|started| started.elapsed() >= interval) {
|
||||
(Some(callsign.clone()), true)
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = &mut stop => return UsbTxPumpExit::StopRequested,
|
||||
payload = application_rx.recv() => (payload, false),
|
||||
}
|
||||
};
|
||||
let Some(payload) = payload else {
|
||||
return UsbTxPumpExit::ApplicationClosed;
|
||||
@@ -1214,6 +1355,11 @@ pub(crate) async fn run_usb_tx_pump(
|
||||
if let Err(error) = queued {
|
||||
return UsbTxPumpExit::WriterRejected(error);
|
||||
}
|
||||
if station_id {
|
||||
first_tx = None;
|
||||
} else if first_tx.is_none() {
|
||||
first_tx = Some(tokio::time::Instant::now());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1581,6 +1727,81 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn usb_candidate(
|
||||
device_name: &str,
|
||||
vendor_id: u16,
|
||||
product_id: u16,
|
||||
serial_number: Option<&str>,
|
||||
has_permission: bool,
|
||||
) -> UsbDeviceCandidate {
|
||||
UsbDeviceCandidate {
|
||||
device_name: device_name.into(),
|
||||
vendor_id,
|
||||
product_id,
|
||||
serial_number: serial_number.map(str::to_string),
|
||||
has_permission,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_usb_path_learns_stable_identity_and_survives_path_change() {
|
||||
let legacy = UsbDeviceSelector {
|
||||
legacy_device_name: "/dev/bus/usb/001/002".into(),
|
||||
vendor_id: None,
|
||||
product_id: None,
|
||||
serial_number: None,
|
||||
};
|
||||
let first = usb_candidate("/dev/bus/usb/001/002", 0x303a, 0x1001, Some("ABC"), true);
|
||||
let (_, learned) = resolve_usb_device(&legacy, &[first]).expect("legacy first generation");
|
||||
let moved = usb_candidate("/dev/bus/usb/001/009", 0x303a, 0x1001, Some("ABC"), true);
|
||||
let (resolved, _) =
|
||||
resolve_usb_device(&learned, &[moved]).expect("stable selector after replug");
|
||||
assert_eq!(resolved.device_name, "/dev/bus/usb/001/009");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usb_selector_fails_closed_on_ambiguity_and_permission_loss() {
|
||||
let selector = UsbDeviceSelector {
|
||||
legacy_device_name: "old".into(),
|
||||
vendor_id: Some(0x303a),
|
||||
product_id: Some(0x1001),
|
||||
serial_number: None,
|
||||
};
|
||||
let a = usb_candidate("a", 0x303a, 0x1001, None, true);
|
||||
let b = usb_candidate("b", 0x303a, 0x1001, None, true);
|
||||
assert_eq!(
|
||||
resolve_usb_device(&selector, &[a.clone(), b]),
|
||||
Err(UsbDeviceResolutionError::Ambiguous { matches: 2 })
|
||||
);
|
||||
let denied = UsbDeviceCandidate {
|
||||
has_permission: false,
|
||||
..a
|
||||
};
|
||||
assert_eq!(
|
||||
resolve_usb_device(&selector, &[denied]),
|
||||
Err(UsbDeviceResolutionError::PermissionRequired {
|
||||
device_name: "a".into()
|
||||
})
|
||||
);
|
||||
|
||||
let serial_selector = UsbDeviceSelector {
|
||||
serial_number: Some("ABC".into()),
|
||||
..selector
|
||||
};
|
||||
let moved_denied = usb_candidate("moved", 0x303a, 0x1001, None, false);
|
||||
assert_eq!(
|
||||
resolve_usb_device(&serial_selector, &[moved_denied]),
|
||||
Err(UsbDeviceResolutionError::PermissionRequired {
|
||||
device_name: "moved".into()
|
||||
})
|
||||
);
|
||||
let restored = usb_candidate("moved", 0x303a, 0x1001, Some("ABC"), true);
|
||||
let (resolved, learned) = resolve_usb_device(&serial_selector, &[restored])
|
||||
.expect("restored permission confirms saved serial");
|
||||
assert_eq!(resolved.device_name, "moved");
|
||||
assert_eq!(learned.serial_number.as_deref(), Some("ABC"));
|
||||
}
|
||||
use md5::{Digest, Md5};
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
@@ -3134,6 +3355,7 @@ mod tests {
|
||||
});
|
||||
|
||||
let (application_tx, application_rx) = mpsc::channel(1);
|
||||
let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx));
|
||||
let (pump_stop_tx, pump_stop_rx) = oneshot::channel();
|
||||
let transmitted = Arc::new(AtomicU64::new(0));
|
||||
let expected_frame_length = kiss::frame(&[4, 5, 6]).len() as u64;
|
||||
@@ -3143,6 +3365,7 @@ mod tests {
|
||||
queue: UsbWriteQueue::new(1),
|
||||
},
|
||||
transmitted.clone(),
|
||||
None,
|
||||
pump_stop_rx,
|
||||
));
|
||||
application_tx
|
||||
@@ -3168,9 +3391,95 @@ mod tests {
|
||||
assert_eq!(pump.await.expect("pump join"), UsbTxPumpExit::StopRequested);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn application_queue_survives_sequential_usb_generations() {
|
||||
let (application_tx, application_rx) = mpsc::channel(2);
|
||||
let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx));
|
||||
let transmitted = Arc::new(AtomicU64::new(0));
|
||||
|
||||
let (first_stop_tx, first_stop_rx) = oneshot::channel();
|
||||
let first_pump = tokio::spawn(run_usb_tx_pump(
|
||||
application_rx.clone(),
|
||||
UsbWriterHandle {
|
||||
queue: UsbWriteQueue::new(1),
|
||||
},
|
||||
transmitted.clone(),
|
||||
None,
|
||||
first_stop_rx,
|
||||
));
|
||||
first_stop_tx.send(()).expect("stop first generation");
|
||||
assert_eq!(
|
||||
first_pump.await.expect("first pump join"),
|
||||
UsbTxPumpExit::StopRequested
|
||||
);
|
||||
|
||||
let payload = Bytes::from_static(&[4, 2, 4, 2]);
|
||||
let expected_frame_length = kiss::frame(&payload).len() as u64;
|
||||
application_tx
|
||||
.send(payload)
|
||||
.await
|
||||
.expect("queue payload between generations");
|
||||
|
||||
let (second_stop_tx, second_stop_rx) = oneshot::channel();
|
||||
let second_pump = tokio::spawn(run_usb_tx_pump(
|
||||
application_rx,
|
||||
UsbWriterHandle {
|
||||
queue: UsbWriteQueue::new(1),
|
||||
},
|
||||
transmitted.clone(),
|
||||
None,
|
||||
second_stop_rx,
|
||||
));
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while transmitted.load(Ordering::Relaxed) != expected_frame_length {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("second generation did not receive the queued payload");
|
||||
|
||||
second_stop_tx.send(()).expect("stop second generation");
|
||||
assert_eq!(
|
||||
second_pump.await.expect("second pump join"),
|
||||
UsbTxPumpExit::StopRequested
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn android_usb_station_id_is_armed_only_after_application_tx() {
|
||||
let (application_tx, application_rx) = mpsc::channel(1);
|
||||
let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx));
|
||||
let transmitted = Arc::new(AtomicU64::new(0));
|
||||
let (stop_tx, stop_rx) = oneshot::channel();
|
||||
let payload = Bytes::from_static(b"payload");
|
||||
let callsign = Bytes::from_static(b"N0CALL");
|
||||
let expected = (kiss::frame(&payload).len() + kiss::frame(&callsign).len()) as u64;
|
||||
let pump = tokio::spawn(run_usb_tx_pump(
|
||||
application_rx,
|
||||
UsbWriterHandle {
|
||||
queue: UsbWriteQueue::new(2),
|
||||
},
|
||||
transmitted.clone(),
|
||||
Some((Duration::ZERO, callsign)),
|
||||
stop_rx,
|
||||
));
|
||||
assert_eq!(transmitted.load(Ordering::Relaxed), 0);
|
||||
application_tx.send(payload).await.expect("application tx");
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
while transmitted.load(Ordering::Relaxed) != expected {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("station ID did not follow application TX");
|
||||
let _ = stop_tx.send(());
|
||||
assert_eq!(pump.await.expect("pump join"), UsbTxPumpExit::StopRequested);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn blocked_tx_admission_does_not_stall_inbound_forwarding() {
|
||||
let (application_tx, application_rx) = mpsc::channel(1);
|
||||
let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx));
|
||||
let (pump_stop_tx, pump_stop_rx) = oneshot::channel();
|
||||
let transmitted = Arc::new(AtomicU64::new(0));
|
||||
let pump = tokio::spawn(run_usb_tx_pump(
|
||||
@@ -3179,6 +3488,7 @@ mod tests {
|
||||
queue: UsbWriteQueue::new(0),
|
||||
},
|
||||
transmitted.clone(),
|
||||
None,
|
||||
pump_stop_rx,
|
||||
));
|
||||
application_tx
|
||||
|
||||
@@ -2004,7 +2004,6 @@ mod tests {
|
||||
#[test]
|
||||
fn test_constants() {
|
||||
assert_eq!(HW_MTU, 1196);
|
||||
const { assert!(FIXED_MTU) };
|
||||
assert_eq!(DISCOVERY_PORT, 29716);
|
||||
assert_eq!(DATA_PORT, 42671);
|
||||
assert_eq!(UNICAST_DISCOVERY_PORT, 29717);
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
//! - RX: `…28e5` (WRITE, WRITE_NO_RESPONSE)
|
||||
//! - TX: `…28e4` (READ, NOTIFY, INDICATE)
|
||||
//!
|
||||
//! Peer identity binds only from signature-verified announces. There is no ID
|
||||
//! characteristic: a statically readable identity hash was a tracking vector
|
||||
//! that defeated BLE MAC rotation.
|
||||
//! Peer identity binds only from directly-originated, signature-verified LXMF
|
||||
//! delivery announces. There is no ID characteristic: a statically readable
|
||||
//! identity hash was a tracking vector that defeated BLE MAC rotation.
|
||||
//!
|
||||
//! ## Fragmentation
|
||||
//!
|
||||
@@ -196,74 +196,42 @@ impl BlePeerLinkRegistry {
|
||||
self.identity_by_address.insert(address, identity_hash);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(test, target_os = "android", target_os = "ios", target_os = "macos"))]
|
||||
fn address_for_writer_key<'a>(&self, writer_key: &'a str) -> &'a str {
|
||||
writer_key.strip_prefix("central:").unwrap_or(writer_key)
|
||||
}
|
||||
|
||||
#[cfg(any(test, target_os = "android", target_os = "ios", target_os = "macos"))]
|
||||
fn should_send_peripheral_subscriber(
|
||||
&self,
|
||||
subscriber_address: &str,
|
||||
central_writer_keys: &[String],
|
||||
) -> bool {
|
||||
if central_writer_keys
|
||||
.iter()
|
||||
.any(|key| self.address_for_writer_key(key) == subscriber_address)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let Some(subscriber_identity) = self.identity_by_address.get(subscriber_address) else {
|
||||
return true;
|
||||
};
|
||||
|
||||
!central_writer_keys.iter().any(|key| {
|
||||
let writer_address = self.address_for_writer_key(key);
|
||||
self.identity_by_address
|
||||
.get(writer_address)
|
||||
.is_some_and(|writer_identity| writer_identity == subscriber_identity)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type LinkRegistry = Arc<tokio::sync::RwLock<BlePeerLinkRegistry>>;
|
||||
|
||||
/// Returns the destination-hash hex of `raw` ONLY if it is a signed announce
|
||||
/// whose Ed25519 signature verifies. Binding a peer's identity from an
|
||||
/// unverified announce let an in-range attacker claim a known contact's
|
||||
/// identity (mislabelling the peer and poisoning the dual-role dedup registry);
|
||||
/// the signature check means a claim can't be forged without the private key.
|
||||
fn verified_announce_identity_hex(raw: &[u8]) -> Option<String> {
|
||||
/// Mobile peers can briefly hold both central and peripheral roles during a
|
||||
/// connection race or reconnect. Only the packet-source anti-loop may suppress
|
||||
/// the peripheral leg: native central APIs acknowledge local queue insertion,
|
||||
/// not delivery of the current packet to the peer.
|
||||
#[cfg(any(test, target_os = "android", target_os = "ios", target_os = "macos"))]
|
||||
fn mobile_peripheral_fanout_allowed(anti_loop_allows: bool) -> bool {
|
||||
anti_loop_allows
|
||||
}
|
||||
|
||||
/// Returns the LXMF delivery destination of a directly-originated, signed
|
||||
/// announce. Relayed announces cannot identify the adjacent BLE peer: on a
|
||||
/// multipoint interface the same packet is deliberately fanned back out to
|
||||
/// other peers, including a second central/peripheral leg to the originator.
|
||||
fn verified_direct_lxmf_announce_destination_hex(raw: &[u8]) -> Option<String> {
|
||||
let (header, payload_offset) = rns_wire::header::PacketHeader::unpack(raw).ok()?;
|
||||
if header.flags.packet_type != rns_wire::flags::PacketType::Announce {
|
||||
if header.flags.packet_type != rns_wire::flags::PacketType::Announce || header.hops != 0 {
|
||||
return None;
|
||||
}
|
||||
let payload = raw.get(payload_offset..)?;
|
||||
let announce =
|
||||
rns_identity::announce::AnnounceData::unpack(payload, header.flags.context_flag).ok()?;
|
||||
announce.verify_signature(&header.destination_hash).ok()?;
|
||||
let identity = announce.verify_signature(&header.destination_hash).ok()?;
|
||||
let delivery_destination = rns_identity::destination::Destination::hash_from_name_and_identity(
|
||||
"lxmf.delivery",
|
||||
Some(&identity.hash),
|
||||
);
|
||||
if header.destination_hash != delivery_destination {
|
||||
return None;
|
||||
}
|
||||
Some(hex::encode(header.destination_hash))
|
||||
}
|
||||
|
||||
#[cfg(any(test, target_os = "android", target_os = "ios", target_os = "macos"))]
|
||||
fn payload_needs_redundant_role_fanout(payload: &[u8]) -> bool {
|
||||
rns_wire::header::PacketHeader::unpack(payload)
|
||||
.is_ok_and(|(header, _)| header.flags.packet_type == rns_wire::flags::PacketType::Proof)
|
||||
}
|
||||
|
||||
#[cfg(any(test, target_os = "android", target_os = "ios", target_os = "macos"))]
|
||||
fn should_send_peripheral_payload(
|
||||
registry: &BlePeerLinkRegistry,
|
||||
subscriber_address: &str,
|
||||
central_writer_keys: &[String],
|
||||
payload: &[u8],
|
||||
) -> bool {
|
||||
payload_needs_redundant_role_fanout(payload)
|
||||
|| registry.should_send_peripheral_subscriber(subscriber_address, central_writer_keys)
|
||||
}
|
||||
|
||||
fn reconnect_in_backoff(map: &RecentlyDisconnected, address: &str) -> bool {
|
||||
if in_churn_backoff(address) {
|
||||
return true;
|
||||
@@ -520,11 +488,10 @@ pub enum BlePeerEvent {
|
||||
SubscribeReady {
|
||||
address: String,
|
||||
},
|
||||
/// Identity hash learned from the first signed Reticulum announce.
|
||||
/// Used to dedup peers across central+peripheral roles where the BLE
|
||||
/// address differs for the same physical device — notably on Apple,
|
||||
/// where `CBPeripheral.identifier` vs `CBCentral.identifier` don't
|
||||
/// match without bonding.
|
||||
/// Verified LXMF delivery destination learned from a directly-originated
|
||||
/// signed Reticulum announce. Repeated observations may be emitted so the
|
||||
/// embedding owner can bind them to its live connection generation and
|
||||
/// dedup central/peripheral views of the same device.
|
||||
IdentityResolved {
|
||||
address: String,
|
||||
identity_hash: String,
|
||||
@@ -4948,7 +4915,33 @@ async fn connect_mesh_peer(
|
||||
/// to transport. Linux + Windows only — Apple's notify delegate pushes
|
||||
/// directly into `apple_peripheral::INBOUND_TX` so the global per-peer
|
||||
/// reassembler handles inbound without a per-connection task.
|
||||
type PeerWriterRegistry = Arc<tokio::sync::RwLock<HashMap<String, mpsc::Sender<Bytes>>>>;
|
||||
#[derive(Clone)]
|
||||
struct PeerWriterLease {
|
||||
id: u64,
|
||||
sender: mpsc::Sender<Bytes>,
|
||||
}
|
||||
|
||||
impl PeerWriterLease {
|
||||
fn new(sender: mpsc::Sender<Bytes>) -> Self {
|
||||
static NEXT_LEASE_ID: AtomicU64 = AtomicU64::new(1);
|
||||
Self {
|
||||
id: NEXT_LEASE_ID.fetch_add(1, Ordering::Relaxed),
|
||||
sender,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type PeerWriterMap = HashMap<String, PeerWriterLease>;
|
||||
type PeerWriterRegistry = Arc<tokio::sync::RwLock<PeerWriterMap>>;
|
||||
|
||||
fn remove_peer_writer_if_current(writers: &mut PeerWriterMap, key: &str, lease_id: u64) -> bool {
|
||||
if writers.get(key).is_some_and(|writer| writer.id == lease_id) {
|
||||
writers.remove(key);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn central_writer_key(address: &str) -> String {
|
||||
format!("central:{address}")
|
||||
@@ -4965,6 +4958,7 @@ struct PeerReadLoopCtx {
|
||||
rxb: Arc<AtomicU64>,
|
||||
peer_writers: PeerWriterRegistry,
|
||||
peer_writer_key: String,
|
||||
peer_writer_lease_id: u64,
|
||||
recently_disconnected: RecentlyDisconnected,
|
||||
anti_loop: AntiLoopMap,
|
||||
link_registry: LinkRegistry,
|
||||
@@ -4982,6 +4976,7 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
|
||||
rxb,
|
||||
peer_writers,
|
||||
peer_writer_key,
|
||||
peer_writer_lease_id,
|
||||
recently_disconnected,
|
||||
anti_loop,
|
||||
link_registry,
|
||||
@@ -5001,7 +4996,6 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
|
||||
|
||||
// Fragment reassembly buffer: maps total_count to per-sequence payload slots.
|
||||
let mut reassembly: FragmentReassembly = HashMap::new();
|
||||
let mut identity_announced = false;
|
||||
let mut missed_keepalives: u32 = 0;
|
||||
|
||||
loop {
|
||||
@@ -5075,18 +5069,19 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
|
||||
// Forward complete packet to transport
|
||||
if let Some(raw) = complete_packet {
|
||||
rxb.fetch_add(raw.len() as u64, Ordering::Relaxed);
|
||||
if !identity_announced {
|
||||
if let Some(id_hex) = verified_announce_identity_hex(&raw) {
|
||||
link_registry
|
||||
.write()
|
||||
.await
|
||||
.set_identity(conn.ble_address.clone(), id_hex.clone());
|
||||
dispatch_event(BlePeerEvent::IdentityResolved {
|
||||
address: conn.ble_address.clone(),
|
||||
identity_hash: id_hex,
|
||||
});
|
||||
identity_announced = true;
|
||||
}
|
||||
// Emit every directly-originated delivery announce. The
|
||||
// embedding owner deduplicates within its current
|
||||
// connection generation; repeated emission is what lets a
|
||||
// reconnect re-verify the same stable BLE address.
|
||||
if let Some(id_hex) = verified_direct_lxmf_announce_destination_hex(&raw) {
|
||||
link_registry
|
||||
.write()
|
||||
.await
|
||||
.set_identity(conn.ble_address.clone(), id_hex.clone());
|
||||
dispatch_event(BlePeerEvent::IdentityResolved {
|
||||
address: conn.ble_address.clone(),
|
||||
identity_hash: id_hex,
|
||||
});
|
||||
}
|
||||
// Register the source so the fan-out anti-loop filter
|
||||
// doesn't echo this exact payload back to the peer it
|
||||
@@ -5123,7 +5118,7 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
|
||||
reg.remove(&peer_address);
|
||||
}
|
||||
let mut writers = peer_writers.write().await;
|
||||
writers.remove(&peer_writer_key);
|
||||
remove_peer_writer_if_current(&mut writers, &peer_writer_key, peer_writer_lease_id);
|
||||
tracing::info!(address = %peer_address, "BLE mesh peer disconnected and cleaned up");
|
||||
|
||||
// Mark this peer as a wanted-reconnect target keyed by BLE address.
|
||||
@@ -5326,11 +5321,6 @@ pub async fn spawn_ble_peer_interface(
|
||||
// can no longer corrupt each other's reassembly buffers.
|
||||
type PeerReassembly = FragmentReassembly;
|
||||
let mut reassembly: HashMap<String, PeerReassembly> = HashMap::new();
|
||||
// Identity is learned from the first signed Reticulum announce.
|
||||
// Emit once per peer address so callers can dedupe
|
||||
// central/peripheral views of the same device.
|
||||
let mut identity_announced: std::collections::HashSet<String> =
|
||||
std::collections::HashSet::new();
|
||||
while let Some((peer, data)) = rx.recv().await {
|
||||
if !generation_is_current(generation) {
|
||||
break;
|
||||
@@ -5370,24 +5360,23 @@ pub async fn spawn_ble_peer_interface(
|
||||
"BLE Peer reassembly: complete packet (parse failed)"
|
||||
),
|
||||
}
|
||||
// Identity learning: associate this peer address
|
||||
// with an identity for caller-side dedup, but only
|
||||
// from a signature-verified announce. Binding from
|
||||
// an unverified announce let an in-range attacker
|
||||
// claim a known contact's identity and poison the
|
||||
// dual-role dedup registry.
|
||||
if !identity_announced.contains(&peer) {
|
||||
if let Some(id_hex) = verified_announce_identity_hex(&raw) {
|
||||
identity_announced.insert(peer.clone());
|
||||
link_registry_p
|
||||
.write()
|
||||
.await
|
||||
.set_identity(peer.clone(), id_hex.clone());
|
||||
dispatch_event(BlePeerEvent::IdentityResolved {
|
||||
address: peer.clone(),
|
||||
identity_hash: id_hex,
|
||||
});
|
||||
}
|
||||
// Direct signed delivery announces are emitted on
|
||||
// every observation. Address-level suppression here
|
||||
// used to survive disconnect/reconnect and made a
|
||||
// stable mobile address impossible to re-verify.
|
||||
// The embedding owner now deduplicates only within
|
||||
// its current live connection generation.
|
||||
if let Some(id_hex) =
|
||||
verified_direct_lxmf_announce_destination_hex(&raw)
|
||||
{
|
||||
link_registry_p
|
||||
.write()
|
||||
.await
|
||||
.set_identity(peer.clone(), id_hex.clone());
|
||||
dispatch_event(BlePeerEvent::IdentityResolved {
|
||||
address: peer.clone(),
|
||||
identity_hash: id_hex,
|
||||
});
|
||||
}
|
||||
// Record this packet's source so the outbound
|
||||
// fan-out can skip echoing it back to the same peer.
|
||||
@@ -5437,8 +5426,6 @@ pub async fn spawn_ble_peer_interface(
|
||||
let txb_w = shared_txb.clone();
|
||||
let writers_w = peer_writers.clone();
|
||||
let anti_loop_fan = anti_loop.clone();
|
||||
#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
|
||||
let link_registry_fan = link_registry.clone();
|
||||
track_child_task(
|
||||
generation,
|
||||
tokio::spawn(async move {
|
||||
@@ -5461,24 +5448,21 @@ pub async fn spawn_ble_peer_interface(
|
||||
let readers = writers_w.read().await;
|
||||
readers
|
||||
.iter()
|
||||
.map(|(key, tx)| (key.clone(), tx.clone()))
|
||||
.map(|(key, writer)| (key.clone(), writer.clone()))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
#[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
|
||||
let central_writer_keys = writer_snapshot
|
||||
.iter()
|
||||
.map(|(key, _)| key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut closed_writers = Vec::new();
|
||||
for (key, peer_tx) in writer_snapshot {
|
||||
for (key, writer) in writer_snapshot {
|
||||
// try_send, not send().await: a full per-peer channel means
|
||||
// that peer's radio is backed up, and awaiting it would
|
||||
// head-of-line-block the broadcast to every other peer.
|
||||
// Drop for the slow peer (transport retransmits) and keep
|
||||
// fanning out; only a closed channel retires the writer.
|
||||
match peer_tx.try_send(payload.clone()) {
|
||||
match writer.sender.try_send(payload.clone()) {
|
||||
Ok(()) => {}
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => closed_writers.push(key),
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => {
|
||||
closed_writers.push((key, writer.id));
|
||||
}
|
||||
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||
tracing::warn!(peer = %key, "BLE fan-out: peer write queue full, dropping");
|
||||
}
|
||||
@@ -5486,8 +5470,8 @@ pub async fn spawn_ble_peer_interface(
|
||||
}
|
||||
if !closed_writers.is_empty() {
|
||||
let mut writers = writers_w.write().await;
|
||||
for key in closed_writers {
|
||||
writers.remove(&key);
|
||||
for (key, lease_id) in closed_writers {
|
||||
remove_peer_writer_if_current(&mut writers, &key, lease_id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5514,24 +5498,15 @@ pub async fn spawn_ble_peer_interface(
|
||||
(COLUMBA_TX_UUID, &col_subs, "columba"),
|
||||
] {
|
||||
for addr in subs {
|
||||
let send_on_peripheral = {
|
||||
let links = link_registry_fan.read().await;
|
||||
should_send_peripheral_payload(
|
||||
&links,
|
||||
addr,
|
||||
¢ral_writer_keys,
|
||||
&payload,
|
||||
)
|
||||
};
|
||||
if !send_on_peripheral {
|
||||
tracing::debug!(
|
||||
peer = %addr,
|
||||
char = label,
|
||||
"Apple BLE fan-out: central path preferred"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if !anti_loop_should_send(&anti_loop_fan, addr, &payload) {
|
||||
// A central-side enqueue is not evidence that the
|
||||
// current packet reached a live native GATT link.
|
||||
// During dual-role overlap, deliver through both
|
||||
// roles and let Reticulum's packet hashlist dedup.
|
||||
if !mobile_peripheral_fanout_allowed(anti_loop_should_send(
|
||||
&anti_loop_fan,
|
||||
addr,
|
||||
&payload,
|
||||
)) {
|
||||
tracing::info!(peer = %addr, char = label, "Apple BLE fan-out: anti-loop skip");
|
||||
continue;
|
||||
}
|
||||
@@ -5611,67 +5586,74 @@ pub async fn spawn_ble_peer_interface(
|
||||
.unwrap_or((182, 182, Vec::new(), Vec::new()));
|
||||
let rats_frags = fragment_packet(&payload, rats_mtu);
|
||||
for addr in &rats_subs {
|
||||
let send_on_peripheral = {
|
||||
let links = link_registry_fan.read().await;
|
||||
should_send_peripheral_payload(
|
||||
&links,
|
||||
addr,
|
||||
¢ral_writer_keys,
|
||||
&payload,
|
||||
)
|
||||
};
|
||||
if !send_on_peripheral {
|
||||
continue;
|
||||
}
|
||||
if !anti_loop_should_send(&anti_loop_fan, addr, &payload) {
|
||||
// See the Apple branch: both roles remain live until
|
||||
// native disconnect is observed, so never suppress a
|
||||
// current peripheral send from historical central state.
|
||||
if !mobile_peripheral_fanout_allowed(anti_loop_should_send(
|
||||
&anti_loop_fan,
|
||||
addr,
|
||||
&payload,
|
||||
)) {
|
||||
continue;
|
||||
}
|
||||
let addr_owned = addr.clone();
|
||||
let frags_owned = rats_frags.clone();
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
let notify_ok = tokio::task::spawn_blocking(move || {
|
||||
let total = frags_owned.len();
|
||||
for (idx, frag) in frags_owned.iter().enumerate() {
|
||||
let _ = android_peripheral::notify_tx(
|
||||
if !android_peripheral::notify_tx(
|
||||
&addr_owned,
|
||||
RATSPEAK_TX_UUID,
|
||||
frag,
|
||||
);
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
sleep_after_ble_fragment_blocking(idx, total);
|
||||
}
|
||||
true
|
||||
})
|
||||
.await;
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if !notify_ok {
|
||||
tracing::warn!(
|
||||
peer = %addr,
|
||||
"Android BLE peripheral fan-out stopped after notification backpressure"
|
||||
);
|
||||
}
|
||||
}
|
||||
let col_frags = fragment_packet(&payload, col_mtu);
|
||||
for addr in &col_subs {
|
||||
let send_on_peripheral = {
|
||||
let links = link_registry_fan.read().await;
|
||||
should_send_peripheral_payload(
|
||||
&links,
|
||||
addr,
|
||||
¢ral_writer_keys,
|
||||
&payload,
|
||||
)
|
||||
};
|
||||
if !send_on_peripheral {
|
||||
continue;
|
||||
}
|
||||
if !anti_loop_should_send(&anti_loop_fan, addr, &payload) {
|
||||
if !mobile_peripheral_fanout_allowed(anti_loop_should_send(
|
||||
&anti_loop_fan,
|
||||
addr,
|
||||
&payload,
|
||||
)) {
|
||||
continue;
|
||||
}
|
||||
let addr_owned = addr.clone();
|
||||
let frags_owned = col_frags.clone();
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
let notify_ok = tokio::task::spawn_blocking(move || {
|
||||
let total = frags_owned.len();
|
||||
for (idx, frag) in frags_owned.iter().enumerate() {
|
||||
let _ = android_peripheral::notify_tx(
|
||||
if !android_peripheral::notify_tx(
|
||||
&addr_owned,
|
||||
COLUMBA_TX_UUID,
|
||||
frag,
|
||||
);
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
sleep_after_ble_fragment_blocking(idx, total);
|
||||
}
|
||||
true
|
||||
})
|
||||
.await;
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if !notify_ok {
|
||||
tracing::warn!(
|
||||
peer = %addr,
|
||||
"Android BLE peripheral fan-out stopped after notification backpressure"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5867,10 +5849,12 @@ pub async fn spawn_ble_peer_interface(
|
||||
// Per-peer write channel
|
||||
let (peer_write_tx, peer_write_rx) = mpsc::channel::<Bytes>(64);
|
||||
let peer_writer_key = central_writer_key(&peer.ble_address);
|
||||
let peer_writer = PeerWriterLease::new(peer_write_tx);
|
||||
let peer_writer_lease_id = peer_writer.id;
|
||||
writers
|
||||
.write()
|
||||
.await
|
||||
.insert(peer_writer_key.clone(), peer_write_tx.clone());
|
||||
.insert(peer_writer_key.clone(), peer_writer);
|
||||
|
||||
// Track this peer
|
||||
connected_addrs
|
||||
@@ -5921,6 +5905,7 @@ pub async fn spawn_ble_peer_interface(
|
||||
rxb: rxb_r,
|
||||
peer_writers: writers_r,
|
||||
peer_writer_key,
|
||||
peer_writer_lease_id,
|
||||
recently_disconnected: recently_r,
|
||||
anti_loop: anti_loop_r,
|
||||
link_registry: link_registry_r,
|
||||
@@ -6157,10 +6142,12 @@ pub async fn spawn_ble_peer_interface(
|
||||
let (peer_write_tx, mut peer_write_rx) =
|
||||
mpsc::channel::<Bytes>(64);
|
||||
let peer_writer_key = central_writer_key(&peer.ble_address);
|
||||
let peer_writer = PeerWriterLease::new(peer_write_tx);
|
||||
let peer_writer_lease_id = peer_writer.id;
|
||||
writers
|
||||
.write()
|
||||
.await
|
||||
.insert(peer_writer_key.clone(), peer_write_tx.clone());
|
||||
.insert(peer_writer_key.clone(), peer_writer);
|
||||
connected_addrs
|
||||
.insert(peer.ble_address.clone(), online.clone());
|
||||
|
||||
@@ -6247,10 +6234,12 @@ pub async fn spawn_ble_peer_interface(
|
||||
);
|
||||
}
|
||||
}
|
||||
writers_cleanup
|
||||
.write()
|
||||
.await
|
||||
.remove(&writer_key_cleanup);
|
||||
let mut writers = writers_cleanup.write().await;
|
||||
remove_peer_writer_if_current(
|
||||
&mut writers,
|
||||
&writer_key_cleanup,
|
||||
peer_writer_lease_id,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -6497,10 +6486,12 @@ pub async fn spawn_ble_peer_interface(
|
||||
|
||||
let (peer_write_tx, mut peer_write_rx) = mpsc::channel::<Bytes>(64);
|
||||
let peer_writer_key = central_writer_key(addr);
|
||||
let peer_writer = PeerWriterLease::new(peer_write_tx);
|
||||
let peer_writer_lease_id = peer_writer.id;
|
||||
writers
|
||||
.write()
|
||||
.await
|
||||
.insert(peer_writer_key.clone(), peer_write_tx.clone());
|
||||
.insert(peer_writer_key.clone(), peer_writer);
|
||||
connected_addrs.insert(addr.clone(), peer_online.clone());
|
||||
|
||||
// Per-peer write loop: bytes from the fan-out task
|
||||
@@ -6580,7 +6571,12 @@ pub async fn spawn_ble_peer_interface(
|
||||
break;
|
||||
}
|
||||
}
|
||||
writers_cleanup.write().await.remove(&writer_key_cleanup);
|
||||
let mut writers = writers_cleanup.write().await;
|
||||
remove_peer_writer_if_current(
|
||||
&mut writers,
|
||||
&writer_key_cleanup,
|
||||
peer_writer_lease_id,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -6670,6 +6666,56 @@ pub async fn spawn_ble_peer_interface(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn signed_announce_raw(
|
||||
identity: &rns_identity::identity::Identity,
|
||||
app_name: &str,
|
||||
hops: u8,
|
||||
) -> ([u8; 16], Vec<u8>) {
|
||||
let destination_hash = rns_identity::destination::Destination::hash_from_name_and_identity(
|
||||
app_name,
|
||||
Some(&identity.hash),
|
||||
);
|
||||
let announce =
|
||||
rns_identity::announce::AnnounceData::create(identity, app_name, None, None).unwrap();
|
||||
let mut raw = 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::Announce,
|
||||
},
|
||||
hops,
|
||||
transport_id: None,
|
||||
destination_hash,
|
||||
context: rns_wire::context::PacketContext::None,
|
||||
}
|
||||
.pack();
|
||||
raw.extend_from_slice(&announce.pack());
|
||||
(destination_hash, raw)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_identity_accepts_only_direct_lxmf_delivery_announces() {
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let (delivery_destination, direct) = signed_announce_raw(&identity, "lxmf.delivery", 0);
|
||||
let expected_destination = hex::encode(delivery_destination);
|
||||
assert_eq!(
|
||||
verified_direct_lxmf_announce_destination_hex(&direct).as_deref(),
|
||||
Some(expected_destination.as_str())
|
||||
);
|
||||
|
||||
let (_, relayed) = signed_announce_raw(&identity, "lxmf.delivery", 1);
|
||||
assert!(verified_direct_lxmf_announce_destination_hex(&relayed).is_none());
|
||||
|
||||
let (_, wrong_aspect) = signed_announce_raw(&identity, "lxmf.propagation", 0);
|
||||
assert!(verified_direct_lxmf_announce_destination_hex(&wrong_aspect).is_none());
|
||||
|
||||
let mut tampered = direct;
|
||||
*tampered.last_mut().unwrap() ^= 0x01;
|
||||
assert!(verified_direct_lxmf_announce_destination_hex(&tampered).is_none());
|
||||
}
|
||||
|
||||
// ── Fragmentation ──
|
||||
|
||||
#[test]
|
||||
@@ -7056,100 +7102,35 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_registry_prefers_central_same_address() {
|
||||
let registry = BlePeerLinkRegistry::default();
|
||||
assert!(!registry.should_send_peripheral_subscriber(
|
||||
"AA:BB:CC:DD:EE:FF",
|
||||
&[central_writer_key("AA:BB:CC:DD:EE:FF")]
|
||||
));
|
||||
assert!(registry.should_send_peripheral_subscriber(
|
||||
"11:22:33:44:55:66",
|
||||
&[central_writer_key("AA:BB:CC:DD:EE:FF")]
|
||||
));
|
||||
}
|
||||
fn reconnect_writer_cleanup_is_exact_lease_owned() {
|
||||
let (old_tx, _old_rx) = mpsc::channel(1);
|
||||
let (new_tx, _new_rx) = mpsc::channel(1);
|
||||
let old = PeerWriterLease::new(old_tx);
|
||||
let replacement = PeerWriterLease::new(new_tx);
|
||||
let old_id = old.id;
|
||||
let replacement_id = replacement.id;
|
||||
let key = central_writer_key("AA:BB:CC:DD:EE:FF");
|
||||
let mut writers = PeerWriterMap::new();
|
||||
writers.insert(key.clone(), old);
|
||||
writers.insert(key.clone(), replacement);
|
||||
|
||||
#[test]
|
||||
fn link_registry_prefers_central_same_identity() {
|
||||
let mut registry = BlePeerLinkRegistry::default();
|
||||
registry.set_identity("central-addr".into(), "identity-a".into());
|
||||
registry.set_identity("peripheral-addr".into(), "identity-a".into());
|
||||
registry.set_identity("other-addr".into(), "identity-b".into());
|
||||
|
||||
assert!(!registry.should_send_peripheral_subscriber(
|
||||
"peripheral-addr",
|
||||
&[central_writer_key("central-addr")]
|
||||
));
|
||||
assert!(registry.should_send_peripheral_subscriber(
|
||||
"other-addr",
|
||||
&[central_writer_key("central-addr")]
|
||||
));
|
||||
}
|
||||
|
||||
fn raw_test_packet(
|
||||
packet_type: rns_wire::flags::PacketType,
|
||||
context: rns_wire::context::PacketContext,
|
||||
) -> Vec<u8> {
|
||||
let header = rns_wire::header::PacketHeader {
|
||||
flags: rns_wire::flags::PacketFlags {
|
||||
header_type: rns_wire::flags::HeaderType::Header1,
|
||||
context_flag: false,
|
||||
transport_type: rns_wire::flags::TransportType::Broadcast,
|
||||
destination_type: rns_wire::flags::DestinationType::Link,
|
||||
packet_type,
|
||||
},
|
||||
hops: 0,
|
||||
transport_id: None,
|
||||
destination_hash: [0x44; 16],
|
||||
context,
|
||||
};
|
||||
let mut raw = header.pack();
|
||||
raw.extend_from_slice(&[0xAA; 96]);
|
||||
raw
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proof_payload_bypasses_role_preference() {
|
||||
let registry = BlePeerLinkRegistry::default();
|
||||
let writer_keys = [central_writer_key("AA:BB:CC:DD:EE:FF")];
|
||||
let proof = raw_test_packet(
|
||||
rns_wire::flags::PacketType::Proof,
|
||||
rns_wire::context::PacketContext::LinkProof,
|
||||
assert!(!remove_peer_writer_if_current(&mut writers, &key, old_id));
|
||||
assert_eq!(
|
||||
writers.get(&key).map(|writer| writer.id),
|
||||
Some(replacement_id)
|
||||
);
|
||||
let data = raw_test_packet(
|
||||
rns_wire::flags::PacketType::Data,
|
||||
rns_wire::context::PacketContext::None,
|
||||
);
|
||||
|
||||
assert!(payload_needs_redundant_role_fanout(&proof));
|
||||
assert!(should_send_peripheral_payload(
|
||||
®istry,
|
||||
"AA:BB:CC:DD:EE:FF",
|
||||
&writer_keys,
|
||||
&proof,
|
||||
));
|
||||
assert!(!payload_needs_redundant_role_fanout(&data));
|
||||
assert!(!should_send_peripheral_payload(
|
||||
®istry,
|
||||
"AA:BB:CC:DD:EE:FF",
|
||||
&writer_keys,
|
||||
&data,
|
||||
assert!(remove_peer_writer_if_current(
|
||||
&mut writers,
|
||||
&key,
|
||||
replacement_id
|
||||
));
|
||||
assert!(!writers.contains_key(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_payload_uses_normal_role_preference() {
|
||||
let registry = BlePeerLinkRegistry::default();
|
||||
let writer_keys = [central_writer_key("AA:BB:CC:DD:EE:FF")];
|
||||
|
||||
assert!(!payload_needs_redundant_role_fanout(
|
||||
b"not-a-reticulum-packet"
|
||||
));
|
||||
assert!(!should_send_peripheral_payload(
|
||||
®istry,
|
||||
"AA:BB:CC:DD:EE:FF",
|
||||
&writer_keys,
|
||||
b"not-a-reticulum-packet",
|
||||
));
|
||||
fn mobile_dual_role_fanout_is_gated_only_by_packet_source_anti_loop() {
|
||||
assert!(mobile_peripheral_fanout_allowed(true));
|
||||
assert!(!mobile_peripheral_fanout_allowed(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -50,9 +50,10 @@ pub const NUS_RX_CHAR_UUID: Uuid = Uuid::from_u128(0x6E400002_B5A3_F393_E0A9_E50
|
||||
/// Device notifies the host here.
|
||||
pub const NUS_TX_CHAR_UUID: Uuid = Uuid::from_u128(0x6E400003_B5A3_F393_E0A9_E50E24DCCA9E);
|
||||
|
||||
const RECONNECT_WAIT: u64 = 5;
|
||||
/// Capped below TCP's 300s — a BLE radio is either in range or not.
|
||||
const RECONNECT_WAIT_MAX: u64 = 120;
|
||||
const RECONNECT_WAIT: u64 = 1;
|
||||
/// Fast early recovery, then indefinite low-duty retries. A two-minute cap made
|
||||
/// a reachable radio appear dead long after returning to range.
|
||||
const RECONNECT_WAIT_MAX: u64 = 30;
|
||||
/// `None` retries forever; teardown goes via `stop_ble_rnode_interface`.
|
||||
const MAX_RECONNECT_TRIES: Option<usize> = None;
|
||||
const SCAN_TIMEOUT: u64 = 3;
|
||||
@@ -133,6 +134,52 @@ fn reconnect_try_exhausted(tries: &mut usize) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn reconnect_delay_with_jitter(seconds: u64, random: u64) -> Duration {
|
||||
let base = Duration::from_secs(seconds.max(1));
|
||||
let jitter_cap_ms = seconds.max(1).saturating_mul(200); // 0..20%
|
||||
let jitter_ms = random % jitter_cap_ms.saturating_add(1);
|
||||
base + Duration::from_millis(jitter_ms)
|
||||
}
|
||||
|
||||
fn ble_reconnect_delay(seconds: u64) -> Duration {
|
||||
reconnect_delay_with_jitter(seconds, rand::rngs::OsRng.next_u64())
|
||||
}
|
||||
|
||||
/// Claim the generation-local one-packet RNode transmit permit.
|
||||
///
|
||||
/// A valid positive `CMD_READY` replenishes the boolean permit and every data
|
||||
/// packet, including a station-ID packet, must atomically consume it. Merely
|
||||
/// observing `true` lets multiple queued packets pass on one READY response.
|
||||
fn claim_ble_packet_permit(flow_control: bool, ready: &AtomicBool) -> bool {
|
||||
!flow_control
|
||||
|| ready
|
||||
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Packet admission becomes latched only after the physical generation has
|
||||
/// completed its startup boundary. Later protocol evidence may degrade the
|
||||
/// observation snapshot, but cannot retroactively turn valid active-session
|
||||
/// `CMD_DATA` into startup traffic. A reconnect constructs a fresh latch.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct ActiveBlePacketAdmission {
|
||||
admitted: bool,
|
||||
}
|
||||
|
||||
impl ActiveBlePacketAdmission {
|
||||
fn for_startup_policy(strict: bool) -> Self {
|
||||
Self { admitted: !strict }
|
||||
}
|
||||
|
||||
fn observe_readiness(&mut self, readiness: RNodeReadiness) {
|
||||
self.admitted |= matches!(readiness, RNodeReadiness::Ready);
|
||||
}
|
||||
|
||||
fn allows_packet(self) -> bool {
|
||||
self.admitted
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn is_registered(id: InterfaceId) -> bool {
|
||||
running_map()
|
||||
@@ -1843,6 +1890,21 @@ fn project_ble_rnode_frame(
|
||||
publisher.protocol_effect(protocol_state, effect);
|
||||
}
|
||||
|
||||
/// Apply one active-session frame to both the observer and the generation's
|
||||
/// packet-admission latch. Both desktop GATT and Android's native loopback
|
||||
/// path use this exact boundary.
|
||||
fn project_active_ble_rnode_frame(
|
||||
publisher: &RNodeSnapshotPublisher,
|
||||
protocol_state: &mut RNodeProtocolState,
|
||||
packet_admission: &mut ActiveBlePacketAdmission,
|
||||
command: u8,
|
||||
frame: &[u8],
|
||||
) -> bool {
|
||||
project_ble_rnode_frame(publisher, protocol_state, command, frame);
|
||||
packet_admission.observe_readiness(protocol_state.readiness());
|
||||
packet_admission.allows_packet()
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Eq, PartialEq)]
|
||||
struct BleStartupProjection {
|
||||
complete_frames: usize,
|
||||
@@ -2191,7 +2253,7 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
|
||||
conn.peripheral.disconnect(),
|
||||
)
|
||||
.await;
|
||||
snapshot_publisher.stopped(RNodeRuntimeReason::CapabilityAdmissionRejected);
|
||||
snapshot_publisher.stopped_for_admission_rejection(error.failure_class());
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -2465,6 +2527,10 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
|
||||
}
|
||||
};
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let mut active_packet_admission = ActiveBlePacketAdmission::for_startup_policy(
|
||||
options.requires_capability_admission(),
|
||||
);
|
||||
active_packet_admission.observe_readiness(protocol_state.readiness());
|
||||
|
||||
let ready = Arc::new(AtomicBool::new(true));
|
||||
|
||||
@@ -2507,15 +2573,13 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
|
||||
first_tx = Some(tokio::time::Instant::now());
|
||||
}
|
||||
}
|
||||
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
if flow_control {
|
||||
while !ready_w.load(Ordering::SeqCst) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
while !claim_ble_packet_permit(flow_control, ready_w.as_ref()) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
let framed = kiss::frame(&data);
|
||||
if let Err(e) =
|
||||
ble_write(&peripheral_write, &rx_char_write, &framed, write_mtu).await
|
||||
@@ -2594,14 +2658,13 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
|
||||
match notification {
|
||||
Some(n) if n.uuid == NUS_TX_CHAR_UUID => {
|
||||
for (cmd, frame) in deframer.feed(&n.value) {
|
||||
project_ble_rnode_frame(
|
||||
let data_allowed = project_active_ble_rnode_frame(
|
||||
&snapshot_publisher,
|
||||
&mut protocol_state,
|
||||
&mut active_packet_admission,
|
||||
cmd,
|
||||
&frame,
|
||||
);
|
||||
let data_allowed = !options.requires_capability_admission()
|
||||
|| matches!(protocol_state.readiness(), RNodeReadiness::Ready);
|
||||
match rnode::process_rnode_response(
|
||||
cmd,
|
||||
&frame,
|
||||
@@ -2661,7 +2724,7 @@ pub async fn spawn_ble_rnode_interface_with_driver_and_options(
|
||||
return;
|
||||
}
|
||||
tracing::info!(name = %log_name, seconds = backoff, "BLE RNode reconnecting");
|
||||
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
|
||||
if wait_or_shutdown(ble_reconnect_delay(backoff), &running_task).await {
|
||||
publish_ble_stopped(&mut snapshot_publisher, RNodeRuntimeReason::StopRequested);
|
||||
return;
|
||||
}
|
||||
@@ -2891,7 +2954,7 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
|
||||
admission_failure = error.log_class(),
|
||||
"BLE RNode native capability admission rejected"
|
||||
);
|
||||
snapshot_publisher.stopped(RNodeRuntimeReason::CapabilityAdmissionRejected);
|
||||
snapshot_publisher.stopped_for_admission_rejection(error.failure_class());
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -3134,6 +3197,10 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
|
||||
}
|
||||
|
||||
let ready = Arc::new(AtomicBool::new(true));
|
||||
let mut active_packet_admission = ActiveBlePacketAdmission::for_startup_policy(
|
||||
options.requires_capability_admission(),
|
||||
);
|
||||
active_packet_admission.observe_readiness(protocol_state.readiness());
|
||||
|
||||
let (conn_tx, mut conn_rx) = mpsc::channel::<NativeBridgeWrite>(256);
|
||||
let conn_tx_for_stop = conn_tx.clone();
|
||||
@@ -3173,15 +3240,13 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
|
||||
first_tx = Some(tokio::time::Instant::now());
|
||||
}
|
||||
}
|
||||
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
if flow_control {
|
||||
while !ready_w.load(Ordering::SeqCst) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
while !claim_ble_packet_permit(flow_control, ready_w.as_ref()) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
let framed = kiss::frame(&data);
|
||||
if let Err(e) = tcp_write.write_all(&framed).await {
|
||||
tracing::warn!(error = %e, "BLE RNode native write error");
|
||||
@@ -3262,9 +3327,13 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
|
||||
|
||||
let data = &buf[..n];
|
||||
for (cmd, frame) in deframer.feed(data) {
|
||||
project_ble_rnode_frame(&snapshot_publisher, &mut protocol_state, cmd, &frame);
|
||||
let data_allowed = !options.requires_capability_admission()
|
||||
|| matches!(protocol_state.readiness(), RNodeReadiness::Ready);
|
||||
let data_allowed = project_active_ble_rnode_frame(
|
||||
&snapshot_publisher,
|
||||
&mut protocol_state,
|
||||
&mut active_packet_admission,
|
||||
cmd,
|
||||
&frame,
|
||||
);
|
||||
match rnode::process_rnode_response(
|
||||
cmd,
|
||||
&frame,
|
||||
@@ -3316,7 +3385,7 @@ pub async fn spawn_ble_rnode_interface_native_with_driver_and_options(
|
||||
return;
|
||||
}
|
||||
tracing::info!(name = %log_name, seconds = backoff, "BLE RNode native reconnecting");
|
||||
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
|
||||
if wait_or_shutdown(ble_reconnect_delay(backoff), &running_task).await {
|
||||
publish_ble_stopped(&mut snapshot_publisher, RNodeRuntimeReason::StopRequested);
|
||||
return;
|
||||
}
|
||||
@@ -3366,7 +3435,16 @@ mod tests {
|
||||
bytes
|
||||
}
|
||||
|
||||
fn strict_capability_response(model: u8) -> Vec<u8> {
|
||||
fn unprovisioned_capability_eeprom() -> Vec<u8> {
|
||||
let mut bytes = capability_eeprom(0xB8);
|
||||
bytes[0x9B] = 0xFF;
|
||||
for byte in &mut bytes[11..27] {
|
||||
*byte = 0x5A;
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
fn strict_capability_response_with_eeprom(eeprom: &[u8]) -> Vec<u8> {
|
||||
let mut response = kiss::frame_with_command(kiss::CMD_DATA, b"preflight-private");
|
||||
response.extend(kiss::frame_with_command(
|
||||
rnode::CMD_DETECT,
|
||||
@@ -3376,13 +3454,14 @@ mod tests {
|
||||
rnode::CMD_FW_VERSION,
|
||||
&[rnode::REQUIRED_FW_VER_MAJ, rnode::REQUIRED_FW_VER_MIN],
|
||||
));
|
||||
response.extend(kiss::frame_with_command(
|
||||
rnode::CMD_ROM_READ,
|
||||
&capability_eeprom(model),
|
||||
));
|
||||
response.extend(kiss::frame_with_command(rnode::CMD_ROM_READ, eeprom));
|
||||
response
|
||||
}
|
||||
|
||||
fn strict_capability_response(model: u8) -> Vec<u8> {
|
||||
strict_capability_response_with_eeprom(&capability_eeprom(model))
|
||||
}
|
||||
|
||||
fn capability_notifications(bytes: &[u8]) -> Vec<ValueNotification> {
|
||||
bytes
|
||||
.chunks(180)
|
||||
@@ -3405,6 +3484,56 @@ mod tests {
|
||||
wire
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ble_flow_ready_is_a_saturating_one_packet_permit() {
|
||||
let ready = AtomicBool::new(true);
|
||||
assert!(claim_ble_packet_permit(true, &ready));
|
||||
assert!(
|
||||
!claim_ble_packet_permit(true, &ready),
|
||||
"one positive READY must not release a second packet"
|
||||
);
|
||||
|
||||
ready.store(true, Ordering::SeqCst);
|
||||
assert!(claim_ble_packet_permit(true, &ready));
|
||||
assert!(!ready.load(Ordering::SeqCst));
|
||||
|
||||
assert!(claim_ble_packet_permit(false, &ready));
|
||||
assert!(claim_ble_packet_permit(false, &ready));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ble_reconnect_jitter_stays_within_twenty_percent() {
|
||||
assert_eq!(reconnect_delay_with_jitter(1, 0), Duration::from_secs(1));
|
||||
assert!(reconnect_delay_with_jitter(1, u64::MAX) <= Duration::from_millis(1_200));
|
||||
assert!(reconnect_delay_with_jitter(30, u64::MAX) <= Duration::from_secs(36));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_packet_admission_latches_for_one_physical_generation() {
|
||||
let mut startup = ActiveBlePacketAdmission::for_startup_policy(true);
|
||||
assert!(!startup.allows_packet());
|
||||
|
||||
startup.observe_readiness(RNodeReadiness::Ready);
|
||||
assert!(startup.allows_packet());
|
||||
|
||||
startup.observe_readiness(RNodeReadiness::Blocked(
|
||||
crate::rnode_protocol::RNodeReadinessBlocker::Missing(
|
||||
crate::rnode_protocol::RNodeReadinessEvidence::Frequency,
|
||||
),
|
||||
));
|
||||
assert!(
|
||||
startup.allows_packet(),
|
||||
"later evidence regression must not discard active-session packets"
|
||||
);
|
||||
|
||||
let legacy = ActiveBlePacketAdmission::for_startup_policy(false);
|
||||
assert!(legacy.allows_packet());
|
||||
|
||||
// A reconnect never inherits the prior generation's active boundary.
|
||||
let reconnect = ActiveBlePacketAdmission::for_startup_policy(true);
|
||||
assert!(!reconnect.allows_packet());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ble_rnode_config_defaults() {
|
||||
let cfg = BleRNodeConfig::new("ble-rnode", "ble://RNode 3B87");
|
||||
@@ -4379,8 +4508,20 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_desktop_ble_preflight_admits_verified_and_unverified_without_data_leakage() {
|
||||
for (model, verified) in [(0xB8, true), (0xFE, false)] {
|
||||
let response = strict_capability_response(model);
|
||||
for (response, expected_capability) in [
|
||||
(
|
||||
strict_capability_response(0xB8),
|
||||
rnode::RNodeCapabilityState::Verified,
|
||||
),
|
||||
(
|
||||
strict_capability_response(0xFE),
|
||||
rnode::RNodeCapabilityState::Unverified,
|
||||
),
|
||||
(
|
||||
strict_capability_response_with_eeprom(&unprovisioned_capability_eeprom()),
|
||||
rnode::RNodeCapabilityState::Unprovisioned,
|
||||
),
|
||||
] {
|
||||
let mut queued = capability_notifications(&response);
|
||||
queued.push(ValueNotification {
|
||||
uuid: NUS_TX_CHAR_UUID,
|
||||
@@ -4407,7 +4548,11 @@ mod tests {
|
||||
};
|
||||
assert_eq!(
|
||||
matches!(admission, RNodeRadioAdmission::Verified { .. }),
|
||||
verified
|
||||
expected_capability == rnode::RNodeCapabilityState::Verified
|
||||
);
|
||||
assert_eq!(
|
||||
matches!(admission, RNodeRadioAdmission::Unprovisioned),
|
||||
expected_capability == rnode::RNodeCapabilityState::Unprovisioned
|
||||
);
|
||||
let evidence = protocol_state.evidence();
|
||||
assert!(evidence.detected);
|
||||
@@ -4424,14 +4569,7 @@ mod tests {
|
||||
publisher.capability_connection_established(&protocol_state, admission);
|
||||
let snapshot = driver.snapshot();
|
||||
assert_eq!(snapshot.connection_generation, 1);
|
||||
assert_eq!(
|
||||
snapshot.capability,
|
||||
if verified {
|
||||
rnode::RNodeCapabilityState::Verified
|
||||
} else {
|
||||
rnode::RNodeCapabilityState::Unverified
|
||||
}
|
||||
);
|
||||
assert_eq!(snapshot.capability, expected_capability);
|
||||
assert_eq!(
|
||||
snapshot.configuration,
|
||||
rnode::RNodeConfigurationState::Unknown
|
||||
@@ -4743,9 +4881,16 @@ mod tests {
|
||||
let mut last_snr = None;
|
||||
let mut packets = 0usize;
|
||||
let mut flow_ready = false;
|
||||
let mut packet_admission = ActiveBlePacketAdmission::for_startup_policy(true);
|
||||
packet_admission.observe_readiness(state.readiness());
|
||||
for (command, frame) in deframer.feed(¬ification) {
|
||||
project_ble_rnode_frame(&publisher, &mut state, command, &frame);
|
||||
let data_allowed = matches!(state.readiness(), RNodeReadiness::Ready);
|
||||
let data_allowed = project_active_ble_rnode_frame(
|
||||
&publisher,
|
||||
&mut state,
|
||||
&mut packet_admission,
|
||||
command,
|
||||
&frame,
|
||||
);
|
||||
match rnode::process_rnode_response(command, &frame, 1, &mut last_rssi, &mut last_snr) {
|
||||
RNodeResponse::Packet(_) if data_allowed => packets += 1,
|
||||
RNodeResponse::Ready(value) => flow_ready = value,
|
||||
@@ -4765,6 +4910,55 @@ mod tests {
|
||||
publisher.stopped(RNodeRuntimeReason::StopRequested);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_active_admission_survives_first_frame_readiness_regression() {
|
||||
let target = RNodeProtocolTarget::new(915_000_000, 125_000, 8, 6, 17);
|
||||
let mut state = RNodeProtocolState::new(target);
|
||||
state.apply_frame(rnode::CMD_DETECT, &[rnode::DETECT_RESP]);
|
||||
state.apply_frame(
|
||||
rnode::CMD_FW_VERSION,
|
||||
&[rnode::REQUIRED_FW_VER_MAJ, rnode::REQUIRED_FW_VER_MIN],
|
||||
);
|
||||
state.apply_frame(rnode::CMD_FREQUENCY, &target.frequency.to_be_bytes());
|
||||
state.apply_frame(rnode::CMD_BANDWIDTH, &target.bandwidth.to_be_bytes());
|
||||
state.apply_frame(rnode::CMD_SF, &[target.spreading_factor]);
|
||||
state.apply_frame(rnode::CMD_CR, &[target.coding_rate]);
|
||||
state.apply_frame(rnode::CMD_TXPOWER, &[target.tx_power]);
|
||||
state.apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON]);
|
||||
assert_eq!(state.readiness(), RNodeReadiness::Ready);
|
||||
|
||||
let (publisher, _driver) = rnode::new_rnode_driver_observation(RNodeTransportClass::Ble);
|
||||
let mut admission = ActiveBlePacketAdmission::for_startup_policy(true);
|
||||
admission.observe_readiness(state.readiness());
|
||||
|
||||
let mismatched_frequency = target.frequency.saturating_add(101).to_be_bytes();
|
||||
assert!(project_active_ble_rnode_frame(
|
||||
&publisher,
|
||||
&mut state,
|
||||
&mut admission,
|
||||
rnode::CMD_FREQUENCY,
|
||||
&mismatched_frequency,
|
||||
));
|
||||
assert_ne!(state.readiness(), RNodeReadiness::Ready);
|
||||
assert!(project_active_ble_rnode_frame(
|
||||
&publisher,
|
||||
&mut state,
|
||||
&mut admission,
|
||||
kiss::CMD_DATA,
|
||||
b"valid-active-packet",
|
||||
));
|
||||
|
||||
let mut reconnect = ActiveBlePacketAdmission::for_startup_policy(true);
|
||||
let mut reconnect_state = RNodeProtocolState::new(target);
|
||||
assert!(!project_active_ble_rnode_frame(
|
||||
&publisher,
|
||||
&mut reconnect_state,
|
||||
&mut reconnect,
|
||||
kiss::CMD_DATA,
|
||||
b"pre-admission-packet",
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_native_ble_preflight_orders_one_rom_request_before_admission() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -4855,6 +5049,71 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_native_ble_preflight_admits_unprovisioned_eeprom() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
|
||||
.await
|
||||
.expect("bind unprovisioned strict bridge");
|
||||
let address = listener.local_addr().expect("unprovisioned bridge address");
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener
|
||||
.accept()
|
||||
.await
|
||||
.expect("accept unprovisioned bridge");
|
||||
let mut commands = Vec::new();
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let mut buffer = [0u8; 1024];
|
||||
while !commands.contains(&rnode::CMD_ROM_READ) {
|
||||
let count = tokio::time::timeout(Duration::from_secs(1), stream.read(&mut buffer))
|
||||
.await
|
||||
.expect("unprovisioned request timeout")
|
||||
.expect("unprovisioned request read");
|
||||
assert!(count > 0, "request ended before ROM read");
|
||||
commands.extend(
|
||||
deframer
|
||||
.feed(&buffer[..count])
|
||||
.into_iter()
|
||||
.map(|(command, _)| command),
|
||||
);
|
||||
}
|
||||
stream
|
||||
.write_all(&strict_capability_response_with_eeprom(
|
||||
&unprovisioned_capability_eeprom(),
|
||||
))
|
||||
.await
|
||||
.expect("write unprovisioned response");
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
});
|
||||
|
||||
let stream = tokio::net::TcpStream::connect(address)
|
||||
.await
|
||||
.expect("connect unprovisioned bridge");
|
||||
let (mut read, mut write) = stream.into_split();
|
||||
let running = AtomicBool::new(true);
|
||||
let config = BleRNodeConfig::new("ble0", "ble://RNode 1234");
|
||||
let outcome = run_native_ble_capability_preflight(
|
||||
&mut read,
|
||||
&mut write,
|
||||
ble_radio_settings(&config),
|
||||
&running,
|
||||
Duration::from_secs(1),
|
||||
Duration::from_millis(100),
|
||||
)
|
||||
.await;
|
||||
let BleCapabilityPreflightOutcome::Admitted {
|
||||
protocol_state,
|
||||
admission,
|
||||
} = outcome
|
||||
else {
|
||||
panic!("unprovisioned EEPROM must admit on the native path");
|
||||
};
|
||||
assert_eq!(admission, RNodeRadioAdmission::Unprovisioned);
|
||||
assert!(protocol_state.evidence().detected);
|
||||
server.await.expect("unprovisioned bridge server task");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_native_ble_stop_before_preflight_writes_nothing() {
|
||||
use tokio::io::AsyncReadExt;
|
||||
@@ -5071,6 +5330,10 @@ mod tests {
|
||||
terminal.reason,
|
||||
Some(RNodeRuntimeReason::CapabilityAdmissionRejected)
|
||||
);
|
||||
assert_eq!(
|
||||
terminal.capability_admission_failure,
|
||||
Some(rnode::RNodeCapabilityAdmissionFailureClass::InvalidCapabilityImage)
|
||||
);
|
||||
assert!(!spawned.interface.online.load(Ordering::SeqCst));
|
||||
spawned
|
||||
.interface
|
||||
|
||||
@@ -235,7 +235,69 @@ pub enum RNodeCapabilityAdmissionError {
|
||||
RadioSettings(#[source] crate::rnode_capabilities::RNodeRadioAdmissionError),
|
||||
}
|
||||
|
||||
/// Closed, privacy-safe classification of a capability admission failure.
|
||||
///
|
||||
/// Variants mirror [`RNodeCapabilityAdmissionError`] one-to-one but carry no
|
||||
/// limits, values, or device data, so the classification can cross the
|
||||
/// observation boundary. [`Self::log_class`] returns the stable log token for
|
||||
/// each class.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeCapabilityAdmissionFailureClass {
|
||||
ResponseTimedOut,
|
||||
ReadLimit,
|
||||
InputLimit,
|
||||
FrameLimit,
|
||||
MalformedProtocol,
|
||||
DeviceError,
|
||||
DetectionRejected,
|
||||
UnsupportedFirmware,
|
||||
DuplicateEeprom,
|
||||
InvalidCapabilityImage,
|
||||
RadioSettingsRejected,
|
||||
}
|
||||
|
||||
impl RNodeCapabilityAdmissionFailureClass {
|
||||
/// Stable log token for this failure class.
|
||||
pub const fn log_class(self) -> &'static str {
|
||||
match self {
|
||||
Self::ResponseTimedOut => "response_timeout",
|
||||
Self::ReadLimit => "read_limit",
|
||||
Self::InputLimit => "input_limit",
|
||||
Self::FrameLimit => "frame_limit",
|
||||
Self::MalformedProtocol => "malformed_protocol",
|
||||
Self::DeviceError => "device_error",
|
||||
Self::DetectionRejected => "detection_rejected",
|
||||
Self::UnsupportedFirmware => "unsupported_firmware",
|
||||
Self::DuplicateEeprom => "duplicate_eeprom",
|
||||
Self::InvalidCapabilityImage => "invalid_capability_image",
|
||||
Self::RadioSettingsRejected => "radio_settings_rejected",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RNodeCapabilityAdmissionError {
|
||||
/// The privacy-safe classification for this admission failure.
|
||||
pub fn failure_class(&self) -> RNodeCapabilityAdmissionFailureClass {
|
||||
match self {
|
||||
Self::ResponseTimedOut => RNodeCapabilityAdmissionFailureClass::ResponseTimedOut,
|
||||
Self::ReadLimitExceeded { .. } => RNodeCapabilityAdmissionFailureClass::ReadLimit,
|
||||
Self::InputLimitExceeded { .. } => RNodeCapabilityAdmissionFailureClass::InputLimit,
|
||||
Self::FrameLimitExceeded { .. } => RNodeCapabilityAdmissionFailureClass::FrameLimit,
|
||||
Self::MalformedProtocolFrame { .. } => {
|
||||
RNodeCapabilityAdmissionFailureClass::MalformedProtocol
|
||||
}
|
||||
Self::DeviceError => RNodeCapabilityAdmissionFailureClass::DeviceError,
|
||||
Self::DetectionRejected => RNodeCapabilityAdmissionFailureClass::DetectionRejected,
|
||||
Self::UnsupportedFirmware => RNodeCapabilityAdmissionFailureClass::UnsupportedFirmware,
|
||||
Self::DuplicateEepromResponse => RNodeCapabilityAdmissionFailureClass::DuplicateEeprom,
|
||||
Self::CapabilityImage(_) => {
|
||||
RNodeCapabilityAdmissionFailureClass::InvalidCapabilityImage
|
||||
}
|
||||
Self::RadioSettings(_) => RNodeCapabilityAdmissionFailureClass::RadioSettingsRejected,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
@@ -243,19 +305,7 @@ impl RNodeCapabilityAdmissionError {
|
||||
target_os = "android"
|
||||
))]
|
||||
pub(crate) fn log_class(&self) -> &'static str {
|
||||
match self {
|
||||
Self::ResponseTimedOut => "response_timeout",
|
||||
Self::ReadLimitExceeded { .. } => "read_limit",
|
||||
Self::InputLimitExceeded { .. } => "input_limit",
|
||||
Self::FrameLimitExceeded { .. } => "frame_limit",
|
||||
Self::MalformedProtocolFrame { .. } => "malformed_protocol",
|
||||
Self::DeviceError => "device_error",
|
||||
Self::DetectionRejected => "detection_rejected",
|
||||
Self::UnsupportedFirmware => "unsupported_firmware",
|
||||
Self::DuplicateEepromResponse => "duplicate_eeprom",
|
||||
Self::CapabilityImage(_) => "invalid_capability_image",
|
||||
Self::RadioSettings(_) => "radio_settings_rejected",
|
||||
}
|
||||
self.failure_class().log_class()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,6 +417,10 @@ pub enum RNodeCapabilityState {
|
||||
/// quarantined, so only generic bounds were applied. Fresh post-init RF
|
||||
/// echoes are still required for runtime readiness.
|
||||
Unverified,
|
||||
/// No locked EEPROM identity was present, so only generic bounds were
|
||||
/// applied and no product or model claim exists. Fresh post-init RF
|
||||
/// echoes are still required for runtime readiness.
|
||||
Unprovisioned,
|
||||
}
|
||||
|
||||
/// Radio power state observed from the active RNode connection.
|
||||
@@ -429,6 +483,9 @@ pub struct RNodeRuntimeSnapshot {
|
||||
pub radio: RNodeObservedRadioState,
|
||||
pub transmit_flow: RNodeTransmitFlowState,
|
||||
pub reason: Option<RNodeRuntimeReason>,
|
||||
/// Set only by a terminal capability admission rejection; identifies the
|
||||
/// failure class without carrying any device data.
|
||||
pub capability_admission_failure: Option<RNodeCapabilityAdmissionFailureClass>,
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
@@ -454,6 +511,7 @@ impl RNodeRuntimeSnapshot {
|
||||
radio: RNodeObservedRadioState::Unknown,
|
||||
transmit_flow: RNodeTransmitFlowState::Unknown,
|
||||
reason: None,
|
||||
capability_admission_failure: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -804,6 +862,7 @@ impl RNodeSnapshotPublisher {
|
||||
snapshot.connection_generation = generation;
|
||||
snapshot.reconnect_attempt = 0;
|
||||
snapshot.reason = None;
|
||||
snapshot.capability_admission_failure = None;
|
||||
snapshot.reset_protocol_observations();
|
||||
});
|
||||
}
|
||||
@@ -826,6 +885,7 @@ impl RNodeSnapshotPublisher {
|
||||
snapshot.connection_generation = generation;
|
||||
snapshot.reconnect_attempt = 0;
|
||||
snapshot.reason = None;
|
||||
snapshot.capability_admission_failure = None;
|
||||
snapshot.reset_protocol_observations();
|
||||
snapshot.capability = match admission {
|
||||
crate::rnode_capabilities::RNodeRadioAdmission::Verified { .. } => {
|
||||
@@ -834,12 +894,20 @@ impl RNodeSnapshotPublisher {
|
||||
crate::rnode_capabilities::RNodeRadioAdmission::Unverified { .. } => {
|
||||
RNodeCapabilityState::Unverified
|
||||
}
|
||||
crate::rnode_capabilities::RNodeRadioAdmission::Unprovisioned => {
|
||||
RNodeCapabilityState::Unprovisioned
|
||||
}
|
||||
};
|
||||
project_rnode_protocol_state(snapshot, state);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))]
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android"
|
||||
))]
|
||||
pub(crate) fn reconnect_started(&self) {
|
||||
self.update(|snapshot| {
|
||||
snapshot.phase = RNodeRuntimePhase::Connecting;
|
||||
@@ -847,11 +915,17 @@ impl RNodeSnapshotPublisher {
|
||||
snapshot.reconnect_attempt = snapshot.reconnect_attempt.saturating_add(1);
|
||||
snapshot.reconnect_total = snapshot.reconnect_total.saturating_add(1);
|
||||
snapshot.reason = None;
|
||||
snapshot.capability_admission_failure = None;
|
||||
snapshot.reset_protocol_observations();
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))]
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android"
|
||||
))]
|
||||
pub(crate) fn connection_attempt_failed(&self) {
|
||||
self.update(|snapshot| {
|
||||
snapshot.phase = RNodeRuntimePhase::ReconnectBackoff;
|
||||
@@ -861,7 +935,12 @@ impl RNodeSnapshotPublisher {
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))]
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android"
|
||||
))]
|
||||
pub(crate) fn connection_lost(&self) {
|
||||
self.update(|snapshot| {
|
||||
snapshot.phase = RNodeRuntimePhase::ReconnectBackoff;
|
||||
@@ -934,6 +1013,22 @@ impl RNodeSnapshotPublisher {
|
||||
});
|
||||
self.terminal = true;
|
||||
}
|
||||
|
||||
/// Terminal stop for a rejected capability admission, publishing the
|
||||
/// failure class atomically with the phase and reason.
|
||||
pub(crate) fn stopped_for_admission_rejection(
|
||||
&mut self,
|
||||
failure: RNodeCapabilityAdmissionFailureClass,
|
||||
) {
|
||||
self.update(|snapshot| {
|
||||
snapshot.phase = RNodeRuntimePhase::Stopped;
|
||||
snapshot.connection_generation = 0;
|
||||
snapshot.reason = Some(RNodeRuntimeReason::CapabilityAdmissionRejected);
|
||||
snapshot.capability_admission_failure = Some(failure);
|
||||
snapshot.reset_protocol_observations();
|
||||
});
|
||||
self.terminal = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
@@ -3269,7 +3364,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
"RNode reconnect capability admission rejected"
|
||||
);
|
||||
snapshot_publisher
|
||||
.stopped(RNodeRuntimeReason::CapabilityAdmissionRejected);
|
||||
.stopped_for_admission_rejection(error.failure_class());
|
||||
return;
|
||||
}
|
||||
Err(RNodeStrictPreflightError::Transport(error)) => {
|
||||
@@ -3520,6 +3615,113 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn admission_failure_classes_keep_legacy_log_tokens() {
|
||||
let cases: &[(RNodeCapabilityAdmissionError, &str)] = &[
|
||||
(
|
||||
RNodeCapabilityAdmissionError::ResponseTimedOut,
|
||||
"response_timeout",
|
||||
),
|
||||
(
|
||||
RNodeCapabilityAdmissionError::ReadLimitExceeded { limit: 1 },
|
||||
"read_limit",
|
||||
),
|
||||
(
|
||||
RNodeCapabilityAdmissionError::InputLimitExceeded { limit: 1 },
|
||||
"input_limit",
|
||||
),
|
||||
(
|
||||
RNodeCapabilityAdmissionError::FrameLimitExceeded { limit: 1 },
|
||||
"frame_limit",
|
||||
),
|
||||
(
|
||||
RNodeCapabilityAdmissionError::MalformedProtocolFrame {
|
||||
rejection: crate::rnode_protocol::RNodeFrameRejection::UnknownCommand,
|
||||
},
|
||||
"malformed_protocol",
|
||||
),
|
||||
(RNodeCapabilityAdmissionError::DeviceError, "device_error"),
|
||||
(
|
||||
RNodeCapabilityAdmissionError::DetectionRejected,
|
||||
"detection_rejected",
|
||||
),
|
||||
(
|
||||
RNodeCapabilityAdmissionError::UnsupportedFirmware,
|
||||
"unsupported_firmware",
|
||||
),
|
||||
(
|
||||
RNodeCapabilityAdmissionError::DuplicateEepromResponse,
|
||||
"duplicate_eeprom",
|
||||
),
|
||||
(
|
||||
RNodeCapabilityAdmissionError::CapabilityImage(
|
||||
crate::rnode_capabilities::RNodeCapabilityParseError::InfoNotLocked,
|
||||
),
|
||||
"invalid_capability_image",
|
||||
),
|
||||
(
|
||||
RNodeCapabilityAdmissionError::RadioSettings(
|
||||
crate::rnode_capabilities::RNodeRadioAdmissionError::TxPowerExceedsMaximum {
|
||||
requested_dbm: 23,
|
||||
max_dbm: 22,
|
||||
},
|
||||
),
|
||||
"radio_settings_rejected",
|
||||
),
|
||||
];
|
||||
for (error, token) in cases {
|
||||
assert_eq!(error.failure_class().log_class(), *token);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_rejection_stop_carries_class_and_ordinary_stops_do_not() {
|
||||
let (mut publisher, driver) = new_rnode_driver_observation(RNodeTransportClass::Ble);
|
||||
publisher.stopped_for_admission_rejection(
|
||||
RNodeCapabilityAdmissionFailureClass::InvalidCapabilityImage,
|
||||
);
|
||||
let snapshot = driver.snapshot();
|
||||
assert_eq!(snapshot.phase, RNodeRuntimePhase::Stopped);
|
||||
assert_eq!(
|
||||
snapshot.reason,
|
||||
Some(RNodeRuntimeReason::CapabilityAdmissionRejected)
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.capability_admission_failure,
|
||||
Some(RNodeCapabilityAdmissionFailureClass::InvalidCapabilityImage)
|
||||
);
|
||||
|
||||
let (mut ordinary, driver) = new_rnode_driver_observation(RNodeTransportClass::Ble);
|
||||
ordinary.stopped(RNodeRuntimeReason::StopRequested);
|
||||
let snapshot = driver.snapshot();
|
||||
assert_eq!(snapshot.capability_admission_failure, None);
|
||||
}
|
||||
|
||||
// reconnect_started only exists under the transport features.
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android"
|
||||
))]
|
||||
#[test]
|
||||
fn new_generations_clear_a_stale_admission_failure_class() {
|
||||
let (mut publisher, driver) = new_rnode_driver_observation(RNodeTransportClass::Ble);
|
||||
publisher.update(|snapshot| {
|
||||
snapshot.capability_admission_failure =
|
||||
Some(RNodeCapabilityAdmissionFailureClass::DeviceError);
|
||||
});
|
||||
publisher.reconnect_started();
|
||||
assert_eq!(driver.snapshot().capability_admission_failure, None);
|
||||
|
||||
publisher.update(|snapshot| {
|
||||
snapshot.capability_admission_failure =
|
||||
Some(RNodeCapabilityAdmissionFailureClass::DeviceError);
|
||||
});
|
||||
publisher.connection_established();
|
||||
assert_eq!(driver.snapshot().capability_admission_failure, None);
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[derive(Default)]
|
||||
struct ScriptedWriterState {
|
||||
|
||||
@@ -146,29 +146,36 @@ pub enum RNodeCapabilityParseError {
|
||||
///
|
||||
/// `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
|
||||
/// model profile was inferred. `Unprovisioned` means the device presented no
|
||||
/// locked EEPROM identity at all, so no product or model claim exists and only
|
||||
/// generic validation was applied. 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 },
|
||||
Unprovisioned,
|
||||
}
|
||||
|
||||
impl RNodeRadioAdmission {
|
||||
/// Validated EEPROM product code associated with this admission result.
|
||||
pub const fn product_code(self) -> u8 {
|
||||
/// Validated EEPROM product code, when a locked identity supplied one.
|
||||
pub const fn product_code(self) -> Option<u8> {
|
||||
match self {
|
||||
Self::Verified { product_code, .. } | Self::Unverified { product_code, .. } => {
|
||||
product_code
|
||||
Some(product_code)
|
||||
}
|
||||
Self::Unprovisioned => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact, unnormalised EEPROM model code associated with this result.
|
||||
pub const fn model_code(self) -> u8 {
|
||||
/// Exact, unnormalised EEPROM model code, when a locked identity supplied one.
|
||||
pub const fn model_code(self) -> Option<u8> {
|
||||
match self {
|
||||
Self::Verified { model_code, .. } | Self::Unverified { model_code, .. } => model_code,
|
||||
Self::Verified { model_code, .. } | Self::Unverified { model_code, .. } => {
|
||||
Some(model_code)
|
||||
}
|
||||
Self::Unprovisioned => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,15 +201,31 @@ pub enum RNodeRadioAdmissionError {
|
||||
TxPowerExceedsMaximum { requested_dbm: u8, max_dbm: u8 },
|
||||
}
|
||||
|
||||
/// Validate an EEPROM image and retain only non-identifying capability data.
|
||||
/// Bounded classification of a full-length RNode EEPROM image.
|
||||
///
|
||||
/// 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(
|
||||
/// `Provisioned` carries validated capabilities from a locked, checksummed
|
||||
/// identity. `Unprovisioned` means the info lock at `0x9b` is absent: the
|
||||
/// device carries no attested identity, so product, model, and checksum bytes
|
||||
/// are deliberately never read.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeEepromImage {
|
||||
Provisioned(RNodeCapabilities),
|
||||
Unprovisioned,
|
||||
}
|
||||
|
||||
/// Classify an EEPROM image, admitting unprovisioned devices as a typed state.
|
||||
///
|
||||
/// The image must still span the identity-information lock at `0x9b`. An
|
||||
/// unlocked image classifies as [`RNodeEepromImage::Unprovisioned`] without
|
||||
/// consulting the checksum or identity bytes — an unattested model byte must
|
||||
/// never impose or relax model-specific limits. A locked image validates the
|
||||
/// MD5 checksum over the exact stored bytes `0x00..0x0b` (model aliases are
|
||||
/// deliberately not normalised first); bytes after the identity prefix,
|
||||
/// including the signature region, are ignored.
|
||||
pub fn classify_rnode_eeprom_image(
|
||||
eeprom: &[u8],
|
||||
) -> Result<RNodeCapabilities, RNodeCapabilityParseError> {
|
||||
) -> Result<RNodeEepromImage, RNodeCapabilityParseError> {
|
||||
if eeprom.len() < REQUIRED_EEPROM_LEN {
|
||||
return Err(RNodeCapabilityParseError::TooShort {
|
||||
required: REQUIRED_EEPROM_LEN,
|
||||
@@ -210,7 +233,7 @@ pub fn parse_rnode_capabilities(
|
||||
});
|
||||
}
|
||||
if eeprom[INFO_LOCK_ADDRESS] != INFO_LOCK_BYTE {
|
||||
return Err(RNodeCapabilityParseError::InfoNotLocked);
|
||||
return Ok(RNodeEepromImage::Unprovisioned);
|
||||
}
|
||||
|
||||
let calculated: [u8; 16] = Md5::digest(&eeprom[..IDENTITY_CHECKSUM_INPUT_END]).into();
|
||||
@@ -222,11 +245,26 @@ pub fn parse_rnode_capabilities(
|
||||
let model_code = eeprom[MODEL_ADDRESS];
|
||||
let radio = rnode_model_capabilities(model_code);
|
||||
|
||||
Ok(RNodeCapabilities {
|
||||
Ok(RNodeEepromImage::Provisioned(RNodeCapabilities {
|
||||
product_code,
|
||||
model_code,
|
||||
radio,
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
/// Validate an EEPROM image and retain only non-identifying capability data.
|
||||
///
|
||||
/// Strict form of [`classify_rnode_eeprom_image`] for callers that require a
|
||||
/// provisioned identity (for example rnodeconf mutation preflights): an
|
||||
/// unlocked image is an [`RNodeCapabilityParseError::InfoNotLocked`] error
|
||||
/// here rather than a typed classification.
|
||||
pub fn parse_rnode_capabilities(
|
||||
eeprom: &[u8],
|
||||
) -> Result<RNodeCapabilities, RNodeCapabilityParseError> {
|
||||
match classify_rnode_eeprom_image(eeprom)? {
|
||||
RNodeEepromImage::Provisioned(capabilities) => Ok(capabilities),
|
||||
RNodeEepromImage::Unprovisioned => Err(RNodeCapabilityParseError::InfoNotLocked),
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify a validated model without admitting radio settings.
|
||||
@@ -284,6 +322,20 @@ pub fn admit_rnode_radio_settings(
|
||||
Ok(classify_rnode_radio_capabilities(capabilities))
|
||||
}
|
||||
|
||||
/// Admit radio settings for a device that presented no locked EEPROM identity.
|
||||
///
|
||||
/// Only generic RNode validation applies: with no attested model there are no
|
||||
/// model-specific limits to consult, matching the treatment of unknown and
|
||||
/// quarantined model codes.
|
||||
pub fn admit_unprovisioned_rnode_radio_settings(
|
||||
settings: RNodeRadioSettings,
|
||||
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
|
||||
settings
|
||||
.validate()
|
||||
.map_err(RNodeRadioAdmissionError::GenericValidation)?;
|
||||
Ok(RNodeRadioAdmission::Unprovisioned)
|
||||
}
|
||||
|
||||
/// Return the reviewed display name for an RNode product code.
|
||||
///
|
||||
/// Unknown product codes return `None`. Names are static code-table values and
|
||||
@@ -560,6 +612,77 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlocked_images_classify_unprovisioned_without_reading_identity() {
|
||||
// Both fresh-erase (0xFF) and zeroed lock bytes count as unlocked, and
|
||||
// neither the checksum nor the identity bytes may be consulted.
|
||||
for lock in [0x00, 0xFF] {
|
||||
let mut bytes = image(0x11);
|
||||
bytes[INFO_LOCK_ADDRESS] = lock;
|
||||
for byte in &mut bytes[CHECKSUM_ADDRESS..CHECKSUM_END] {
|
||||
*byte = 0xA5;
|
||||
}
|
||||
assert_eq!(
|
||||
classify_rnode_eeprom_image(&bytes),
|
||||
Ok(RNodeEepromImage::Unprovisioned),
|
||||
"lock byte {lock:#04x} must classify unprovisioned"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classification_preserves_strict_short_and_checksum_failures() {
|
||||
let short = &image(0xA4)[..REQUIRED_EEPROM_LEN - 1];
|
||||
assert_eq!(
|
||||
classify_rnode_eeprom_image(short),
|
||||
Err(RNodeCapabilityParseError::TooShort {
|
||||
required: 156,
|
||||
actual: 155,
|
||||
})
|
||||
);
|
||||
|
||||
let mut corrupt = image(0xA4);
|
||||
corrupt[CHECKSUM_ADDRESS] ^= 0x01;
|
||||
assert_eq!(
|
||||
classify_rnode_eeprom_image(&corrupt),
|
||||
Err(RNodeCapabilityParseError::ChecksumMismatch)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
classify_rnode_eeprom_image(&image(0x11)),
|
||||
Ok(RNodeEepromImage::Provisioned(
|
||||
parse_rnode_capabilities(&image(0x11)).expect("valid image")
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unprovisioned_admission_applies_generic_validation_only() {
|
||||
assert_eq!(
|
||||
admit_unprovisioned_rnode_radio_settings(settings(868_000_000, 37)),
|
||||
Ok(RNodeRadioAdmission::Unprovisioned)
|
||||
);
|
||||
assert!(matches!(
|
||||
admit_unprovisioned_rnode_radio_settings(settings(1, 14)),
|
||||
Err(RNodeRadioAdmissionError::GenericValidation(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_codes_are_present_only_for_locked_identities() {
|
||||
let verified = RNodeRadioAdmission::Verified {
|
||||
product_code: PRODUCT,
|
||||
model_code: 0x11,
|
||||
};
|
||||
assert_eq!(verified.product_code(), Some(PRODUCT));
|
||||
assert_eq!(verified.model_code(), Some(0x11));
|
||||
assert!(verified.is_verified());
|
||||
|
||||
assert_eq!(RNodeRadioAdmission::Unprovisioned.product_code(), None);
|
||||
assert_eq!(RNodeRadioAdmission::Unprovisioned.model_code(), None);
|
||||
assert!(!RNodeRadioAdmission::Unprovisioned.is_verified());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_covers_exact_identity_prefix_without_model_normalisation() {
|
||||
let mut bytes = image(0x04);
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
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,
|
||||
RNodeEepromImage, RNodeRadioAdmission, admit_rnode_radio_settings,
|
||||
admit_unprovisioned_rnode_radio_settings, classify_rnode_eeprom_image,
|
||||
};
|
||||
use crate::rnode_protocol::{
|
||||
RNodeFrameRejection, RNodeProtocolEffect, RNodeProtocolState, RNodeProtocolTarget,
|
||||
@@ -100,12 +101,19 @@ impl RNodeCapabilityPreflight {
|
||||
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)?,
|
||||
);
|
||||
let admission = match classify_rnode_eeprom_image(&payload)
|
||||
.map_err(RNodeCapabilityAdmissionError::CapabilityImage)?
|
||||
{
|
||||
RNodeEepromImage::Provisioned(capabilities) => {
|
||||
admit_rnode_radio_settings(capabilities, self.settings)
|
||||
.map_err(RNodeCapabilityAdmissionError::RadioSettings)?
|
||||
}
|
||||
RNodeEepromImage::Unprovisioned => {
|
||||
admit_unprovisioned_rnode_radio_settings(self.settings)
|
||||
.map_err(RNodeCapabilityAdmissionError::RadioSettings)?
|
||||
}
|
||||
};
|
||||
self.admission = Some(admission);
|
||||
continue;
|
||||
}
|
||||
if command == CMD_ERROR {
|
||||
@@ -217,6 +225,70 @@ mod tests {
|
||||
frames
|
||||
}
|
||||
|
||||
fn unlocked_eeprom(model: u8) -> Vec<u8> {
|
||||
let mut bytes = eeprom(model);
|
||||
bytes[0x9B] = 0xFF;
|
||||
// Corrupt the checksum region too: unlocked images must admit without
|
||||
// consulting it.
|
||||
for byte in &mut bytes[11..27] {
|
||||
*byte = 0x5A;
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
fn unprovisioned_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, &unlocked_eeprom(model), &mut frames);
|
||||
frames
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlocked_eeprom_admits_unprovisioned_and_never_consults_model_bounds() {
|
||||
// Model 0xB4 at 868 MHz is a typed FrequencyOutOfRange when locked
|
||||
// (see known_model_mismatch_and_bounds_are_typed); unlocked, the model
|
||||
// byte is unattested and must impose nothing.
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let result = observe_chunked(&mut preflight, &unprovisioned_frames(0xB4)).unwrap();
|
||||
assert_eq!(result, Some(RNodeRadioAdmission::Unprovisioned));
|
||||
|
||||
let seed = preflight.into_protocol_state();
|
||||
assert!(seed.evidence().detected);
|
||||
assert!(seed.evidence().firmware.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlocked_eeprom_still_fails_generic_radio_validation() {
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(1, 14));
|
||||
assert!(matches!(
|
||||
observe_chunked(&mut preflight, &unprovisioned_frames(0xB8)),
|
||||
Err(RNodeCapabilityAdmissionError::RadioSettings(
|
||||
crate::rnode_capabilities::RNodeRadioAdmissionError::GenericValidation(_)
|
||||
))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlocked_then_duplicate_rom_response_remains_fatal() {
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
observe_chunked(&mut preflight, &unprovisioned_frames(0xB8)).unwrap(),
|
||||
Some(RNodeRadioAdmission::Unprovisioned)
|
||||
);
|
||||
assert_eq!(
|
||||
observe_chunked(
|
||||
&mut preflight,
|
||||
&kiss::frame_with_command(CMD_ROM_READ, &unlocked_eeprom(0xB8)),
|
||||
),
|
||||
Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_request_is_one_standalone_rom_read_zero_frame() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
//! Multi-radio RNode: up to 11 sub-interfaces on one serial connection.
|
||||
//! One read task demuxes by per-vport command byte; one write task prepends
|
||||
//! `CMD_SEL_INT` so the device picks the right radio.
|
||||
//! One read task demuxes canonical `CMD_DATA` frames by the most recently
|
||||
//! selected virtual port; one write task prepends `CMD_SEL_INT` so the device
|
||||
//! picks the right radio.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::mpsc;
|
||||
@@ -29,8 +32,12 @@ pub const CMD_ERROR: u8 = 0x90;
|
||||
pub const ERROR_INITRADIO: u8 = 0x01;
|
||||
pub const ERROR_TXFAILED: u8 = 0x02;
|
||||
|
||||
/// Per-sub-interface data command bytes. NOT port-nibble; some collide
|
||||
/// (e.g. `CMD_INT5_DATA == CMD_ERROR`) — demux by vport index, not byte.
|
||||
/// Legacy per-interface constants exposed by the firmware protocol.
|
||||
///
|
||||
/// Live RNodeMulti traffic is not demultiplexed with this table. The canonical
|
||||
/// wire form selects a vport with [`CMD_SEL_INT`] and then sends one ordinary
|
||||
/// [`kiss::CMD_DATA`] frame. Treating these values as inbound data commands
|
||||
/// makes `0x90` indistinguishable from [`CMD_ERROR`].
|
||||
pub const CMD_INT_DATA: [u8; 12] = [
|
||||
0x00, 0x10, 0x20, 0x70, 0x75, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
|
||||
];
|
||||
@@ -83,7 +90,7 @@ impl RadioType {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SubInterfaceConfig {
|
||||
pub name: String,
|
||||
/// vport index on RNode (0..MAX_SUBINTERFACES).
|
||||
/// vport index on RNode (`0..MAX_SUBINTERFACES`).
|
||||
pub vport: u8,
|
||||
pub frequency: u32,
|
||||
pub bandwidth: u32,
|
||||
@@ -158,10 +165,12 @@ impl SubInterfaceConfig {
|
||||
));
|
||||
}
|
||||
}
|
||||
if self.vport as usize > MAX_SUBINTERFACES {
|
||||
if self.vport as usize >= MAX_SUBINTERFACES {
|
||||
return Err(format!(
|
||||
"Virtual port {} exceeds max {} for sub-interface {}",
|
||||
self.vport, MAX_SUBINTERFACES, self.name
|
||||
"Virtual port {} is outside 0..{} for sub-interface {}",
|
||||
self.vport,
|
||||
MAX_SUBINTERFACES - 1,
|
||||
self.name
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
@@ -249,6 +258,14 @@ pub fn build_subinterface_data_frame(index: u8, data: &[u8]) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Map a legacy `CMD_INTn_DATA` constant to its nominal vport.
|
||||
///
|
||||
/// This helper is retained for protocol inspection and compatibility only.
|
||||
/// It must not be used to route live RNodeMulti input; use `CMD_SEL_INT`
|
||||
/// followed by `CMD_DATA` instead.
|
||||
#[deprecated(
|
||||
note = "legacy constants collide with control commands; route CMD_DATA by CMD_SEL_INT"
|
||||
)]
|
||||
pub fn command_to_subinterface(cmd_byte: u8) -> Option<usize> {
|
||||
for (i, &port_cmd) in CMD_INT_DATA.iter().enumerate() {
|
||||
if cmd_byte == port_cmd {
|
||||
@@ -258,6 +275,345 @@ pub fn command_to_subinterface(cmd_byte: u8) -> Option<usize> {
|
||||
None
|
||||
}
|
||||
|
||||
const RNODE_HW_MTU: u32 = 508;
|
||||
const RNODE_OPEN_SETTLE: Duration = Duration::from_secs(2);
|
||||
const RNODE_SUBINTERFACE_SETTLE: Duration = Duration::from_secs(2);
|
||||
const RNODE_SUBINTERFACE_READY_SETTLE: Duration = Duration::from_millis(300);
|
||||
const RNODE_DISCOVERY_DEADLINE: Duration = Duration::from_secs(2);
|
||||
const RNODE_CONFIGURATION_DEADLINE: Duration = Duration::from_secs(2);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
struct RadioEvidence {
|
||||
frequency: Option<u32>,
|
||||
bandwidth: Option<u32>,
|
||||
spreading_factor: Option<u8>,
|
||||
coding_rate: Option<u8>,
|
||||
tx_power: Option<u8>,
|
||||
radio_state: Option<u8>,
|
||||
}
|
||||
|
||||
impl RadioEvidence {
|
||||
fn complete(self) -> bool {
|
||||
self.frequency.is_some()
|
||||
&& self.bandwidth.is_some()
|
||||
&& self.spreading_factor.is_some()
|
||||
&& self.coding_rate.is_some()
|
||||
&& self.tx_power.is_some()
|
||||
&& self.radio_state.is_some()
|
||||
}
|
||||
|
||||
fn validate(self, config: &SubInterfaceConfig) -> Result<(), String> {
|
||||
let frequency = self
|
||||
.frequency
|
||||
.ok_or_else(|| format!("{} did not report frequency", config.name))?;
|
||||
if frequency.abs_diff(config.frequency) > crate::rnode_protocol::FREQUENCY_TOLERANCE_HZ {
|
||||
return Err(format!("{} reported a different frequency", config.name));
|
||||
}
|
||||
if self.bandwidth != Some(config.bandwidth) {
|
||||
return Err(format!("{} reported a different bandwidth", config.name));
|
||||
}
|
||||
if self.spreading_factor != Some(config.spreading_factor) {
|
||||
return Err(format!(
|
||||
"{} reported a different spreading factor",
|
||||
config.name
|
||||
));
|
||||
}
|
||||
if self.coding_rate != Some(config.coding_rate) {
|
||||
return Err(format!("{} reported a different coding rate", config.name));
|
||||
}
|
||||
if self.tx_power != Some(config.tx_power) {
|
||||
return Err(format!("{} reported a different TX power", config.name));
|
||||
}
|
||||
if self.radio_state != Some(rnode::RADIO_STATE_ON) {
|
||||
return Err(format!("{} did not report its radio online", config.name));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct StartupEvidence {
|
||||
detected: bool,
|
||||
firmware: Option<(u8, u8)>,
|
||||
interfaces: [Option<RadioType>; MAX_SUBINTERFACES],
|
||||
selected_vport: Option<u8>,
|
||||
radios: [RadioEvidence; MAX_SUBINTERFACES],
|
||||
}
|
||||
|
||||
impl Default for StartupEvidence {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
detected: false,
|
||||
firmware: None,
|
||||
interfaces: [None; MAX_SUBINTERFACES],
|
||||
selected_vport: None,
|
||||
radios: [RadioEvidence::default(); MAX_SUBINTERFACES],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StartupEvidence {
|
||||
fn apply_frame(&mut self, command: u8, payload: &[u8]) -> Result<(), String> {
|
||||
match command {
|
||||
rnode::CMD_DETECT => {
|
||||
if payload.len() != 1 {
|
||||
return Err("RNodeMulti returned malformed detection evidence".into());
|
||||
}
|
||||
self.detected = payload[0] == rnode::DETECT_RESP;
|
||||
}
|
||||
rnode::CMD_FW_VERSION => {
|
||||
if payload.len() != 2 {
|
||||
return Err("RNodeMulti returned malformed firmware evidence".into());
|
||||
}
|
||||
self.firmware = Some((payload[0], payload[1]));
|
||||
}
|
||||
CMD_INTERFACES => {
|
||||
if payload.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if payload.len() % 2 != 0 {
|
||||
return Err("RNodeMulti returned a malformed interface list".into());
|
||||
}
|
||||
for pair in payload.chunks_exact(2) {
|
||||
let vport = pair[0] as usize;
|
||||
if vport >= MAX_SUBINTERFACES {
|
||||
return Err(format!(
|
||||
"RNodeMulti reported unsupported virtual port {}",
|
||||
pair[0]
|
||||
));
|
||||
}
|
||||
let radio_type = RadioType::from_u8(pair[1]).ok_or_else(|| {
|
||||
format!(
|
||||
"RNodeMulti reported unknown radio type 0x{:02X} on virtual port {}",
|
||||
pair[1], pair[0]
|
||||
)
|
||||
})?;
|
||||
if self.interfaces[vport].is_some_and(|known| known != radio_type) {
|
||||
return Err(format!(
|
||||
"RNodeMulti changed the radio type reported for virtual port {}",
|
||||
pair[0]
|
||||
));
|
||||
}
|
||||
self.interfaces[vport] = Some(radio_type);
|
||||
}
|
||||
}
|
||||
CMD_SEL_INT => {
|
||||
if payload.len() != 1 || payload[0] as usize >= MAX_SUBINTERFACES {
|
||||
self.selected_vport = None;
|
||||
return Err("RNodeMulti returned an invalid virtual-port selection".into());
|
||||
}
|
||||
self.selected_vport = Some(payload[0]);
|
||||
}
|
||||
rnode::CMD_FREQUENCY => {
|
||||
if payload.len() != 4 {
|
||||
return Err("RNodeMulti returned malformed frequency evidence".into());
|
||||
}
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.frequency = Some(u32::from_be_bytes(
|
||||
payload.try_into().expect("length checked"),
|
||||
));
|
||||
}
|
||||
}
|
||||
rnode::CMD_BANDWIDTH => {
|
||||
if payload.len() != 4 {
|
||||
return Err("RNodeMulti returned malformed bandwidth evidence".into());
|
||||
}
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.bandwidth = Some(u32::from_be_bytes(
|
||||
payload.try_into().expect("length checked"),
|
||||
));
|
||||
}
|
||||
}
|
||||
rnode::CMD_SF => {
|
||||
let value = one_byte(payload, "spreading factor")?;
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.spreading_factor = Some(value);
|
||||
}
|
||||
}
|
||||
rnode::CMD_CR => {
|
||||
let value = one_byte(payload, "coding rate")?;
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.coding_rate = Some(value);
|
||||
}
|
||||
}
|
||||
rnode::CMD_TXPOWER => {
|
||||
let value = one_byte(payload, "TX power")?;
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.tx_power = Some(value);
|
||||
}
|
||||
}
|
||||
rnode::CMD_RADIO_STATE => {
|
||||
let value = one_byte(payload, "radio state")?;
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.radio_state = Some(value);
|
||||
}
|
||||
}
|
||||
CMD_ERROR => {
|
||||
let class = match payload.first().copied() {
|
||||
Some(ERROR_INITRADIO) => "radio initialisation",
|
||||
Some(ERROR_TXFAILED) => "radio transmission",
|
||||
_ => "unknown hardware",
|
||||
};
|
||||
return Err(format!("RNodeMulti reported a {class} error"));
|
||||
}
|
||||
rnode::CMD_RESET if payload.first().copied() == Some(0xF8) => {
|
||||
return Err("RNodeMulti reset during startup".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn selected_radio_mut(&mut self) -> Option<&mut RadioEvidence> {
|
||||
self.selected_vport
|
||||
.and_then(|vport| self.radios.get_mut(vport as usize))
|
||||
}
|
||||
|
||||
fn discovery_complete(&self, config: &RNodeMultiConfig) -> bool {
|
||||
self.detected
|
||||
&& self.firmware.is_some()
|
||||
&& config
|
||||
.subinterfaces
|
||||
.iter()
|
||||
.all(|sub| self.interfaces[sub.vport as usize].is_some())
|
||||
}
|
||||
|
||||
fn validate_discovery(&self, config: &RNodeMultiConfig) -> Result<(), String> {
|
||||
if !self.detected {
|
||||
return Err("RNodeMulti device did not answer detection".into());
|
||||
}
|
||||
let (major, minor) = self
|
||||
.firmware
|
||||
.ok_or_else(|| "RNodeMulti did not report its firmware version".to_string())?;
|
||||
if (major, minor) < (REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN) {
|
||||
return Err(format!(
|
||||
"RNodeMulti firmware {major}.{minor} is below required {}.{}",
|
||||
REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN
|
||||
));
|
||||
}
|
||||
for sub in &config.subinterfaces {
|
||||
let radio_type = self.interfaces[sub.vport as usize].ok_or_else(|| {
|
||||
format!(
|
||||
"virtual port {} for {} was not reported by the RNodeMulti device",
|
||||
sub.vport, sub.name
|
||||
)
|
||||
})?;
|
||||
if !radio_type.validate_frequency(sub.frequency) {
|
||||
return Err(format!(
|
||||
"frequency {} is outside the {} range reported for {}",
|
||||
sub.frequency,
|
||||
radio_type.family_name(),
|
||||
sub.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reset_radio(&mut self, vport: u8) {
|
||||
self.radios[vport as usize] = RadioEvidence::default();
|
||||
self.selected_vport = None;
|
||||
}
|
||||
|
||||
fn radio_complete(&self, vport: u8) -> bool {
|
||||
self.radios[vport as usize].complete()
|
||||
}
|
||||
}
|
||||
|
||||
fn one_byte(payload: &[u8], field: &str) -> Result<u8, String> {
|
||||
if payload.len() != 1 {
|
||||
return Err(format!("RNodeMulti returned malformed {field} evidence"));
|
||||
}
|
||||
Ok(payload[0])
|
||||
}
|
||||
|
||||
fn read_startup_until(
|
||||
port: &mut dyn serialport::SerialPort,
|
||||
deframer: &mut kiss::RawKissDeframer,
|
||||
evidence: &mut StartupEvidence,
|
||||
deadline: Instant,
|
||||
ready: impl Fn(&StartupEvidence) -> bool,
|
||||
) -> Result<(), String> {
|
||||
let mut buffer = [0u8; 1024];
|
||||
while Instant::now() < deadline {
|
||||
match port.read(&mut buffer) {
|
||||
Ok(0) => {}
|
||||
Ok(read) => {
|
||||
for (command, payload) in deframer.feed(&buffer[..read]) {
|
||||
evidence.apply_frame(command, &payload)?;
|
||||
if ready(evidence) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => {}
|
||||
Err(error) => return Err(format!("RNodeMulti startup read failed: {error}")),
|
||||
}
|
||||
}
|
||||
Err("RNodeMulti startup validation timed out".into())
|
||||
}
|
||||
|
||||
fn initialise_rnode_multi(
|
||||
mut port: Box<dyn serialport::SerialPort>,
|
||||
config: &RNodeMultiConfig,
|
||||
) -> Result<Box<dyn serialport::SerialPort>, String> {
|
||||
std::thread::sleep(RNODE_OPEN_SETTLE);
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let mut evidence = StartupEvidence::default();
|
||||
|
||||
port.write_all(&build_detect_sequence())
|
||||
.map_err(|error| format!("RNodeMulti detect write failed: {error}"))?;
|
||||
port.flush()
|
||||
.map_err(|error| format!("RNodeMulti detect flush failed: {error}"))?;
|
||||
read_startup_until(
|
||||
port.as_mut(),
|
||||
&mut deframer,
|
||||
&mut evidence,
|
||||
Instant::now() + RNODE_DISCOVERY_DEADLINE,
|
||||
|state| state.discovery_complete(config),
|
||||
)?;
|
||||
evidence.validate_discovery(config)?;
|
||||
|
||||
for sub in &config.subinterfaces {
|
||||
// RNode firmware configures one physical radio at a time. Match the
|
||||
// established RNodeMulti startup cadence and let the selected radio
|
||||
// settle before sending its reset/init sequence.
|
||||
std::thread::sleep(RNODE_SUBINTERFACE_SETTLE);
|
||||
evidence.reset_radio(sub.vport);
|
||||
port.write_all(&build_subinterface_init(sub.vport, sub))
|
||||
.map_err(|error| format!("RNodeMulti {} init write failed: {error}", sub.name))?;
|
||||
port.flush()
|
||||
.map_err(|error| format!("RNodeMulti {} init flush failed: {error}", sub.name))?;
|
||||
read_startup_until(
|
||||
port.as_mut(),
|
||||
&mut deframer,
|
||||
&mut evidence,
|
||||
Instant::now() + RNODE_CONFIGURATION_DEADLINE,
|
||||
|state| state.radio_complete(sub.vport),
|
||||
)?;
|
||||
evidence.radios[sub.vport as usize].validate(sub)?;
|
||||
// Match upstream's brief post-validation pause before exposing this
|
||||
// radio or beginning configuration of the next physical radio.
|
||||
std::thread::sleep(RNODE_SUBINTERFACE_READY_SETTLE);
|
||||
}
|
||||
|
||||
Ok(port)
|
||||
}
|
||||
|
||||
fn selected_data_target(
|
||||
command: u8,
|
||||
selected_vport: Option<u8>,
|
||||
vport_map: &[Option<usize>; MAX_SUBINTERFACES],
|
||||
) -> Option<usize> {
|
||||
if command != kiss::CMD_DATA {
|
||||
return None;
|
||||
}
|
||||
selected_vport
|
||||
.and_then(|vport| vport_map.get(vport as usize))
|
||||
.copied()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
struct WriteRequest {
|
||||
index: u8,
|
||||
/// Raw payload, not yet KISS-escaped.
|
||||
@@ -334,6 +690,15 @@ pub async fn spawn_rnode_multi_interface(
|
||||
sub.validate()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti config: {}", e)))?;
|
||||
}
|
||||
let mut configured_vports = HashSet::with_capacity(config.subinterfaces.len());
|
||||
for sub in &config.subinterfaces {
|
||||
if !configured_vports.insert(sub.vport) {
|
||||
return Err(InterfaceError::SendFailed(format!(
|
||||
"RNodeMulti config: virtual port {} is configured more than once",
|
||||
sub.vport
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
let port = serialport::new(&config.port, config.baud_rate)
|
||||
.timeout(Duration::from_millis(RNODE_READ_TIMEOUT_MS))
|
||||
@@ -347,36 +712,13 @@ pub async fn spawn_rnode_multi_interface(
|
||||
"RNodeMulti interface opened"
|
||||
);
|
||||
|
||||
{
|
||||
let mut detect_port = port
|
||||
.try_clone()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?;
|
||||
let detect_seq = build_detect_sequence();
|
||||
use std::io::Write;
|
||||
detect_port
|
||||
.write_all(&detect_seq)
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti detect write: {}", e)))?;
|
||||
detect_port
|
||||
.flush()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti detect flush: {}", e)))?;
|
||||
}
|
||||
|
||||
{
|
||||
let mut init_port = port
|
||||
.try_clone()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?;
|
||||
let mut init_seq = Vec::new();
|
||||
for sub in &config.subinterfaces {
|
||||
init_seq.extend_from_slice(&build_subinterface_init(sub.vport, sub));
|
||||
}
|
||||
use std::io::Write;
|
||||
init_port
|
||||
.write_all(&init_seq)
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti init write: {}", e)))?;
|
||||
init_port
|
||||
.flush()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti init flush: {}", e)))?;
|
||||
}
|
||||
let startup_config = config.clone();
|
||||
let port = tokio::task::spawn_blocking(move || initialise_rnode_multi(port, &startup_config))
|
||||
.await
|
||||
.map_err(|error| {
|
||||
InterfaceError::SendFailed(format!("RNodeMulti startup worker failed: {error}"))
|
||||
})?
|
||||
.map_err(|error| InterfaceError::SendFailed(format!("RNodeMulti startup: {error}")))?;
|
||||
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
|
||||
@@ -478,7 +820,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
repeat: false,
|
||||
},
|
||||
bitrate,
|
||||
mtu: rns_wire::constants::MTU as u32,
|
||||
mtu: RNODE_HW_MTU,
|
||||
online: sub_onlines[i].clone(),
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
@@ -602,13 +944,11 @@ pub async fn spawn_rnode_multi_interface(
|
||||
let parent_name = config.name.clone();
|
||||
|
||||
// `vport_map[vport] -> Some(local_index)` for configured sub-interfaces.
|
||||
let mut vport_map: [Option<usize>; 12] = [None; 12];
|
||||
let mut vport_map: [Option<usize>; MAX_SUBINTERFACES] = [None; MAX_SUBINTERFACES];
|
||||
let mut sub_ids: Vec<InterfaceId> = Vec::with_capacity(num_subs);
|
||||
for (i, sub_cfg) in config.subinterfaces.iter().enumerate() {
|
||||
let vp = sub_cfg.vport as usize;
|
||||
if vp < 12 {
|
||||
vport_map[vp] = Some(i);
|
||||
}
|
||||
vport_map[vp] = Some(i);
|
||||
sub_ids.push(ids[i]);
|
||||
}
|
||||
|
||||
@@ -622,10 +962,8 @@ pub async fn spawn_rnode_multi_interface(
|
||||
.collect();
|
||||
|
||||
// Which sub-interface the device is currently addressing via
|
||||
// CMD_SEL_INT; status commands below target this index.
|
||||
let mut selected_index: usize = 0;
|
||||
|
||||
let mut interfaces_buf: Vec<u8> = Vec::new();
|
||||
// CMD_SEL_INT; status and canonical CMD_DATA frames target this vport.
|
||||
let mut selected_vport: Option<u8> = Some(0);
|
||||
|
||||
loop {
|
||||
if !flags_r.device_running() {
|
||||
@@ -641,11 +979,13 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
|
||||
for (raw_cmd, frame) in deframer.feed(&buf[..n]) {
|
||||
if let Some(vport) = command_to_subinterface(raw_cmd) {
|
||||
if raw_cmd == kiss::CMD_DATA {
|
||||
if frame.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(local_idx) = vport_map[vport] {
|
||||
if let Some(local_idx) =
|
||||
selected_data_target(raw_cmd, selected_vport, &vport_map)
|
||||
{
|
||||
sub_rxb[local_idx].fetch_add(frame.len() as u64, Ordering::Relaxed);
|
||||
|
||||
let rssi = signals[local_idx].last_rssi.take();
|
||||
@@ -669,7 +1009,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
} else {
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport,
|
||||
vport = ?selected_vport,
|
||||
"data for unconfigured sub-interface, dropping"
|
||||
);
|
||||
}
|
||||
@@ -681,7 +1021,15 @@ pub async fn spawn_rnode_multi_interface(
|
||||
// Device echoes selection before emitting any
|
||||
// status/config responses for that sub-interface.
|
||||
if let Some(&idx) = frame.first() {
|
||||
selected_index = idx as usize;
|
||||
selected_vport =
|
||||
((idx as usize) < MAX_SUBINTERFACES).then_some(idx);
|
||||
if selected_vport.is_none() {
|
||||
tracing::warn!(
|
||||
parent = %parent_name,
|
||||
vport = idx,
|
||||
"RNodeMulti selected an invalid virtual port"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -689,7 +1037,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
if !frame.is_empty() {
|
||||
let rssi = rnode::decode_rssi_byte(frame[0]);
|
||||
if let Some(local_idx) =
|
||||
vport_map.get(selected_index).copied().flatten()
|
||||
selected_vport.and_then(|vport| vport_map[vport as usize])
|
||||
{
|
||||
signals[local_idx].last_rssi = Some(rssi);
|
||||
}
|
||||
@@ -699,7 +1047,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
if !frame.is_empty() {
|
||||
let snr = rnode::decode_snr_byte(frame[0]);
|
||||
if let Some(local_idx) =
|
||||
vport_map.get(selected_index).copied().flatten()
|
||||
selected_vport.and_then(|vport| vport_map[vport as usize])
|
||||
{
|
||||
signals[local_idx].last_snr = Some(snr);
|
||||
}
|
||||
@@ -746,20 +1094,20 @@ pub async fn spawn_rnode_multi_interface(
|
||||
|
||||
rnode::CMD_RADIO_STATE => {
|
||||
if let Some(local_idx) =
|
||||
vport_map.get(selected_index).copied().flatten()
|
||||
selected_vport.and_then(|vport| vport_map[vport as usize])
|
||||
{
|
||||
if frame.first().copied() == Some(rnode::RADIO_STATE_ON) {
|
||||
tracing::info!(
|
||||
parent = %parent_name,
|
||||
subinterface = local_idx,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
"RNodeMulti sub-interface radio online"
|
||||
);
|
||||
} else {
|
||||
tracing::warn!(
|
||||
parent = %parent_name,
|
||||
subinterface = local_idx,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
"RNodeMulti sub-interface radio offline"
|
||||
);
|
||||
}
|
||||
@@ -773,7 +1121,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
]);
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
freq_mhz = format!("{:.3}", freq as f64 / 1_000_000.0),
|
||||
"Radio reporting frequency"
|
||||
);
|
||||
@@ -787,7 +1135,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
]);
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
bw_khz = format!("{:.1}", bw as f64 / 1000.0),
|
||||
"Radio reporting bandwidth"
|
||||
);
|
||||
@@ -798,7 +1146,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
if !frame.is_empty() {
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
sf = frame[0],
|
||||
"Radio reporting spreading factor"
|
||||
);
|
||||
@@ -809,7 +1157,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
if !frame.is_empty() {
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
cr = frame[0],
|
||||
"Radio reporting coding rate"
|
||||
);
|
||||
@@ -821,7 +1169,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
let txp = frame[0] as i8;
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
txpower_dbm = txp,
|
||||
"Radio reporting TX power"
|
||||
);
|
||||
@@ -834,7 +1182,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
let pct = at as f32 / 100.0;
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
"RNodeMulti short-term airtime limit: {:.2}%", pct,
|
||||
);
|
||||
}
|
||||
@@ -846,7 +1194,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
let pct = at as f32 / 100.0;
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
"RNodeMulti long-term airtime limit: {:.2}%", pct,
|
||||
);
|
||||
}
|
||||
@@ -873,12 +1221,10 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
|
||||
CMD_INTERFACES => {
|
||||
// Reply is a stream of 2-byte `[vport, radio_type]`
|
||||
// pairs, one per radio module; accumulate then pop.
|
||||
interfaces_buf.extend_from_slice(&frame);
|
||||
if interfaces_buf.len() >= 2 {
|
||||
let vp = interfaces_buf[0];
|
||||
let rt = interfaces_buf[1];
|
||||
// Reply is one or more `[vport, radio_type]` pairs.
|
||||
for pair in frame.chunks_exact(2) {
|
||||
let vp = pair[0];
|
||||
let rt = pair[1];
|
||||
let rtype = RadioType::from_u8(rt)
|
||||
.map(|r| r.family_name().to_string())
|
||||
.unwrap_or_else(|| format!("unknown(0x{:02X})", rt));
|
||||
@@ -888,13 +1234,30 @@ pub async fn spawn_rnode_multi_interface(
|
||||
radio_type = %rtype,
|
||||
"RNodeMulti radio module reported"
|
||||
);
|
||||
interfaces_buf.clear();
|
||||
}
|
||||
if frame.len() % 2 != 0 {
|
||||
tracing::warn!(
|
||||
parent = %parent_name,
|
||||
"RNodeMulti returned a malformed interface list"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// No CMD_ERROR arm: 0x90 collides with CMD_INT5_DATA
|
||||
// and is consumed by the vport demux above — same
|
||||
// collision as Python RNodeMultiInterface.
|
||||
CMD_ERROR => {
|
||||
let class = match frame.first().copied() {
|
||||
Some(ERROR_INITRADIO) => "radio initialisation",
|
||||
Some(ERROR_TXFAILED) => "radio transmission",
|
||||
_ => "unknown hardware",
|
||||
};
|
||||
tracing::error!(
|
||||
parent = %parent_name,
|
||||
class,
|
||||
"RNodeMulti hardware error"
|
||||
);
|
||||
flags_r.trip_device();
|
||||
return;
|
||||
}
|
||||
|
||||
rnode::CMD_RESET => {
|
||||
if frame.first().copied() == Some(0xF8) {
|
||||
tracing::error!(
|
||||
@@ -1019,25 +1382,6 @@ mod tests {
|
||||
assert_eq!(frames.len(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_command_to_subinterface() {
|
||||
assert_eq!(command_to_subinterface(0x00), Some(0));
|
||||
assert_eq!(command_to_subinterface(0x10), Some(1));
|
||||
assert_eq!(command_to_subinterface(0x20), Some(2));
|
||||
assert_eq!(command_to_subinterface(0x70), Some(3));
|
||||
assert_eq!(command_to_subinterface(0x75), Some(4));
|
||||
assert_eq!(command_to_subinterface(0x90), Some(5));
|
||||
assert_eq!(command_to_subinterface(0xA0), Some(6));
|
||||
assert_eq!(command_to_subinterface(0xB0), Some(7));
|
||||
assert_eq!(command_to_subinterface(0xC0), Some(8));
|
||||
assert_eq!(command_to_subinterface(0xD0), Some(9));
|
||||
assert_eq!(command_to_subinterface(0xE0), Some(10));
|
||||
assert_eq!(command_to_subinterface(0xF0), Some(11));
|
||||
assert_eq!(command_to_subinterface(0x55), None);
|
||||
assert_eq!(command_to_subinterface(0xFF), None);
|
||||
assert_eq!(command_to_subinterface(0x01), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_radio_type() {
|
||||
assert_eq!(RadioType::from_u8(0x00), Some(RadioType::SX127X));
|
||||
@@ -1068,7 +1412,12 @@ mod tests {
|
||||
#[test]
|
||||
fn test_max_subinterfaces() {
|
||||
assert_eq!(MAX_SUBINTERFACES, 11);
|
||||
assert_eq!(CMD_INT_DATA.len(), 12);
|
||||
assert_eq!(RNODE_HW_MTU, 508);
|
||||
|
||||
let highest = SubInterfaceConfig::new("radio10", 10, 868_000_000);
|
||||
assert!(highest.validate().is_ok());
|
||||
let outside = SubInterfaceConfig::new("radio11", 11, 868_000_000);
|
||||
assert!(outside.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1099,9 +1448,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_raw_kiss_deframer_preserves_command() {
|
||||
// CMD_INT5_DATA = 0x90 collides with CMD_ERROR after masking; the raw
|
||||
// deframer must keep the high nibble intact.
|
||||
let payload = b"test data";
|
||||
// CMD_ERROR is 0x90. The raw deframer must retain that exact command
|
||||
// so it can never be mistaken for vport-5 packet data.
|
||||
let payload = &[ERROR_INITRADIO];
|
||||
let mut raw_frame = Vec::new();
|
||||
raw_frame.push(kiss::FEND);
|
||||
raw_frame.push(0x90);
|
||||
@@ -1111,10 +1460,12 @@ mod tests {
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let frames = deframer.feed(&raw_frame);
|
||||
assert_eq!(frames.len(), 1);
|
||||
assert_eq!(frames[0].0, 0x90);
|
||||
assert_eq!(frames[0].0, CMD_ERROR);
|
||||
assert_eq!(frames[0].1, payload);
|
||||
|
||||
assert_eq!(command_to_subinterface(0x90), Some(5));
|
||||
let mut vport_map = [None; MAX_SUBINTERFACES];
|
||||
vport_map[5] = Some(0);
|
||||
assert_eq!(selected_data_target(CMD_ERROR, Some(5), &vport_map), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1214,7 +1565,7 @@ mod tests {
|
||||
bad.st_alock = Some(101.0);
|
||||
assert!(bad.validate().is_err());
|
||||
|
||||
let bad = SubInterfaceConfig::new("radio0", 12, 868_000_000);
|
||||
let bad = SubInterfaceConfig::new("radio0", 11, 868_000_000);
|
||||
assert!(bad.validate().is_err());
|
||||
}
|
||||
|
||||
@@ -1284,55 +1635,118 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_all_subinterface_data_commands_unique() {
|
||||
for (i, lhs) in CMD_INT_DATA.iter().enumerate() {
|
||||
for (j, rhs) in CMD_INT_DATA.iter().enumerate().skip(i + 1) {
|
||||
assert_ne!(
|
||||
lhs, rhs,
|
||||
"CMD_INT_DATA[{}] == CMD_INT_DATA[{}] == 0x{:02X}",
|
||||
i, j, *lhs
|
||||
);
|
||||
}
|
||||
}
|
||||
fn canonical_data_routing_uses_selected_vport_only() {
|
||||
let mut vport_map = [None; MAX_SUBINTERFACES];
|
||||
vport_map[0] = Some(0);
|
||||
vport_map[5] = Some(1);
|
||||
|
||||
assert_eq!(
|
||||
selected_data_target(kiss::CMD_DATA, Some(5), &vport_map),
|
||||
Some(1)
|
||||
);
|
||||
assert_eq!(
|
||||
selected_data_target(kiss::CMD_DATA, Some(0), &vport_map),
|
||||
Some(0)
|
||||
);
|
||||
assert_eq!(
|
||||
selected_data_target(kiss::CMD_DATA, Some(4), &vport_map),
|
||||
None
|
||||
);
|
||||
assert_eq!(selected_data_target(CMD_ERROR, Some(5), &vport_map), None);
|
||||
assert_eq!(selected_data_target(0xA0, Some(5), &vport_map), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_commands_dont_collide_with_control_commands() {
|
||||
let control_cmds = [
|
||||
CMD_SEL_INT,
|
||||
rnode::CMD_STAT_RSSI,
|
||||
rnode::CMD_STAT_SNR,
|
||||
rnode::CMD_READY,
|
||||
rnode::CMD_DETECT,
|
||||
rnode::CMD_FW_VERSION,
|
||||
rnode::CMD_RADIO_STATE,
|
||||
rnode::CMD_FREQUENCY,
|
||||
rnode::CMD_BANDWIDTH,
|
||||
rnode::CMD_SF,
|
||||
rnode::CMD_CR,
|
||||
rnode::CMD_TXPOWER,
|
||||
rnode::CMD_ST_ALOCK,
|
||||
rnode::CMD_LT_ALOCK,
|
||||
rnode::CMD_PLATFORM,
|
||||
rnode::CMD_MCU,
|
||||
CMD_INTERFACES,
|
||||
rnode::CMD_RESET,
|
||||
];
|
||||
fn startup_discovery_validates_firmware_interface_types_and_ranges() {
|
||||
let mut config = RNodeMultiConfig::new("multi0", "/dev/null");
|
||||
config
|
||||
.subinterfaces
|
||||
.push(SubInterfaceConfig::new("low", 0, 868_000_000));
|
||||
config
|
||||
.subinterfaces
|
||||
.push(SubInterfaceConfig::new("high", 3, 2_400_000_000));
|
||||
|
||||
for &data_cmd in &CMD_INT_DATA {
|
||||
for &ctrl_cmd in &control_cmds {
|
||||
// CMD_INT0_DATA == CMD_DATA (0x00) and CMD_INT5_DATA ==
|
||||
// CMD_ERROR (0x90) are known, intentional overlaps; the read
|
||||
// loop disambiguates by checking data commands first.
|
||||
if data_cmd == 0x00 || data_cmd == 0x90 {
|
||||
continue;
|
||||
}
|
||||
assert_ne!(
|
||||
data_cmd, ctrl_cmd,
|
||||
"CMD_INT_DATA 0x{:02X} collides with control cmd 0x{:02X}",
|
||||
data_cmd, ctrl_cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut state = StartupEvidence::default();
|
||||
state
|
||||
.apply_frame(rnode::CMD_DETECT, &[rnode::DETECT_RESP])
|
||||
.unwrap();
|
||||
// Lexicographic comparison accepts newer major versions.
|
||||
state.apply_frame(rnode::CMD_FW_VERSION, &[2, 0]).unwrap();
|
||||
state
|
||||
.apply_frame(
|
||||
CMD_INTERFACES,
|
||||
&[0, RadioType::SX1276 as u8, 3, RadioType::SX1280 as u8],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(state.discovery_complete(&config));
|
||||
assert!(state.validate_discovery(&config).is_ok());
|
||||
|
||||
config.subinterfaces[1].frequency = 915_000_000;
|
||||
assert!(state.validate_discovery(&config).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_discovery_rejects_malformed_or_unknown_interfaces() {
|
||||
let mut state = StartupEvidence::default();
|
||||
assert!(state.apply_frame(CMD_INTERFACES, &[0]).is_err());
|
||||
assert!(state.apply_frame(CMD_INTERFACES, &[0, 0xFF]).is_err());
|
||||
assert!(
|
||||
state
|
||||
.apply_frame(CMD_INTERFACES, &[MAX_SUBINTERFACES as u8, 0x00])
|
||||
.is_err()
|
||||
);
|
||||
assert!(state.apply_frame(CMD_ERROR, &[ERROR_INITRADIO]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_requires_matching_echoes_before_radio_is_ready() {
|
||||
let config = SubInterfaceConfig::new("radio0", 0, 868_000_000);
|
||||
let mut state = StartupEvidence::default();
|
||||
state.apply_frame(CMD_SEL_INT, &[0]).unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_FREQUENCY, &config.frequency.to_be_bytes())
|
||||
.unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_BANDWIDTH, &config.bandwidth.to_be_bytes())
|
||||
.unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_SF, &[config.spreading_factor])
|
||||
.unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_CR, &[config.coding_rate])
|
||||
.unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_TXPOWER, &[config.tx_power])
|
||||
.unwrap();
|
||||
assert!(!state.radio_complete(0));
|
||||
state
|
||||
.apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON])
|
||||
.unwrap();
|
||||
|
||||
assert!(state.radio_complete(0));
|
||||
assert!(state.radios[0].validate(&config).is_ok());
|
||||
|
||||
let mut mismatch = state.radios[0];
|
||||
mismatch.coding_rate = Some(config.coding_rate + 1);
|
||||
assert!(mismatch.validate(&config).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicate_vports_are_rejected_before_opening_serial() {
|
||||
let mut config = RNodeMultiConfig::new("multi0", "/does/not/exist");
|
||||
config
|
||||
.subinterfaces
|
||||
.push(SubInterfaceConfig::new("first", 0, 868_000_000));
|
||||
config
|
||||
.subinterfaces
|
||||
.push(SubInterfaceConfig::new("second", 0, 915_000_000));
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(1);
|
||||
let result = spawn_rnode_multi_interface(config, &[1, 2], transport_tx).await;
|
||||
let error = match result {
|
||||
Ok(_) => panic!("duplicate vports must fail before serial open"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(error.to_string().contains("configured more than once"));
|
||||
}
|
||||
}
|
||||
@@ -336,7 +336,6 @@ mod tests {
|
||||
#[test]
|
||||
fn test_weave_constants() {
|
||||
assert_eq!(HW_MTU, 1024);
|
||||
const { assert!(FIXED_MTU) };
|
||||
assert_eq!(PEERING_TIMEOUT, 20.0);
|
||||
assert_eq!(BITRATE_GUESS, 250_000);
|
||||
assert_eq!(DEFAULT_IFAC_SIZE, 16);
|
||||
|
||||
@@ -1090,7 +1090,13 @@ impl Link {
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
|
||||
{
|
||||
if self.state != LinkState::Active && self.state != LinkState::Stale {
|
||||
// A responder can receive ordinary Link data immediately after its
|
||||
// proof, before the initiator's LRRTT activates the responder side.
|
||||
// Python proves that data in HANDSHAKE, and the session keys/signing
|
||||
// identity are already established at this point.
|
||||
let can_prove = matches!(self.state, LinkState::Active | LinkState::Stale)
|
||||
|| (!self.is_initiator && self.state == LinkState::Handshake);
|
||||
if !can_prove {
|
||||
return Err(LinkCryptoError::EncryptionFailed);
|
||||
}
|
||||
|
||||
@@ -1698,6 +1704,25 @@ mod tests {
|
||||
assert_eq!(pt2, msg2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responder_can_prove_packet_before_lrrtt_activation() {
|
||||
let dest_hash = [0xAB; 16];
|
||||
let identity_key = Ed25519PrivateKey::generate();
|
||||
let identity_pub = identity_key.public_key();
|
||||
let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1);
|
||||
let (responder, proof_data) =
|
||||
Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap();
|
||||
let _rtt_data = initiator
|
||||
.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes())
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(responder.state, LinkState::Handshake);
|
||||
assert_eq!(initiator.state, LinkState::Active);
|
||||
let packet_hash = [0xCD; 32];
|
||||
let packet_proof = responder.prove_packet(&packet_hash, &identity_key).unwrap();
|
||||
assert!(initiator.validate_packet_proof(&packet_hash, &packet_proof));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_teardown() {
|
||||
let dest_hash = [0xAA; 16];
|
||||
|
||||
@@ -612,8 +612,8 @@ impl InboundResource {
|
||||
tracing::trace!(
|
||||
result = %format!("{:02x}{:02x}{:02x}{:02x}", mh[0], mh[1], mh[2], mh[3]),
|
||||
data_len = data.len(),
|
||||
data_first16 = %data.iter().take(16).map(|b| format!("{:02x}", b)).collect::<String>(),
|
||||
random_hash = %self.random_hash.iter().map(|b| format!("{:02x}", b)).collect::<String>(),
|
||||
data_first16 = %hex::encode(&data[..data.len().min(16)]),
|
||||
random_hash = %hex::encode(self.random_hash),
|
||||
random_len = self.random_hash.len(),
|
||||
"resource part map hash"
|
||||
);
|
||||
@@ -811,6 +811,28 @@ pub struct MultiSegmentOutbound {
|
||||
pub data_size: usize,
|
||||
}
|
||||
|
||||
/// Sender-side plan that materialises at most one split Resource segment at a
|
||||
/// time.
|
||||
///
|
||||
/// The signed/application payload remains owned by the plan, but plaintext,
|
||||
/// encrypted parts and hash maps for future segments are not allocated until
|
||||
/// [`Self::next_segment`] is called. This is the bounded primitive used by
|
||||
/// large LXMF Direct deliveries; the eager [`MultiSegmentOutbound`] facade is
|
||||
/// retained for callers that need random access to every segment.
|
||||
pub struct LazyMultiSegmentOutbound {
|
||||
data: Vec<u8>,
|
||||
auto_compress: bool,
|
||||
metadata: Option<Vec<u8>>,
|
||||
metadata_wire_size: usize,
|
||||
request_id: Option<Vec<u8>>,
|
||||
is_response: bool,
|
||||
next_offset: usize,
|
||||
next_segment_index: usize,
|
||||
pub original_hash: [u8; 32],
|
||||
pub total_segments: usize,
|
||||
pub data_size: usize,
|
||||
}
|
||||
|
||||
fn required_segment_count(data_size: usize, metadata_wire_size: usize) -> usize {
|
||||
if data_size == 0 {
|
||||
return 1;
|
||||
@@ -851,69 +873,19 @@ impl MultiSegmentOutbound {
|
||||
is_response: bool,
|
||||
encrypt_fn: Option<&ResourceEncryptor<'_>>,
|
||||
) -> Result<Self, ResourceError> {
|
||||
if data.len() > MAX_RESOURCE_SIZE {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
|
||||
let data_size = data.len();
|
||||
|
||||
// `original_hash` covers the uncompressed concatenated payload so
|
||||
// the receiver can verify reassembly across all segments.
|
||||
let random_hash: [u8; RANDOM_HASH_SIZE] =
|
||||
rns_crypto::random::random_bytes(RANDOM_HASH_SIZE)
|
||||
.try_into()
|
||||
.unwrap();
|
||||
let original_hash = compute_resource_hash(&data, &random_hash);
|
||||
|
||||
let metadata_wire_size = metadata.as_ref().map(|m| 3 + m.len()).unwrap_or(0);
|
||||
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::with_capacity(planned_segments);
|
||||
|
||||
if data.is_empty() {
|
||||
chunk_specs.push((Vec::new(), metadata.clone()));
|
||||
} else {
|
||||
let first_len = data.len().min(first_payload_max);
|
||||
chunk_specs.push((data[..first_len].to_vec(), metadata.clone()));
|
||||
let mut offset = first_len;
|
||||
|
||||
while offset < data.len() {
|
||||
let end = (offset + MAX_EFFICIENT_SIZE).min(data.len());
|
||||
chunk_specs.push((data[offset..end].to_vec(), None));
|
||||
offset = end;
|
||||
}
|
||||
}
|
||||
|
||||
let total_segments = chunk_specs.len();
|
||||
debug_assert_eq!(total_segments, planned_segments);
|
||||
let mut lazy = LazyMultiSegmentOutbound::with_options(
|
||||
data,
|
||||
auto_compress,
|
||||
metadata,
|
||||
request_id,
|
||||
is_response,
|
||||
)?;
|
||||
let original_hash = lazy.original_hash;
|
||||
let total_segments = lazy.total_segments;
|
||||
let data_size = lazy.data_size;
|
||||
let mut segments = Vec::with_capacity(total_segments);
|
||||
|
||||
for (i, (chunk, segment_metadata)) in chunk_specs.into_iter().enumerate() {
|
||||
let mut resource = OutboundResource::with_options(
|
||||
chunk,
|
||||
auto_compress,
|
||||
segment_metadata,
|
||||
None,
|
||||
encrypt_fn,
|
||||
)?;
|
||||
resource.flags.split = true;
|
||||
resource.flags.is_response = is_response;
|
||||
resource.segment_index = i + 1;
|
||||
resource.total_segments = total_segments;
|
||||
resource.request_id = request_id.clone();
|
||||
resource.advertisement_data_size = data_size + metadata_wire_size;
|
||||
// Stamps the shared `original_hash` onto each segment so the wire
|
||||
// ADV (built later via `create_advertisement`) carries the
|
||||
// coordinator key the receiver needs to reassemble.
|
||||
resource.original_hash = Some(original_hash);
|
||||
segments.push(resource);
|
||||
while let Some(segment) = lazy.next_segment(encrypt_fn)? {
|
||||
segments.push(segment);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
@@ -962,6 +934,120 @@ impl MultiSegmentOutbound {
|
||||
}
|
||||
}
|
||||
|
||||
impl LazyMultiSegmentOutbound {
|
||||
/// Create a sequential split-Resource plan without metadata or request
|
||||
/// flags.
|
||||
pub fn new(data: Vec<u8>, auto_compress: bool) -> Result<Self, ResourceError> {
|
||||
Self::with_options(data, auto_compress, None, None, false)
|
||||
}
|
||||
|
||||
/// Create a sequential split-Resource plan while preserving metadata and
|
||||
/// request flags. Metadata is moved into the first segment when it is
|
||||
/// materialised.
|
||||
pub fn with_options(
|
||||
data: Vec<u8>,
|
||||
auto_compress: bool,
|
||||
metadata: Option<Vec<u8>>,
|
||||
request_id: Option<Vec<u8>>,
|
||||
is_response: bool,
|
||||
) -> Result<Self, ResourceError> {
|
||||
if data.len() > MAX_RESOURCE_SIZE {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
|
||||
let data_size = data.len();
|
||||
let metadata_wire_size = metadata.as_ref().map(|value| 3 + value.len()).unwrap_or(0);
|
||||
if metadata_wire_size > MAX_EFFICIENT_SIZE {
|
||||
return Err(ResourceError::MetadataTooLarge);
|
||||
}
|
||||
let total_segments = required_segment_count(data_size, metadata_wire_size);
|
||||
if total_segments > MAX_SEGMENTS {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
|
||||
// `original_hash` covers the uncompressed concatenated payload so the
|
||||
// receiver can verify reassembly across all segments.
|
||||
let random_hash: [u8; RANDOM_HASH_SIZE] =
|
||||
rns_crypto::random::random_bytes(RANDOM_HASH_SIZE)
|
||||
.try_into()
|
||||
.expect("fixed random-hash length");
|
||||
let original_hash = compute_resource_hash(&data, &random_hash);
|
||||
|
||||
Ok(Self {
|
||||
data,
|
||||
auto_compress,
|
||||
metadata,
|
||||
metadata_wire_size,
|
||||
request_id,
|
||||
is_response,
|
||||
next_offset: 0,
|
||||
next_segment_index: 1,
|
||||
original_hash,
|
||||
total_segments,
|
||||
data_size,
|
||||
})
|
||||
}
|
||||
|
||||
/// Number of segments that have not yet been materialised.
|
||||
pub fn remaining_segments(&self) -> usize {
|
||||
self.total_segments
|
||||
.saturating_sub(self.next_segment_index.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// Build the next standalone outbound Resource. The caller owns the
|
||||
/// returned segment and should request another only after the current one
|
||||
/// has completed or been terminally discarded.
|
||||
pub fn next_segment(
|
||||
&mut self,
|
||||
encrypt_fn: Option<&ResourceEncryptor<'_>>,
|
||||
) -> Result<Option<OutboundResource>, ResourceError> {
|
||||
if self.next_segment_index > self.total_segments {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let segment_index = self.next_segment_index;
|
||||
let segment_metadata = if segment_index == 1 {
|
||||
self.metadata.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let payload_limit = if segment_index == 1 {
|
||||
MAX_EFFICIENT_SIZE - self.metadata_wire_size
|
||||
} else {
|
||||
MAX_EFFICIENT_SIZE
|
||||
};
|
||||
let end = self
|
||||
.next_offset
|
||||
.saturating_add(payload_limit)
|
||||
.min(self.data.len());
|
||||
let chunk = self.data[self.next_offset..end].to_vec();
|
||||
|
||||
let mut resource = OutboundResource::with_options(
|
||||
chunk,
|
||||
self.auto_compress,
|
||||
segment_metadata,
|
||||
None,
|
||||
encrypt_fn,
|
||||
)?;
|
||||
resource.flags.split = true;
|
||||
resource.flags.is_response = self.is_response;
|
||||
resource.segment_index = segment_index;
|
||||
resource.total_segments = self.total_segments;
|
||||
resource.request_id = self.request_id.clone();
|
||||
resource.advertisement_data_size = self.data_size + self.metadata_wire_size;
|
||||
resource.original_hash = Some(self.original_hash);
|
||||
|
||||
self.next_offset = end;
|
||||
self.next_segment_index += 1;
|
||||
if self.next_segment_index > self.total_segments {
|
||||
// The current segment now owns its bytes. Release the complete
|
||||
// source allocation before it begins transferring.
|
||||
self.data = Vec::new();
|
||||
}
|
||||
Ok(Some(resource))
|
||||
}
|
||||
}
|
||||
|
||||
/// Inbound multi-segment resource coordinator: collects `InboundResource`
|
||||
/// segments and reassembles the original payload. Two ingest paths feed
|
||||
/// `assembled_segments`: `set_segment` + `assemble_segment` (unit tests) and
|
||||
@@ -3382,6 +3468,74 @@ mod tests {
|
||||
assert_eq!(multi.segments[1].data.len(), 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lazy_multi_segment_materialises_only_on_demand() {
|
||||
let data = vec![0xA6; MAX_EFFICIENT_SIZE * 2 + 321];
|
||||
let mut lazy = LazyMultiSegmentOutbound::new(data.clone(), false).unwrap();
|
||||
|
||||
assert_eq!(lazy.total_segments, 3);
|
||||
assert_eq!(lazy.remaining_segments(), 3);
|
||||
|
||||
let first = lazy.next_segment(None).unwrap().unwrap();
|
||||
assert_eq!(first.segment_index, 1);
|
||||
assert_eq!(first.total_segments, 3);
|
||||
assert_eq!(first.data.len(), MAX_EFFICIENT_SIZE);
|
||||
assert_eq!(lazy.remaining_segments(), 2);
|
||||
|
||||
let second = lazy.next_segment(None).unwrap().unwrap();
|
||||
assert_eq!(second.segment_index, 2);
|
||||
assert_eq!(second.data.len(), MAX_EFFICIENT_SIZE);
|
||||
assert_eq!(lazy.remaining_segments(), 1);
|
||||
|
||||
let third = lazy.next_segment(None).unwrap().unwrap();
|
||||
assert_eq!(third.segment_index, 3);
|
||||
assert_eq!(third.data.len(), 321);
|
||||
assert_eq!(lazy.remaining_segments(), 0);
|
||||
assert!(lazy.next_segment(None).unwrap().is_none());
|
||||
|
||||
let rebuilt: Vec<u8> = [first, second, third]
|
||||
.into_iter()
|
||||
.flat_map(|segment| segment.data)
|
||||
.collect();
|
||||
assert_eq!(rebuilt, data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lazy_multi_segment_preserves_metadata_and_request_flags() {
|
||||
let metadata = b"\x81\xa4name\xa8file.bin".to_vec();
|
||||
let request_id = vec![0x42; 16];
|
||||
let data = vec![0x5C; MAX_EFFICIENT_SIZE + 10];
|
||||
let mut lazy = LazyMultiSegmentOutbound::with_options(
|
||||
data,
|
||||
false,
|
||||
Some(metadata.clone()),
|
||||
Some(request_id.clone()),
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let first = lazy.next_segment(None).unwrap().unwrap();
|
||||
let second = lazy.next_segment(None).unwrap().unwrap();
|
||||
assert!(first.flags.has_metadata);
|
||||
assert!(
|
||||
first
|
||||
.metadata
|
||||
.as_deref()
|
||||
.is_some_and(|wire| wire.ends_with(&metadata))
|
||||
);
|
||||
assert_eq!(first.metadata_size, metadata.len() + 3);
|
||||
assert!(!second.flags.has_metadata);
|
||||
assert_eq!(first.request_id, Some(request_id.clone()));
|
||||
assert_eq!(second.request_id, Some(request_id));
|
||||
assert!(first.flags.is_response);
|
||||
assert!(second.flags.is_response);
|
||||
assert_eq!(first.original_hash, second.original_hash);
|
||||
assert_eq!(
|
||||
first.advertisement_data_size,
|
||||
second.advertisement_data_size
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multi_segment_outbound_too_large() {
|
||||
let data = vec![0; MAX_RESOURCE_SIZE + 1];
|
||||
|
||||
@@ -7,13 +7,17 @@
|
||||
//! closed.
|
||||
|
||||
use rns_identity::destination::{
|
||||
AllowPolicy, DestType, Destination, DestinationError, Direction, ProofStrategy,
|
||||
AllowPolicy, DefaultAppData, DestType, Destination, DestinationError, Direction, ProofStrategy,
|
||||
};
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_link::link::{CloseReason, ResourceStrategy};
|
||||
use rns_protocol::channel::ChannelError;
|
||||
use rns_protocol::channel_message::{ChannelMessageError, MessageBase};
|
||||
use rns_protocol::resource_adv::ResourceAdvertisement;
|
||||
use rns_transport::messages::TransportMessage;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::link_manager::{
|
||||
@@ -26,12 +30,24 @@ use crate::link_manager::{
|
||||
const DEFAULT_EVENT_CAPACITY: usize = 128;
|
||||
const COMMAND_CAPACITY: usize = 256;
|
||||
|
||||
type ResourceAcceptCallback = dyn Fn([u8; 16], &ResourceAdvertisement) -> bool + Send + Sync;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DestinationRuntimeOptions {
|
||||
pub proof_strategy: ProofStrategy,
|
||||
pub accepts_links: bool,
|
||||
pub resource_strategy: ResourceStrategy,
|
||||
pub event_capacity: usize,
|
||||
/// Announce app data used whenever an announce (including a path
|
||||
/// response) carries none explicitly.
|
||||
pub default_app_data: Option<Vec<u8>>,
|
||||
/// Per-advertisement acceptance policy consulted when
|
||||
/// `resource_strategy` is `AcceptApp`.
|
||||
pub resource_accept: Option<ResourceAcceptPolicy>,
|
||||
/// Synchronous LinkIdentify gate; returning false closes the link.
|
||||
pub identity_gate: Option<IdentityGatePolicy>,
|
||||
/// User Channel message types registered before the manager starts.
|
||||
pub channel_message_types: Vec<u16>,
|
||||
}
|
||||
|
||||
impl Default for DestinationRuntimeOptions {
|
||||
@@ -41,10 +57,49 @@ impl Default for DestinationRuntimeOptions {
|
||||
accepts_links: true,
|
||||
resource_strategy: ResourceStrategy::AcceptNone,
|
||||
event_capacity: DEFAULT_EVENT_CAPACITY,
|
||||
default_app_data: None,
|
||||
resource_accept: None,
|
||||
identity_gate: None,
|
||||
channel_message_types: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clonable per-advertisement inbound Resource acceptance policy.
|
||||
#[derive(Clone)]
|
||||
pub struct ResourceAcceptPolicy(Arc<ResourceAcceptCallback>);
|
||||
|
||||
impl ResourceAcceptPolicy {
|
||||
pub fn new(
|
||||
policy: impl Fn([u8; 16], &ResourceAdvertisement) -> bool + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
Self(Arc::new(policy))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ResourceAcceptPolicy {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("ResourceAcceptPolicy")
|
||||
}
|
||||
}
|
||||
|
||||
/// Clonable synchronous LinkIdentify gate, consulted before any later
|
||||
/// resource advertisement can race the admission decision.
|
||||
#[derive(Clone)]
|
||||
pub struct IdentityGatePolicy(Arc<dyn Fn([u8; 16], [u8; 16]) -> bool + Send + Sync>);
|
||||
|
||||
impl IdentityGatePolicy {
|
||||
pub fn new(gate: impl Fn([u8; 16], [u8; 16]) -> bool + Send + Sync + 'static) -> Self {
|
||||
Self(Arc::new(gate))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for IdentityGatePolicy {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("IdentityGatePolicy")
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistent forward-secrecy settings for a live inbound destination.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DestinationRatchetOptions {
|
||||
@@ -70,12 +125,14 @@ pub struct DestinationPacket {
|
||||
pub raw: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Bounded event receivers owned by one registered destination.
|
||||
/// Event receivers owned by one registered destination. All are bounded by
|
||||
/// `event_capacity` except `link_packets`: inbound link data is proved to the
|
||||
/// peer on receipt, so its local delivery is lossless and must be drained.
|
||||
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_packets: mpsc::UnboundedReceiver<(Vec<u8>, [u8; 16])>,
|
||||
pub link_packet_proofs: mpsc::Receiver<LinkPacketProof>,
|
||||
pub resource_completions: mpsc::Receiver<ResourceCompletion>,
|
||||
pub resource_proofs: mpsc::Receiver<LinkResourceProof>,
|
||||
@@ -94,6 +151,8 @@ pub enum DestinationRuntimeError {
|
||||
LinkSend(#[from] LinkSendError),
|
||||
#[error(transparent)]
|
||||
ChannelSend(#[from] ChannelSendError),
|
||||
#[error(transparent)]
|
||||
Channel(#[from] ChannelError),
|
||||
#[error("destination event capacity must be greater than zero")]
|
||||
InvalidEventCapacity,
|
||||
#[error("destination manager is no longer available")]
|
||||
@@ -149,6 +208,26 @@ impl DestinationHandle {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set or clear the default app data used whenever an announce (including
|
||||
/// a path response) carries none explicitly.
|
||||
pub async fn set_default_app_data(
|
||||
&self,
|
||||
app_data: Option<Vec<u8>>,
|
||||
) -> Result<(), DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SetDefaultAppData {
|
||||
app_data,
|
||||
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>,
|
||||
@@ -366,11 +445,23 @@ impl RegisteredDestination {
|
||||
}
|
||||
manager.set_resource_strategy(options.resource_strategy);
|
||||
manager.set_use_implicit_proof(true);
|
||||
if let Some(policy) = options.resource_accept.clone() {
|
||||
manager.set_resource_accept_handler(move |link_id, adv| (policy.0)(link_id, adv));
|
||||
}
|
||||
if let Some(gate) = options.identity_gate.clone() {
|
||||
manager.set_link_identity_gate(move |link_id, identity| (gate.0)(link_id, identity));
|
||||
}
|
||||
for msg_type in &options.channel_message_types {
|
||||
manager.register_channel_message_type(*msg_type)?;
|
||||
}
|
||||
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);
|
||||
if let Some(app_data) = options.default_app_data.clone() {
|
||||
owned_destination.set_default_app_data(DefaultAppData::Static(app_data));
|
||||
}
|
||||
|
||||
transport_tx
|
||||
.send(TransportMessage::RegisterDestination {
|
||||
@@ -392,7 +483,7 @@ impl RegisteredDestination {
|
||||
|
||||
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_packets_tx, link_packets) = mpsc::unbounded_channel();
|
||||
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);
|
||||
@@ -495,7 +586,50 @@ impl MessageBase for RawChannelMessage {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::link_session::{LinkSession, LinkSessionConfig, LinkSessionEvent};
|
||||
use rns_protocol::channel_message::SYSTEM_MESSAGE_TYPE_MIN;
|
||||
use rns_transport::actor::TransportActor;
|
||||
use rns_transport::messages::TransportMessage;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn register_applies_policy_options_and_rejects_reserved_channel_types() {
|
||||
let identity = Identity::new();
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(16);
|
||||
|
||||
let reserved = RegisteredDestination::register(
|
||||
transport_tx.clone(),
|
||||
identity.clone(),
|
||||
"example.runtime.policies",
|
||||
DestinationRuntimeOptions {
|
||||
channel_message_types: vec![SYSTEM_MESSAGE_TYPE_MIN],
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(reserved, Err(DestinationRuntimeError::Channel(_))));
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"a reserved channel type must fail before transport registration"
|
||||
);
|
||||
|
||||
let registration = RegisteredDestination::register(
|
||||
transport_tx,
|
||||
identity,
|
||||
"example.runtime.policies",
|
||||
DestinationRuntimeOptions {
|
||||
resource_strategy: ResourceStrategy::AcceptApp,
|
||||
resource_accept: Some(ResourceAcceptPolicy::new(|_, _| false)),
|
||||
identity_gate: Some(IdentityGatePolicy::new(|_, _| true)),
|
||||
channel_message_types: vec![0x0100],
|
||||
default_app_data: Some(b"policy app data".to_vec()),
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("valid policy options must register");
|
||||
registration.close().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn registration_announces_and_deregisters_exact_destination() {
|
||||
@@ -535,6 +669,101 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn link_session_connects_to_destination_on_same_transport_actor() {
|
||||
let (actor, transport_tx) = TransportActor::new();
|
||||
let actor_task = tokio::spawn(actor.run());
|
||||
let server_identity = Identity::new();
|
||||
let server_public_key = server_identity.get_public_key();
|
||||
let mut registration = RegisteredDestination::register(
|
||||
transport_tx.clone(),
|
||||
server_identity,
|
||||
"example.runtime.loopback",
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let destination_hash = registration.handle.destination_hash();
|
||||
let client_identity = Identity::new();
|
||||
let expected_client = client_identity.hash;
|
||||
|
||||
let mut session = tokio::time::timeout(
|
||||
Duration::from_secs(3),
|
||||
LinkSession::connect(
|
||||
transport_tx.clone(),
|
||||
client_identity,
|
||||
LinkSessionConfig {
|
||||
destination_hash,
|
||||
remote_public_key: server_public_key,
|
||||
hops: 1,
|
||||
establishment_timeout: Duration::from_secs(2),
|
||||
client_label: "test.same-actor-link".into(),
|
||||
identify: true,
|
||||
track_phy_stats: false,
|
||||
},
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("same-actor Link establishment timed out")
|
||||
.expect("same-actor Link establishment failed");
|
||||
let link_id = session.handle.link_id();
|
||||
|
||||
assert_eq!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
registration.events.links_established.recv()
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
Some(link_id)
|
||||
);
|
||||
assert_eq!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
registration.events.links_identified.recv()
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
Some((link_id, expected_client))
|
||||
);
|
||||
|
||||
session
|
||||
.handle
|
||||
.send_packet(b"client to server".to_vec())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
registration.events.link_packets.recv()
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
Some((b"client to server".to_vec(), link_id))
|
||||
);
|
||||
|
||||
registration
|
||||
.handle
|
||||
.send_link_packet(link_id, b"server to client".to_vec())
|
||||
.await
|
||||
.unwrap();
|
||||
let received = tokio::time::timeout(Duration::from_secs(1), async {
|
||||
loop {
|
||||
if let Some(LinkSessionEvent::Packet { data, .. }) = session.events.recv().await {
|
||||
break data;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(received, b"server to client");
|
||||
|
||||
session.handle.close().await;
|
||||
registration.close().await.unwrap();
|
||||
transport_tx.send(TransportMessage::Shutdown).await.unwrap();
|
||||
actor_task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ratcheted_registration_advertises_and_decrypts_owned_ring() {
|
||||
let identity = Identity::new();
|
||||
|
||||
@@ -32,7 +32,7 @@ pub enum InterfaceConfig {
|
||||
#[cfg(feature = "serial")]
|
||||
KissSerial(KissSerialConfig),
|
||||
Auto(AutoInterfaceConfig),
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
RNode(RNodeInterfaceConfig),
|
||||
Local(LocalInterfaceConfig),
|
||||
I2P(I2PInterfaceConfig),
|
||||
@@ -94,11 +94,17 @@ pub struct AutoInterfaceConfig {
|
||||
pub mode: InterfaceMode,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RNodeInterfaceConfig {
|
||||
pub name: String,
|
||||
pub port: String,
|
||||
/// Android USB stable identity. These are ignored for non-AndroidUSB
|
||||
/// ports, and serial remains optional because Android hides it pre-grant.
|
||||
pub usb_vendor_id: Option<u16>,
|
||||
pub usb_product_id: Option<u16>,
|
||||
pub usb_serial_number: Option<String>,
|
||||
pub baud_rate: u32,
|
||||
pub frequency: u32,
|
||||
pub bandwidth: u32,
|
||||
pub spreading_factor: u8,
|
||||
@@ -116,7 +122,7 @@ pub struct RNodeInterfaceConfig {
|
||||
pub id_callsign: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
impl RNodeInterfaceConfig {
|
||||
/// Convert runtime configuration into the lower driver type while
|
||||
/// preserving signed-value and RF-range validation.
|
||||
@@ -129,6 +135,7 @@ impl RNodeInterfaceConfig {
|
||||
message: format!("{} is outside 0..=37 dBm", self.tx_power),
|
||||
})?;
|
||||
let mut config = rns_interface::rnode::RNodeConfig::new(&self.name, &self.port);
|
||||
config.baud_rate = self.baud_rate;
|
||||
config.frequency = self.frequency;
|
||||
config.bandwidth = self.bandwidth;
|
||||
config.spreading_factor = self.spreading_factor;
|
||||
@@ -476,12 +483,20 @@ pub fn synthesize_interface(
|
||||
)));
|
||||
}
|
||||
}
|
||||
// Android USB-OTG ports vanish on replug; add them at runtime after
|
||||
// the device is present.
|
||||
if port.starts_with("androidusb://") {
|
||||
return Err(InterfaceFactoryError::Disabled(format!(
|
||||
"RNodeInterface '{name}' is an Android USB-OTG entry — skipped at startup; re-add from the UI after plugging the device in"
|
||||
)));
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
// Keep Android USB entries in the same persisted
|
||||
// RNodeInterface schema as serial, TCP and BLE. The
|
||||
// runtime selects the JNI transport from the URI.
|
||||
return synthesize_rnode(name, section, mode);
|
||||
}
|
||||
#[cfg(not(target_os = "android"))]
|
||||
{
|
||||
return Err(InterfaceFactoryError::Disabled(format!(
|
||||
"RNodeInterface '{name}' uses an Android USB-OTG port on a non-Android build"
|
||||
)));
|
||||
}
|
||||
}
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
{
|
||||
@@ -769,7 +784,7 @@ fn synthesize_auto(
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
fn synthesize_rnode(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -783,14 +798,31 @@ fn synthesize_rnode(
|
||||
})?
|
||||
.to_string();
|
||||
|
||||
let baud_rate = section
|
||||
.get_uint("speed")
|
||||
.or_else(|| section.get_uint("baud_rate"))
|
||||
.unwrap_or(115200) as u32;
|
||||
|
||||
let (frequency, bandwidth, spreading_factor, coding_rate, tx_power) =
|
||||
require_generic_rnode_radio_params(name, section)?;
|
||||
|
||||
let (flow_control, st_alock, lt_alock) = parse_generic_rnode_airtime(name, section)?;
|
||||
let usb_vendor_id = parse_optional_u16(name, section, "usb_vendor_id")?;
|
||||
let usb_product_id = parse_optional_u16(name, section, "usb_product_id")?;
|
||||
if usb_vendor_id.is_some() != usb_product_id.is_some() {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.usb_vendor_id/usb_product_id"),
|
||||
message: "vendor and product IDs must be configured together".into(),
|
||||
});
|
||||
}
|
||||
|
||||
let config = RNodeInterfaceConfig {
|
||||
name: name.to_string(),
|
||||
port,
|
||||
usb_vendor_id,
|
||||
usb_product_id,
|
||||
usb_serial_number: section.get("usb_serial_number").map(str::to_string),
|
||||
baud_rate,
|
||||
frequency,
|
||||
bandwidth,
|
||||
spreading_factor,
|
||||
@@ -810,7 +842,24 @@ fn synthesize_rnode(
|
||||
Ok(InterfaceConfig::RNode(config))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
fn parse_optional_u16(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
field: &str,
|
||||
) -> Result<Option<u16>, InterfaceFactoryError> {
|
||||
section
|
||||
.get_uint(field)
|
||||
.map(|value| {
|
||||
u16::try_from(value).map_err(|_| InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.{field}"),
|
||||
message: format!("{value} is outside 0..={}", u16::MAX),
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
fn require_generic_rnode_radio_params(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -872,7 +921,7 @@ fn require_generic_rnode_radio_params(
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
fn required_rnode_scalar<'a>(
|
||||
name: &str,
|
||||
section: &'a ConfigSection,
|
||||
@@ -889,7 +938,7 @@ fn required_rnode_scalar<'a>(
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
fn parse_required_rnode_unsigned<T>(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -912,7 +961,7 @@ where
|
||||
Ok((key, value))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
fn parse_required_rnode_signed<T>(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -935,7 +984,7 @@ where
|
||||
Ok((key, value))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
fn validate_parsed_rnode_integer<T>(
|
||||
name: &str,
|
||||
key: &str,
|
||||
@@ -956,7 +1005,7 @@ where
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
fn parse_generic_rnode_airtime(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -969,7 +1018,7 @@ fn parse_generic_rnode_airtime(
|
||||
Ok((flow_control, st_alock, lt_alock))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
fn parse_generic_rnode_airtime_value(
|
||||
name: &str,
|
||||
section: &ConfigSection,
|
||||
@@ -1215,13 +1264,13 @@ fn synthesize_rnode_multi(
|
||||
name: format!("{name}/{sub_name}"),
|
||||
field: "vport".to_string(),
|
||||
})? as u8;
|
||||
if vport as usize > rns_interface::rnode_multi::MAX_SUBINTERFACES {
|
||||
if vport as usize >= rns_interface::rnode_multi::MAX_SUBINTERFACES {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{sub_name}.vport"),
|
||||
message: format!(
|
||||
"virtual port {} exceeds max {}",
|
||||
"virtual port {} is outside 0..{}",
|
||||
vport,
|
||||
rns_interface::rnode_multi::MAX_SUBINTERFACES
|
||||
rns_interface::rnode_multi::MAX_SUBINTERFACES - 1
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -1605,7 +1654,7 @@ pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize {
|
||||
| InterfaceConfig::KissSerial(_)
|
||||
| InterfaceConfig::RNodeMulti(_)
|
||||
| InterfaceConfig::AX25KISS(_) => 8,
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
InterfaceConfig::RNode(_) => 8,
|
||||
InterfaceConfig::Local(_) | InterfaceConfig::Pipe(_) => 8,
|
||||
#[cfg(feature = "ble")]
|
||||
@@ -2229,6 +2278,7 @@ mod tests {
|
||||
InterfaceConfig::RNode(c) => {
|
||||
assert_eq!(c.name, "test_rnode");
|
||||
assert_eq!(c.port, "/dev/ttyACM0");
|
||||
assert_eq!(c.baud_rate, 115200);
|
||||
assert_eq!(c.frequency, 868000000);
|
||||
assert_eq!(c.bandwidth, 125000);
|
||||
assert_eq!(c.spreading_factor, 7);
|
||||
@@ -2456,6 +2506,7 @@ mod tests {
|
||||
section.set("type", "RNodeInterface");
|
||||
section.set("port", "tcp://rnode.local");
|
||||
section.set("frequency", "915000000");
|
||||
section.set("speed", "230400");
|
||||
set_rnode_radio_params(&mut section);
|
||||
|
||||
let config = synthesize_interface("rnode_tcp", §ion).unwrap();
|
||||
@@ -2463,12 +2514,28 @@ mod tests {
|
||||
InterfaceConfig::RNode(c) => {
|
||||
assert_eq!(c.name, "rnode_tcp");
|
||||
assert_eq!(c.port, "tcp://rnode.local");
|
||||
assert_eq!(c.baud_rate, 230400);
|
||||
assert_eq!(c.frequency, 915000000);
|
||||
}
|
||||
_ => panic!("expected RNode"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
not(target_os = "android"),
|
||||
any(feature = "serial", feature = "rnode-tcp")
|
||||
))]
|
||||
#[test]
|
||||
fn test_android_usb_rnode_is_not_synthesized_off_android() {
|
||||
let mut section = complete_rnode_section();
|
||||
section.set("port", "androidusb:///dev/bus/usb/001/002");
|
||||
assert!(matches!(
|
||||
synthesize_interface("android_usb", §ion),
|
||||
Err(InterfaceFactoryError::Disabled(message))
|
||||
if message.contains("non-Android build")
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_missing_port() {
|
||||
@@ -2484,6 +2551,69 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn android_usb_stable_selector_and_station_id_round_trip_through_factory() {
|
||||
let mut section = ConfigSection::new();
|
||||
for (key, value) in [
|
||||
("port", "androidusb:///dev/bus/usb/001/002"),
|
||||
("frequency", "915000000"),
|
||||
("bandwidth", "125000"),
|
||||
("spreadingfactor", "8"),
|
||||
("codingrate", "6"),
|
||||
("txpower", "17"),
|
||||
("usb_vendor_id", "12346"),
|
||||
("usb_product_id", "4097"),
|
||||
("usb_serial_number", "ABC123"),
|
||||
("id_interval", "900"),
|
||||
("id_callsign", "N0CALL"),
|
||||
] {
|
||||
section.set(key, value);
|
||||
}
|
||||
let config = synthesize_rnode("USB RNode", §ion, InterfaceMode::Roaming)
|
||||
.expect("stable Android USB config");
|
||||
let InterfaceConfig::RNode(config) = config else {
|
||||
panic!("expected RNode config")
|
||||
};
|
||||
assert_eq!(config.usb_vendor_id, Some(0x303a));
|
||||
assert_eq!(config.usb_product_id, Some(0x1001));
|
||||
assert_eq!(config.usb_serial_number.as_deref(), Some("ABC123"));
|
||||
assert_eq!(config.id_interval, Some(900));
|
||||
assert_eq!(config.id_callsign.as_deref(), Some("N0CALL"));
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn android_usb_stable_selector_rejects_partial_or_narrowed_ids() {
|
||||
let base = |vendor: &str, product: Option<&str>| {
|
||||
let mut section = ConfigSection::new();
|
||||
for (key, value) in [
|
||||
("port", "androidusb:///dev/bus/usb/001/002"),
|
||||
("frequency", "915000000"),
|
||||
("bandwidth", "125000"),
|
||||
("spreadingfactor", "8"),
|
||||
("codingrate", "6"),
|
||||
("txpower", "17"),
|
||||
("usb_vendor_id", vendor),
|
||||
] {
|
||||
section.set(key, value);
|
||||
}
|
||||
if let Some(product) = product {
|
||||
section.set("usb_product_id", product);
|
||||
}
|
||||
section
|
||||
};
|
||||
assert!(synthesize_rnode("partial", &base("12346", None), InterfaceMode::Full).is_err());
|
||||
assert!(
|
||||
synthesize_rnode(
|
||||
"narrowed",
|
||||
&base("65536", Some("4097")),
|
||||
InterfaceMode::Full,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_missing_frequency() {
|
||||
@@ -2576,6 +2706,10 @@ mod tests {
|
||||
let _rnode = InterfaceConfig::RNode(RNodeInterfaceConfig {
|
||||
name: "r".to_string(),
|
||||
port: "/dev/ttyACM0".to_string(),
|
||||
usb_vendor_id: None,
|
||||
usb_product_id: None,
|
||||
usb_serial_number: None,
|
||||
baud_rate: 115200,
|
||||
frequency: 868000000,
|
||||
bandwidth: 125000,
|
||||
spreading_factor: 7,
|
||||
@@ -3076,6 +3210,31 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_multi_rejects_first_out_of_range_vport() {
|
||||
let mut section = ConfigSection::new();
|
||||
section.set("type", "RNodeMultiInterface");
|
||||
section.set("port", "/dev/ttyACM0");
|
||||
|
||||
let mut sub = ConfigSection::new();
|
||||
sub.set(
|
||||
"vport",
|
||||
&rns_interface::rnode_multi::MAX_SUBINTERFACES.to_string(),
|
||||
);
|
||||
sub.set("frequency", "865600000");
|
||||
sub.set("bandwidth", "125000");
|
||||
sub.set("txpower", "14");
|
||||
sub.set("spreadingfactor", "7");
|
||||
sub.set("codingrate", "5");
|
||||
section.subsections.insert("Invalid".to_string(), sub);
|
||||
|
||||
assert!(matches!(
|
||||
synthesize_interface("test_rnodemulti", §ion),
|
||||
Err(InterfaceFactoryError::InvalidValue { field, .. }) if field == "Invalid.vport"
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
#[test]
|
||||
fn test_synthesize_rnode_multi_duplicate_vport() {
|
||||
|
||||
@@ -849,12 +849,10 @@ impl Drop for InterfaceRegistration {
|
||||
stop_owned_task(&mut task, &mut driver, Some(id)).await;
|
||||
registry.mark_abandoned_pending(id, owner);
|
||||
});
|
||||
} else {
|
||||
if let Some(driver) = driver.take() {
|
||||
driver.request_shutdown();
|
||||
} else if let Some(task) = task.take() {
|
||||
task.abort();
|
||||
}
|
||||
} else if let Some(driver) = driver.take() {
|
||||
driver.request_shutdown();
|
||||
} else if let Some(task) = task.take() {
|
||||
task.abort();
|
||||
}
|
||||
// The exact owner remains fail-closed until the detached cleanup has
|
||||
// joined the task. During a runtime drain the coordinator claims the
|
||||
|
||||
@@ -29,7 +29,8 @@ pub mod rpc_server;
|
||||
pub mod prelude {
|
||||
pub use crate::destination_runtime::{
|
||||
DestinationEvents, DestinationHandle, DestinationPacket, DestinationRatchetOptions,
|
||||
DestinationRuntimeError, DestinationRuntimeOptions, RegisteredDestination,
|
||||
DestinationRuntimeError, DestinationRuntimeOptions, IdentityGatePolicy,
|
||||
RegisteredDestination, ResourceAcceptPolicy,
|
||||
};
|
||||
pub use crate::lifecycle::ShutdownSignal;
|
||||
pub use crate::link_manager::{DestinationAnnounceOptions, DestinationRequest, RequestOutcome};
|
||||
@@ -54,10 +55,10 @@ pub mod prelude {
|
||||
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,
|
||||
RNodeCapabilityAdmissionError, RNodeCapabilityAdmissionFailureClass, RNodeCapabilityState,
|
||||
RNodeConfigurationState, RNodeDetectionState, RNodeFirmwareCompatibility,
|
||||
RNodeObservedRadioState, RNodeRuntimePhase, RNodeRuntimeReason, RNodeRuntimeSnapshot,
|
||||
RNodeSpawnError, RNodeStartupOptions, RNodeTransmitFlowState, RNodeTransportClass,
|
||||
};
|
||||
pub use rns_link::link::{CloseReason, ResourceStrategy};
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::time::timeout;
|
||||
|
||||
use rns_crypto::ed25519::Ed25519PublicKey;
|
||||
@@ -17,7 +17,9 @@ use rns_link::link::{CloseReason, Link};
|
||||
use rns_protocol::resource::{InboundTransfer, TransferAction};
|
||||
use rns_protocol::resource_adv::ResourceAdvertisement;
|
||||
use rns_transport::link_messages::DestinationEvent;
|
||||
use rns_transport::messages::{AnnounceHandlerEvent, OutboundRequest, TransportMessage};
|
||||
use rns_transport::messages::{
|
||||
AnnounceHandlerEvent, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse,
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LinkClientError {
|
||||
@@ -70,27 +72,36 @@ impl LinkClient {
|
||||
let dest_hash =
|
||||
Destination::hash_from_name_and_identity(app_name, Some(&remote_transport_hash));
|
||||
|
||||
// Register the handler before the path request so the answering
|
||||
// announce (carrying the pubkey) is observed.
|
||||
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
|
||||
self.send_msg(TransportMessage::RegisterAnnounceHandler {
|
||||
aspect_filter: Some(app_name.to_string()),
|
||||
receive_path_responses: true,
|
||||
callback_tx: ann_tx,
|
||||
})
|
||||
.await?;
|
||||
let pubkey =
|
||||
if let Some(public_key) = self.recall_routable_pubkey(dest_hash, deadline).await? {
|
||||
public_key
|
||||
} else {
|
||||
// Register the handler before the path request so the answering
|
||||
// announce (carrying the pubkey) is observed.
|
||||
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
|
||||
self.send_msg(TransportMessage::RegisterAnnounceHandler {
|
||||
aspect_filter: Some(app_name.to_string()),
|
||||
receive_path_responses: true,
|
||||
callback_tx: ann_tx,
|
||||
})
|
||||
.await?;
|
||||
|
||||
self.send_msg(TransportMessage::RequestPath {
|
||||
destination_hash: dest_hash,
|
||||
})
|
||||
.await?;
|
||||
self.send_msg(TransportMessage::RequestPath {
|
||||
destination_hash: dest_hash,
|
||||
})
|
||||
.await?;
|
||||
|
||||
let pubkey = wait_for_pubkey(&mut ann_rx, dest_hash, time_remaining(deadline)?).await?;
|
||||
let _ = self
|
||||
.transport_tx
|
||||
.try_send(TransportMessage::DeregisterAnnounceHandler {
|
||||
aspect_filter: Some(app_name.to_string()),
|
||||
});
|
||||
let public_key = match time_remaining(deadline) {
|
||||
Ok(remaining) => wait_for_pubkey(&mut ann_rx, dest_hash, remaining).await,
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
let _ = self
|
||||
.transport_tx
|
||||
.try_send(TransportMessage::DeregisterAnnounceHandler {
|
||||
aspect_filter: Some(app_name.to_string()),
|
||||
});
|
||||
public_key?
|
||||
};
|
||||
|
||||
let (mut link, request_data) = Link::new_initiator(dest_hash, hops);
|
||||
let link_id = link.link_id;
|
||||
@@ -197,6 +208,58 @@ impl LinkClient {
|
||||
.map_err(|_| LinkClientError::TransportUnavailable)
|
||||
}
|
||||
|
||||
async fn recall_routable_pubkey(
|
||||
&self,
|
||||
destination_hash: [u8; 16],
|
||||
deadline: Instant,
|
||||
) -> Result<Option<[u8; 64]>, LinkClientError> {
|
||||
let has_path = self
|
||||
.transport_query(
|
||||
TransportQuery::HasPath {
|
||||
dest: destination_hash,
|
||||
},
|
||||
deadline,
|
||||
)
|
||||
.await?;
|
||||
if !matches!(has_path, TransportQueryResponse::BoolResult(true)) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
match self
|
||||
.transport_query(
|
||||
TransportQuery::RecallDestination {
|
||||
dest: destination_hash,
|
||||
},
|
||||
deadline,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
TransportQueryResponse::RecalledDestination(Some(destination))
|
||||
if destination.dest_hash == destination_hash =>
|
||||
{
|
||||
Ok(Some(destination.public_key))
|
||||
}
|
||||
TransportQueryResponse::RecalledDestination(None) => Ok(None),
|
||||
response => Err(LinkClientError::UnexpectedResponse(format!(
|
||||
"destination recall returned {response:?}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn transport_query(
|
||||
&self,
|
||||
query: TransportQuery,
|
||||
deadline: Instant,
|
||||
) -> Result<TransportQueryResponse, LinkClientError> {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
self.send_msg(TransportMessage::Rpc { query, response_tx })
|
||||
.await?;
|
||||
timeout(time_remaining(deadline)?, response_rx)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::Timeout("transport query"))?
|
||||
.map_err(|_| LinkClientError::TransportUnavailable)
|
||||
}
|
||||
|
||||
async fn send_close(&self, link: &mut Link) -> Result<(), LinkClientError> {
|
||||
let link_id = link.link_id;
|
||||
let Some(teardown_data) = link.teardown(CloseReason::InitiatorClosed) else {
|
||||
@@ -673,6 +736,62 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validated_cached_identity_and_live_path_skip_network_discovery() {
|
||||
let destination_hash = [0xD4; 16];
|
||||
let remote_identity = Identity::new();
|
||||
let public_key = remote_identity.get_public_key();
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(4);
|
||||
let responder = tokio::spawn(async move {
|
||||
let Some(TransportMessage::Rpc { query, response_tx }) = transport_rx.recv().await
|
||||
else {
|
||||
panic!("expected path query");
|
||||
};
|
||||
assert!(matches!(
|
||||
query,
|
||||
TransportQuery::HasPath { dest } if dest == destination_hash
|
||||
));
|
||||
response_tx
|
||||
.send(TransportQueryResponse::BoolResult(true))
|
||||
.unwrap();
|
||||
|
||||
let Some(TransportMessage::Rpc { query, response_tx }) = transport_rx.recv().await
|
||||
else {
|
||||
panic!("expected destination recall");
|
||||
};
|
||||
assert!(matches!(
|
||||
query,
|
||||
TransportQuery::RecallDestination { dest } if dest == destination_hash
|
||||
));
|
||||
response_tx
|
||||
.send(TransportQueryResponse::RecalledDestination(Some(
|
||||
rns_transport::messages::RecalledDestinationRpcEntry {
|
||||
dest_hash: destination_hash,
|
||||
public_key,
|
||||
app_data: None,
|
||||
ratchet: None,
|
||||
hops: 1,
|
||||
timestamp: 1.0,
|
||||
},
|
||||
)))
|
||||
.unwrap();
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"cache hit must not emit a path request"
|
||||
);
|
||||
});
|
||||
|
||||
let client = LinkClient::new(transport_tx, Identity::new());
|
||||
assert_eq!(
|
||||
client
|
||||
.recall_routable_pubkey(destination_hash, Instant::now() + Duration::from_secs(1),)
|
||||
.await
|
||||
.unwrap(),
|
||||
Some(public_key)
|
||||
);
|
||||
responder.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn send_close_uses_authenticated_teardown_payload() {
|
||||
let dest_hash = [0xCC; 16];
|
||||
|
||||
+1131
-210
File diff suppressed because it is too large.
Load diff
@@ -381,6 +381,8 @@ pub struct ReticulumHandle {
|
||||
/// still install a stamper and start publishing.
|
||||
pub discovery: Arc<DiscoveryRuntime>,
|
||||
startup_rnode_runtimes: Vec<StartupRNodeRuntime>,
|
||||
#[cfg(feature = "ble")]
|
||||
deferred_android_ble_rnodes: Vec<interface_factory::BleRNodeInterfaceConfig>,
|
||||
shutdown_coordinator: RuntimeShutdownCoordinator,
|
||||
started_at: std::time::Instant,
|
||||
}
|
||||
@@ -696,6 +698,19 @@ impl RNodeReadinessError {
|
||||
| Self::ObservationClosed { last } => last.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The typed capability admission failure class, when the driver stopped
|
||||
/// because a capability admission was rejected.
|
||||
pub fn capability_admission_failure(
|
||||
&self,
|
||||
) -> Option<rns_interface::rnode::RNodeCapabilityAdmissionFailureClass> {
|
||||
match self {
|
||||
Self::Timeout { last }
|
||||
| Self::ShuttingDown { last }
|
||||
| Self::Stopped { last }
|
||||
| Self::ObservationClosed { last } => last.capability_admission_failure,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for [`ReticulumHandle::send_to`].
|
||||
@@ -1131,6 +1146,18 @@ impl ReticulumHandle {
|
||||
self.startup_rnode_runtimes.clone()
|
||||
}
|
||||
|
||||
/// Return the exact enabled BLE RNode configurations deferred to Android's
|
||||
/// Kotlin-owned native GATT bridge during startup.
|
||||
///
|
||||
/// This config-order snapshot is inventory only. It grants no registration,
|
||||
/// reconnect, or teardown authority; the application must use the native
|
||||
/// runtime spawn APIs and retain the returned exact owner. It is empty on
|
||||
/// non-Android platforms and in shared-instance client mode.
|
||||
#[cfg(feature = "ble")]
|
||||
pub fn deferred_android_ble_rnodes(&self) -> Vec<interface_factory::BleRNodeInterfaceConfig> {
|
||||
self.deferred_android_ble_rnodes.clone()
|
||||
}
|
||||
|
||||
pub fn link_mtu_discovery(&self) -> bool {
|
||||
self.config.link_mtu_discovery
|
||||
}
|
||||
@@ -1406,34 +1433,40 @@ impl ReticulumHandle {
|
||||
async fn query_transport_result(
|
||||
&self,
|
||||
query: TransportQuery,
|
||||
) -> Result<TransportQueryResponse, ControlError> {
|
||||
self.query_transport_result_with_timeout(query, Duration::from_secs(5))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn query_transport_result_with_timeout(
|
||||
&self,
|
||||
query: TransportQuery,
|
||||
timeout: Duration,
|
||||
) -> Result<TransportQueryResponse, ControlError> {
|
||||
let variant = format!("{query:?}");
|
||||
let started = std::time::Instant::now();
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
if self
|
||||
.transport_tx
|
||||
.send(TransportMessage::Rpc {
|
||||
query,
|
||||
response_tx: tx,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(query = %variant, "transport query channel closed");
|
||||
return Err(ControlError::ChannelClosed);
|
||||
}
|
||||
let send_elapsed = started.elapsed();
|
||||
let timeout = Duration::from_secs(5);
|
||||
let result = match tokio::time::timeout(timeout, rx).await {
|
||||
Ok(Ok(result)) => Ok(result),
|
||||
Ok(Err(_)) => Err(ControlError::ChannelClosed),
|
||||
let mut send_elapsed = None;
|
||||
let transaction = async {
|
||||
self.transport_tx
|
||||
.send(TransportMessage::Rpc {
|
||||
query,
|
||||
response_tx: tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ControlError::ChannelClosed)?;
|
||||
send_elapsed = Some(started.elapsed());
|
||||
rx.await.map_err(|_| ControlError::ChannelClosed)
|
||||
};
|
||||
let result = match tokio::time::timeout(timeout, transaction).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => Err(ControlError::Timeout(timeout)),
|
||||
};
|
||||
let total = started.elapsed();
|
||||
if result.is_err() || total > Duration::from_millis(1000) {
|
||||
tracing::warn!(
|
||||
query = %variant,
|
||||
send_ms = send_elapsed.as_millis() as u64,
|
||||
send_ms = send_elapsed.unwrap_or(total).as_millis() as u64,
|
||||
total_ms = total.as_millis() as u64,
|
||||
timed_out = matches!(&result, Err(ControlError::Timeout(_))),
|
||||
"transport query slow or failed"
|
||||
@@ -2941,7 +2974,10 @@ pub async fn init_with_options_and_rnode_startup_options(
|
||||
let socket_path = shared_unix_socket_path(&rc.instance_name, &socket_base);
|
||||
// Probe before binding: spawn_local_server unconditionally removes
|
||||
// the socket, which would otherwise hijack a live sibling's listener.
|
||||
#[cfg(unix)]
|
||||
let mut live_server_detected = false;
|
||||
#[cfg(not(unix))]
|
||||
let live_server_detected = false;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let is_abstract = socket_path.as_bytes().first() == Some(&0);
|
||||
@@ -3133,10 +3169,23 @@ pub async fn init_with_options_and_rnode_startup_options(
|
||||
*discovery_runtime.store.lock().await = Some(Arc::new(store));
|
||||
}
|
||||
let mut startup_rnode_runtimes = Vec::new();
|
||||
#[cfg(feature = "ble")]
|
||||
let deferred_android_ble_rnodes = collect_deferred_android_ble_rnodes(
|
||||
&interfaces,
|
||||
cfg!(target_os = "android") && instance_mode != InstanceMode::Client,
|
||||
);
|
||||
|
||||
// Client mode leaves hardware to the Shared sibling.
|
||||
if instance_mode != InstanceMode::Client {
|
||||
for iface_config in &interfaces {
|
||||
#[cfg(feature = "ble")]
|
||||
if should_defer_android_ble_rnode(iface_config, cfg!(target_os = "android")) {
|
||||
tracing::info!(
|
||||
interface = %interface_config_name(iface_config),
|
||||
"deferring configured BLE RNode to Android native GATT owner"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let spawn_permit = match interface_registry.acquire_spawn_permit() {
|
||||
Ok(permit) => permit,
|
||||
Err(_) => {
|
||||
@@ -3249,6 +3298,8 @@ pub async fn init_with_options_and_rnode_startup_options(
|
||||
network_identity: network_identity.clone(),
|
||||
discovery: discovery_runtime,
|
||||
startup_rnode_runtimes,
|
||||
#[cfg(feature = "ble")]
|
||||
deferred_android_ble_rnodes,
|
||||
shutdown_coordinator: shutdown_coordinator.clone(),
|
||||
started_at,
|
||||
};
|
||||
@@ -3508,10 +3559,48 @@ fn next_id(id_gen: &Arc<AtomicU64>) -> u64 {
|
||||
id_gen.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[cfg(feature = "ble")]
|
||||
fn should_defer_android_ble_rnode(
|
||||
config: &interface_factory::InterfaceConfig,
|
||||
android_native_gatt_owner: bool,
|
||||
) -> bool {
|
||||
android_native_gatt_owner && matches!(config, interface_factory::InterfaceConfig::BleRNode(_))
|
||||
}
|
||||
|
||||
#[cfg(feature = "ble")]
|
||||
fn collect_deferred_android_ble_rnodes(
|
||||
configs: &[interface_factory::InterfaceConfig],
|
||||
owns_android_hardware: bool,
|
||||
) -> Vec<interface_factory::BleRNodeInterfaceConfig> {
|
||||
if !owns_android_hardware {
|
||||
return Vec::new();
|
||||
}
|
||||
configs
|
||||
.iter()
|
||||
.filter_map(|config| match config {
|
||||
interface_factory::InterfaceConfig::BleRNode(config) => Some(config.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn interface_kind_for_config(config: &interface_factory::InterfaceConfig) -> InterfaceKind {
|
||||
match config {
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
interface_factory::InterfaceConfig::RNode(_) => InterfaceKind::RNode,
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
interface_factory::InterfaceConfig::RNode(_config) => {
|
||||
#[cfg(target_os = "android")]
|
||||
if _config.port.starts_with("androidusb://") {
|
||||
return InterfaceKind::AndroidUsbRNode;
|
||||
}
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
{
|
||||
InterfaceKind::RNode
|
||||
}
|
||||
#[cfg(not(any(feature = "serial", feature = "rnode-tcp")))]
|
||||
{
|
||||
InterfaceKind::Standard
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "serial")]
|
||||
interface_factory::InterfaceConfig::RNodeMulti(_) => InterfaceKind::RNodeMulti,
|
||||
#[cfg(feature = "ble")]
|
||||
@@ -3554,13 +3643,18 @@ impl PendingConfiguredRNodeRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", feature = "ble"))]
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android"
|
||||
))]
|
||||
fn pending_configured_rnode_runtime(
|
||||
config: &interface_factory::InterfaceConfig,
|
||||
handles: &[OwnedInterfaceHandle],
|
||||
) -> Option<PendingConfiguredRNodeRuntime> {
|
||||
let configured_name = match config {
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
interface_factory::InterfaceConfig::RNode(config) => config.name.clone(),
|
||||
#[cfg(feature = "ble")]
|
||||
interface_factory::InterfaceConfig::BleRNode(config) => config.name.clone(),
|
||||
@@ -3581,7 +3675,12 @@ fn pending_configured_rnode_runtime(
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "serial", feature = "rnode-tcp", feature = "ble")))]
|
||||
#[cfg(not(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android"
|
||||
)))]
|
||||
fn pending_configured_rnode_runtime(
|
||||
_config: &interface_factory::InterfaceConfig,
|
||||
_handles: &[OwnedInterfaceHandle],
|
||||
@@ -5094,7 +5193,7 @@ fn interface_config_name(iface_config: &interface_factory::InterfaceConfig) -> &
|
||||
#[cfg(feature = "serial")]
|
||||
interface_factory::InterfaceConfig::KissSerial(c) => &c.name,
|
||||
interface_factory::InterfaceConfig::Auto(c) => &c.name,
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
interface_factory::InterfaceConfig::RNode(c) => &c.name,
|
||||
interface_factory::InterfaceConfig::Local(c) => &c.name,
|
||||
interface_factory::InterfaceConfig::I2P(c) => &c.name,
|
||||
@@ -5129,7 +5228,7 @@ fn interface_config_mode_mut(
|
||||
#[cfg(feature = "serial")]
|
||||
interface_factory::InterfaceConfig::KissSerial(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::Auto(c) => &mut c.mode,
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
interface_factory::InterfaceConfig::RNode(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::Local(c) => &mut c.mode,
|
||||
interface_factory::InterfaceConfig::I2P(c) => &mut c.mode,
|
||||
@@ -5167,7 +5266,7 @@ fn apply_discovery_mode_autocorrect(
|
||||
let is_rnode = {
|
||||
#[allow(unused_mut)]
|
||||
let mut rnode = false;
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
{
|
||||
rnode |= matches!(iface_config, interface_factory::InterfaceConfig::RNode(_));
|
||||
}
|
||||
@@ -5283,7 +5382,7 @@ fn discovery_config_for_interface(
|
||||
None,
|
||||
None,
|
||||
),
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
interface_factory::InterfaceConfig::RNode(c) => (
|
||||
"RNodeInterface",
|
||||
configured_reachable_on(section),
|
||||
@@ -6526,8 +6625,6 @@ pub async fn spawn_ble_rnode_runtime_native_observed_with_options(
|
||||
tcp_port: u16,
|
||||
rnode_startup_options: rns_interface::rnode::RNodeStartupOptions,
|
||||
) -> Result<SpawnedRNodeRuntime, RNodeRuntimeSpawnError> {
|
||||
let spawn_permit = ensure_runtime_interface_admission(handle)
|
||||
.map_err(RNodeRuntimeSpawnError::RuntimeAdmission)?;
|
||||
let BleRnodeRuntimeArgs {
|
||||
name,
|
||||
port,
|
||||
@@ -6542,26 +6639,77 @@ pub async fn spawn_ble_rnode_runtime_native_observed_with_options(
|
||||
flow_control,
|
||||
} = args;
|
||||
|
||||
let mut config = rns_interface::ble_rnode::BleRNodeConfig::new(name, port);
|
||||
config.frequency = frequency;
|
||||
config.bandwidth = bandwidth;
|
||||
config.spreading_factor = spreading_factor;
|
||||
config.coding_rate = coding_rate;
|
||||
config.tx_power = u8::try_from(tx_power).map_err(|_| {
|
||||
spawn_ble_rnode_runtime_native_with_config_and_options(
|
||||
handle,
|
||||
interface_factory::BleRNodeInterfaceConfig {
|
||||
name: name.to_string(),
|
||||
port: port.to_string(),
|
||||
frequency,
|
||||
bandwidth,
|
||||
spreading_factor,
|
||||
coding_rate,
|
||||
tx_power,
|
||||
mode,
|
||||
flow_control,
|
||||
st_alock,
|
||||
lt_alock,
|
||||
id_interval: None,
|
||||
id_callsign: None,
|
||||
},
|
||||
tcp_port,
|
||||
rnode_startup_options,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(feature = "ble")]
|
||||
fn native_ble_driver_config(
|
||||
source: interface_factory::BleRNodeInterfaceConfig,
|
||||
) -> Result<rns_interface::ble_rnode::BleRNodeConfig, RNodeRuntimeSpawnError> {
|
||||
let name = source.name.clone();
|
||||
let mut config = rns_interface::ble_rnode::BleRNodeConfig::new(&source.name, &source.port);
|
||||
config.frequency = source.frequency;
|
||||
config.bandwidth = source.bandwidth;
|
||||
config.spreading_factor = source.spreading_factor;
|
||||
config.coding_rate = source.coding_rate;
|
||||
config.tx_power = u8::try_from(source.tx_power).map_err(|_| {
|
||||
RNodeRuntimeSpawnError::InvalidConfiguration(format!(
|
||||
"invalid value for '{name}.txpower': {tx_power} is below 0 dBm"
|
||||
"invalid value for '{name}.txpower': {} is below 0 dBm",
|
||||
source.tx_power
|
||||
))
|
||||
})?;
|
||||
config.mode = mode;
|
||||
config.st_alock = st_alock;
|
||||
config.lt_alock = lt_alock;
|
||||
config.flow_control = flow_control;
|
||||
config.mode = source.mode;
|
||||
config.st_alock = source.st_alock;
|
||||
config.lt_alock = source.lt_alock;
|
||||
config.flow_control = source.flow_control;
|
||||
config.id_interval = source.id_interval;
|
||||
config.id_callsign = source.id_callsign.map(String::into_bytes);
|
||||
config.validate().map_err(|error| {
|
||||
RNodeRuntimeSpawnError::InvalidConfiguration(format!(
|
||||
"invalid value for '{name}.{}': {error}",
|
||||
error.field()
|
||||
))
|
||||
})?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Spawn and register a native-bridge BLE RNode from the lossless typed
|
||||
/// interface configuration returned by [`ReticulumHandle::deferred_android_ble_rnodes`].
|
||||
///
|
||||
/// Kotlin remains the physical GATT owner. This entry point preserves every
|
||||
/// configured radio, airtime, flow-control, mode, and station-ID field while
|
||||
/// Rust owns the stable loopback KISS session and Reticulum registration.
|
||||
#[cfg(feature = "ble")]
|
||||
pub async fn spawn_ble_rnode_runtime_native_with_config_and_options(
|
||||
handle: &ReticulumHandle,
|
||||
config: interface_factory::BleRNodeInterfaceConfig,
|
||||
tcp_port: u16,
|
||||
rnode_startup_options: rns_interface::rnode::RNodeStartupOptions,
|
||||
) -> Result<SpawnedRNodeRuntime, RNodeRuntimeSpawnError> {
|
||||
let spawn_permit = ensure_runtime_interface_admission(handle)
|
||||
.map_err(RNodeRuntimeSpawnError::RuntimeAdmission)?;
|
||||
let name = config.name.clone();
|
||||
let config = native_ble_driver_config(config)?;
|
||||
|
||||
let id = handle
|
||||
.id_gen
|
||||
@@ -6827,8 +6975,6 @@ pub async fn spawn_android_usb_rnode_runtime_observed_with_options(
|
||||
flow_control: bool,
|
||||
rnode_startup_options: rns_interface::rnode::RNodeStartupOptions,
|
||||
) -> Result<SpawnedRNodeRuntime, RNodeRuntimeSpawnError> {
|
||||
let spawn_permit = ensure_runtime_interface_admission(handle)
|
||||
.map_err(RNodeRuntimeSpawnError::RuntimeAdmission)?;
|
||||
let mut config = rns_interface::android_usb::AndroidUsbConfig::new(name, device_name);
|
||||
config.frequency = frequency;
|
||||
config.bandwidth = bandwidth;
|
||||
@@ -6843,6 +6989,24 @@ pub async fn spawn_android_usb_rnode_runtime_observed_with_options(
|
||||
config.st_alock = st_alock;
|
||||
config.lt_alock = lt_alock;
|
||||
config.flow_control = flow_control;
|
||||
spawn_android_usb_rnode_runtime_with_config_and_options(handle, config, rnode_startup_options)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Spawn and register Android USB from one lossless typed configuration.
|
||||
///
|
||||
/// Applications that persist stable VID/PID/serial selectors or station-ID
|
||||
/// settings should use this form. The historical argument-list facade above
|
||||
/// remains source-compatible but can only express a legacy transient path.
|
||||
#[cfg(target_os = "android")]
|
||||
pub async fn spawn_android_usb_rnode_runtime_with_config_and_options(
|
||||
handle: &ReticulumHandle,
|
||||
config: rns_interface::android_usb::AndroidUsbConfig,
|
||||
rnode_startup_options: rns_interface::rnode::RNodeStartupOptions,
|
||||
) -> Result<SpawnedRNodeRuntime, RNodeRuntimeSpawnError> {
|
||||
let spawn_permit = ensure_runtime_interface_admission(handle)
|
||||
.map_err(RNodeRuntimeSpawnError::RuntimeAdmission)?;
|
||||
let name = config.name.clone();
|
||||
config.validate().map_err(|error| {
|
||||
RNodeRuntimeSpawnError::InvalidConfiguration(format!(
|
||||
"invalid value for '{name}.{}': {error}",
|
||||
@@ -7036,7 +7200,12 @@ async fn spawn_interface_with_rnode_startup_options(
|
||||
is_foreground: Arc<AtomicBool>,
|
||||
rnode_startup_options: rns_interface::rnode::RNodeStartupOptions,
|
||||
) -> Result<Vec<OwnedInterfaceHandle>, String> {
|
||||
#[cfg(not(any(feature = "serial", feature = "rnode-tcp", feature = "ble")))]
|
||||
#[cfg(not(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android"
|
||||
)))]
|
||||
let _ = rnode_startup_options;
|
||||
|
||||
match iface_config {
|
||||
@@ -7116,20 +7285,72 @@ async fn spawn_interface_with_rnode_startup_options(
|
||||
.map(|h| vec![h.into()])
|
||||
.map_err(|e| format!("Auto: {e}"))
|
||||
}
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp", target_os = "android"))]
|
||||
interface_factory::InterfaceConfig::RNode(c) => {
|
||||
let rnode_config = c
|
||||
.to_rnode_config()
|
||||
.map_err(|error| format!("RNode: {error}"))?;
|
||||
rns_interface::rnode::spawn_rnode_interface_with_driver_and_options(
|
||||
rnode_config,
|
||||
id,
|
||||
transport_tx,
|
||||
rnode_startup_options,
|
||||
)
|
||||
.await
|
||||
.map(|spawned| vec![spawned.into()])
|
||||
.map_err(|e| format!("RNode: {e}"))
|
||||
#[cfg(target_os = "android")]
|
||||
if let Some(device_name) = c.port.strip_prefix("androidusb://") {
|
||||
if device_name.is_empty() {
|
||||
return Err(format!(
|
||||
"Android USB RNode '{}': empty USB device name",
|
||||
c.name
|
||||
));
|
||||
}
|
||||
let tx_power = u8::try_from(c.tx_power)
|
||||
.map_err(|_| format!("Android USB RNode '{}': invalid TX power", c.name))?;
|
||||
let mut config =
|
||||
rns_interface::android_usb::AndroidUsbConfig::new(&c.name, device_name);
|
||||
config.device_vendor_id = c.usb_vendor_id;
|
||||
config.device_product_id = c.usb_product_id;
|
||||
config.device_serial_number = c.usb_serial_number.clone();
|
||||
config.baud_rate = c.baud_rate;
|
||||
config.frequency = c.frequency;
|
||||
config.bandwidth = c.bandwidth;
|
||||
config.spreading_factor = c.spreading_factor;
|
||||
config.coding_rate = c.coding_rate;
|
||||
config.tx_power = tx_power;
|
||||
config.mode = c.mode;
|
||||
config.flow_control = c.flow_control;
|
||||
config.st_alock = c.st_alock;
|
||||
config.lt_alock = c.lt_alock;
|
||||
config.id_interval = c.id_interval;
|
||||
config.id_callsign = c
|
||||
.id_callsign
|
||||
.as_ref()
|
||||
.map(|callsign| callsign.as_bytes().to_vec());
|
||||
return rns_interface::android_usb::spawn_android_usb_rnode_interface_with_driver_and_options(
|
||||
config,
|
||||
id,
|
||||
transport_tx,
|
||||
rnode_startup_options,
|
||||
)
|
||||
.await
|
||||
.map(|spawned| vec![spawned.into()])
|
||||
.map_err(|error| format!("Android USB RNode: {error}"));
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
{
|
||||
let rnode_config = c
|
||||
.to_rnode_config()
|
||||
.map_err(|error| format!("RNode: {error}"))?;
|
||||
rns_interface::rnode::spawn_rnode_interface_with_driver_and_options(
|
||||
rnode_config,
|
||||
id,
|
||||
transport_tx,
|
||||
rnode_startup_options,
|
||||
)
|
||||
.await
|
||||
.map(|spawned| vec![spawned.into()])
|
||||
.map_err(|e| format!("RNode: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "serial", feature = "rnode-tcp")))]
|
||||
{
|
||||
Err(format!(
|
||||
"RNodeInterface '{}': non-Android port requires serial or rnode-tcp support",
|
||||
c.name
|
||||
))
|
||||
}
|
||||
}
|
||||
interface_factory::InterfaceConfig::Local(c) => {
|
||||
let local_config = rns_interface::local::LocalClientConfig {
|
||||
@@ -8352,6 +8573,41 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "ble")]
|
||||
#[test]
|
||||
fn native_ble_typed_config_preserves_every_driver_field() {
|
||||
let config = native_ble_driver_config(interface_factory::BleRNodeInterfaceConfig {
|
||||
name: "native-lossless".into(),
|
||||
port: "ble://AA:BB:CC:DD:EE:FF".into(),
|
||||
frequency: 915_125_000,
|
||||
bandwidth: 62_500,
|
||||
spreading_factor: 9,
|
||||
coding_rate: 7,
|
||||
tx_power: 17,
|
||||
mode: rns_interface::traits::InterfaceMode::Roaming,
|
||||
flow_control: true,
|
||||
st_alock: Some(12.5),
|
||||
lt_alock: Some(3.25),
|
||||
id_interval: Some(900),
|
||||
id_callsign: Some("N0CALL".into()),
|
||||
})
|
||||
.expect("valid typed native BLE config");
|
||||
|
||||
assert_eq!(config.name, "native-lossless");
|
||||
assert_eq!(config.ble_uri, "ble://AA:BB:CC:DD:EE:FF");
|
||||
assert_eq!(config.frequency, 915_125_000);
|
||||
assert_eq!(config.bandwidth, 62_500);
|
||||
assert_eq!(config.spreading_factor, 9);
|
||||
assert_eq!(config.coding_rate, 7);
|
||||
assert_eq!(config.tx_power, 17);
|
||||
assert_eq!(config.mode, rns_interface::traits::InterfaceMode::Roaming);
|
||||
assert!(config.flow_control);
|
||||
assert_eq!(config.st_alock, Some(12.5));
|
||||
assert_eq!(config.lt_alock, Some(3.25));
|
||||
assert_eq!(config.id_interval, Some(900));
|
||||
assert_eq!(config.id_callsign.as_deref(), Some(b"N0CALL".as_slice()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ble")]
|
||||
#[tokio::test]
|
||||
async fn ble_runtime_spawns_validate_before_allocating_interface_ids() {
|
||||
@@ -9173,6 +9429,8 @@ loglevel = 7
|
||||
network_identity: None,
|
||||
discovery: Arc::new(DiscoveryRuntime::default()),
|
||||
startup_rnode_runtimes: Vec::new(),
|
||||
#[cfg(feature = "ble")]
|
||||
deferred_android_ble_rnodes: Vec::new(),
|
||||
shutdown_coordinator,
|
||||
started_at: std::time::Instant::now(),
|
||||
}
|
||||
@@ -9794,6 +10052,51 @@ loglevel = 7
|
||||
responder.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_transport_query_deadline_includes_channel_submission() {
|
||||
let timeout = Duration::from_millis(40);
|
||||
let (transport_tx, transport_rx) = mpsc::channel::<TransportMessage>(1);
|
||||
transport_tx
|
||||
.send(TransportMessage::Shutdown)
|
||||
.await
|
||||
.expect("prefill actor channel");
|
||||
|
||||
let mut handle = dummy_handle();
|
||||
handle.transport_tx = transport_tx;
|
||||
let started = std::time::Instant::now();
|
||||
let result = handle
|
||||
.query_transport_result_with_timeout(TransportQuery::GetPathTable, timeout)
|
||||
.await;
|
||||
|
||||
assert!(matches!(result, Err(ControlError::Timeout(t)) if t == timeout));
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
drop(transport_rx);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_transport_query_deadline_includes_response_wait() {
|
||||
let timeout = Duration::from_millis(40);
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(1);
|
||||
let responder = tokio::spawn(async move {
|
||||
let TransportMessage::Rpc { response_tx, .. } =
|
||||
transport_rx.recv().await.expect("transport query")
|
||||
else {
|
||||
panic!("expected transport RPC");
|
||||
};
|
||||
std::future::pending::<()>().await;
|
||||
drop(response_tx);
|
||||
});
|
||||
|
||||
let mut handle = dummy_handle();
|
||||
handle.transport_tx = transport_tx;
|
||||
let result = handle
|
||||
.query_transport_result_with_timeout(TransportQuery::GetPathTable, timeout)
|
||||
.await;
|
||||
|
||||
assert!(matches!(result, Err(ControlError::Timeout(t)) if t == timeout));
|
||||
responder.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_path_forwards_explicit_transport_options() {
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(1);
|
||||
@@ -12111,6 +12414,97 @@ listen_port = 5555
|
||||
assert_eq!(interfaces.len(), 2);
|
||||
}
|
||||
|
||||
#[cfg(feature = "ble")]
|
||||
#[test]
|
||||
fn android_native_ble_manifest_is_ordered_lossless_and_inventory_only() {
|
||||
let make_ble = |name: &str, port: &str, frequency: u32| {
|
||||
interface_factory::InterfaceConfig::BleRNode(
|
||||
interface_factory::BleRNodeInterfaceConfig {
|
||||
name: name.into(),
|
||||
port: port.into(),
|
||||
frequency,
|
||||
bandwidth: 62_500,
|
||||
spreading_factor: 9,
|
||||
coding_rate: 7,
|
||||
tx_power: 14,
|
||||
mode: rns_interface::traits::InterfaceMode::Roaming,
|
||||
flow_control: true,
|
||||
st_alock: Some(12.5),
|
||||
lt_alock: Some(3.25),
|
||||
id_interval: Some(900),
|
||||
id_callsign: Some("N0CALL".into()),
|
||||
},
|
||||
)
|
||||
};
|
||||
let configs = vec![
|
||||
make_ble("first", "ble://AA:BB:CC:DD:EE:01", 915_000_000),
|
||||
interface_factory::InterfaceConfig::TcpClient(
|
||||
rns_interface::tcp::TcpClientConfig::new("not-rnode", "127.0.0.1", 4242),
|
||||
),
|
||||
make_ble("second", "ble://Custom RNode", 868_000_000),
|
||||
];
|
||||
|
||||
let deferred = collect_deferred_android_ble_rnodes(&configs, true);
|
||||
assert_eq!(deferred.len(), 2);
|
||||
assert_eq!(deferred[0].name, "first");
|
||||
assert_eq!(deferred[0].port, "ble://AA:BB:CC:DD:EE:01");
|
||||
assert_eq!(deferred[0].frequency, 915_000_000);
|
||||
assert_eq!(deferred[0].bandwidth, 62_500);
|
||||
assert_eq!(deferred[0].spreading_factor, 9);
|
||||
assert_eq!(deferred[0].coding_rate, 7);
|
||||
assert_eq!(deferred[0].tx_power, 14);
|
||||
assert_eq!(
|
||||
deferred[0].mode,
|
||||
rns_interface::traits::InterfaceMode::Roaming
|
||||
);
|
||||
assert!(deferred[0].flow_control);
|
||||
assert_eq!(deferred[0].st_alock, Some(12.5));
|
||||
assert_eq!(deferred[0].lt_alock, Some(3.25));
|
||||
assert_eq!(deferred[0].id_interval, Some(900));
|
||||
assert_eq!(deferred[0].id_callsign.as_deref(), Some("N0CALL"));
|
||||
assert_eq!(deferred[1].name, "second");
|
||||
assert_eq!(deferred[1].port, "ble://Custom RNode");
|
||||
|
||||
assert!(should_defer_android_ble_rnode(&configs[0], true));
|
||||
assert!(!should_defer_android_ble_rnode(&configs[1], true));
|
||||
assert!(!should_defer_android_ble_rnode(&configs[0], false));
|
||||
assert!(collect_deferred_android_ble_rnodes(&configs, false).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ble")]
|
||||
#[test]
|
||||
fn android_native_ble_manifest_excludes_disabled_sections_without_duplicates() {
|
||||
let input = r#"
|
||||
[interfaces]
|
||||
|
||||
[[Enabled BLE]]
|
||||
type = RNodeInterface
|
||||
enabled = yes
|
||||
port = ble://Enabled
|
||||
frequency = 915000000
|
||||
bandwidth = 125000
|
||||
spreadingfactor = 8
|
||||
codingrate = 6
|
||||
txpower = 17
|
||||
|
||||
[[Disabled BLE]]
|
||||
type = RNodeInterface
|
||||
enabled = no
|
||||
port = ble://Disabled
|
||||
frequency = 868000000
|
||||
bandwidth = 125000
|
||||
spreadingfactor = 8
|
||||
codingrate = 6
|
||||
txpower = 17
|
||||
"#;
|
||||
let config = Config::parse(input).unwrap();
|
||||
let interfaces = synthesize_interfaces(&config, true).unwrap();
|
||||
let deferred = collect_deferred_android_ble_rnodes(&interfaces, true);
|
||||
assert_eq!(deferred.len(), 1);
|
||||
assert_eq!(deferred[0].name, "Enabled BLE");
|
||||
assert_eq!(deferred[0].port, "ble://Enabled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_panic_on_interface_error_fails_bad_config() {
|
||||
let input = r#"
|
||||
|
||||
@@ -33,6 +33,13 @@ pub const FETCH_PATH_NAME: &str = "fetch_file";
|
||||
|
||||
pub const DEFAULT_RNCP_APP_NAME: &str = "rncp.receive";
|
||||
|
||||
/// Python sends the final Resource proof before it runs the receiver-side
|
||||
/// conclusion callback that materialises the file. Keep the Link alive for a
|
||||
/// short, bounded settlement window after a valid proof so an immediate
|
||||
/// teardown cannot race that callback and turn a proven Resource into
|
||||
/// `FAILED` on a loaded peer.
|
||||
const RNCP_POST_PROOF_SETTLE: Duration = Duration::from_millis(250);
|
||||
|
||||
pub fn default_rncp_app_name() -> &'static str {
|
||||
DEFAULT_RNCP_APP_NAME
|
||||
}
|
||||
@@ -639,6 +646,10 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
|
||||
completed_parts += segment_parts;
|
||||
}
|
||||
|
||||
if transfer_result.is_ok() {
|
||||
tokio::time::sleep(RNCP_POST_PROOF_SETTLE).await;
|
||||
}
|
||||
|
||||
if let Some(close_pkt) = build_link_close(&mut link) {
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
@@ -1565,4 +1576,9 @@ mod tests {
|
||||
assert_eq!(header.context, rns_wire::context::PacketContext::LinkClose);
|
||||
assert!(responder.receive_teardown(&raw[offset..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_rncp_send_retains_python_receiver_settlement_window() {
|
||||
assert_eq!(RNCP_POST_PROOF_SETTLE, Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
@@ -165,6 +165,7 @@ fn bind_abstract_unix_listener(_name: &str) -> std::io::Result<tokio::net::UnixL
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn display_socket_path(path: &str) -> String {
|
||||
if let Some(rest) = path.strip_prefix('\0') {
|
||||
format!("\\0{rest}")
|
||||
|
||||
@@ -366,8 +366,11 @@ impl MutationOutcome {
|
||||
}
|
||||
|
||||
fn model_verification_summary(admission: RNodeRadioAdmission) -> String {
|
||||
let product = admission.product_code();
|
||||
let model = admission.model_code();
|
||||
// rnodeconf admissions derive from a locked, parsed identity, so the
|
||||
// codes are always present; the unprovisioned arm is unreachable here.
|
||||
let (Some(product), Some(model)) = (admission.product_code(), admission.model_code()) else {
|
||||
return "generic RF validation only; no provisioned identity".to_string();
|
||||
};
|
||||
if admission.is_verified() {
|
||||
format!("model-specific limits verified for product 0x{product:02x}, model 0x{model:02x}")
|
||||
} else {
|
||||
|
||||
@@ -853,19 +853,12 @@ impl TransportActor {
|
||||
}
|
||||
|
||||
// Cache the relay so the matching LRPROOF can be routed back to
|
||||
// the initiator without a fresh path lookup. Proof timeout scales
|
||||
// with remaining hops and adds a serialization allowance for
|
||||
// slow outbound interfaces.
|
||||
// the initiator without a fresh path lookup. The transport table
|
||||
// uses the canonical bounded per-hop proof window; Link session
|
||||
// policy owns any interface-specific establishment allowance.
|
||||
let link_id = rns_wire::hash::link_id_from_raw(raw, header.flags.header_type);
|
||||
let now = now_f64();
|
||||
let base_timeout = 60.0 * (remaining_hops.max(1) as f64);
|
||||
let extra_timeout = if let Some(iface) = self.interfaces.get(&target_interface) {
|
||||
let bitrate = iface.bitrate.max(1) as f64;
|
||||
(raw.len() as f64 * 8.0) / bitrate
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let proof_timeout = now + base_timeout + extra_timeout;
|
||||
let proof_timeout = crate::link_table::pending_link_proof_deadline(now, remaining_hops);
|
||||
let link_entry = crate::link_table::LinkEntry {
|
||||
timestamp: now,
|
||||
next_hop,
|
||||
@@ -1076,19 +1069,31 @@ impl TransportActor {
|
||||
trunc = hex::encode(header.destination_hash),
|
||||
"delivery proof received for outbound message"
|
||||
);
|
||||
// Broadcast the DeliveryProof to every destination channel —
|
||||
// we don't know which local identity originated the outbound
|
||||
// message, so LXMF filters by msg_id on its side.
|
||||
for (dest_hash, tx) in &self.destination_channels {
|
||||
if let Err(e) =
|
||||
tx.try_send(crate::link_messages::DestinationEvent::DeliveryProof {
|
||||
if let Some(proof_tx) = self.receipt_proof_txs.remove(&header.destination_hash) {
|
||||
if proof_tx
|
||||
.send(crate::link_messages::DestinationEvent::DeliveryProof {
|
||||
msg_id: msg_id.clone(),
|
||||
rtt,
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
self.channel_drops += 1;
|
||||
error!(dest = hex::encode(dest_hash), msg_id = %msg_id, drops = self.channel_drops, err = %e,
|
||||
"failed to deliver DeliveryProof; sender will not receive confirmation");
|
||||
error!(msg_id = %msg_id,
|
||||
"direct delivery-proof owner closed before confirmation");
|
||||
}
|
||||
} else {
|
||||
// Legacy receipts predate direct proof ownership. Preserve
|
||||
// their broadcast behavior for compatibility.
|
||||
for (dest_hash, tx) in &self.destination_channels {
|
||||
if let Err(e) =
|
||||
tx.try_send(crate::link_messages::DestinationEvent::DeliveryProof {
|
||||
msg_id: msg_id.clone(),
|
||||
rtt,
|
||||
})
|
||||
{
|
||||
self.channel_drops += 1;
|
||||
error!(dest = hex::encode(dest_hash), msg_id = %msg_id, drops = self.channel_drops, err = %e,
|
||||
"failed to deliver legacy DeliveryProof; sender will not receive confirmation");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,6 +162,7 @@ impl TransportActor {
|
||||
for (key, update) in concluded {
|
||||
self.receipt_table.remove(&key);
|
||||
self.receipt_msg_ids.remove(&key);
|
||||
self.receipt_proof_txs.remove(&key);
|
||||
if let Some(status_tx) = self.receipt_updates.remove(&key) {
|
||||
status_tx.send_replace(update);
|
||||
}
|
||||
@@ -181,6 +182,7 @@ impl TransportActor {
|
||||
receipt.cull();
|
||||
}
|
||||
self.receipt_msg_ids.remove(&key);
|
||||
self.receipt_proof_txs.remove(&key);
|
||||
if let Some(status_tx) = self.receipt_updates.remove(&key) {
|
||||
status_tx.send_replace(crate::messages::ReceiptUpdate::Culled);
|
||||
}
|
||||
|
||||
@@ -31,6 +31,19 @@ mod outbound;
|
||||
mod persistence;
|
||||
mod rpc;
|
||||
|
||||
// In-process Links need two distinguishable ingress edges even though both
|
||||
// endpoints are owned by this actor. Real interface ids are allocated upward
|
||||
// from zero by the runtime, so reserve the top two values for this private
|
||||
// duplex route. They never appear on the wire or in the interface registry.
|
||||
const LOCAL_LINK_INITIATOR_INTERFACE: InterfaceId = InterfaceId::MAX;
|
||||
const LOCAL_LINK_RESPONDER_INTERFACE: InterfaceId = InterfaceId::MAX - 1;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct LocalLinkRoute {
|
||||
initiator_tx: mpsc::Sender<crate::link_messages::DestinationEvent>,
|
||||
responder_tx: mpsc::Sender<crate::link_messages::DestinationEvent>,
|
||||
}
|
||||
|
||||
/// Owns every routing table and drains the `TransportMessage` channel in one
|
||||
/// task. The single-owner model means the hot path has no shared state and no
|
||||
/// locks — callers drive the actor by sending typed commands rather than
|
||||
@@ -59,6 +72,10 @@ pub struct TransportActor {
|
||||
/// Truncated packet hash → LXMF msg_id for pairing delivery proofs back
|
||||
/// to their originating outbound message.
|
||||
pub receipt_msg_ids: HashMap<[u8; 16], String>,
|
||||
/// Direct application proof sinks for receipt owners that cannot tolerate
|
||||
/// loss through the legacy bounded destination-event fan-out.
|
||||
pub receipt_proof_txs:
|
||||
HashMap<[u8; 16], mpsc::UnboundedSender<crate::link_messages::DestinationEvent>>,
|
||||
/// Direct per-send receipt observers used by the high-level runtime API.
|
||||
pub receipt_updates:
|
||||
HashMap<[u8; 16], tokio::sync::watch::Sender<crate::messages::ReceiptUpdate>>,
|
||||
@@ -68,6 +85,11 @@ pub struct TransportActor {
|
||||
pub local_destinations: HashSet<[u8; 16]>,
|
||||
pub destination_channels:
|
||||
HashMap<[u8; 16], mpsc::Sender<crate::link_messages::DestinationEvent>>,
|
||||
/// Duplex routes for Links whose initiator and responder are registered
|
||||
/// on this same transport actor. Keeping both endpoints here avoids the
|
||||
/// single `destination_channels[link_id]` slot aliasing one side over the
|
||||
/// other after the responder registers the Link.
|
||||
local_link_routes: HashMap<[u8; 16], LocalLinkRoute>,
|
||||
pub path_requests: HashMap<[u8; 16], f64>,
|
||||
/// Python `discovery_path_requests`: external interfaces waiting for a
|
||||
/// matching announce while this transport recursively searches elsewhere.
|
||||
@@ -303,10 +325,12 @@ impl TransportActor {
|
||||
packet_metrics_order: VecDeque::new(),
|
||||
receipt_table: HashMap::new(),
|
||||
receipt_msg_ids: HashMap::new(),
|
||||
receipt_proof_txs: HashMap::new(),
|
||||
receipt_updates: HashMap::new(),
|
||||
interfaces: HashMap::new(),
|
||||
local_destinations: HashSet::new(),
|
||||
destination_channels: HashMap::new(),
|
||||
local_link_routes: HashMap::new(),
|
||||
path_requests: HashMap::new(),
|
||||
discovery_path_requests: HashMap::new(),
|
||||
discovery_pr_tags: HashMap::new(),
|
||||
@@ -549,6 +573,7 @@ impl TransportActor {
|
||||
TransportMessage::DeregisterDestination { hash } => {
|
||||
self.local_destinations.remove(&hash);
|
||||
self.destination_channels.remove(&hash);
|
||||
self.local_link_routes.remove(&hash);
|
||||
}
|
||||
TransportMessage::CacheRequest {
|
||||
packet_hash,
|
||||
@@ -766,11 +791,35 @@ impl TransportActor {
|
||||
receipt.set_destination_identity(destination_hash, Some(destination_public_key));
|
||||
self.receipt_table.insert(truncated_hash, receipt);
|
||||
self.receipt_msg_ids.insert(truncated_hash, msg_id);
|
||||
self.receipt_proof_txs.remove(&truncated_hash);
|
||||
debug!(
|
||||
trunc = hex::encode(truncated_hash),
|
||||
"registered receipt for outbound LXMF message"
|
||||
);
|
||||
}
|
||||
TransportMessage::RegisterReceiptWithProof {
|
||||
truncated_hash,
|
||||
full_hash,
|
||||
destination_hash,
|
||||
destination_public_key,
|
||||
msg_id,
|
||||
timeout,
|
||||
proof_tx,
|
||||
} => {
|
||||
let mut receipt = PacketReceipt::new(
|
||||
full_hash,
|
||||
truncated_hash,
|
||||
Some(timeout.unwrap_or(std::time::Duration::from_secs(180))),
|
||||
);
|
||||
receipt.set_destination_identity(destination_hash, Some(destination_public_key));
|
||||
self.receipt_table.insert(truncated_hash, receipt);
|
||||
self.receipt_msg_ids.insert(truncated_hash, msg_id);
|
||||
self.receipt_proof_txs.insert(truncated_hash, proof_tx);
|
||||
debug!(
|
||||
trunc = hex::encode(truncated_hash),
|
||||
"registered receipt with direct application proof owner"
|
||||
);
|
||||
}
|
||||
TransportMessage::RegisterLink {
|
||||
link_id,
|
||||
destination_hash,
|
||||
@@ -779,6 +828,15 @@ impl TransportActor {
|
||||
remaining_hops,
|
||||
initiator,
|
||||
} => {
|
||||
if interface_id == LOCAL_LINK_RESPONDER_INTERFACE
|
||||
&& self.local_link_routes.contains_key(&link_id)
|
||||
{
|
||||
// The private duplex route owns both directions. A normal
|
||||
// LinkTable entry would point at a non-registry interface,
|
||||
// be culled as dead, and is not consulted for local sends.
|
||||
debug!(link_id = hex::encode(link_id), "registered in-process Link");
|
||||
return;
|
||||
}
|
||||
// Initiators start pending (validated=false) until the proof
|
||||
// arrives; non-initiators already hold a validated link.
|
||||
let now = now_f64();
|
||||
@@ -790,7 +848,10 @@ impl TransportActor {
|
||||
destination_hash,
|
||||
established: !initiator,
|
||||
validated: !initiator,
|
||||
proof_timeout: now + 60.0,
|
||||
proof_timeout: crate::link_table::pending_link_proof_deadline(
|
||||
now,
|
||||
remaining_hops,
|
||||
),
|
||||
receiving_interface: interface_id,
|
||||
taken_hops: 0,
|
||||
};
|
||||
@@ -949,6 +1010,7 @@ impl TransportActor {
|
||||
self.path_states.clear();
|
||||
self.packet_metrics.clear();
|
||||
self.packet_metrics_order.clear();
|
||||
self.receipt_proof_txs.clear();
|
||||
self.discovery_path_requests.clear();
|
||||
self.pending_local_path_requests.clear();
|
||||
self.pending_discovery_prs.clear();
|
||||
@@ -2921,7 +2983,8 @@ mod tests {
|
||||
actor.transport_identity_hash = Some(transport_id);
|
||||
|
||||
let (entry1, _rx1) = make_test_interface("iface1");
|
||||
let (entry2, mut rx2) = make_test_interface("iface2");
|
||||
let (mut entry2, mut rx2) = make_test_interface("iface2");
|
||||
entry2.bitrate = 5;
|
||||
actor.interfaces.insert(1, entry1);
|
||||
actor.interfaces.insert(2, entry2);
|
||||
|
||||
@@ -2933,6 +2996,7 @@ mod tests {
|
||||
|
||||
// Inject in-transport link request on interface 1
|
||||
let raw = make_header2_link_request_packet(transport_id, dest_hash, 0, &[0x42; 64]);
|
||||
let link_id = rns_wire::hash::link_id_from_raw(&raw, rns_wire::flags::HeaderType::Header2);
|
||||
actor.on_inbound(InboundPacket {
|
||||
raw,
|
||||
interface_id: 1,
|
||||
@@ -2950,6 +3014,16 @@ mod tests {
|
||||
rns_wire::flags::HeaderType::Header1
|
||||
);
|
||||
assert_eq!(forwarded_header.transport_id, None);
|
||||
|
||||
let link_entry = actor.link_table.get(&link_id).unwrap();
|
||||
assert_eq!(
|
||||
link_entry.proof_timeout,
|
||||
crate::link_table::pending_link_proof_deadline(
|
||||
link_entry.timestamp,
|
||||
link_entry.remaining_hops,
|
||||
),
|
||||
"relay proof lifetime must not grow with interface serialization time"
|
||||
);
|
||||
}
|
||||
|
||||
fn make_lrproof_packet_with_payload(link_id: [u8; 16], hops: u8, payload: &[u8]) -> Bytes {
|
||||
@@ -3981,6 +4055,103 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_process_link_route_keeps_initiator_and_responder_duplex() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let destination_hash = [0xC1; 16];
|
||||
let request_raw = make_link_request_packet(destination_hash, 0);
|
||||
let link_id =
|
||||
rns_wire::hash::link_id_from_raw(&request_raw, rns_wire::flags::HeaderType::Header1);
|
||||
let (initiator_tx, mut initiator_rx) = mpsc::channel(8);
|
||||
let (responder_tx, mut responder_rx) = mpsc::channel(8);
|
||||
actor.local_destinations.insert(destination_hash);
|
||||
actor.local_destinations.insert(link_id);
|
||||
actor
|
||||
.destination_channels
|
||||
.insert(destination_hash, responder_tx);
|
||||
actor.destination_channels.insert(link_id, initiator_tx);
|
||||
|
||||
assert!(actor.on_outbound_with_receipt_policy(
|
||||
OutboundRequest {
|
||||
raw: request_raw.clone(),
|
||||
destination_hash,
|
||||
},
|
||||
true,
|
||||
));
|
||||
assert!(matches!(
|
||||
responder_rx.try_recv().unwrap(),
|
||||
crate::link_messages::DestinationEvent::LinkRequest {
|
||||
raw,
|
||||
interface_id: LOCAL_LINK_RESPONDER_INTERFACE,
|
||||
..
|
||||
} if raw == request_raw
|
||||
));
|
||||
|
||||
actor.handle_message(TransportMessage::RegisterLink {
|
||||
link_id,
|
||||
destination_hash,
|
||||
interface_id: LOCAL_LINK_RESPONDER_INTERFACE,
|
||||
next_hop: None,
|
||||
remaining_hops: 0,
|
||||
initiator: false,
|
||||
});
|
||||
assert!(actor.link_table.get(&link_id).is_none());
|
||||
|
||||
let proof = make_link_proof_packet(link_id, 0);
|
||||
assert!(actor.on_outbound_attached(
|
||||
OutboundRequest {
|
||||
raw: proof.clone(),
|
||||
destination_hash: link_id,
|
||||
},
|
||||
LOCAL_LINK_RESPONDER_INTERFACE,
|
||||
));
|
||||
assert!(matches!(
|
||||
initiator_rx.try_recv().unwrap(),
|
||||
crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw,
|
||||
interface_id: LOCAL_LINK_INITIATOR_INTERFACE,
|
||||
..
|
||||
} if raw == proof
|
||||
));
|
||||
|
||||
let from_initiator = make_link_data_packet(link_id, 0);
|
||||
assert!(actor.on_outbound_attached(
|
||||
OutboundRequest {
|
||||
raw: from_initiator.clone(),
|
||||
destination_hash: link_id,
|
||||
},
|
||||
LOCAL_LINK_INITIATOR_INTERFACE,
|
||||
));
|
||||
assert!(matches!(
|
||||
responder_rx.try_recv().unwrap(),
|
||||
crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw,
|
||||
interface_id: LOCAL_LINK_RESPONDER_INTERFACE,
|
||||
..
|
||||
} if raw == from_initiator
|
||||
));
|
||||
|
||||
let from_responder = make_link_data_packet(link_id, 0);
|
||||
assert!(actor.on_outbound_with_receipt_policy(
|
||||
OutboundRequest {
|
||||
raw: from_responder.clone(),
|
||||
destination_hash: link_id,
|
||||
},
|
||||
true,
|
||||
));
|
||||
assert!(matches!(
|
||||
initiator_rx.try_recv().unwrap(),
|
||||
crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw,
|
||||
interface_id: LOCAL_LINK_INITIATOR_INTERFACE,
|
||||
..
|
||||
} if raw == from_responder
|
||||
));
|
||||
|
||||
actor.handle_message(TransportMessage::DeregisterDestination { hash: link_id });
|
||||
assert!(!actor.local_link_routes.contains_key(&link_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_path_response_context_does_not_install_path() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
@@ -5700,6 +5871,10 @@ mod tests {
|
||||
let entry = actor.link_table.get(&link_id).unwrap();
|
||||
assert!(!entry.validated);
|
||||
assert!(!entry.established);
|
||||
assert_eq!(
|
||||
entry.proof_timeout,
|
||||
crate::link_table::pending_link_proof_deadline(entry.timestamp, 3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -8078,6 +8253,57 @@ mod tests {
|
||||
assert!(!actor.receipt_msg_ids.contains_key(&proof_hash));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_delivery_proof_owner_bypasses_full_destination_channel() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let (iface, _rx) = make_test_interface("direct-proof-owner");
|
||||
actor.interfaces.insert(1, iface);
|
||||
|
||||
let destination = rns_identity::identity::Identity::new();
|
||||
let destination_hash = [0xD3; 16];
|
||||
let packet_hash = [0x63; 32];
|
||||
let mut proof_hash = [0u8; 16];
|
||||
proof_hash.copy_from_slice(&packet_hash[..16]);
|
||||
let (proof_tx, mut proof_rx) = mpsc::unbounded_channel();
|
||||
|
||||
actor.handle_message(TransportMessage::RegisterReceiptWithProof {
|
||||
truncated_hash: proof_hash,
|
||||
full_hash: packet_hash,
|
||||
destination_hash,
|
||||
destination_public_key: destination.get_public_key(),
|
||||
msg_id: "direct-owner-message".to_string(),
|
||||
timeout: Some(Duration::from_secs(180)),
|
||||
proof_tx,
|
||||
});
|
||||
|
||||
let (legacy_tx, _legacy_rx) = mpsc::channel(1);
|
||||
legacy_tx
|
||||
.try_send(crate::link_messages::DestinationEvent::LinkClosed {
|
||||
link_id: [0x64; 16],
|
||||
})
|
||||
.unwrap();
|
||||
actor.destination_channels.insert([0x65; 16], legacy_tx);
|
||||
|
||||
let signature = destination.sign(&packet_hash).unwrap();
|
||||
actor.on_inbound(InboundPacket {
|
||||
raw: make_proof_packet_with_payload(proof_hash, 0, &signature),
|
||||
interface_id: 1,
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
});
|
||||
|
||||
assert!(matches!(
|
||||
proof_rx.try_recv(),
|
||||
Ok(crate::link_messages::DestinationEvent::DeliveryProof { msg_id, .. })
|
||||
if msg_id == "direct-owner-message"
|
||||
));
|
||||
assert!(!actor.receipt_table.contains_key(&proof_hash));
|
||||
assert!(!actor.receipt_msg_ids.contains_key(&proof_hash));
|
||||
assert!(!actor.receipt_proof_txs.contains_key(&proof_hash));
|
||||
assert_eq!(actor.channel_drops, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_receipt_timeout_updates_only_pending_receipts() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
|
||||
@@ -30,6 +30,14 @@ impl TransportActor {
|
||||
Err(_) => return false,
|
||||
};
|
||||
|
||||
// A Link can be initiated to another destination registered on this
|
||||
// same actor (for example, Ratspeak joining the RRC hub it hosts).
|
||||
// Route that traffic through two private logical edges so initiator
|
||||
// and responder never overwrite each other's `link_id` channel.
|
||||
if let Some(sent) = self.dispatch_local_link_outbound(&request, &parsed) {
|
||||
return sent;
|
||||
}
|
||||
|
||||
// Seed the dedup set with our own packet hash so echoes looped back
|
||||
// from the fabric aren't re-processed.
|
||||
let pkt_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type);
|
||||
@@ -204,6 +212,10 @@ impl TransportActor {
|
||||
) -> bool {
|
||||
self.traffic.record_tx(0, request.raw.len() as u64);
|
||||
|
||||
if let Some(sent) = self.dispatch_local_link_attached(&request, interface_id) {
|
||||
return sent;
|
||||
}
|
||||
|
||||
if let Ok((parsed, _)) = rns_wire::header::PacketHeader::unpack(&request.raw) {
|
||||
let pkt_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type);
|
||||
self.packet_hashlist.insert(pkt_hash);
|
||||
@@ -229,6 +241,118 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_local_link_outbound(
|
||||
&mut self,
|
||||
request: &crate::messages::OutboundRequest,
|
||||
header: &rns_wire::header::PacketHeader,
|
||||
) -> Option<bool> {
|
||||
if header.flags.packet_type == rns_wire::flags::PacketType::LinkRequest
|
||||
&& self.local_destinations.contains(&request.destination_hash)
|
||||
{
|
||||
let link_id = rns_wire::hash::link_id_from_raw(&request.raw, header.flags.header_type);
|
||||
let initiator_tx = self.destination_channels.get(&link_id)?.clone();
|
||||
let responder_tx = self
|
||||
.destination_channels
|
||||
.get(&request.destination_hash)?
|
||||
.clone();
|
||||
self.local_link_routes.insert(
|
||||
link_id,
|
||||
LocalLinkRoute {
|
||||
initiator_tx,
|
||||
responder_tx: responder_tx.clone(),
|
||||
},
|
||||
);
|
||||
let delivered =
|
||||
responder_tx.try_send(crate::link_messages::DestinationEvent::LinkRequest {
|
||||
raw: request.raw.clone(),
|
||||
interface_id: LOCAL_LINK_RESPONDER_INTERFACE,
|
||||
metrics: PacketMetrics::default(),
|
||||
});
|
||||
if let Err(error) = delivered {
|
||||
self.local_link_routes.remove(&link_id);
|
||||
self.channel_drops += 1;
|
||||
warn!(
|
||||
link_id = %hex::encode(link_id),
|
||||
drops = self.channel_drops,
|
||||
err = %error,
|
||||
"failed to deliver in-process Link request"
|
||||
);
|
||||
return Some(false);
|
||||
}
|
||||
self.traffic.record_rx(0, request.raw.len() as u64);
|
||||
debug!(
|
||||
link_id = %hex::encode(link_id),
|
||||
dest = %hex::encode(request.destination_hash),
|
||||
"in-process Link request routed to local destination"
|
||||
);
|
||||
return Some(true);
|
||||
}
|
||||
|
||||
// LinkManager responder traffic uses ordinary Outbound messages.
|
||||
// Initiator traffic is pinned with OutboundAttached below, so the
|
||||
// message shape itself supplies the side without changing public APIs.
|
||||
let route = self.local_link_routes.get(&request.destination_hash)?;
|
||||
let delivered =
|
||||
route
|
||||
.initiator_tx
|
||||
.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw: request.raw.clone(),
|
||||
interface_id: LOCAL_LINK_INITIATOR_INTERFACE,
|
||||
metrics: PacketMetrics::default(),
|
||||
});
|
||||
if let Err(error) = delivered {
|
||||
self.channel_drops += 1;
|
||||
warn!(
|
||||
link_id = %hex::encode(request.destination_hash),
|
||||
drops = self.channel_drops,
|
||||
err = %error,
|
||||
"failed to deliver in-process responder Link packet"
|
||||
);
|
||||
return Some(false);
|
||||
}
|
||||
self.traffic.record_rx(0, request.raw.len() as u64);
|
||||
Some(true)
|
||||
}
|
||||
|
||||
fn dispatch_local_link_attached(
|
||||
&mut self,
|
||||
request: &crate::messages::OutboundRequest,
|
||||
interface_id: InterfaceId,
|
||||
) -> Option<bool> {
|
||||
let route = self.local_link_routes.get(&request.destination_hash)?;
|
||||
let (target, target_interface, direction) = match interface_id {
|
||||
LOCAL_LINK_INITIATOR_INTERFACE => (
|
||||
&route.responder_tx,
|
||||
LOCAL_LINK_RESPONDER_INTERFACE,
|
||||
"initiator",
|
||||
),
|
||||
LOCAL_LINK_RESPONDER_INTERFACE => (
|
||||
&route.initiator_tx,
|
||||
LOCAL_LINK_INITIATOR_INTERFACE,
|
||||
"responder",
|
||||
),
|
||||
_ => return None,
|
||||
};
|
||||
let delivered = target.try_send(crate::link_messages::DestinationEvent::InboundPacket {
|
||||
raw: request.raw.clone(),
|
||||
interface_id: target_interface,
|
||||
metrics: PacketMetrics::default(),
|
||||
});
|
||||
if let Err(error) = delivered {
|
||||
self.channel_drops += 1;
|
||||
warn!(
|
||||
link_id = %hex::encode(request.destination_hash),
|
||||
side = direction,
|
||||
drops = self.channel_drops,
|
||||
err = %error,
|
||||
"failed to deliver in-process attached Link packet"
|
||||
);
|
||||
return Some(false);
|
||||
}
|
||||
self.traffic.record_rx(0, request.raw.len() as u64);
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// Payload is a 32-byte packet hash identifying a cached announce. Look
|
||||
/// up the destination via `path_table.packet_hash`, fetch the stored raw
|
||||
/// announce in `recent_announces`, and rebroadcast it so the requester
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//!
|
||||
//! Mirrors Python `Transport.await_path(destination_hash, timeout=None)`
|
||||
//! (RNS/Transport.py:2524). The helper sends an [`AwaitPath`] actor
|
||||
//! message and races the oneshot reply against a caller-supplied timeout. The
|
||||
//! actor emits the upstream-compatible path request before parking the waiter.
|
||||
//! message and applies one caller-supplied deadline to both actor submission
|
||||
//! and the oneshot reply. The actor emits the upstream-compatible path request
|
||||
//! before parking the waiter.
|
||||
//!
|
||||
//! [`AwaitPath`]: crate::messages::TransportMessage::AwaitPath
|
||||
|
||||
@@ -39,20 +40,26 @@ pub async fn await_path(
|
||||
timeout: Duration,
|
||||
) -> Result<(), AwaitPathError> {
|
||||
let (reply_tx, reply_rx) = oneshot::channel();
|
||||
tx.send(TransportMessage::AwaitPath {
|
||||
dest: destination_hash,
|
||||
reply: reply_tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| AwaitPathError::TransportDown)?;
|
||||
let operation = async {
|
||||
tx.send(TransportMessage::AwaitPath {
|
||||
dest: destination_hash,
|
||||
reply: reply_tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| AwaitPathError::TransportDown)?;
|
||||
|
||||
match tokio::time::timeout(timeout, reply_rx).await {
|
||||
Ok(Ok(true)) => Ok(()),
|
||||
// Actor responded `false` → its own internal timer expired.
|
||||
Ok(Ok(false)) => Err(AwaitPathError::Timeout),
|
||||
// Actor dropped the reply sender without replying — treat as timeout.
|
||||
Ok(Err(_)) => Err(AwaitPathError::Timeout),
|
||||
// Caller timeout fired first.
|
||||
match reply_rx.await {
|
||||
Ok(true) => Ok(()),
|
||||
// Actor responded `false` → its own internal timer expired.
|
||||
Ok(false) => Err(AwaitPathError::Timeout),
|
||||
// Actor dropped the reply sender without replying — treat as timeout.
|
||||
Err(_) => Err(AwaitPathError::Timeout),
|
||||
}
|
||||
};
|
||||
|
||||
match tokio::time::timeout(timeout, operation).await {
|
||||
Ok(result) => result,
|
||||
// The deadline covers both actor-channel admission and the reply.
|
||||
Err(_) => Err(AwaitPathError::Timeout),
|
||||
}
|
||||
}
|
||||
@@ -129,4 +136,16 @@ mod tests {
|
||||
let out = await_path(&tx, [0x55; 16], Duration::from_millis(200)).await;
|
||||
assert_eq!(out, Err(AwaitPathError::Timeout));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn timeout_includes_actor_channel_submission() {
|
||||
let (tx, rx) = mpsc::channel::<TransportMessage>(1);
|
||||
tx.send(TransportMessage::Shutdown)
|
||||
.await
|
||||
.expect("prefill actor channel");
|
||||
|
||||
let out = await_path(&tx, [0x66; 16], Duration::from_millis(50)).await;
|
||||
assert_eq!(out, Err(AwaitPathError::Timeout));
|
||||
drop(rx);
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,15 @@ impl From<&LinkEntry> for ExpiredLink {
|
||||
}
|
||||
}
|
||||
|
||||
/// Absolute deadline for transport bookkeeping that is waiting on a Link proof.
|
||||
///
|
||||
/// The Link state machine owns interface-specific establishment allowances.
|
||||
/// Transport entries stay bounded to the canonical per-hop proof window so a
|
||||
/// slow or adversarial interface cannot extend unvalidated routing state.
|
||||
pub(crate) fn pending_link_proof_deadline(now: f64, remaining_hops: u8) -> f64 {
|
||||
now + rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT * f64::from(remaining_hops.max(1))
|
||||
}
|
||||
|
||||
pub struct LinkTable {
|
||||
entries: HashMap<LinkId, LinkEntry>,
|
||||
}
|
||||
@@ -144,6 +153,16 @@ impl Default for LinkTable {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pending_link_proof_deadline_uses_the_canonical_per_hop_window() {
|
||||
let now = 1_000.25;
|
||||
|
||||
assert_eq!(pending_link_proof_deadline(now, 0), 1_006.25);
|
||||
assert_eq!(pending_link_proof_deadline(now, 1), 1_006.25);
|
||||
assert_eq!(pending_link_proof_deadline(now, 3), 1_018.25);
|
||||
assert_eq!(pending_link_proof_deadline(now, u8::MAX), 2_530.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_table_basic() {
|
||||
let mut table = LinkTable::new();
|
||||
|
||||
@@ -462,6 +462,19 @@ pub enum TransportMessage {
|
||||
/// Override default 180s timeout when `Some`.
|
||||
timeout: Option<std::time::Duration>,
|
||||
},
|
||||
/// Register an application-owned receipt with a direct, capacity-lossless
|
||||
/// proof sink. Unlike the legacy destination fan-out, a validated terminal
|
||||
/// proof cannot be discarded because an unrelated destination mailbox is
|
||||
/// full.
|
||||
RegisterReceiptWithProof {
|
||||
truncated_hash: [u8; 16],
|
||||
full_hash: [u8; 32],
|
||||
destination_hash: [u8; 16],
|
||||
destination_public_key: [u8; 64],
|
||||
msg_id: String,
|
||||
timeout: Option<std::time::Duration>,
|
||||
proof_tx: mpsc::UnboundedSender<crate::link_messages::DestinationEvent>,
|
||||
},
|
||||
/// Record a new link in the table. `initiator=true` means we started the
|
||||
/// handshake, so the entry is pending until `ActivateLink` arrives.
|
||||
RegisterLink {
|
||||
@@ -517,6 +530,7 @@ pub fn msg_variant_name(msg: &TransportMessage) -> &'static str {
|
||||
TransportMessage::SharedConnectionRestored { .. } => "SharedConnectionRestored",
|
||||
TransportMessage::SynthesizeTunnel { .. } => "SynthesizeTunnel",
|
||||
TransportMessage::RegisterReceipt { .. } => "RegisterReceipt",
|
||||
TransportMessage::RegisterReceiptWithProof { .. } => "RegisterReceiptWithProof",
|
||||
TransportMessage::RegisterLink { .. } => "RegisterLink",
|
||||
TransportMessage::ActivateLink { .. } => "ActivateLink",
|
||||
TransportMessage::AwaitPath { .. } => "AwaitPath",
|
||||
@@ -573,7 +587,10 @@ pub enum TransportQuery {
|
||||
FirstHopTimeout {
|
||||
dest: [u8; 16],
|
||||
},
|
||||
/// Extra link-proof timeout for a slow interface: `MTU * per_byte_latency`.
|
||||
/// Python-compatible slow-interface timing query: `MTU * per_byte_latency`.
|
||||
///
|
||||
/// Link sessions may use this as establishment policy. Unvalidated
|
||||
/// transport-table retention deliberately remains bitrate-independent.
|
||||
ExtraLinkProofTimeout {
|
||||
interface_id: InterfaceId,
|
||||
},
|
||||
@@ -948,6 +965,15 @@ impl std::fmt::Debug for TransportMessage {
|
||||
.field("truncated_hash", truncated_hash)
|
||||
.field("msg_id", msg_id)
|
||||
.finish(),
|
||||
Self::RegisterReceiptWithProof {
|
||||
truncated_hash,
|
||||
msg_id,
|
||||
..
|
||||
} => f
|
||||
.debug_struct("RegisterReceiptWithProof")
|
||||
.field("truncated_hash", truncated_hash)
|
||||
.field("msg_id", msg_id)
|
||||
.finish(),
|
||||
Self::RegisterLink {
|
||||
link_id,
|
||||
destination_hash,
|
||||
|
||||
Reference in new issue
Block a user