interfaces: open every TCP, Backbone and I2P client connection with a tunnel synthesis

This commit is contained in:
DeFiDude committed 2026-10-24 23:29:20 -06:00
1 parent b774544cbb
commit 6e412dc9e0
11 files changed
+694 -22

No files matched your search

+1
View File
@@ -14,6 +14,7 @@
- After a restart, a hub no longer gives a previous client's saved paths to a new client that reuses its interface name, and it keeps saved tunnels that had no live interface, as in Python Reticulum.
- Transport hubs now accept tunnel synthesis, so a Python client that reconnects gets its paths back without announcing again, and losing a tunnel's interface no longer drops paths the hub learned through other interfaces, as in Python Reticulum.
- PLAIN and GROUP packets that arrive from more than one hop away, and announces typed PLAIN or GROUP, are dropped before deduplication, as in Python Reticulum.
- TCP, Backbone and I2P client interfaces open every connection with a tunnel synthesis, so a transport hub restores their paths after a reconnect, and traffic queued while a connection was down is dropped when it returns, as in Python Reticulum.
## 1.4.0 - 2026-10-12
+7
View File
@@ -49,11 +49,18 @@ accepted clients report as `parent_id`. `InterfaceEntry::parent_id` carries it
into transport; set it from `InterfaceHandle::parent_id`. Persisted tunnels now
load unbound into the tunnel table, so `TransportActor::pending_tunnel_entries`
is gone.
`TunnelSynthesisData::unpack` accepts exactly 176 bytes. Announces join the
tunnel named by their interface's latest synthesis, which `handle_tunnel` and
`TunnelTable::insert` record and `TunnelTable::void_interface` clears; writing
`interface_id` directly no longer rebinds an interface.
`TcpClientConfig`, `BackboneClientConfig` and `I2PClientConfig` gain
`tunnel_identity`. With a `TunnelIdentity` set, the client opens every
connection with a tunnel synthesis signed by it; the runtime sets it from
`ReticulumHandle::transport_identity`. Build these configs with `new` so the
field defaults to `None`.
The compatibility floor remains unchanged. Its cumulative exact-removal list
also retains the already-reviewed [1.3 migration](1.3.md) for discovery ownership
and nullable coordinates; it is not reclassified as a new 1.4 change. Additive
+8
View File
@@ -121,6 +121,7 @@ pub rns_interface::backbone::BackboneClientConfig::name: alloc::string::String
pub rns_interface::backbone::BackboneClientConfig::prefer_ipv6: bool
pub rns_interface::backbone::BackboneClientConfig::target_host: alloc::string::String
pub rns_interface::backbone::BackboneClientConfig::target_port: u16
pub rns_interface::backbone::BackboneClientConfig::tunnel_identity: core::option::Option<rns_interface::traits::TunnelIdentity>
impl rns_interface::backbone::BackboneClientConfig
pub fn rns_interface::backbone::BackboneClientConfig::new(&str, &str, u16) -> Self
pub struct rns_interface::backbone::BackboneServerConfig
@@ -454,6 +455,7 @@ pub rns_interface::i2p::I2PClientConfig::peer_destination: alloc::string::String
pub rns_interface::i2p::I2PClientConfig::reconnect_delay: u64
pub rns_interface::i2p::I2PClientConfig::sam_host: alloc::string::String
pub rns_interface::i2p::I2PClientConfig::sam_port: u16
pub rns_interface::i2p::I2PClientConfig::tunnel_identity: core::option::Option<rns_interface::traits::TunnelIdentity>
impl rns_interface::i2p::I2PClientConfig
pub fn rns_interface::i2p::I2PClientConfig::new(&str, &str) -> Self
pub struct rns_interface::i2p::I2PServerConfig
@@ -1160,6 +1162,7 @@ pub rns_interface::tcp::TcpClientConfig::mode: rns_interface::traits::InterfaceM
pub rns_interface::tcp::TcpClientConfig::name: alloc::string::String
pub rns_interface::tcp::TcpClientConfig::target_host: alloc::string::String
pub rns_interface::tcp::TcpClientConfig::target_port: u16
pub rns_interface::tcp::TcpClientConfig::tunnel_identity: core::option::Option<rns_interface::traits::TunnelIdentity>
impl rns_interface::tcp::TcpClientConfig
pub fn rns_interface::tcp::TcpClientConfig::new(&str, &str, u16) -> Self
pub struct rns_interface::tcp::TcpInterfaceState
@@ -1236,6 +1239,11 @@ pub rns_interface::traits::InterfaceHandle::read_task: tokio::runtime::task::joi
pub rns_interface::traits::InterfaceHandle::rxb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
pub rns_interface::traits::InterfaceHandle::tx: tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>
pub rns_interface::traits::InterfaceHandle::txb: core::option::Option<alloc::sync::Arc<core::sync::atomic::AtomicU64>>
pub struct rns_interface::traits::TunnelIdentity(pub alloc::sync::Arc<rns_identity::identity::Identity>)
impl rns_interface::traits::TunnelIdentity
pub fn rns_interface::traits::TunnelIdentity::synthesis(&self, &str) -> core::option::Option<bytes::bytes::Bytes>
impl core::fmt::Debug for rns_interface::traits::TunnelIdentity
pub fn rns_interface::traits::TunnelIdentity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub const rns_interface::traits::AR_FREQ_DECAY: f64
pub const rns_interface::traits::AR_MINFREQ_HZ: f64
pub const rns_interface::traits::DEFAULT_AR_GRACE: u32
+2 -2
View File
@@ -78,8 +78,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-interface.txt",
"itemCount": 1420,
"sha256": "5e88a0e267d37a3d3ec8552749333841cd298f41362701ef293694b9d14e483a"
"itemCount": 1428,
"sha256": "e34b67309d70de46edbcec1941517a5602603bdf76a1944e249bd3fa95bf2146"
},
{
"name": "rns-runtime",
+51 -2
View File
@@ -19,7 +19,8 @@ use tokio::sync::mpsc;
use crate::hdlc;
use crate::socket_tuning::{iface_addr_for, set_keepalive_tuned, set_socket_buffers};
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection, python_host,
};
use rns_transport::messages::{
InboundPacket, InterfaceInspectionSnapshot, InterfaceInspectionSource, TransportMessage,
@@ -103,6 +104,8 @@ pub struct BackboneClientConfig {
pub connect_timeout_secs: u64,
pub max_reconnect_tries: Option<usize>,
pub mode: InterfaceMode,
/// Signs a tunnel synthesis for every connection; `None` sends none.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl BackboneClientConfig {
@@ -115,8 +118,19 @@ impl BackboneClientConfig {
connect_timeout_secs: INITIAL_CONNECT_TIMEOUT,
max_reconnect_tries: None,
mode: InterfaceMode::Full,
tunnel_identity: None,
}
}
/// Python `str(BackboneClientInterface)` (BackboneInterface.py:1114-1117).
fn python_name(&self) -> String {
format!(
"BackboneInterface[{}/{}:{}]",
self.name,
python_host(&self.target_host),
self.target_port
)
}
}
#[derive(Debug, Clone, Copy)]
@@ -690,9 +704,11 @@ pub async fn spawn_backbone_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let max_tries = config.max_reconnect_tries;
let mut tries: usize = 0;
let mut connected_before = false;
loop {
let target = match tokio::time::timeout(
@@ -770,8 +786,21 @@ pub async fn spawn_backbone_client(
};
tune_stream(&stream);
online2.store(true, Ordering::SeqCst);
tries = 0;
// Python synthesizes on every connection (BackboneInterface.py:922,
// :1019).
let synthesis = config
.tunnel_identity
.as_ref()
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(
&rx,
std::mem::replace(&mut connected_before, true),
&transport_tx,
synthesis,
&online2,
)
.await;
let c_online = Arc::new(AtomicBool::new(true));
let (reader, writer) = stream.into_split();
@@ -849,6 +878,26 @@ mod tests {
use super::*;
use std::net::{Ipv4Addr, SocketAddr};
#[test]
fn client_python_names_match_python() {
// Python 1.5.5 `str()` output for these interfaces.
for (host, expected) in [
(
"10.0.0.1",
"BackboneInterface[Golden Backbone/10.0.0.1:4243]",
),
(
"fd00::1",
"BackboneInterface[Golden Backbone/[fd00::1]:4243]",
),
] {
assert_eq!(
BackboneClientConfig::new("Golden Backbone", host, 4243).python_name(),
expected
);
}
}
#[derive(Clone)]
struct TestClock {
now: Arc<Mutex<Duration>>,
+36 -2
View File
@@ -13,7 +13,8 @@ use tokio::sync::mpsc;
use crate::hdlc;
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
@@ -318,6 +319,8 @@ pub struct I2PClientConfig {
pub max_reconnect_tries: Option<usize>,
pub reconnect_delay: u64,
pub mode: InterfaceMode,
/// Signs a tunnel synthesis for every connection; `None` sends none.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl I2PClientConfig {
@@ -330,8 +333,14 @@ impl I2PClientConfig {
max_reconnect_tries: None,
reconnect_delay: RECONNECT_WAIT,
mode: InterfaceMode::Full,
tunnel_identity: None,
}
}
/// Python `str(I2PInterfacePeer)` (I2PInterface.py:714-715).
fn python_name(&self) -> String {
format!("I2PInterfacePeer[{}]", self.name)
}
}
/// Connect via SAM streaming session, run HDLC-framed I/O; exponential reconnect.
@@ -356,8 +365,10 @@ pub async fn spawn_i2p_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let mut pacer = ReconnectPacer::new(config.reconnect_delay, config.max_reconnect_tries);
let mut connected_before = false;
loop {
let session_id = generate_session_id();
@@ -508,8 +519,21 @@ pub async fn spawn_i2p_client(
"I2P client: stream connected"
);
online_task.store(true, Ordering::SeqCst);
pacer.reset();
// Python synthesizes on every connection (I2PInterface.py:503,
// :533).
let synthesis = config
.tunnel_identity
.as_ref()
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(
&rx,
std::mem::replace(&mut connected_before, true),
&transport_tx,
synthesis,
&online_task,
)
.await;
// BufReader may have prefetched past the handshake; flush its tail first.
let buffered = stream_buf_reader.buffer().to_vec();
@@ -962,6 +986,16 @@ impl ReconnectPacer {
mod tests {
use super::*;
#[test]
fn peer_python_name_matches_python() {
// Python 1.5.5 `str()` output for this interface.
let peer = "abcdefghijklmnop.b32.i2p";
assert_eq!(
I2PClientConfig::new(&format!("Golden I2P to {peer}"), peer).python_name(),
"I2PInterfacePeer[Golden I2P to abcdefghijklmnop.b32.i2p]"
);
}
#[test]
fn test_i2p_client_config() {
let cfg = I2PClientConfig::new("i2p0", "ABCDEF1234.b32.i2p");
+54 -2
View File
@@ -10,7 +10,8 @@ use tokio::sync::mpsc;
use crate::hdlc;
use crate::kiss;
use crate::traits::{
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity,
handoff_accepted_interface, open_client_connection, python_host,
};
use rns_transport::messages::{InboundPacket, TransportMessage};
@@ -50,6 +51,9 @@ pub struct TcpClientConfig {
pub mode: InterfaceMode,
/// Override HW MTU for link MTU discovery (Python `fixed_mtu`, >= 500).
pub fixed_mtu: Option<u32>,
/// Signs a tunnel synthesis for every connection unless KISS-framed;
/// `None` sends none.
pub tunnel_identity: Option<TunnelIdentity>,
}
impl TcpClientConfig {
@@ -63,8 +67,19 @@ impl TcpClientConfig {
max_reconnect_tries: None,
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
}
}
/// Python `str(TCPClientInterface)` (TCPInterface.py:457-461).
fn python_name(&self) -> String {
format!(
"TCPInterface[{}/{}:{}]",
self.name,
python_host(&self.target_host),
self.target_port
)
}
}
#[derive(Debug, Clone)]
@@ -321,10 +336,12 @@ pub async fn spawn_tcp_client(
let task_rxb = shared_rxb.clone();
let task_txb = shared_txb.clone();
let python_name = config.python_name();
let read_task = tokio::spawn(async move {
let max_tries = config.max_reconnect_tries;
let mut tries: usize = 0;
let mut backoff = RECONNECT_WAIT_INITIAL;
let mut connected_before = false;
loop {
let addr = format!("{}:{}", config.target_host, config.target_port);
@@ -379,9 +396,23 @@ pub async fn spawn_tcp_client(
let state = TcpInterfaceState::with_shared_counters(task_rxb.clone(), task_txb.clone());
state.online.store(true, Ordering::SeqCst);
online2.store(true, Ordering::SeqCst);
tries = 0;
backoff = RECONNECT_WAIT_INITIAL;
// Python synthesizes on every non-KISS connection
// (TCPInterface.py:178-179, :298-299).
let synthesis = config
.tunnel_identity
.as_ref()
.filter(|_| !kiss_framing)
.and_then(|identity| identity.synthesis(&python_name));
open_client_connection(
&rx,
std::mem::replace(&mut connected_before, true),
&transport_tx,
synthesis,
&online2,
)
.await;
let (reader, writer) = stream.into_split();
@@ -647,6 +678,24 @@ pub async fn spawn_tcp_server(
mod tests {
use super::*;
#[test]
fn client_python_names_match_python() {
// Python 1.5.5 `str()` output for these interfaces.
for (host, expected) in [
("127.0.0.1", "TCPInterface[Golden Uplink/127.0.0.1:4242]"),
("::1", "TCPInterface[Golden Uplink/[::1]:4242]"),
(
"hub.example.org",
"TCPInterface[Golden Uplink/hub.example.org:4242]",
),
] {
assert_eq!(
TcpClientConfig::new("Golden Uplink", host, 4242).python_name(),
expected
);
}
}
#[test]
fn test_tcp_client_config() {
let config = TcpClientConfig::new("test", "127.0.0.1", 4242);
@@ -813,6 +862,7 @@ mod tests {
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone())
.await
@@ -909,6 +959,7 @@ mod tests {
max_reconnect_tries: Some(2),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let handle = spawn_tcp_client(config, 99, transport_tx).await.unwrap();
@@ -953,6 +1004,7 @@ mod tests {
max_reconnect_tries: Some(1),
mode: InterfaceMode::Full,
fixed_mtu: None,
tunnel_identity: None,
};
let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone())
.await
+61
View File
@@ -52,6 +52,67 @@ pub(crate) async fn handoff_accepted_interface(
}
}
/// The transport identity a client signs its tunnel syntheses with (Python
/// `Transport.identity`). Debug shows only its hash.
#[derive(Clone)]
pub struct TunnelIdentity(pub Arc<rns_identity::identity::Identity>);
impl TunnelIdentity {
/// A fresh synthesis for the interface whose Python `str()` is
/// `python_name` (Transport.py:2764-2785).
pub fn synthesis(&self, python_name: &str) -> Option<Bytes> {
rns_transport::tunnel::build_tunnel_synthesis_packet(
&self.0,
rns_transport::tunnel::interface_hash(python_name),
)
.map(Bytes::from)
}
}
impl std::fmt::Debug for TunnelIdentity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("TunnelIdentity")
.field(&hex::encode(self.0.hash))
.finish()
}
}
/// A host as Python's interface `str()` renders it: IPv6 in brackets.
pub(crate) fn python_host(host: &str) -> std::borrow::Cow<'_, str> {
if host.contains(':') {
format!("[{host}]").into()
} else {
host.into()
}
}
/// Start a client connection as Python does: traffic queued during an outage
/// is dropped (TCPInterface.py:314-315), then the connection's synthesis is
/// queued, and only then does the interface report online.
pub(crate) async fn open_client_connection(
outbound: &tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
after_outage: bool,
transport_tx: &rns_transport::messages::InterfaceTransportSender,
synthesis: Option<Bytes>,
online: &AtomicBool,
) {
if after_outage {
let mut queued = outbound.lock().await;
while queued.try_recv().is_ok() {}
}
if let Some(raw_packet) = synthesis {
let _ = transport_tx
.send(
rns_transport::messages::TransportMessage::SynthesizeTunnel {
interface_id: transport_tx.interface_id(),
raw_packet,
},
)
.await;
}
online.store(true, std::sync::atomic::Ordering::SeqCst);
}
/// Interface operating mode. Byte values are on-wire constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
+19 -2
View File
@@ -3429,6 +3429,8 @@ pub async fn init_with_policy(
// Client mode leaves hardware to the Shared sibling.
if instance_mode != InstanceMode::Client {
let tunnel_identity =
rns_interface::traits::TunnelIdentity(wire_transport_identity.clone());
for iface_config in &interfaces {
#[cfg(feature = "ble")]
if should_defer_android_ble_rnode(iface_config, cfg!(target_os = "android")) {
@@ -3492,6 +3494,7 @@ pub async fn init_with_policy(
&socket_base,
is_foreground.clone(),
rnode_startup_options,
&tunnel_identity,
)
.await
{
@@ -6408,6 +6411,9 @@ async fn spawn_discovered_backbone_client(
);
let mut config = rns_interface::backbone::BackboneClientConfig::new(&name, host, port);
config.mode = discovered_backbone_client_mode(&handle.config);
config.tunnel_identity = Some(rns_interface::traits::TunnelIdentity(
handle.transport_identity.clone(),
));
let iface_handle =
rns_interface::backbone::spawn_backbone_client(config, id, handle.transport_tx.clone())
.await
@@ -6721,7 +6727,10 @@ pub async fn spawn_tcp_client_runtime_with_ifac(
.id_gen
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let post_init = runtime_ifac_post_init(ifac, 16)?;
let config = rns_interface::tcp::TcpClientConfig::new(name, host, port);
let mut config = rns_interface::tcp::TcpClientConfig::new(name, host, port);
config.tunnel_identity = Some(rns_interface::traits::TunnelIdentity(
handle.transport_identity.clone(),
));
if let Some(post_init) = &post_init {
interface_factory::validate_config_capacity(
&interface_factory::InterfaceConfig::TcpClient(config.clone()),
@@ -6879,6 +6888,9 @@ pub async fn spawn_backbone_client_runtime_with_ifac(
config.connect_timeout_secs = t;
}
config.max_reconnect_tries = runtime_config.max_reconnect_tries;
config.tunnel_identity = Some(rns_interface::traits::TunnelIdentity(
handle.transport_identity.clone(),
));
let iface_handle =
rns_interface::backbone::spawn_backbone_client(config, id, handle.transport_tx.clone())
@@ -7884,6 +7896,7 @@ async fn spawn_interface_with_rnode_startup_options(
socket_base: &Path,
is_foreground: Arc<AtomicBool>,
rnode_startup_options: rns_interface::rnode::RNodeStartupOptions,
tunnel_identity: &rns_interface::traits::TunnelIdentity,
) -> Result<Vec<OwnedInterfaceHandle>, String> {
#[cfg(not(any(
feature = "serial",
@@ -7895,7 +7908,9 @@ async fn spawn_interface_with_rnode_startup_options(
match iface_config {
interface_factory::InterfaceConfig::TcpClient(c) => {
rns_interface::tcp::spawn_tcp_client(c.clone(), id, transport_tx)
let mut config = c.clone();
config.tunnel_identity = Some(tunnel_identity.clone());
rns_interface::tcp::spawn_tcp_client(config, id, transport_tx)
.await
.map(|h| vec![h.into()])
.map_err(|e| format!("TCP client: {e}"))
@@ -8086,6 +8101,7 @@ async fn spawn_interface_with_rnode_startup_options(
client_config.sam_host = c.i2p_sam_host.clone();
client_config.sam_port = c.i2p_sam_port;
client_config.mode = c.mode;
client_config.tunnel_identity = Some(tunnel_identity.clone());
let peer_id = next.take().unwrap_or_else(|| next_id(&id_gen));
match rns_interface::i2p::spawn_i2p_client(
client_config,
@@ -8215,6 +8231,7 @@ async fn spawn_interface_with_rnode_startup_options(
config.prefer_ipv6 = c.prefer_ipv6;
config.connect_timeout_secs = c.connect_timeout;
config.max_reconnect_tries = c.max_reconnect_tries;
config.tunnel_identity = Some(tunnel_identity.clone());
rns_interface::backbone::spawn_backbone_client(config, id, transport_tx)
.await
.map(|h| vec![h.into()])
+452 -12
View File
@@ -1,9 +1,13 @@
//! Runtime wiring for server interface ids and accepted clients' routing
//! state, observed from the public handle.
//! Runtime wiring for tunnel synthesis, server interface ids and accepted
//! clients' routing state, observed from the wire and the public handle.
use super::*;
use rns_transport::messages::InterfaceStatRpcEntry;
use rns_transport::path_table::{PathEntry, PathTable};
use rns_wire::flags::HeaderType;
use rns_transport::tunnel::TunnelSynthesisData;
use rns_wire::context::PacketContext;
use rns_wire::flags::{DestinationType, HeaderType, PacketFlags, PacketType, TransportType};
use rns_wire::header::PacketHeader;
use std::collections::VecDeque;
use std::sync::atomic::AtomicUsize;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
@@ -214,20 +218,28 @@ async fn an_i2p_interface_runs_its_server_and_every_peer() {
handle.startup_interface_failures()
);
let mut commands = Vec::new();
while commands.len() < peers.len() {
let (command, _stream) = tokio::time::timeout(Duration::from_secs(10), streams.recv())
let mut openings = HashMap::new();
while openings.len() < peers.len() {
let (command, stream) = tokio::time::timeout(Duration::from_secs(10), streams.recv())
.await
.expect("every peer opens a SAM stream")
.unwrap();
commands.push(command);
let peer = peers
.into_iter()
.find(|peer| command.contains(&format!("DESTINATION={peer} ")))
.unwrap_or_else(|| panic!("unexpected stream: {command}"));
let opening = Frames::new(stream, false)
.next(Duration::from_secs(5))
.await
.and_then(|frame| synthesis_in(&frame))
.expect("every peer connection opens with a tunnel synthesis");
openings.insert(peer, opening.interface_hash);
}
for peer in peers {
assert!(
commands
.iter()
.any(|command| command.contains(&format!("DESTINATION={peer} "))),
"{peer}: {commands:?}"
assert_eq!(
openings[peer],
python_interface_hash(&format!("I2PInterfacePeer[Golden I2P to {peer}]")),
"each peer synthesizes under its own Python name"
);
assert!(
wait_for_interface(&handle, |entry| entry.name
@@ -436,3 +448,431 @@ async fn accepted_client_paths_are_not_persisted() {
);
let _ = std::fs::remove_dir_all(dir);
}
/// Forwards connections to `upstream`; `cut` drops every live connection.
struct Proxy {
port: u16,
cut: watch::Sender<u64>,
}
impl Proxy {
async fn start(upstream: u16) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (cut, cut_rx) = watch::channel(0u64);
tokio::spawn(async move {
while let Ok((mut inbound, _)) = listener.accept().await {
let mut cut_rx = cut_rx.clone();
cut_rx.borrow_and_update();
tokio::spawn(async move {
let Ok(mut outbound) = TcpStream::connect(("127.0.0.1", upstream)).await else {
return;
};
tokio::select! {
_ = tokio::io::copy_bidirectional(&mut inbound, &mut outbound) => {}
_ = cut_rx.changed() => {}
}
});
}
});
Self { port, cut }
}
fn cut(&self) {
self.cut.send_modify(|generation| *generation += 1);
}
}
/// Frames a hub reads from one client connection, in arrival order.
struct Frames {
reader: BufReader<TcpStream>,
kiss: bool,
hdlc: rns_interface::hdlc::HdlcDeframer,
kiss_frames: rns_interface::kiss::KissDeframer,
ready: VecDeque<Vec<u8>>,
}
impl Frames {
fn new(reader: BufReader<TcpStream>, kiss: bool) -> Self {
Self {
reader,
kiss,
hdlc: rns_interface::hdlc::HdlcDeframer::new(),
kiss_frames: rns_interface::kiss::KissDeframer::new(),
ready: VecDeque::new(),
}
}
async fn accept(listener: &TcpListener, kiss: bool) -> Self {
let (stream, _) = tokio::time::timeout(Duration::from_secs(20), listener.accept())
.await
.expect("the client connects")
.unwrap();
Self::new(BufReader::new(stream), kiss)
}
async fn next(&mut self, within: Duration) -> Option<Vec<u8>> {
let deadline = tokio::time::Instant::now() + within;
loop {
if let Some(frame) = self.ready.pop_front() {
return Some(frame);
}
let mut buf = [0u8; 4096];
let n = match tokio::time::timeout_at(deadline, self.reader.read(&mut buf)).await {
Ok(Ok(n)) if n > 0 => n,
_ => return None,
};
if self.kiss {
let frames = self.kiss_frames.feed(&buf[..n]);
self.ready.extend(
frames
.into_iter()
.filter(|(command, _)| *command == 0)
.map(|(_, frame)| frame),
);
} else {
self.ready.extend(self.hdlc.feed(&buf[..n]));
}
self.ready.retain(|frame| !frame.is_empty());
}
}
async fn collect(&mut self, within: Duration) -> Vec<Vec<u8>> {
let deadline = tokio::time::Instant::now() + within;
let mut frames = Vec::new();
while let Some(frame) = self
.next(deadline.saturating_duration_since(tokio::time::Instant::now()))
.await
{
frames.push(frame);
}
frames
}
}
fn synthesis_in(frame: &[u8]) -> Option<TunnelSynthesisData> {
let (header, offset) = PacketHeader::unpack(frame).ok()?;
let synthesize =
Destination::hash_from_name_and_identity("rnstransport.tunnel.synthesize", None);
let shape = header.destination_hash == synthesize
&& header.flags.header_type == HeaderType::Header1
&& header.flags.transport_type == TransportType::Broadcast
&& header.flags.destination_type == DestinationType::Plain
&& header.flags.packet_type == PacketType::Data
&& header.hops == 0
&& header.context == PacketContext::None
&& frame.len() == offset + 176;
shape
.then(|| TunnelSynthesisData::unpack(&frame[offset..]))
.flatten()
}
fn assert_signed(synthesis: &TunnelSynthesisData) {
let signer = Identity::from_public_key(&synthesis.public_key).unwrap();
let mut signed = synthesis.public_key.to_vec();
signed.extend_from_slice(&synthesis.interface_hash);
signed.extend_from_slice(&synthesis.random_hash);
assert!(
signer.verify(&signed, &synthesis.signature),
"the synthesis verifies under its own Ed25519 key"
);
}
/// Python `Interface.get_hash()`: the full hash of `str(interface)`.
fn python_interface_hash(python_str: &str) -> [u8; 32] {
rns_transport::tunnel::interface_hash(python_str)
}
/// Queue a PLAIN broadcast for every interface; returns its wire bytes.
async fn send_plain_marker(handle: &ReticulumHandle, app: &str) -> Vec<u8> {
let destination_hash = Destination::hash_from_name_and_identity(app, None);
let mut marker = PacketHeader {
flags: PacketFlags {
header_type: HeaderType::Header1,
context_flag: false,
transport_type: TransportType::Broadcast,
destination_type: DestinationType::Plain,
packet_type: PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash,
context: PacketContext::None,
}
.pack();
marker.extend_from_slice(app.as_bytes());
handle
.transport_tx
.send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(marker.clone()),
destination_hash,
}))
.await
.unwrap();
marker
}
#[tokio::test]
async fn a_tcp_client_opens_every_connection_with_its_tunnel_synthesis() {
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = hub.local_addr().unwrap().port();
let dir = config_dir(
"tcp-synthesis",
&format!(
"[reticulum]\n share_instance = No\n\n[interfaces]\n [[Uplink]]\n type = TCPClientInterface\n enabled = yes\n target_host = 127.0.0.1\n target_port = {port}\n"
),
);
let handle = start(&dir).await;
let mut first = Frames::accept(&hub, false).await;
let opening = first
.next(Duration::from_secs(5))
.await
.and_then(|frame| synthesis_in(&frame))
.expect("a new connection opens with a tunnel synthesis (TCPInterface.py:178-179)");
assert_eq!(
opening.public_key,
handle.transport_identity.get_public_key(),
"signed with the per-process transport identity (Transport.py:2767)"
);
assert_eq!(
opening.interface_hash,
python_interface_hash(&format!("TCPInterface[Uplink/127.0.0.1:{port}]")),
"the interface hash is Python's get_hash() of str(TCPClientInterface)"
);
assert_signed(&opening);
drop(first);
let mut second = Frames::accept(&hub, false).await;
let reopening = second
.next(Duration::from_secs(5))
.await
.and_then(|frame| synthesis_in(&frame))
.expect("a reconnect opens with a fresh synthesis (TCPInterface.py:298-299)");
assert_eq!(reopening.tunnel_id(), opening.tunnel_id());
assert_ne!(reopening.random_hash, opening.random_hash);
assert_signed(&reopening);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_tcp_client_drops_traffic_queued_while_it_was_disconnected() {
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = hub.local_addr().unwrap().port();
let dir = config_dir(
"tcp-backlog",
&format!(
"[reticulum]\n share_instance = No\n\n[interfaces]\n [[Uplink]]\n type = TCPClientInterface\n enabled = yes\n target_host = 127.0.0.1\n target_port = {port}\n"
),
);
let handle = start(&dir).await;
drop(Frames::accept(&hub, false).await);
assert!(
wait_for_interface(&handle, |entry| entry.name == "Uplink" && !entry.online)
.await
.is_some(),
"the client notices the lost connection"
);
tokio::time::sleep(Duration::from_millis(200)).await;
let marker = send_plain_marker(&handle, "wp4.backlog").await;
let mut second = Frames::accept(&hub, false).await;
let frames = second.collect(Duration::from_secs(2)).await;
assert!(
!frames.contains(&marker),
"Python drops packets while offline (TCPInterface.py:314-315)"
);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_tcp_client_keeps_traffic_queued_before_its_first_connection() {
let port = unused_port().await;
let dir = config_dir(
"tcp-first-backlog",
&format!(
"[reticulum]\n share_instance = No\n\n[interfaces]\n [[Uplink]]\n type = TCPClientInterface\n enabled = yes\n target_host = 127.0.0.1\n target_port = {port}\n"
),
);
let handle = start(&dir).await;
let marker = send_plain_marker(&handle, "wp4.first.backlog").await;
let hub = TcpListener::bind(("127.0.0.1", port)).await.unwrap();
let mut first = Frames::accept(&hub, false).await;
let frames = first.collect(Duration::from_secs(2)).await;
assert!(
frames.iter().any(|frame| synthesis_in(frame).is_some()),
"control: the first connection opens with its synthesis"
);
assert!(
frames.contains(&marker),
"only an outage drops queued traffic; the first connection delivers it"
);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn the_shared_instance_client_never_synthesizes() {
assert!(
shared_tcp_client_config(37428).tunnel_identity.is_none(),
"Python's LocalInterface never synthesizes"
);
}
#[tokio::test]
async fn a_kiss_framed_tcp_client_never_synthesizes() {
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = hub.local_addr().unwrap().port();
let dir = config_dir(
"tcp-kiss",
&format!(
"[reticulum]\n share_instance = No\n\n[interfaces]\n [[KISS Uplink]]\n type = TCPClientInterface\n enabled = yes\n kiss_framing = yes\n target_host = 127.0.0.1\n target_port = {port}\n"
),
);
let handle = start(&dir).await;
let mut connection = Frames::accept(&hub, true).await;
let frames = connection.collect(Duration::from_secs(2)).await;
assert!(
frames.iter().all(|frame| synthesis_in(frame).is_none()),
"Python never synthesizes on KISS framing (TCPInterface.py:178-179, :298-299)"
);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_backbone_client_opens_with_its_tunnel_synthesis() {
let hub = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = hub.local_addr().unwrap().port();
let dir = config_dir(
"backbone-synthesis",
&format!(
"[reticulum]\n share_instance = No\n\n[interfaces]\n [[Backbone Up]]\n type = BackboneInterface\n enabled = yes\n target_host = 127.0.0.1\n port = {port}\n"
),
);
let handle = start(&dir).await;
let mut connection = Frames::accept(&hub, false).await;
let opening = connection
.next(Duration::from_secs(5))
.await
.and_then(|frame| synthesis_in(&frame))
.expect("a Backbone connection opens with a tunnel synthesis (BackboneInterface.py:922)");
assert_eq!(
opening.public_key,
handle.transport_identity.get_public_key()
);
assert_eq!(
opening.interface_hash,
python_interface_hash(&format!("BackboneInterface[Backbone Up/127.0.0.1:{port}]"))
);
assert_signed(&opening);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn an_i2p_client_opens_with_its_tunnel_synthesis() {
let (sam_port, mut streams) = fake_sam(0).await;
let peer = "abcdefghijklmnop.b32.i2p";
let dir = config_dir(
"i2p-synthesis",
&format!(
"[reticulum]\n share_instance = No\n\n[interfaces]\n [[Golden I2P]]\n type = I2PInterface\n enabled = yes\n peers = {peer}\n i2p_sam_host = 127.0.0.1\n i2p_sam_port = {sam_port}\n"
),
);
let handle = start(&dir).await;
let (command, stream) = tokio::time::timeout(Duration::from_secs(10), streams.recv())
.await
.expect("the client opens a SAM stream")
.unwrap();
assert!(command.starts_with("STREAM CONNECT"), "{command}");
let mut connection = Frames::new(stream, false);
let opening = connection
.next(Duration::from_secs(5))
.await
.and_then(|frame| synthesis_in(&frame))
.expect("an I2P peer connection opens with a tunnel synthesis (I2PInterface.py:503)");
assert_eq!(
opening.public_key,
handle.transport_identity.get_public_key()
);
assert_eq!(
opening.interface_hash,
python_interface_hash(&format!("I2PInterfacePeer[Golden I2P to {peer}]"))
);
assert_signed(&opening);
handle.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_rust_hub_restores_a_reconnecting_rust_clients_paths() {
let uplink_port = unused_port().await;
let hub_port = unused_port().await;
let hub_dir = config_dir("rust-hub", &hub_config(hub_port, uplink_port));
let hub = start(&hub_dir).await;
let proxy = Proxy::start(hub_port).await;
let client_dir = config_dir(
"rust-client",
&format!(
"[reticulum]\n share_instance = No\n\n[interfaces]\n [[Hub Uplink]]\n type = TCPClientInterface\n enabled = yes\n target_host = 127.0.0.1\n target_port = {}\n",
proxy.port
),
);
let client = start(&client_dir).await;
// An interface reports online once its synthesis is queued; Python's
// startup likewise synthesizes before applications announce.
assert!(
wait_for_interface(&client, |entry| entry.name == "Hub Uplink" && entry.online)
.await
.is_some(),
"the client connects"
);
let destination = client
.register_destination(
Identity::new(),
"wp4.tunnel.rust",
crate::destination_runtime::DestinationRuntimeOptions::default(),
)
.await
.unwrap();
destination
.handle
.announce(crate::link_manager::DestinationAnnounceOptions::default())
.await
.unwrap();
let dest = destination.handle.destination_hash();
assert!(
wait_for_path(&hub, dest).await,
"the hub learns the client's announce"
);
proxy.cut();
assert!(
path_state_within(&hub, dest, false, Duration::from_secs(10)).await,
"the hub drops the lost connection's paths"
);
assert!(
path_state_within(&hub, dest, true, Duration::from_secs(20)).await,
"the client's reconnect synthesis restores its path without a new announce"
);
client.shutdown_and_wait().await;
hub.shutdown_and_wait().await;
let _ = std::fs::remove_dir_all(client_dir);
let _ = std::fs::remove_dir_all(hub_dir);
}
+3
View File
@@ -565,6 +565,9 @@ impl TransportActor {
}
TransportMessage::SharedConnectionLost => true,
TransportMessage::Rpc { .. } => true,
TransportMessage::SynthesizeTunnel {
interface_id: id, ..
} => *id == interface_id,
_ => false,
};
if matches_owner {