api: hide the last transport actor fields and move their tests in-crate

This commit is contained in:
DeFiDude committed 2026-11-13 17:11:21 -07:00
1 parent 0b619340ac
commit 0d08659d8d
23 files changed
+1783 -11

No files matched your search

Generated
+2
View File
@@ -1913,9 +1913,11 @@ dependencies = [
"rmpv",
"rns-crypto",
"rns-identity",
"rns-link",
"rns-wire",
"rusqlite",
"serde",
"serde_json",
"subtle",
"thiserror 2.0.21",
"tokio",
+2
View File
@@ -35,4 +35,6 @@ rusqlite = { workspace = true, optional = true }
[dev-dependencies]
proptest = { workspace = true }
rns-link = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["test-util"] }
+15 -11
View File
@@ -81,8 +81,7 @@ struct LinkEndpointQueuedPacket {
/// Owns transport routing tables and processes mailbox/control-channel work
/// on one task. Configure it before calling `run`; use commands and replies
/// for running operations. Public table mutations do not automatically perform
/// command-side housekeeping, mark persistence dirty or refresh shared snapshots.
/// for running operations.
///
/// Driver counters, the blackhole snapshot and background persistence state
/// use shared atomics or locks. Sequential command handling is not a claim
@@ -111,8 +110,8 @@ pub struct TransportActor {
local_link_route_attempts:
HashMap<crate::path_recovery::FailedRouteAttempt, path_recovery::LocalLinkRouteAttempt>,
pub path_table: PathTable,
pub link_table: LinkTable,
path_table: PathTable,
link_table: LinkTable,
pub(crate) announce_table: AnnounceTable,
/// Queued announces temporarily displaced while a known-path response
/// occupies `announce_table`.
@@ -176,13 +175,13 @@ pub struct TransportActor {
/// the transit `link_table`: transit forwarding and local session
/// ownership have different lifetimes and authority.
link_endpoints: HashMap<([u8; 16], crate::messages::LinkEndpointRole), LinkEndpointEntry>,
pub path_requests: HashMap<[u8; 16], f64>,
path_requests: HashMap<[u8; 16], f64>,
// One canonical owner; detached public snapshots cannot mutate registrations.
discovery_path_requests: HashMap<[u8; 16], recursive_discovery::DiscoveryOperation>,
/// Destination hash plus request tag, current generation.
pub discovery_pr_tags: HashSet<[u8; 32]>,
discovery_pr_tags: HashSet<[u8; 32]>,
/// Previous tag generation; a tag in either generation is a duplicate.
pub discovery_pr_tags_prev: HashSet<[u8; 32]>,
discovery_pr_tags_prev: HashSet<[u8; 32]>,
/// Failed-Link rediscovery requests awaiting throttled emission.
pub(crate) pending_discovery_prs: VecDeque<PendingDiscoveryPathRequest>,
// Only rejected driver admissions live here; successfully admitted targets
@@ -195,7 +194,7 @@ pub struct TransportActor {
pub(crate) path_interface_suppressions: HashMap<([u8; 16], InterfaceId), f64>,
last_discovery_pr_tx: f64,
/// External interface waiting for a path response from a local shared client.
pub pending_local_path_requests: HashMap<[u8; 16], InterfaceId>,
pending_local_path_requests: HashMap<[u8; 16], InterfaceId>,
/// Legacy separate path-state map, cleared on shared-connection reset.
/// Current path-state queries use `PathTable`'s state instead.
pub(crate) path_states: HashMap<[u8; 16], PathState>,
@@ -208,7 +207,7 @@ pub struct TransportActor {
last_tables_cull: f64,
/// Last never-used path pool check; starts at construction so the first
/// check waits one interval (Transport.py).
pub path_pool_last_checked: f64,
path_pool_last_checked: f64,
/// Destinations with a path request admitted and not yet answered
/// (Python `inflight_path_requests`), with the admission time.
pub(crate) inflight_path_requests: HashMap<[u8; 16], f64>,
@@ -270,11 +269,11 @@ pub struct TransportActor {
/// Whether this actor currently uses a shared-instance peer. Routing policy
/// uses that peer and reconnect handling invalidates prior routing state.
pub is_shared_instance: bool,
is_shared_instance: bool,
/// Sticky process-mode marker for shared-instance clients. It remains true
/// after a shared connection drops so shutdown cannot persist an empty
/// local routing table over the real shared instance's cache.
pub shared_instance_client_mode: bool,
shared_instance_client_mode: bool,
/// Trusted persistence root. Prefer `initialize_storage` to assigning this
/// field when saved state must also be loaded.
@@ -2601,8 +2600,13 @@ mod tests {
mod inbound_queues;
mod interface_stats;
mod link_endpoint_dispatch;
mod local_client_path_response;
mod outbound_wrap;
mod packet_capacity;
mod path_request_tags;
mod path_table_lifecycle;
mod slow_media_discovery;
mod transport_api_defaults;
mod tunnels;
fn owned_event(
@@ -0,0 +1,118 @@
//! A local client's path response to a pending external request against
//! upstream RNS 1.6.0. Expected values come from
//! `tests/fixtures/local_client_path_response/generate.py`.
use super::*;
use crate::InterfaceTransportSender;
use rns_wire::{context::PacketContext, flags::HeaderType, header::PacketHeader};
use serde_json::Value;
/// An actor that keeps the hash from `SetTransportIdentity` on the wire while
/// forwarding is off.
fn fixed_identity_actor() -> (TransportActor, mpsc::Sender<TransportMessage>) {
let options = TransportActorOptions {
static_transport_identity: true,
..Default::default()
};
TransportActor::new_with_options(
4096,
crate::constants::HASHLIST_MAXSIZE,
Default::default(),
options,
)
}
fn golden() -> Value {
let v: Value = serde_json::from_str(include_str!(
"../../../tests/fixtures/local_client_path_response/local_client_path_response.json"
))
.unwrap();
assert_eq!(v["provenance"]["rns_version"], "1.6.0");
v
}
fn hexv(v: &Value) -> Vec<u8> {
hex::decode(v.as_str().unwrap()).unwrap()
}
fn iface(name: &str, tx: mpsc::Sender<Bytes>) -> InterfaceEntry {
InterfaceEntry::new(
name.into(),
InterfaceMode::Full,
InterfaceDirection::bidirectional(),
1_000_000,
500,
tx,
)
}
/// A local client's path response to a pending external request enters the
/// announce table and is rebroadcast once, context NONE, on every interface.
#[tokio::test]
async fn local_client_path_response_is_rebroadcast_once_everywhere() {
let g = golden();
let lp = &g["local_pr"];
assert_eq!(lp["pending_cleared"], true);
assert!(lp["ext_a_sent_before_jobs"].as_array().unwrap().is_empty());
let none_ctx = g["consts"]["NONE"].as_u64().unwrap() as u8;
let raw = Bytes::from(hexv(&lp["announce_raw"]));
let dest: [u8; 16] = hexv(&lp["destination_hash"]).try_into().unwrap();
let (mut actor, tx) = fixed_identity_actor();
let transport_id = [0x77; 16];
tx.try_send(TransportMessage::SetTransportIdentity {
identity_hash: transport_id,
})
.unwrap();
let (a_tx, mut a_rx) = mpsc::channel(64);
let (b_tx, mut b_rx) = mpsc::channel(64);
let (lc_tx, _lc_rx) = mpsc::channel(64);
let entry = iface("ext-a", a_tx);
tx.try_send(TransportMessage::RegisterInterface { id: 1, entry })
.unwrap();
let entry = iface("ext-b", b_tx);
tx.try_send(TransportMessage::RegisterInterface { id: 2, entry })
.unwrap();
let lc = iface("local-client", lc_tx).with_role(InterfaceRole::LocalClient);
let lc_owner = lc.owner.clone();
tx.try_send(TransportMessage::RegisterInterface { id: 3, entry: lc })
.unwrap();
lc_owner.mark_registered();
actor.pending_local_path_requests.insert(dest, 1);
let running = tokio::spawn(actor.run());
let producer = InterfaceTransportSender::bind(3, lc_owner, tx.clone());
producer
.actor_sender()
.send(producer.event(TransportMessage::Inbound(InboundPacket {
raw,
interface_id: 3,
rssi: None,
snr: None,
q: None,
})))
.await
.unwrap();
// Several announce-table passes (one per second).
tokio::time::sleep(Duration::from_millis(2600)).await;
for (name, rx) in [("ext-a", &mut a_rx), ("ext-b", &mut b_rx)] {
let expected = lp["after_jobs"][name].as_array().unwrap();
let mut seen = Vec::new();
while let Ok(frame) = rx.try_recv() {
let (h, _) = PacketHeader::unpack(&frame).unwrap();
if h.destination_hash == dest {
seen.push((h.flags.header_type, h.context.to_byte(), h.transport_id));
}
}
assert_eq!(seen.len(), expected.len(), "{name}: {seen:?}");
assert_eq!(
seen[0],
(HeaderType::Header2, none_ctx, Some(transport_id)),
"{name}"
);
assert_eq!(expected[0]["context"].as_u64(), Some(u64::from(none_ctx)));
assert_ne!(seen[0].1, PacketContext::PathResponse.to_byte());
}
tx.send(TransportMessage::Shutdown).await.unwrap();
running.await.unwrap();
}
@@ -0,0 +1,135 @@
//! HEADER_2 wrapping on a send against upstream RNS 1.6.0: only beyond one
//! hop or behind a shared instance (Transport.py).
//! Vectors come from `tests/fixtures/outbound_wrap/generate.py`.
use super::*;
use crate::messages::OutboundDispatchResult;
use serde_json::Value;
use tokio::sync::oneshot;
fn golden() -> Value {
serde_json::from_str(include_str!(
"../../../tests/fixtures/outbound_wrap/outbound_wrap.json"
))
.unwrap()
}
fn hexv(v: &Value) -> Vec<u8> {
hex::decode(v.as_str().expect("hex string")).expect("hex")
}
fn h16(b: &[u8]) -> [u8; 16] {
b[..16].try_into().unwrap()
}
fn dest_of(raw: &[u8]) -> [u8; 16] {
if raw[0] & 0x40 != 0 {
h16(&raw[18..])
} else {
h16(&raw[2..])
}
}
fn iface(name: &str, bitrate: u64, tx: mpsc::Sender<Bytes>) -> InterfaceEntry {
InterfaceEntry::new(
name.into(),
InterfaceMode::Full,
InterfaceDirection::bidirectional(),
bitrate,
500,
tx,
)
}
async fn barrier(tx: &mpsc::Sender<TransportMessage>) {
let (response_tx, response_rx) = oneshot::channel();
tx.send(TransportMessage::Rpc {
query: TransportQuery::GetPathTable,
response_tx,
})
.await
.unwrap();
response_rx.await.unwrap();
}
fn drain(rx: &mut mpsc::Receiver<Bytes>) -> Vec<Bytes> {
let mut v = Vec::new();
while let Ok(b) = rx.try_recv() {
v.push(b);
}
v
}
async fn send_packet(tx: &mpsc::Sender<TransportMessage>, raw: &[u8]) -> OutboundDispatchResult {
let (result_tx, result_rx) = oneshot::channel();
tx.send(TransportMessage::SendPacket {
request: OutboundRequest {
raw: Bytes::copy_from_slice(raw),
destination_hash: dest_of(raw),
},
attached_interface: None,
receipt: None,
result_tx,
})
.await
.unwrap();
result_rx.await.unwrap()
}
async fn stop(tx: mpsc::Sender<TransportMessage>, running: tokio::task::JoinHandle<()>) {
tx.send(TransportMessage::Shutdown).await.unwrap();
running.await.unwrap();
}
#[tokio::test]
async fn known_paths_wrap_beyond_one_hop_or_behind_a_shared_instance() {
let g = golden();
assert_eq!(g["rns_version"], "1.6.0");
let next_hop = [0xAB; 16];
for case in g["wrap"].as_array().unwrap() {
let hops = case["path_hops"].as_u64().unwrap() as u8;
let packed = hexv(&case["packed"]);
let emitted: Vec<Vec<u8>> = case["emitted"]
.as_array()
.unwrap()
.iter()
.map(hexv)
.collect();
let (raw, expected) = if case["already_header2"].as_bool().unwrap() {
// Upstream hands an already-wrapped packet on unchanged or not at all.
assert!(emitted.iter().all(|e| *e == packed), "{case}");
let mut raw = vec![0x40 | 0x10 | (packed[0] & 0x0F), packed[1]];
raw.extend_from_slice(&next_hop);
raw.extend_from_slice(&packed[2..]);
let expected = emitted.iter().map(|_| raw.clone()).collect::<Vec<_>>();
(raw, expected)
} else {
(packed, emitted)
};
let (mut actor, tx) = TransportActor::new();
let (itx, mut irx) = mpsc::channel(16);
let entry = iface("a", 10_000_000, itx);
tx.try_send(TransportMessage::RegisterInterface { id: 1, entry })
.unwrap();
actor.is_shared_instance = case["shared_client"].as_bool().unwrap();
actor.path_table.insert(
dest_of(&raw),
PathEntry::new(Some(next_hop), hops, 1, InterfaceMode::Full),
);
let running = tokio::spawn(actor.run());
let result = send_packet(&tx, &raw).await;
barrier(&tx).await;
let frames: Vec<String> = drain(&mut irx).iter().map(hex::encode).collect();
stop(tx, running).await;
assert_eq!(
frames,
expected.iter().map(hex::encode).collect::<Vec<_>>(),
"{case}"
);
assert_eq!(
result == OutboundDispatchResult::Sent,
case["sent"].as_bool().unwrap(),
"{case}"
);
}
}
@@ -0,0 +1,308 @@
//! Path-request tags against upstream RNS 1.6.0: one tag across a
//! blocked-interface rediscovery, and a tag memory with no time expiry that
//! rotates above `max_pr_tags` (Transport.py).
//! Goldens come from `tests/fixtures/path_request_tags/gen_*.py`.
use super::*;
use crate::InterfaceTransportSender;
use crate::link_messages::DestinationEvent;
use crate::link_table::LinkEntry;
use crate::messages::{InterfaceStatRpcEntry, TimerTick};
use rns_wire::header::PacketHeader;
use serde_json::Value;
use tokio::sync::oneshot;
fn h16(v: &Value) -> [u8; 16] {
hex::decode(v.as_str().unwrap())
.unwrap()
.try_into()
.unwrap()
}
fn pr_dest() -> [u8; 16] {
rns_identity::destination::Destination::hash_from_name_and_identity(
"rnstransport.path.request",
None,
)
}
/// Wrap a PR payload in a Header1/Broadcast/Plain/Data packet.
fn pr_raw(payload: &[u8]) -> Vec<u8> {
let 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::Plain,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: pr_dest(),
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(payload);
raw
}
/// Returns the PR payload if `raw` is a path request.
fn pr_payload(raw: &[u8]) -> Option<Vec<u8>> {
let (header, offset) = PacketHeader::unpack(raw).ok()?;
(header.destination_hash == pr_dest()).then(|| raw[offset..].to_vec())
}
struct Fixture {
tx: mpsc::Sender<TransportMessage>,
radios: Vec<mpsc::Receiver<Bytes>>,
producers: Vec<InterfaceTransportSender>,
task: tokio::task::JoinHandle<()>,
}
impl Fixture {
/// Interfaces get ids 1..=n; `setup` seeds tables before the actor runs.
fn new(
transport: bool,
transport_id: [u8; 16],
n: u64,
setup: impl FnOnce(&mut TransportActor),
) -> Self {
// The fixed identity stays on the wire with forwarding off.
let options = TransportActorOptions {
static_transport_identity: true,
..Default::default()
};
let (mut actor, tx) = TransportActor::new_with_options(
4096,
crate::constants::HASHLIST_MAXSIZE,
Default::default(),
options,
);
tx.try_send(TransportMessage::SetTransportIdentity {
identity_hash: transport_id,
})
.unwrap();
tx.try_send(TransportMessage::SetTransportEnabled { enabled: transport })
.unwrap();
let mut radios = Vec::new();
let mut producers = Vec::new();
for id in 1..=n {
let (radio_tx, radio_rx) = mpsc::channel(64);
let entry = InterfaceEntry::new(
format!("prw inert radio {id}"),
InterfaceMode::Full,
InterfaceDirection::bidirectional(),
1_000_000_000,
500,
radio_tx,
);
let owner = entry.owner.clone();
tx.try_send(TransportMessage::RegisterInterface { id, entry })
.unwrap();
producers.push(InterfaceTransportSender::bind(id, owner, tx.clone()));
radios.push(radio_rx);
}
setup(&mut actor);
Self {
tx,
radios,
producers,
task: tokio::spawn(actor.run()),
}
}
async fn inbound(&self, raw: Vec<u8>, interface_id: u64) {
self.producers[(interface_id - 1) as usize]
.actor_sender()
.send(
self.producers[(interface_id - 1) as usize].event(TransportMessage::Inbound(
InboundPacket {
raw: Bytes::from(raw),
interface_id,
rssi: None,
snr: None,
q: None,
},
)),
)
.await
.unwrap();
self.stats().await; // mailbox barrier
}
async fn stats(&self) -> Vec<InterfaceStatRpcEntry> {
let (response_tx, response_rx) = oneshot::channel();
self.tx
.send(TransportMessage::Rpc {
query: TransportQuery::GetInterfaceStats,
response_tx,
})
.await
.unwrap();
match response_rx.await.unwrap() {
TransportQueryResponse::InterfaceStats(s) => s,
other => panic!("unexpected {other:?}"),
}
}
async fn register(&self, hash: [u8; 16]) -> mpsc::Receiver<DestinationEvent> {
let (delivery_tx, mut rx) = mpsc::channel(16);
self.tx
.send(TransportMessage::RegisterDestination {
hash,
app_name: "prw.local".into(),
delivery_tx: Some(delivery_tx),
})
.await
.unwrap();
self.stats().await;
while rx.try_recv().is_ok() {}
rx
}
/// Drain path-request payloads queued on radio `id`.
fn prs_on(&mut self, id: u64) -> Vec<Vec<u8>> {
let mut out = Vec::new();
while let Ok(raw) = self.radios[(id - 1) as usize].try_recv() {
if let Some(p) = pr_payload(&raw) {
out.push(p);
}
}
out
}
async fn stop(self) {
let _ = self.tx.send(TransportMessage::Shutdown).await;
let _ = tokio::time::timeout(Duration::from_secs(2), self.task).await;
}
}
/// PR tag = trailing 16 bytes of a canonical 32/48-byte payload.
fn tag_of(payload: &[u8]) -> Vec<u8> {
match payload.len() {
32 => payload[16..32].to_vec(),
48 | 64 => payload[32..48].to_vec(),
_ => payload[16..].to_vec(),
}
}
#[tokio::test]
async fn blocked_interface_rediscovery_shares_one_tag() {
let g: Value = serde_json::from_str(include_str!(
"../../../tests/fixtures/path_request_tags/blocked_rediscovery.json"
))
.unwrap();
let br = &g["blocked_rediscovery"];
assert_eq!(br["same_tag_on_all_unblocked"], true, "golden sanity");
let dest = h16(&br["destination_hash"]);
// A stale unvalidated transit link (taken_hops 1, 1-hop path) makes the
// maintenance tick queue rediscovery with the receiving interface 1 blocked.
let mut fx = Fixture::new(true, [0x99; 16], 3, |a| {
a.path_table.insert(
dest,
PathEntry::new(Some([0x11; 16]), 1, 2, InterfaceMode::Full),
);
a.link_table.insert(
[0x4c; 16],
LinkEntry {
timestamp: 0.0,
next_hop: Some([0x11; 16]),
interface_id: 2,
remaining_hops: 1,
destination_hash: dest,
established: false,
validated: false,
proof_timeout: 1.0,
receiving_interface: 1,
taken_hops: 1,
interface_owner: None,
receiving_owner: None,
requested_mode: 0,
accepted_mtu_ceiling: 500,
},
);
});
tokio::time::sleep(Duration::from_millis(1600)).await;
let a = fx.prs_on(1);
let b = fx.prs_on(2);
let c = fx.prs_on(3);
fx.stop().await;
assert!(
a.iter().all(|p| p[..16] != dest),
"blocked interface must not get the rediscovery PR"
);
let b: Vec<_> = b.into_iter().filter(|p| p[..16] == dest).collect();
let c: Vec<_> = c.into_iter().filter(|p| p[..16] == dest).collect();
assert!(
!b.is_empty() && !c.is_empty(),
"rediscovery PR not observed on both unblocked interfaces: b={b:?} c={c:?}"
);
let tb = hex::encode(tag_of(&b[0]));
let tc = hex::encode(tag_of(&c[0]));
assert_eq!(
tb, tc,
"upstream 1.6.0 handle_disovery_path_requests generates ONE \
request_tag and sends it on every non-blocked interface (Transport.py:4071-4080@1.6.0; golden \
blocked_rediscovery.json b_tags==c_tags). Rust sent different tags per interface: {tb} vs {tc}"
);
}
/// Tag memory has no time expiry and rotates into a previous generation above
/// `max_pr_tags` (Transport.py). Golden tag_memory.json.
#[tokio::test]
async fn path_request_tag_memory_matches_upstream() {
let g: Value = serde_json::from_str(include_str!(
"../../../tests/fixtures/path_request_tags/tag_memory.json"
))
.unwrap();
assert_eq!(g["rns_version"], "1.6.0");
let max = g["max_pr_tags"].as_u64().unwrap() as usize;
let dest = h16(&g["local_destination_hash"]);
let filler = |byte: u8, i: usize| {
let mut k = [byte; 32];
k[28..].copy_from_slice(&(i as u32).to_be_bytes());
k
};
let mut failures = Vec::new();
for case in g["tag_cases"].as_array().unwrap() {
let label = case["case"].as_str().unwrap();
let tag = h16(&case["tag"]);
let mut key = [0u8; 32];
key[..16].copy_from_slice(&dest);
key[16..].copy_from_slice(&tag);
let fx = Fixture::new(false, [0x36; 16], 1, |a| match label {
"replay_after_121s_and_jobs" => {
a.discovery_pr_tags.insert(key);
}
"at_max_no_rotation" | "above_max_rotates" => {
a.discovery_pr_tags.insert(key);
let n = case["seeded_tags"].as_u64().unwrap() as usize - 1;
a.discovery_pr_tags.extend((0..n).map(|i| filler(0xA0, i)));
}
"second_rotation_forgets" => {
a.discovery_pr_tags.insert(key);
a.discovery_pr_tags_prev
.extend((0..max).map(|i| filler(0xA1, i)));
a.discovery_pr_tags_prev.insert(key);
a.discovery_pr_tags.clear();
a.discovery_pr_tags
.extend((0..=max).map(|i| filler(0xA2, i)));
}
_ => {}
});
let mut rx = fx.register(dest).await;
fx.tx.send(TransportMessage::Tick(TimerTick)).await.unwrap();
fx.inbound(pr_raw(&[&dest[..], &tag[..]].concat()), 1).await;
tokio::time::sleep(Duration::from_millis(150)).await;
let answered = std::iter::from_fn(|| rx.try_recv().ok())
.any(|e| matches!(e, DestinationEvent::AnnounceRequested(_)));
fx.stop().await;
if answered != case["answered"].as_bool().unwrap() {
failures.push(format!(
"{label}: upstream answered={} Rust {answered}",
case["answered"]
));
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
@@ -0,0 +1,320 @@
//! Path-table lifetime against upstream RNS 1.6.0: never-used linger on a
//! leaf and a transport node, the never-used pool cap, traffic marking use
//! without renewing a path, and rediscovery after a local Link that never
//! established.
//!
//! Expected values come from `tests/fixtures/path_table_lifecycle/path_table_lifecycle.json`,
//! which `generate.py` beside it reads back from upstream `Transport.jobs()`
//! and `Transport.outbound()`.
use super::*;
use crate::messages::PathTableRpcEntry;
use serde_json::Value;
use tokio::sync::oneshot;
fn golden() -> Value {
let v: Value = serde_json::from_str(include_str!(
"../../../tests/fixtures/path_table_lifecycle/path_table_lifecycle.json"
))
.unwrap();
assert_eq!(v["provenance"]["version"], "1.6.0");
v
}
fn now() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs_f64()
}
fn h16(i: u64) -> [u8; 16] {
(i as u128).to_be_bytes()
}
fn iface(name: &str, bitrate: u64, mode: InterfaceMode) -> (InterfaceEntry, mpsc::Receiver<Bytes>) {
let (tx, rx) = mpsc::channel(256);
let entry = InterfaceEntry::new(
name.into(),
mode,
InterfaceDirection::bidirectional(),
bitrate,
500,
tx,
);
(entry, rx)
}
fn bitrate(kind: &str) -> u64 {
match kind {
"fast" => 10_000_000,
"slow" => 9600,
"edge" => 25_000,
"zero" | "none" => 0,
other => panic!("interface kind {other}"),
}
}
async fn path_table(tx: &mpsc::Sender<TransportMessage>) -> HashMap<[u8; 16], PathTableRpcEntry> {
let (response_tx, rx) = oneshot::channel();
tx.send(TransportMessage::Rpc {
query: TransportQuery::GetPathTable,
response_tx,
})
.await
.unwrap();
match rx.await.unwrap() {
TransportQueryResponse::PathTable(v) => v.into_iter().map(|e| (e.hash, e)).collect(),
other => panic!("unexpected {other:?}"),
}
}
/// Run the actor until its first table cull has happened.
async fn run(
actor: TransportActor,
tx: &mpsc::Sender<TransportMessage>,
) -> HashMap<[u8; 16], PathTableRpcEntry> {
tokio::spawn(actor.run());
tokio::time::sleep(Duration::from_millis(1500)).await;
path_table(tx).await
}
async fn linger_case(case: &Value) {
let transport = case["transport_enabled"].as_bool().unwrap();
let (mut actor, tx) = TransportActor::new();
tx.try_send(TransportMessage::SetTransportEnabled { enabled: transport })
.unwrap();
let mut ids = HashMap::new();
let mut keep = Vec::new();
for (i, kind) in ["fast", "slow", "zero", "none", "edge"]
.into_iter()
.enumerate()
{
let (entry, rx) = iface(kind, bitrate(kind), InterfaceMode::Full);
tx.try_send(TransportMessage::RegisterInterface {
id: i as u64 + 1,
entry,
})
.unwrap();
ids.insert(kind, i as u64 + 1);
keep.push(rx);
}
let t = now();
let entries = case["entries"].as_array().unwrap();
for (i, e) in entries.iter().enumerate() {
let mut p = PathEntry::new(
None,
1,
ids[e["iface"].as_str().unwrap()],
InterfaceMode::Full,
);
p.timestamp = t - e["age_s"].as_f64().unwrap();
p.expires = t + e["expires_rel_s"].as_f64().unwrap();
p.used = e["used_age_s"].as_f64().map_or(0.0, |age| t - age);
actor.path_table.insert(h16(i as u64 + 1), p);
}
let live = run(actor, &tx).await;
for (i, e) in entries.iter().enumerate() {
assert_eq!(
live.contains_key(&h16(i as u64 + 1)),
e["survives"].as_bool().unwrap(),
"transport={transport} {}: upstream cull (Transport.py:1118-1160@1.6.0)",
e["label"]
);
}
}
#[tokio::test]
async fn never_used_paths_linger_as_upstream_on_a_leaf_and_a_transport_node() {
let g = golden();
linger_case(&g["linger_leaf"]).await;
linger_case(&g["linger_transport"]).await;
}
#[tokio::test]
async fn never_used_pool_is_culled_to_the_upstream_target() {
let g = golden();
let c = &g["pool_cap"];
let (mut actor, tx) = TransportActor::new();
tx.try_send(TransportMessage::SetTransportEnabled { enabled: true })
.unwrap();
actor.path_pool_last_checked = 0.0;
let (fast, _fast_rx) = iface("fast", 10_000_000, InterfaceMode::Full);
let (slow, _slow_rx) = iface("slow", 9600, InterfaceMode::Full);
tx.try_send(TransportMessage::RegisterInterface { id: 1, entry: fast })
.unwrap();
tx.try_send(TransportMessage::RegisterInterface { id: 2, entry: slow })
.unwrap();
let t = now();
let count = c["count"].as_u64().unwrap();
let field = |k: &str| c[k].as_u64().unwrap();
for i in 0..count {
let id = if i % field("slow_every") == 0 { 2 } else { 1 };
let expires_rel =
field("expiry_base_s") + ((i * 7919) % field("expiry_mod")) * field("expiry_step_s");
let mut p = PathEntry::new(None, 1, id, InterfaceMode::Full);
p.timestamp = t - 30.0;
p.expires = t + expires_rel as f64;
actor.path_table.insert(h16(i + 1), p);
}
for j in 0..field("used_count") {
let mut p = PathEntry::new(None, 1, 1, InterfaceMode::Full);
p.timestamp = t - 30.0;
p.expires = t + 60.0;
p.used = t - 1.0;
actor.path_table.insert(h16(count + j + 1), p);
}
let live = run(actor, &tx).await;
let removed: Vec<u64> = (0..count)
.filter(|i| !live.contains_key(&h16(i + 1)))
.collect();
let want: Vec<u64> = c["removed"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_u64().unwrap())
.collect();
assert_eq!(
removed, want,
"PATH_POOL_UNUSED_TARGET cull (Transport.py:1150-1156@1.6.0)"
);
assert_eq!(
(0..field("used_count")).all(|j| live.contains_key(&h16(count + j + 1))),
c["used_survive"].as_bool().unwrap()
);
}
#[tokio::test]
async fn outbound_traffic_marks_use_without_renewing_the_path() {
let g = golden();
for case in g["outbound"].as_array().unwrap() {
let hops = case["hops"].as_u64().unwrap() as u8;
let (mut actor, tx) = TransportActor::new();
let (entry, mut rx) = iface("a", 10_000_000, InterfaceMode::Full);
tx.try_send(TransportMessage::RegisterInterface { id: 1, entry })
.unwrap();
let dest = [0x57u8; 16];
let t = now();
let mut p = PathEntry::new(
(hops > 1).then_some([0x99; 16]),
hops,
1,
InterfaceMode::Full,
);
p.timestamp = t - case["age_s"].as_f64().unwrap();
p.expires = p.timestamp + 604_800.0;
let (ts0, exp0) = (p.timestamp, p.expires);
actor.path_table.insert(dest, p);
tokio::spawn(actor.run());
let mut raw = vec![0x00u8, 0x00];
raw.extend_from_slice(&dest);
raw.push(0x00);
raw.extend_from_slice(b"hello");
let before = now();
tx.send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: dest,
}))
.await
.unwrap();
tokio::time::sleep(Duration::from_millis(300)).await;
let e = path_table(&tx).await.remove(&dest).expect("path present");
let got = serde_json::json!({
"hops": hops, "age_s": case["age_s"], "sent": rx.try_recv().is_ok(),
"timestamp_unchanged": e.timestamp == ts0, "expires_unchanged": e.expires == exp0,
"used_is_send_time": e.used >= before,
});
assert_eq!(&got, case, "Transport.py:1618@1.6.0");
}
}
/// A local initiator Link request is sent, then its temporary destination is
/// released without the Link being bound: upstream's CLOSED pending link.
#[tokio::test]
async fn link_never_established_expires_the_path_and_rediscovers_as_upstream() {
let g = golden();
for case in g["pending_link_rediscovery"].as_array().unwrap() {
let (mut actor, tx) = TransportActor::new();
tx.try_send(TransportMessage::SetTransportEnabled {
enabled: case["transport_enabled"].as_bool().unwrap(),
})
.unwrap();
actor.shared_instance_client_mode = case["shared_client"].as_bool().unwrap();
let (entry, mut rx) = iface("a", 10_000_000, InterfaceMode::Full);
tx.try_send(TransportMessage::RegisterInterface { id: 1, entry })
.unwrap();
let dest = h16(7);
let t = now();
let mut p = PathEntry::new(None, 1, 1, InterfaceMode::Full);
p.timestamp = t - 10.0;
p.used = t - 1.0;
actor.path_table.insert(dest, p);
if let Some(age) = case["last_request_age_s"].as_f64() {
actor.path_requests.insert(dest, t - age);
}
tokio::spawn(actor.run());
let (_, request_data) = rns_link::link::Link::new_initiator(dest, 1);
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::LinkRequest,
},
hops: 0,
transport_id: None,
destination_hash: dest,
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(&request_data);
let link_id = rns_wire::hash::link_id_from_raw(&raw, rns_wire::flags::HeaderType::Header1);
let (delivery_tx, _delivery_rx) = mpsc::channel(8);
tx.send(TransportMessage::RegisterDestination {
hash: link_id,
app_name: "pathlifecycle.link".into(),
delivery_tx: Some(delivery_tx),
})
.await
.unwrap();
tx.send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: dest,
}))
.await
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
let sent = tokio::time::timeout(Duration::from_secs(10), rx.recv())
.await
.expect("no outbound path response within 10 s")
.unwrap();
assert_eq!(
sent[0] & 0x03,
0x02,
"precondition: link request transmitted"
);
tx.send(TransportMessage::DeregisterDestination { hash: link_id })
.await
.unwrap();
tokio::time::sleep(Duration::from_millis(1500)).await;
let mut requested = false;
while let Ok(frame) = rx.try_recv() {
let (header, offset) = rns_wire::header::PacketHeader::unpack(&frame).unwrap();
if header.flags.destination_type == rns_wire::flags::DestinationType::Plain
&& frame.len() >= offset + 16
&& frame[offset..offset + 16] == dest
{
requested = true;
}
}
let got = serde_json::json!({
"transport_enabled": case["transport_enabled"], "shared_client": case["shared_client"],
"last_request_age_s": case["last_request_age_s"],
"path_kept": path_table(&tx).await.contains_key(&dest),
"rediscovery_queued": requested,
});
assert_eq!(&got, case, "Transport.py:839-866@1.6.0");
}
}
@@ -0,0 +1,151 @@
//! Transport API defaults against upstream RNS 1.6.0: the default packet
//! receipt timeout and the next-hop hardware MTU gate. Expected values come
//! from `tests/fixtures/transport_api_defaults/generate.py`.
use super::*;
use crate::InterfacePacketCapacity;
use crate::messages::{ReceiptUpdate, TrackedReceiptRegistration};
use rns_wire::context::PacketContext;
use rns_wire::flags::{DestinationType, HeaderType, PacketFlags, PacketType, TransportType};
use rns_wire::header::PacketHeader;
use serde_json::Value;
use tokio::sync::{oneshot, watch};
fn golden() -> Value {
let v: Value = serde_json::from_str(include_str!(
"../../../tests/fixtures/transport_api_defaults/transport_api_defaults.json"
))
.unwrap();
assert_eq!(v["provenance"]["rns_version"], "1.6.0");
v
}
struct Rig {
tx: mpsc::Sender<TransportMessage>,
_rx: mpsc::Receiver<Bytes>,
running: tokio::task::JoinHandle<()>,
}
fn rig(mtu: u32, capacity: Option<InterfacePacketCapacity>, paths: &[([u8; 16], u8)]) -> Rig {
let (mut actor, tx) = TransportActor::new();
let (if_tx, rx) = mpsc::channel(1024);
let mut entry = InterfaceEntry::new(
"medium".into(),
InterfaceMode::Full,
InterfaceDirection::bidirectional(),
10_000_000,
mtu,
if_tx,
);
if let Some(capacity) = capacity {
entry.packet_capacity = capacity;
}
let owner = entry.owner.clone();
tx.try_send(TransportMessage::RegisterInterface { id: 1, entry })
.unwrap();
owner.mark_registered();
for (dest, hops) in paths {
actor
.path_table
.insert(*dest, PathEntry::new(None, *hops, 1, InterfaceMode::Full));
}
let running = tokio::spawn(actor.run());
Rig {
tx,
_rx: rx,
running,
}
}
impl Rig {
async fn shutdown(self) {
let _ = self.tx.send(TransportMessage::Shutdown).await;
let _ = self.running.await;
}
}
/// A receipt registered without a timeout gets `first_hop_timeout + 6 * hops`.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn receipt_without_timeout_uses_the_hop_based_default() {
let g = golden();
let want = g["receipt"]["timeout"].as_f64().unwrap();
let dest = [0x47u8; 16];
let r = rig(
500,
None,
&[(dest, g["receipt"]["hops"].as_u64().unwrap() as u8)],
);
let mut raw = PacketHeader {
flags: PacketFlags {
header_type: HeaderType::Header1,
context_flag: false,
transport_type: TransportType::Broadcast,
destination_type: DestinationType::Single,
packet_type: PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: dest,
context: PacketContext::None,
}
.pack();
raw.extend_from_slice(&[0xAB; 64]);
let (full, trunc) = rns_wire::hash::packet_hash_pair(&raw, HeaderType::Header1);
let (status_tx, status_rx) = watch::channel(ReceiptUpdate::Sent);
let (result_tx, result_rx) = oneshot::channel();
r.tx.send(TransportMessage::SendPacket {
request: OutboundRequest {
raw: Bytes::from(raw),
destination_hash: dest,
},
attached_interface: None,
receipt: Some(TrackedReceiptRegistration {
truncated_hash: trunc,
full_hash: full,
destination_hash: dest,
destination_public_key: [0u8; 64],
timeout: None,
status_tx,
}),
result_tx,
})
.await
.unwrap();
let _ = result_rx.await.unwrap();
tokio::time::sleep(Duration::from_secs_f64(want - 1.5)).await;
assert_eq!(*status_rx.borrow(), ReceiptUpdate::Sent, "timed out early");
// The receipt sweep runs once a second.
tokio::time::sleep(Duration::from_secs_f64(3.5)).await;
assert_eq!(*status_rx.borrow(), ReceiptUpdate::TimedOut);
r.shutdown().await;
}
/// Only interfaces that may carry a larger Link MTU report their hardware MTU.
#[tokio::test]
async fn next_hop_hardware_mtu_only_for_mtu_capable_interfaces() {
let g = golden();
let dest = [0x22u8; 16];
for (name, upgrade) in [("udp", false), ("tcp", true)] {
let want = &g["next_hop_hw_mtu"][name];
let mtu = want["hw_mtu"].as_u64().unwrap() as u32;
let clear = if upgrade { mtu } else { 500 };
let r = rig(
mtu,
Some(InterfacePacketCapacity::new(clear, mtu, upgrade)),
&[(dest, 1)],
);
let (response_tx, response_rx) = oneshot::channel();
r.tx.send(TransportMessage::Rpc {
query: TransportQuery::GetNextHopHardwareMtu { dest },
response_tx,
})
.await
.unwrap();
let got = match response_rx.await.unwrap() {
TransportQueryResponse::IntResult(v) => v,
other => panic!("unexpected {other:?}"),
};
r.shutdown().await;
assert_eq!(got, want["result"].as_i64().unwrap_or(-1), "{name}");
}
}
@@ -0,0 +1,28 @@
"""Shared bootstrap for the scripts in this directory. Runs upstream RNS 1.6.0 only.
The upstream tree is RATSPEAK_UPSTREAM_RETICULUM_DIR if set, else upstream/Reticulum
in the workspace. Generators take an optional output directory (default: this directory).
"""
import os, subprocess, sys
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, *[".."] * 5))
WORKSPACE = os.path.dirname(REPO)
RNS_DIR = os.environ.get("RATSPEAK_UPSTREAM_RETICULUM_DIR") or os.path.join(WORKSPACE, "upstream", "Reticulum")
sys.path.insert(0, RNS_DIR)
import RNS
assert RNS.__version__ == "1.6.0", RNS.__version__
assert os.path.realpath(RNS.__file__).startswith(os.path.realpath(RNS_DIR) + os.sep), RNS.__file__
RNS_REF = "upstream Reticulum " + RNS.__version__
def repo_path(path):
"""Path relative to the repository root, as recorded in the goldens."""
return os.path.relpath(os.path.abspath(path), REPO).replace(os.sep, "/")
def rns_commit():
return subprocess.check_output(["git", "-C", RNS_DIR, "rev-parse", "HEAD"]).decode().strip()
def provenance(script):
return {"generator": repo_path(script), "rns_version": RNS.__version__, "rns_commit": rns_commit(), "rns_path": RNS_REF}
def out_path(name):
return os.path.join(sys.argv[1] if len(sys.argv) > 1 else HERE, name)
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""A local client's path response to a pending external path request, recorded by driving
upstream RNS 1.6.0 Transport in-process (no daemon): the announce-table entry and what
jobs() sends on two external interfaces (Transport.py:2626-2648, :906-950).
Usage: generate.py [OUT_DIR]
"""
import json, os, tempfile
from _common import RNS, provenance, out_path
T = RNS.Transport
RNS.log = lambda *a, **k: None
out = {"provenance": provenance(__file__)}
RNS.Reticulum.storagepath = tempfile.mkdtemp(prefix="local-client-")
RNS.Reticulum.cachepath = os.path.join(RNS.Reticulum.storagepath, "cache")
os.makedirs(os.path.join(RNS.Reticulum.cachepath, "announces"), exist_ok=True)
RNS.Reticulum._Reticulum__transport_enabled = False
T.USE_INBOUND_QUEUE = False; T.ready = True; T.identity = RNS.Identity()
from RNS.Interfaces.Interface import Interface as _Base
class _StubReticulum(RNS.Reticulum):
# Only supplies the private ic_* config fields (None -> upstream class defaults).
def __init__(self): pass
def __getattr__(self, n): return None
RNS.Reticulum._Reticulum__instance = _StubReticulum()
class Iface(_Base):
def __init__(self, name):
super().__init__()
self.name = name; self.mode = _Base.MODE_FULL; self.sent = []
self.OUT = True; self.IN = True; self.online = True; self.bitrate = 1_000_000
self.HW_MTU = RNS.Reticulum.MTU; self.announce_cap = 2.0
self.ifac_size = None; self.ifac_identity = None; self.announce_rate_target = None
self.announce_rate_grace = None; self.announce_rate_penalty = None; self.tunnel_id = None
self.reports_phy_stats = False
def should_ingress_limit(self): return False
def protocol_violation(self, d=None): raise RuntimeError(d)
def get_hash(self): return (self.name.encode() + bytes(32))[:32]
def process_outgoing(self, raw): self.sent.append(raw); self.txb += len(raw)
def __str__(self): return self.name
class SharedParent(Iface):
is_local_shared_instance = True
class LocalClientIface(Iface):
def __init__(self, name): super().__init__(name); self.parent_interface = SharedParent("shared-parent")
class Owner2:
is_connected_to_shared_instance = False
def _used_destination_data(self, h): pass
T.owner = Owner2()
T.packet_hashlist = set(); T.packet_hashlist_prev = set()
T.path_table = {}; T.announce_table = {}; T.path_states = {}; T.held_announces = {}
T.pending_local_path_requests = {}; T.announce_rate_table = {} if not hasattr(T, "announce_rate_table") else T.announce_rate_table
T.destinations = []; T.destinations_map = {}
ext_a = Iface("ext-a"); ext_b = Iface("ext-b"); lc = LocalClientIface("local-client")
T.interfaces = [ext_a, ext_b, lc]
T.local_client_interfaces = [lc]
T.cache = staticmethod(lambda *a, **k: None)
cident = RNS.Identity()
cdest = RNS.Destination(cident, RNS.Destination.IN, RNS.Destination.SINGLE, "t16", "localclient")
T.destinations = []; T.destinations_map = {}
pr_packet = cdest.announce(path_response=True, send=False)
pr_packet.pack()
pr_raw = pr_packet.raw
T.pending_local_path_requests[cdest.hash] = ext_a
T.inbound(pr_raw, lc)
entry = T.announce_table.get(cdest.hash)
out["local_pr"] = {
"announce_raw": pr_raw.hex(),
"destination_hash": cdest.hash.hex(),
"pending_cleared": cdest.hash not in T.pending_local_path_requests,
"announce_table_entry": None if entry is None else {
"retries": entry[2], "block_rebroadcasts": entry[7],
"attached_interface": None if entry[8] is None else str(entry[8])},
"sent_directly_to_waiting_iface_during_inbound": [r.hex() for r in ext_a.sent],
}
# Run the announce-retransmit part of jobs() once and capture packets on interfaces
ext_a.sent.clear(); ext_b.sent.clear(); lc.sent.clear()
T.announces_last_checked = 0
try:
T.jobs()
except Exception as e:
out["local_pr"]["jobs_error"] = repr(e)
def describe(raws):
res = []
for r in raws:
p = RNS.Packet(None, r); p.unpack()
res.append({"raw": r.hex(), "header_type": p.header_type, "context": p.context,
"packet_type": p.packet_type, "destination_hash": p.destination_hash.hex(),
"transport_id": None if p.transport_id is None else p.transport_id.hex()})
return res
out["local_pr"]["after_jobs"] = {"ext-a": describe(ext_a.sent), "ext-b": describe(ext_b.sent)}
out["local_pr"]["transport_identity_hash"] = T.identity.hash.hex()
out["consts"] = {"PATH_RESPONSE": RNS.Packet.PATH_RESPONSE, "NONE": RNS.Packet.NONE,
"HEADER_2": RNS.Packet.HEADER_2, "PATHFINDER_R": T.PATHFINDER_R}
out["local_pr"]["ext_a_sent_before_jobs"] = out["local_pr"].pop("sent_directly_to_waiting_iface_during_inbound")
with open(out_path("local_client_path_response.json"), "w") as f:
f.write("{\n" + ",\n".join(f" {json.dumps(k)}: {json.dumps(v)}" for k, v in out.items()) + "\n}\n")
os._exit(0)
@@ -0,0 +1,5 @@
{
"provenance": {"generator": "crates/rns-transport/tests/fixtures/local_client_path_response/generate.py", "rns_version": "1.6.0", "rns_commit": "cb1260891d1b6da8f6e9b21542c4f0cc0725cac4", "rns_path": "upstream Reticulum 1.6.0"},
"local_pr": {"announce_raw": "01009c190c86e279db5214ac5fa1d119c2710bac903c39aa02d203062e89e8bdee5001d294eaa15cd72f29f3c44c1851e3f15669d07a3463324e0ea35de5376b13fe0f27d80b5788c1c411967a3023fcea713ff34177a86279c1b8b65586fd551525006af37f54568117ee5933274f5f71deeb18a7de5bae274f347eb988f64e602b00afa229a390235d5f80aa0ee710d752538143c604d3b35567c7e2fa29ee644316cfb94207", "destination_hash": "9c190c86e279db5214ac5fa1d119c271", "pending_cleared": true, "announce_table_entry": {"retries": 1, "block_rebroadcasts": false, "attached_interface": null}, "after_jobs": {"ext-a": [{"raw": "5100e8f7fde90c979a85e17048e2f3e01f9a9c190c86e279db5214ac5fa1d119c27100ac903c39aa02d203062e89e8bdee5001d294eaa15cd72f29f3c44c1851e3f15669d07a3463324e0ea35de5376b13fe0f27d80b5788c1c411967a3023fcea713ff34177a86279c1b8b65586fd551525006af37f54568117ee5933274f5f71deeb18a7de5bae274f347eb988f64e602b00afa229a390235d5f80aa0ee710d752538143c604d3b35567c7e2fa29ee644316cfb94207", "header_type": 1, "context": 0, "packet_type": 1, "destination_hash": "9c190c86e279db5214ac5fa1d119c271", "transport_id": "e8f7fde90c979a85e17048e2f3e01f9a"}], "ext-b": [{"raw": "5100e8f7fde90c979a85e17048e2f3e01f9a9c190c86e279db5214ac5fa1d119c27100ac903c39aa02d203062e89e8bdee5001d294eaa15cd72f29f3c44c1851e3f15669d07a3463324e0ea35de5376b13fe0f27d80b5788c1c411967a3023fcea713ff34177a86279c1b8b65586fd551525006af37f54568117ee5933274f5f71deeb18a7de5bae274f347eb988f64e602b00afa229a390235d5f80aa0ee710d752538143c604d3b35567c7e2fa29ee644316cfb94207", "header_type": 1, "context": 0, "packet_type": 1, "destination_hash": "9c190c86e279db5214ac5fa1d119c271", "transport_id": "e8f7fde90c979a85e17048e2f3e01f9a"}]}, "transport_identity_hash": "e8f7fde90c979a85e17048e2f3e01f9a", "ext_a_sent_before_jobs": []},
"consts": {"PATH_RESPONSE": 11, "NONE": 0, "HEADER_2": 1, "PATHFINDER_R": 1}
}
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""HEADER_2 wrap goldens from upstream RNS 1.6.0.
Every expected value is what upstream Transport.outbound hands to a capture-only interface.
The upstream tree is RATSPEAK_UPSTREAM_RETICULUM_DIR if set, else upstream/Reticulum.
Run: python3 generate.py [out_dir] (writes outbound_wrap.json)
"""
import json, os, shutil, subprocess, sys, tempfile, time
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, *[".."] * 5))
WORKSPACE = os.path.dirname(REPO)
RNS_DIR = os.environ.get("RATSPEAK_UPSTREAM_RETICULUM_DIR") or os.path.join(WORKSPACE, "upstream", "Reticulum")
sys.path.insert(0, RNS_DIR)
import RNS
from RNS.Interfaces.Interface import Interface
assert RNS.__version__ == "1.6.0", RNS.__version__
OUT_DIR = sys.argv[1] if len(sys.argv) > 1 else HERE
cfg = tempfile.mkdtemp(prefix="ratspeak-outbound-rules-")
with open(os.path.join(cfg, "config"), "w") as f:
f.write("[reticulum]\n share_instance = No\n enable_transport = No\n\n[logging]\n loglevel = 0\n\n[interfaces]\n")
r = RNS.Reticulum(configdir=cfg, loglevel=0)
class Capture(Interface):
def __init__(self, name, bitrate=10_000_000, online=True, mode=Interface.MODE_FULL):
super().__init__()
self.name, self.bitrate, self.online, self.mode = name, bitrate, online, mode
self.IN = self.OUT = True
self.frames = []
def process_outgoing(self, data): self.frames.append(bytes(data))
def __str__(self): return "Capture[" + self.name + "]"
def reset(ifaces):
RNS.Transport.interfaces[:] = ifaces
RNS.Transport.path_table.clear()
RNS.Transport.path_requests.clear()
out = {"generator": os.path.relpath(os.path.abspath(__file__), REPO).replace(os.sep, "/"),
"rns_version": RNS.__version__,
"rns_commit": subprocess.check_output(["git", "-C", RNS_DIR, "rev-parse", "HEAD"]).decode().strip()}
dest = RNS.Destination(RNS.Identity(), RNS.Destination.OUT, RNS.Destination.SINGLE, "outbound", "rules")
nh = bytes.fromhex("ab" * 16)
# Transport.py:1622-1665: HEADER_2 wrap by path hops and shared-instance attachment.
wrap_cases = []
for hops, shared, header2 in [(0, False, False), (1, False, False), (1, True, False), (2, False, False), (2, True, False), (2, False, True), (1, False, True)]:
a = Capture("a"); reset([a])
now = time.time()
RNS.Transport.path_table[dest.hash] = [now, nh, hops, now + 3600, [], a, b"\x00" * 32, now]
r.is_connected_to_shared_instance = shared
p = RNS.Packet(dest, b"wrap", create_receipt=False)
p.pack()
packed = p.raw
if header2:
# Packet.pack cannot build a HEADER_2 DATA packet; _outbound reads only header_type here.
p.header_type = RNS.Packet.HEADER_2
res = RNS.Transport.outbound(p)
r.is_connected_to_shared_instance = False
wrap_cases.append({"path_hops": hops, "shared_client": shared, "already_header2": header2, "packed": packed.hex(),
"sent": bool(res), "emitted": [f.hex() for f in a.frames]})
out["wrap"] = wrap_cases
reset([])
with open(os.path.join(OUT_DIR, "outbound_wrap.json"), "w") as f:
def field(k, v):
if isinstance(v, list) and v and isinstance(v[0], dict):
return json.dumps(k) + ": [\n" + ",\n".join(json.dumps(c) for c in v) + "\n]"
return json.dumps(k) + ": " + json.dumps(v)
f.write("{\n" + ",\n".join(field(k, v) for k, v in out.items()) + "\n}\n")
shutil.rmtree(cfg, ignore_errors=True)
sys.stdout.flush()
os._exit(0)
@@ -0,0 +1,14 @@
{
"generator": "crates/rns-transport/tests/fixtures/outbound_wrap/generate.py",
"rns_version": "1.6.0",
"rns_commit": "cb1260891d1b6da8f6e9b21542c4f0cc0725cac4",
"wrap": [
{"path_hops": 0, "shared_client": false, "already_header2": false, "packed": "00001ad994394f8992f290ed361bb83e492b0077d823ee927df72e215d03bee8be896cee46d2a567455250528a672b69652f634e26ddda465e4d69d60e4185541fd7eff3769609ba6fb8ca3b4e83125fb6de268d6706e77cab11c9328936e483adc5fbaf8f61fa498a43f69dd4638af59d2986", "sent": true, "emitted": ["00001ad994394f8992f290ed361bb83e492b0077d823ee927df72e215d03bee8be896cee46d2a567455250528a672b69652f634e26ddda465e4d69d60e4185541fd7eff3769609ba6fb8ca3b4e83125fb6de268d6706e77cab11c9328936e483adc5fbaf8f61fa498a43f69dd4638af59d2986"]},
{"path_hops": 1, "shared_client": false, "already_header2": false, "packed": "00001ad994394f8992f290ed361bb83e492b008a0ee1751a70e094f9bd0ac8ea418ace44a263350d70859b8c23d89639ce363a5cb9f809bb57256a943210696b695f1fd38e62a8ea38f6b810164ca6501378f59c01bb6619be5c3bafb8c63fa941ee19393f6eec8932f542e12ac03831310043", "sent": true, "emitted": ["00001ad994394f8992f290ed361bb83e492b008a0ee1751a70e094f9bd0ac8ea418ace44a263350d70859b8c23d89639ce363a5cb9f809bb57256a943210696b695f1fd38e62a8ea38f6b810164ca6501378f59c01bb6619be5c3bafb8c63fa941ee19393f6eec8932f542e12ac03831310043"]},
{"path_hops": 1, "shared_client": true, "already_header2": false, "packed": "00001ad994394f8992f290ed361bb83e492b00cd2bbc6b4afd226caba6a46ee851f8a957a6b69b620ea23af9f2b0a605525808177b22a2208793846bb6979e9f42399abf536ce936168d3a82b7d75b7e878b110564753b06076744a62ad692c125cab7caab036ac196f77741c6c159f723f0a4", "sent": true, "emitted": ["5000abababababababababababababababab1ad994394f8992f290ed361bb83e492b00cd2bbc6b4afd226caba6a46ee851f8a957a6b69b620ea23af9f2b0a605525808177b22a2208793846bb6979e9f42399abf536ce936168d3a82b7d75b7e878b110564753b06076744a62ad692c125cab7caab036ac196f77741c6c159f723f0a4"]},
{"path_hops": 2, "shared_client": false, "already_header2": false, "packed": "00001ad994394f8992f290ed361bb83e492b0093f908aebbaa6b7a966e0ac95efcf6cee3869e857b34128121fedf5216f4202b219d57fe77744c0f2d1f0ae99c335d1c815c6c48d3a1e4542a371925f87121adefebfe218735d33aa7b85870713d7ee43990dbc3b96ff94aed580357758ebc78", "sent": true, "emitted": ["5000abababababababababababababababab1ad994394f8992f290ed361bb83e492b0093f908aebbaa6b7a966e0ac95efcf6cee3869e857b34128121fedf5216f4202b219d57fe77744c0f2d1f0ae99c335d1c815c6c48d3a1e4542a371925f87121adefebfe218735d33aa7b85870713d7ee43990dbc3b96ff94aed580357758ebc78"]},
{"path_hops": 2, "shared_client": true, "already_header2": false, "packed": "00001ad994394f8992f290ed361bb83e492b0068a6f0f9eb739c554ba45107fa8c4cc9633c0129b6cc6dede70e9ff0a0582a2cdafaa1baade31f935d161a37b93e11ed4a29387aba8df6fac49b0dbada8e21981d322f994d6111b3ca5a1248043a4c14b8e969254e64608d5e0ccf1b8052f2f3", "sent": true, "emitted": ["5000abababababababababababababababab1ad994394f8992f290ed361bb83e492b0068a6f0f9eb739c554ba45107fa8c4cc9633c0129b6cc6dede70e9ff0a0582a2cdafaa1baade31f935d161a37b93e11ed4a29387aba8df6fac49b0dbada8e21981d322f994d6111b3ca5a1248043a4c14b8e969254e64608d5e0ccf1b8052f2f3"]},
{"path_hops": 2, "shared_client": false, "already_header2": true, "packed": "00001ad994394f8992f290ed361bb83e492b009a1c98e9e2a712316c34d3f1fafc4efa7b0ce1dfcfb454633504cdffd0baa60c4518baae4c992e150c2d90d051a902cdd62150a7e8226bd5e654d088aa51eac34115a06621c567970dffd7b500ee9cdb1d34a9bb5f8beeb5e1b31c0e93b15f35", "sent": false, "emitted": []},
{"path_hops": 1, "shared_client": false, "already_header2": true, "packed": "00001ad994394f8992f290ed361bb83e492b0043945ac9f3f2ac4790db93e9427d4bd956c3891c2d9e903959c1a5019464136bb0d7371789dc09eb0064ff3316355d287b06d137b0a188dec53e8c93c0a2fe6d1f038d647ccf31c3290155e8bb8d61e2320c07d213bbf4e077d06b2ef855c7f7", "sent": true, "emitted": ["00001ad994394f8992f290ed361bb83e492b0043945ac9f3f2ac4790db93e9427d4bd956c3891c2d9e903959c1a5019464136bb0d7371789dc09eb0064ff3316355d287b06d137b0a188dec53e8c93c0a2fe6d1f038d647ccf31c3290155e8bb8d61e2320c07d213bbf4e077d06b2ef855c7f7"]}
]
}
@@ -0,0 +1,63 @@
"""Shared bootstrap for the path-request tag generators. Runs upstream RNS 1.6.0 only.
The upstream tree is RATSPEAK_UPSTREAM_RETICULUM_DIR if set, else upstream/Reticulum
in the workspace. Each generator takes an optional output directory (default: this directory).
"""
import os, sys, shutil, time, subprocess, tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, *[".."] * 5))
WORKSPACE = os.path.dirname(REPO)
RNS_DIR = os.environ.get("RATSPEAK_UPSTREAM_RETICULUM_DIR") or os.path.join(WORKSPACE, "upstream", "Reticulum")
sys.path.insert(0, RNS_DIR)
import RNS
from RNS.Interfaces.Interface import Interface
assert RNS.__version__ == "1.6.0", RNS.__version__
assert os.path.realpath(RNS.__file__).startswith(os.path.realpath(RNS_DIR) + os.sep), RNS.__file__
RNS_REF = "upstream Reticulum " + RNS.__version__
OUT_DIR = sys.argv[1] if len(sys.argv) > 1 else HERE
def repo_path(path):
"""Path relative to the repository root, as recorded in the goldens."""
return os.path.relpath(os.path.abspath(path), REPO).replace(os.sep, "/")
def rns_commit():
return subprocess.check_output(["git", "-C", RNS_DIR, "rev-parse", "HEAD"]).decode().strip()
def start(name, transport, **kwargs):
"""Boot upstream Reticulum in a fresh temp config dir. Returns (Transport, workdir)."""
workdir = tempfile.mkdtemp(prefix="ratspeak-%s-" % name)
with open(os.path.join(workdir, "config"), "w") as f:
f.write("[reticulum]\n enable_transport = %s\n share_instance = No\n\n[logging]\n loglevel = 2\n\n[interfaces]\n"
% ("Yes" if transport else "No"))
RNS.Reticulum(configdir=workdir, loglevel=2, **kwargs)
while not RNS.Transport.ready if hasattr(RNS.Transport, "ready") else False: time.sleep(0.05)
return RNS.Transport, workdir
def finish(workdir):
shutil.rmtree(workdir, ignore_errors=True)
sys.stdout.flush(); os._exit(0)
class Dummy(Interface):
"""Capture-only interface."""
def __init__(self, name, mode=None, recursive_prs=False):
super().__init__()
self.name = name; self.online = True; self.IN = True; self.OUT = True
self.bitrate = 10_000_000; self.mode = mode if mode is not None else Interface.MODE_FULL; self.HW_MTU = 500
self.sent = []
self.ifac_size = None; self.ifac_identity = None; self.ifac_netname = None; self.ifac_netkey = None
self.ingress_control = False; self.egress_control = False
self.announce_rate_target = None; self.announce_rate_grace = None; self.announce_rate_penalty = None
self.announces_from_internal = True; self.announces_to_internal = True; self.recursive_prs = recursive_prs
self._destination_cost = None; self._pr_cost = None; self.discoverable = False
def process_outgoing(self, data): self.sent.append(bytes(data)); self.txb += len(data)
def __str__(self): return "Dummy[" + self.name + "]"
def pr_packet(data):
"""Wrap a PR payload with upstream's own Packet packer (no reimplementation)."""
dst = RNS.Destination(None, RNS.Destination.OUT, RNS.Destination.PLAIN, RNS.Transport.APP_NAME, "path", "request")
p = RNS.Packet(dst, data, packet_type=RNS.Packet.DATA, transport_type=RNS.Transport.BROADCAST, header_type=RNS.Packet.HEADER_1)
p.pack()
return p.raw
def parse(raw):
p = RNS.Packet(None, raw); p.unpack(); return p
@@ -0,0 +1,29 @@
{
"STAMP_PRS": false,
"blocked_rediscovery": {
"a_payloads": [],
"b_payloads": [
"5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5eb8105df0dab6859a6bcb03939a33e6fcaf0cc9dfb1015e82195fa2b906752401"
],
"b_tags": [
"af0cc9dfb1015e82195fa2b906752401"
],
"blocked": "a",
"c_payloads": [
"5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5eb8105df0dab6859a6bcb03939a33e6fcaf0cc9dfb1015e82195fa2b906752401"
],
"c_tags": [
"af0cc9dfb1015e82195fa2b906752401"
],
"destination_hash": "5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e",
"payload_lens": [
48,
48
],
"same_tag_on_all_unblocked": true
},
"enable_transport": false,
"generator": "crates/rns-transport/tests/fixtures/path_request_tags/gen_blocked_rediscovery.py",
"rns_commit": "cb1260891d1b6da8f6e9b21542c4f0cc0725cac4",
"rns_version": "1.6.0"
}
@@ -0,0 +1,27 @@
"""Capture which tags upstream 1.6.0 puts on the blocked-interface rediscovery
fan-out (Transport.handle_disovery_path_requests, Transport.py:4058-4080)."""
import sys, os, json, time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _common import *
out = os.path.join(OUT_DIR, "blocked_rediscovery.json")
T, work = start("blocked-rediscovery", transport=False)
res = {"generator": repo_path(__file__), "rns_version": RNS.__version__, "rns_commit": rns_commit(),
"enable_transport": False, "STAMP_PRS": T.STAMP_PRS}
def prs(iface):
return [parse(s).data.hex() for s in iface.sent if parse(s).destination_hash == T.pr_destination_hash]
# Three plain interfaces, the first blocked.
a = Dummy("a"); b = Dummy("b"); c = Dummy("c")
T.interfaces[:] = [a, b, c]
dest2 = bytes.fromhex("5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e")
T.pending_discovery_prs.append((dest2, a))
T.handle_disovery_path_requests()
pa, pb, pc = prs(a), prs(b), prs(c)
res["blocked_rediscovery"] = {"destination_hash": dest2.hex(), "blocked": "a",
"a_payloads": pa, "b_payloads": pb, "c_payloads": pc,
"b_tags": [bytes.fromhex(p)[32:48].hex() for p in pb], "c_tags": [bytes.fromhex(p)[32:48].hex() for p in pc],
"payload_lens": [len(bytes.fromhex(p)) for p in pb + pc]}
res["blocked_rediscovery"]["same_tag_on_all_unblocked"] = len(set(res["blocked_rediscovery"]["b_tags"] + res["blocked_rediscovery"]["c_tags"])) == 1
json.dump(res, open(out, "w"), indent=1, sort_keys=True)
print(json.dumps(res, indent=1)); finish(work)
@@ -0,0 +1,69 @@
"""Capture upstream 1.6.0 path-request tag memory:
duplicate tags have no time expiry, the tag set rotates into a previous generation once it
holds more than max_pr_tags entries at a jobs pass (Transport.py:990-994)."""
import sys, os, json, time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _common import *
out = os.path.join(OUT_DIR, "tag_memory.json")
T, work = start("tag-memory", transport=False)
rx = Dummy("rx")
T.interfaces.append(rx)
local = RNS.Destination(RNS.Identity.from_bytes(bytes([0x52]) * 64), RNS.Destination.IN, RNS.Destination.SINGLE, "prw", "tags")
answers = []
local.announce = lambda *a, **k: answers.append(k.get("tag"))
real_time = time.time
def at(offset):
time.time = lambda: real_time() + offset
def jobs():
T.tables_last_culled = 0; T.pending_prs_last_checked = 0
T.jobs()
def answered(tag):
T.packet_hashlist.swap(); T.packet_hashlist.swap() # clear both generations so only the tag gate decides
n = len(answers)
T.inbound(pr_packet(local.hash + tag), rx)
time.sleep(0.3)
return len(answers) > n
res = {"generator": repo_path(__file__), "rns_version": RNS.__version__, "rns_commit": rns_commit(),
"max_pr_tags": T.max_pr_tags,
"local_destination_hash": local.hash.hex()}
cases = []
tag = bytes([0x02]) * 16
cases.append({"case": "first_request", "tag": tag.hex(), "answered": answered(tag)})
at(121.0); jobs()
cases.append({"case": "replay_after_121s_and_jobs", "tag": tag.hex(), "answered": answered(tag)})
time.time = real_time
def rotation(filler, label):
T.discovery_pr_tags = set(); T.discovery_pr_tags_prev = set()
oldest = bytes([0xEE]) * 16
T.discovery_pr_tags.add(local.hash + oldest)
for i in range(filler):
T.discovery_pr_tags.add(bytes([0xA0]) * 28 + i.to_bytes(4, "big"))
jobs()
r = {"case": label, "seeded_tags": filler + 1, "current_after_jobs": len(T.discovery_pr_tags),
"prev_after_jobs": len(T.discovery_pr_tags_prev), "tag": oldest.hex()}
r["answered"] = answered(oldest)
return r
cases.append(rotation(T.max_pr_tags - 1, "at_max_no_rotation"))
cases.append(rotation(T.max_pr_tags, "above_max_rotates"))
# Second rotation forgets the first generation.
T.discovery_pr_tags = set(); T.discovery_pr_tags_prev = set()
oldest = bytes([0xEF]) * 16
T.discovery_pr_tags.add(local.hash + oldest)
for i in range(T.max_pr_tags): T.discovery_pr_tags.add(bytes([0xA1]) * 28 + i.to_bytes(4, "big"))
jobs()
for i in range(T.max_pr_tags + 1): T.discovery_pr_tags.add(bytes([0xA2]) * 28 + i.to_bytes(4, "big"))
jobs()
cases.append({"case": "second_rotation_forgets", "tag": oldest.hex(), "answered": answered(oldest)})
res["tag_cases"] = cases
with open(out, "w") as f:
f.write("{\n" + ",\n".join(
(" %s:[\n%s\n ]" % (json.dumps(k), ",\n".join(" " + json.dumps(c, sort_keys=True) for c in v)))
if isinstance(v, list) else " %s:%s" % (json.dumps(k), json.dumps(v))
for k, v in sorted(res.items())) + "\n}\n")
print(open(out).read()); finish(work)
@@ -0,0 +1,14 @@
{
"generator":"crates/rns-transport/tests/fixtures/path_request_tags/gen_tag_memory.py",
"local_destination_hash":"2b4dc9913aea9a56f3af1a8f710b49ef",
"max_pr_tags":16000,
"rns_commit":"cb1260891d1b6da8f6e9b21542c4f0cc0725cac4",
"rns_version":"1.6.0",
"tag_cases":[
{"answered": true, "case": "first_request", "tag": "02020202020202020202020202020202"},
{"answered": false, "case": "replay_after_121s_and_jobs", "tag": "02020202020202020202020202020202"},
{"answered": false, "case": "at_max_no_rotation", "current_after_jobs": 16000, "prev_after_jobs": 0, "seeded_tags": 16000, "tag": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"},
{"answered": false, "case": "above_max_rotates", "current_after_jobs": 0, "prev_after_jobs": 16001, "seeded_tags": 16001, "tag": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"},
{"answered": true, "case": "second_rotation_forgets", "tag": "efefefefefefefefefefefefefefefef"}
]
}
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Path-table lifecycle goldens from upstream RNS.
Drives upstream Transport.jobs() and Transport.outbound() on synthetic tables
and records what upstream leaves in them: never-used linger on a leaf and on a
transport node, the never-used pool cap, the outbound
use mark and the rediscovery after a link that never established. Every
expected value is read back from upstream's own tables.
Usage: generate.py [OUT] (default: path_table_lifecycle.json beside this file)
"""
import json, os, subprocess, sys, time
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, *[".."] * 5))
WORKSPACE = os.path.dirname(REPO)
RNS_DIR = os.environ.get("RATSPEAK_UPSTREAM_RETICULUM_DIR") or os.path.join(WORKSPACE, "upstream", "Reticulum")
sys.path.insert(0, RNS_DIR)
import RNS
from RNS.Transport import Transport
from RNS.Interfaces.Interface import Interface
assert RNS.__version__ == "1.6.0", RNS.__version__
T = sys.modules["RNS.Transport"]
RNS.loglevel = RNS.LOG_CRITICAL
OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "path_table_lifecycle.json")
class FakeIface:
def __init__(self, name, bitrate, mode=Interface.MODE_FULL):
self.name = name; self.bitrate = bitrate; self.mode = mode; self.sent = []
self.ifac_identity = None; self.OUT = True; self.IN = True; self.FWD = False; self.RPT = False
self.announce_queue = []; self.tunnel_id = None; self.phy_keepalive = False; self.online = True
def process_outgoing(self, raw): self.sent.append(raw)
def __str__(self): return f"FakeIface[{self.name}]"
class FakeOwner:
def __init__(self, shared_client=False): self.is_connected_to_shared_instance = shared_client
def reset(now, ifaces, linger, transport=False, shared_client=False):
for table in ("path_table", "path_states", "reverse_table", "link_table", "tunnels", "path_requests",
"inflight_path_requests", "discovery_path_requests", "pending_links_map", "active_links_map",
"announce_table", "held_announces", "pending_local_path_requests"):
setattr(Transport, table, {})
Transport.pending_links = []; Transport.active_links = []; Transport.receipts = []
Transport.interfaces = list(ifaces); Transport.announce_cache = None; Transport.mgmt_destinations = []
Transport.owner = FakeOwner(shared_client); Transport.unused_path_linger = linger
RNS.Reticulum.transport_enabled = staticmethod(lambda: transport)
Transport.pending_discovery_prs.clear()
# Only the table cull and link checks run; every other job is "just done".
for attr in ("links_last_checked", "receipts_last_checked", "announces_last_checked",
"pending_prs_last_checked", "cache_last_cleaned", "destinations_last_cleaned",
"rate_table_last_culled", "kd_last_flush", "ac_last_flush", "interface_last_jobs",
"last_mgmt_announce", "blackhole_last_checked", "last_collect", "last_mem_trim"):
setattr(Transport, attr, now + 3600)
Transport.mem_dirty = False; Transport.should_collect = False
Transport.tables_last_culled = 0.0; Transport.pool_size_last_checked = 0.0
Transport.handle_disovery_path_requests = staticmethod(lambda: None)
def path_entry(ts, expires, iface, used, hops=1):
return [ts, None, hops, expires, [], iface, None, used]
def h16(i):
return i.to_bytes(16, "big")
WEEK = Transport.PATH_TIMEOUT
BITRATES = {"fast": 10_000_000, "slow": 9600, "zero": 0, "none": None, "edge": 25000}
def linger(linger_s, transport):
L = linger_s
specs = [("fast_young", "fast", L - 60, None), ("fast_old", "fast", L + 1, None),
("fast_old_used", "fast", L * 20, 5.0), ("slow_past_x1", "slow", L + 60, None),
("slow_past_x10", "slow", L * 10 + 1, None), ("slow_inside_x10", "slow", L * 10 - 60, None),
("zero_bitrate_old", "zero", L + 1, None), ("none_bitrate_old", "none", L + 1, None),
("edge_bitrate_old", "edge", L + 1, None), ("expired_used", "fast", 60, 5.0)]
ifaces = {k: FakeIface(k, b) for k, b in BITRATES.items()}
now = time.time()
reset(now, ifaces.values(), linger_s, transport)
entries = []
for i, (label, kind, age, used_age) in enumerate(specs):
ts = now - age
exp = (now - 10) if label == "expired_used" else ts + WEEK
used = 0 if used_age is None else now - used_age
Transport.path_table[h16(i + 1)] = path_entry(ts, exp, ifaces[kind], used)
entries.append({"label": label, "iface": kind, "age_s": age, "expires_rel_s": exp - now,
"used_age_s": used_age})
Transport.jobs()
for i, e in enumerate(entries):
e["survives"] = h16(i + 1) in Transport.path_table
return {"transport_enabled": transport, "linger_s": linger_s, "entries": entries}
POOL = {"count": 2100, "slow_every": 3, "expiry_base_s": 3600, "expiry_step_s": 240, "expiry_mod": 700,
"used_count": 5}
def pool_inputs(i):
kind = "slow" if i % POOL["slow_every"] == 0 else "fast"
return kind, POOL["expiry_base_s"] + ((i * 7919) % POOL["expiry_mod"]) * POOL["expiry_step_s"]
def pool():
ifaces = {"fast": FakeIface("fast", 10_000_000), "slow": FakeIface("slow", 9600)}
now = time.time()
reset(now, ifaces.values(), Transport.UNUSED_PATH_LINGER, True)
for i in range(POOL["count"]):
kind, exp_rel = pool_inputs(i)
Transport.path_table[h16(i + 1)] = path_entry(now - 30, now + exp_rel, ifaces[kind], 0)
for j in range(POOL["used_count"]):
Transport.path_table[h16(POOL["count"] + j + 1)] = path_entry(now - 30, now + 60, ifaces["fast"], now - 1)
Transport.jobs()
removed = [i for i in range(POOL["count"]) if h16(i + 1) not in Transport.path_table]
used_survive = all(h16(POOL["count"] + j + 1) in Transport.path_table for j in range(POOL["used_count"]))
return dict(POOL, removed=removed, used_survive=used_survive)
def outbound(hops):
a = FakeIface("a", 10_000_000)
now = time.time()
reset(now, [a], Transport.UNUSED_PATH_LINGER, False)
Transport.identity = RNS.Identity()
RNS.Reticulum.get_instance = staticmethod(lambda: Transport.owner)
dest = RNS.Destination(RNS.Identity(), RNS.Destination.OUT, RNS.Destination.SINGLE, "pathlifecycle", "out")
ts0 = now - 3600.0
Transport.path_table[dest.hash] = [ts0, h16(9) if hops > 1 else None, hops, ts0 + WEEK, [], a, None, 0]
pkt = RNS.Packet(dest, b"hello", create_receipt=False); pkt.pack()
before = time.time()
Transport.outbound(pkt)
e = Transport.path_table[dest.hash]
return {"hops": hops, "age_s": 3600.0, "sent": len(a.sent) == 1,
"timestamp_unchanged": e[T.IDX_PT_TIMESTAMP] == ts0, "expires_unchanged": e[T.IDX_PT_EXPIRES] == ts0 + WEEK,
"used_is_send_time": e[T.IDX_PT_USED] >= before}
class FakeLink:
def __init__(self, h, lid):
self.status = RNS.Link.CLOSED; self.destination = type("D", (), {"hash": h})(); self.link_id = lid
def pending_link(transport, shared_client, last_request_age):
a = FakeIface("a", 10_000_000)
now = time.time()
reset(now, [a], Transport.UNUSED_PATH_LINGER_LEAF, transport, shared_client)
Transport.links_last_checked = 0.0
dh = h16(7)
Transport.path_table[dh] = path_entry(now - 10, now + WEEK, a, now - 1)
if last_request_age is not None:
Transport.path_requests[dh] = now - last_request_age
link = FakeLink(dh, h16(8))
Transport.pending_links.append(link); Transport.pending_links_map[link.link_id] = link
Transport.jobs()
return {"transport_enabled": transport, "shared_client": shared_client, "last_request_age_s": last_request_age,
"path_kept": dh in Transport.path_table,
"rediscovery_queued": [e[0] for e in Transport.pending_discovery_prs] == [dh]}
commit = subprocess.run(["git", "-C", RNS_DIR, "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
out = {
"provenance": {"generator": "crates/rns-transport/tests/fixtures/path_table_lifecycle/generate.py",
"upstream": "Reticulum", "version": RNS.__version__, "commit": commit},
"linger_leaf": linger(Transport.UNUSED_PATH_LINGER_LEAF, False),
"linger_transport": linger(Transport.UNUSED_PATH_LINGER, True),
"pool_cap": pool(),
"outbound": [outbound(1), outbound(3)],
"pending_link_rediscovery": [pending_link(False, False, None), pending_link(False, False, 10),
pending_link(False, False, 25), pending_link(False, True, None),
pending_link(True, False, None)],
}
with open(OUT, "w") as f:
f.write("{\n")
items = list(out.items())
for n, (k, v) in enumerate(items):
if isinstance(v, dict) and "entries" in v:
body = json.dumps({kk: vv for kk, vv in v.items() if kk != "entries"})[:-1]
rows = ",\n ".join(json.dumps(e) for e in v["entries"])
f.write(f' "{k}": {body}, "entries": [\n {rows}\n ]}}')
elif isinstance(v, list):
rows = ",\n ".join(json.dumps(e) for e in v)
f.write(f' "{k}": [\n {rows}\n ]')
else:
f.write(f' "{k}": {json.dumps(v)}')
f.write(",\n" if n < len(items) - 1 else "\n")
f.write("}\n")
print("wrote", OUT)
os._exit(0)
@@ -0,0 +1,39 @@
{
"provenance": {"generator": "crates/rns-transport/tests/fixtures/path_table_lifecycle/generate.py", "upstream": "Reticulum", "version": "1.6.0", "commit": "cb1260891d1b6da8f6e9b21542c4f0cc0725cac4"},
"linger_leaf": {"transport_enabled": false, "linger_s": 720, "entries": [
{"label": "fast_young", "iface": "fast", "age_s": 660, "expires_rel_s": 604140.0, "used_age_s": null, "survives": true},
{"label": "fast_old", "iface": "fast", "age_s": 721, "expires_rel_s": 604079.0, "used_age_s": null, "survives": false},
{"label": "fast_old_used", "iface": "fast", "age_s": 14400, "expires_rel_s": 590400.0, "used_age_s": 5.0, "survives": true},
{"label": "slow_past_x1", "iface": "slow", "age_s": 780, "expires_rel_s": 604020.0, "used_age_s": null, "survives": true},
{"label": "slow_past_x10", "iface": "slow", "age_s": 7201, "expires_rel_s": 597599.0, "used_age_s": null, "survives": false},
{"label": "slow_inside_x10", "iface": "slow", "age_s": 7140, "expires_rel_s": 597660.0, "used_age_s": null, "survives": true},
{"label": "zero_bitrate_old", "iface": "zero", "age_s": 721, "expires_rel_s": 604079.0, "used_age_s": null, "survives": false},
{"label": "none_bitrate_old", "iface": "none", "age_s": 721, "expires_rel_s": 604079.0, "used_age_s": null, "survives": false},
{"label": "edge_bitrate_old", "iface": "edge", "age_s": 721, "expires_rel_s": 604079.0, "used_age_s": null, "survives": false},
{"label": "expired_used", "iface": "fast", "age_s": 60, "expires_rel_s": -10.0, "used_age_s": 5.0, "survives": false}
]},
"linger_transport": {"transport_enabled": true, "linger_s": 6300.0, "entries": [
{"label": "fast_young", "iface": "fast", "age_s": 6240.0, "expires_rel_s": 598560.0, "used_age_s": null, "survives": true},
{"label": "fast_old", "iface": "fast", "age_s": 6301.0, "expires_rel_s": 598499.0, "used_age_s": null, "survives": false},
{"label": "fast_old_used", "iface": "fast", "age_s": 126000.0, "expires_rel_s": 478800.0, "used_age_s": 5.0, "survives": true},
{"label": "slow_past_x1", "iface": "slow", "age_s": 6360.0, "expires_rel_s": 598440.0, "used_age_s": null, "survives": true},
{"label": "slow_past_x10", "iface": "slow", "age_s": 63001.0, "expires_rel_s": 541799.0, "used_age_s": null, "survives": false},
{"label": "slow_inside_x10", "iface": "slow", "age_s": 62940.0, "expires_rel_s": 541860.0, "used_age_s": null, "survives": true},
{"label": "zero_bitrate_old", "iface": "zero", "age_s": 6301.0, "expires_rel_s": 598499.0, "used_age_s": null, "survives": false},
{"label": "none_bitrate_old", "iface": "none", "age_s": 6301.0, "expires_rel_s": 598499.0, "used_age_s": null, "survives": false},
{"label": "edge_bitrate_old", "iface": "edge", "age_s": 6301.0, "expires_rel_s": 598499.0, "used_age_s": null, "survives": false},
{"label": "expired_used", "iface": "fast", "age_s": 60, "expires_rel_s": -10.0, "used_age_s": 5.0, "survives": false}
]},
"pool_cap": {"count": 2100, "slow_every": 3, "expiry_base_s": 3600, "expiry_step_s": 240, "expiry_mod": 700, "used_count": 5, "removed": [16, 32, 64, 80, 179, 211, 227, 259, 275, 358, 374, 406, 422, 553, 569, 601, 617, 700, 716, 748, 764, 796, 895, 911, 943, 959, 1058, 1090, 1106, 1138, 1237, 1253, 1285, 1301, 1400, 1432, 1448, 1480, 1496, 1579, 1595, 1627, 1643, 1675, 1774, 1790, 1822, 1838, 1937, 1969, 1985, 2017], "used_survive": true},
"outbound": [
{"hops": 1, "age_s": 3600.0, "sent": true, "timestamp_unchanged": true, "expires_unchanged": true, "used_is_send_time": true},
{"hops": 3, "age_s": 3600.0, "sent": true, "timestamp_unchanged": true, "expires_unchanged": true, "used_is_send_time": true}
],
"pending_link_rediscovery": [
{"transport_enabled": false, "shared_client": false, "last_request_age_s": null, "path_kept": false, "rediscovery_queued": true},
{"transport_enabled": false, "shared_client": false, "last_request_age_s": 10, "path_kept": false, "rediscovery_queued": false},
{"transport_enabled": false, "shared_client": false, "last_request_age_s": 25, "path_kept": false, "rediscovery_queued": true},
{"transport_enabled": false, "shared_client": true, "last_request_age_s": null, "path_kept": false, "rediscovery_queued": false},
{"transport_enabled": true, "shared_client": false, "last_request_age_s": null, "path_kept": true, "rediscovery_queued": false}
]
}
@@ -0,0 +1,28 @@
"""Shared bootstrap for the scripts in this directory. Runs upstream RNS 1.6.0 only.
The upstream tree is RATSPEAK_UPSTREAM_RETICULUM_DIR if set, else upstream/Reticulum
in the workspace. Generators take an optional output directory (default: this directory).
"""
import os, subprocess, sys
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, *[".."] * 5))
WORKSPACE = os.path.dirname(REPO)
RNS_DIR = os.environ.get("RATSPEAK_UPSTREAM_RETICULUM_DIR") or os.path.join(WORKSPACE, "upstream", "Reticulum")
sys.path.insert(0, RNS_DIR)
import RNS
assert RNS.__version__ == "1.6.0", RNS.__version__
assert os.path.realpath(RNS.__file__).startswith(os.path.realpath(RNS_DIR) + os.sep), RNS.__file__
RNS_REF = "upstream Reticulum " + RNS.__version__
def repo_path(path):
"""Path relative to the repository root, as recorded in the goldens."""
return os.path.relpath(os.path.abspath(path), REPO).replace(os.sep, "/")
def rns_commit():
return subprocess.check_output(["git", "-C", RNS_DIR, "rev-parse", "HEAD"]).decode().strip()
def provenance(script):
return {"generator": repo_path(script), "rns_version": RNS.__version__, "rns_commit": rns_commit(), "rns_path": RNS_REF}
def out_path(name):
return os.path.join(sys.argv[1] if len(sys.argv) > 1 else HERE, name)
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Upstream Transport defaults from upstream RNS 1.6.0 code with no Reticulum instance: the
default receipt timeout (Packet.py:427-433) and next_hop_interface_hw_mtu for UDP and TCP next
hops (Transport.py:3516-3523).
Usage: generate.py [OUT_DIR]
"""
import json, os, time
from _common import RNS, provenance, out_path
from RNS.Interfaces.UDPInterface import UDPInterface
from RNS.Interfaces.TCPInterface import TCPClientInterface
T = RNS.Transport
RNS.loglevel = RNS.LOG_CRITICAL
class Owner: is_connected_to_shared_instance = False
T.owner = Owner(); T.identity = RNS.Identity()
def stub(cls, bitrate, hw_mtu):
i = object.__new__(cls); i.name = cls.__name__; i.bitrate = bitrate; i.HW_MTU = hw_mtu
return i
def install_path(dest, iface, hops):
now = time.time()
T.path_table[dest] = [now, os.urandom(16), hops, now + 3600, [], iface, os.urandom(32), now]
udp_dest, tcp_dest = bytes([0x21]) * 16, bytes([0x22]) * 16
install_path(udp_dest, stub(UDPInterface, 10_000_000, 1064), 1)
install_path(tcp_dest, stub(TCPClientInterface, 10_000_000, 262144), 1)
hw_mtu = {"udp": {"hw_mtu": 1064, "result": T.next_hop_interface_hw_mtu(udp_dest)},
"tcp": {"hw_mtu": 262144, "result": T.next_hop_interface_hw_mtu(tcp_dest)}}
class FakeReticulum:
is_connected_to_shared_instance = False
def get_first_hop_timeout(self, h): return T.first_hop_timeout(h)
RNS.Reticulum.get_instance = staticmethod(lambda: FakeReticulum())
def receipt_timeout(dest_hash):
od = RNS.Destination(RNS.Identity(), RNS.Destination.OUT, RNS.Destination.SINGLE, "tad", "receipt")
od.hash = dest_hash
p = RNS.Packet(od, b"x"); p.pack()
return RNS.PacketReceipt(p).timeout
receipt_dest = bytes([0x47]) * 16
install_path(receipt_dest, stub(TCPClientInterface, 10_000_000, 262144), 1)
receipt = {"bitrate": 10_000_000, "hops": 1, "timeout": receipt_timeout(receipt_dest),
"no_path_timeout": receipt_timeout(bytes([0x48]) * 16)}
out = {"provenance": provenance(__file__), "next_hop_hw_mtu": hw_mtu, "receipt": receipt}
with open(out_path("transport_api_defaults.json"), "w") as f:
f.write("{\n" + ",\n".join(f" {json.dumps(k)}: {json.dumps(v)}" for k, v in out.items()) + "\n}\n")
os._exit(0)
@@ -0,0 +1,5 @@
{
"provenance": {"generator": "crates/rns-transport/tests/fixtures/transport_api_defaults/generate.py", "rns_version": "1.6.0", "rns_commit": "cb1260891d1b6da8f6e9b21542c4f0cc0725cac4", "rns_path": "upstream Reticulum 1.6.0"},
"next_hop_hw_mtu": {"udp": {"hw_mtu": 1064, "result": null}, "tcp": {"hw_mtu": 262144, "result": 262144}},
"receipt": {"bitrate": 10000000, "hops": 1, "timeout": 12.000399999999999, "no_path_timeout": 774}
}