From ef1ff3f90c2c23f7f347ddbb716c85942317ff8c Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Wed, 15 Jul 2026 13:35:38 -0600 Subject: [PATCH] =?UTF-8?q?parity:=201.3.8=20wave=203=20=E2=80=94=20local?= =?UTF-8?q?=5Fhops=5Fdelta=20(1.3.7=20semantics)=20+=20logtimestamps=20in?= =?UTF-8?q?=20all=20binaries?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/rns-runtime/src/reticulum.rs | 39 ++ crates/rns-tools/src/commands/rncp.rs | 11 +- crates/rns-tools/src/commands/rnid/main.rs | 11 +- crates/rns-tools/src/commands/rnpath.rs | 8 +- crates/rns-tools/src/commands/rnprobe.rs | 11 +- crates/rns-tools/src/commands/rnsd.rs | 9 +- crates/rns-tools/src/commands/rnsh.rs | 17 +- crates/rns-tools/src/commands/rnstatus.rs | 8 +- crates/rns-tools/src/lib.rs | 27 + crates/rns-transport/src/actor/inbound.rs | 76 ++- crates/rns-transport/src/actor/mod.rs | 563 ++++++++++++++++++++- crates/rns-transport/src/actor/outbound.rs | 28 +- 12 files changed, 768 insertions(+), 40 deletions(-) diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index 3b83b39..c60614a 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -584,6 +584,10 @@ pub struct ReticulumConfig { /// default false): opts a non-transport node out of the per-boot /// ephemeral wire-facing transport identity. pub static_transport_identity: bool, + /// Python 1.3.8 `local_hops_delta` (Reticulum.py:256,506-508, default + /// false): apply a per-boot random 2..=7 hop offset to locally-originated + /// packets (Transport.py:240,1356-1365). + pub local_hops_delta: bool, pub respond_to_probes: bool, pub use_implicit_proof: bool, pub panic_on_interface_error: bool, @@ -644,6 +648,7 @@ impl Default for ReticulumConfig { control_port: LOCAL_CONTROL_PORT, enable_transport: false, static_transport_identity: false, + local_hops_delta: false, respond_to_probes: false, use_implicit_proof: true, panic_on_interface_error: false, @@ -885,6 +890,9 @@ impl ReticulumConfig { if let Some(value) = config_bool("reticulum", sec, "static_transport_identity")? { rc.static_transport_identity = value; } + if let Some(value) = config_bool("reticulum", sec, "local_hops_delta")? { + rc.local_hops_delta = value; + } if let Some(value) = config_bool("reticulum", sec, "respond_to_probes")? { rc.respond_to_probes = value; } @@ -984,6 +992,12 @@ fn uses_ephemeral_transport_identity(rc: &ReticulumConfig) -> bool { !rc.enable_transport && !rc.static_transport_identity } +/// Python 1.3.8 Transport.py:240: per-boot random hop delta, +/// `(ord(os.urandom(1)) % 6) + 2` = 2..=7. +fn generate_local_hops_delta() -> u8 { + (rns_crypto::random::random_bytes(1)[0] % 6) + 2 +} + /// Bring up the Reticulum runtime: config dir, transport actor, interfaces, /// instance mode, jobs runner, and optional RPC / remote-management / probe. pub async fn init( @@ -1015,6 +1029,11 @@ pub async fn init( // is set. Pre-seed the actor's hash so runtime-side wire consumers // (discovery announcer, blackhole publisher/subscriber) share the value. actor.static_transport_identity = rc.static_transport_identity; + // Python 1.3.8 Transport.py:240: one random 2..=7 delta per boot; + // should_apply_delta gates actual application. + if rc.local_hops_delta { + actor.local_hops_delta = generate_local_hops_delta(); + } let ephemeral_transport_identity = uses_ephemeral_transport_identity(&rc).then(rns_identity::identity::Identity::new); if let Some(ephemeral) = &ephemeral_transport_identity { @@ -4506,6 +4525,26 @@ egress_control = Yes assert!(!uses_ephemeral_transport_identity(&rc)); } + #[test] + fn local_hops_delta_key_parses_with_python_default() { + let rc = ReticulumConfig::from_config(&Config::parse("[reticulum]\n").unwrap()); + assert!(!rc.local_hops_delta); + + let rc = ReticulumConfig::from_config( + &Config::parse("[reticulum]\nlocal_hops_delta = yes\n").unwrap(), + ); + assert!(rc.local_hops_delta); + } + + #[test] + fn local_hops_delta_value_stays_in_python_range() { + // Python Transport.py:240: (rand_byte % 6) + 2 = 2..=7. + for _ in 0..256 { + let delta = generate_local_hops_delta(); + assert!((2..=7).contains(&delta), "delta {delta} out of range"); + } + } + #[test] fn blackhole_update_interval_parses_minutes_with_two_minute_clamp() { let rc = ReticulumConfig::from_config(&Config::parse("[reticulum]\n").unwrap()); diff --git a/crates/rns-tools/src/commands/rncp.rs b/crates/rns-tools/src/commands/rncp.rs index 236887c..cad6eb4 100644 --- a/crates/rns-tools/src/commands/rncp.rs +++ b/crates/rns-tools/src/commands/rncp.rs @@ -213,10 +213,13 @@ pub(crate) async fn main() { 0 => tracing::Level::WARN, _ => tracing::Level::ERROR, }; - tracing_subscriber::fmt() - .with_max_level(level) - .with_writer(std::io::stderr) - .init(); + let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref()); + rns_tools::init_tracing( + level, + rns_tools::config_log_timestamps(&config_dir), + true, + std::io::stderr, + ); if args.fetch { run_fetch(args).await; diff --git a/crates/rns-tools/src/commands/rnid/main.rs b/crates/rns-tools/src/commands/rnid/main.rs index 1894e34..568e23e 100644 --- a/crates/rns-tools/src/commands/rnid/main.rs +++ b/crates/rns-tools/src/commands/rnid/main.rs @@ -273,10 +273,13 @@ async fn run(args: Args) -> ExitCode { 5 => tracing::Level::DEBUG, _ => tracing::Level::TRACE, }; - let _ = tracing_subscriber::fmt() - .with_max_level(level) - .with_writer(std::io::stderr) - .try_init(); + let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref()); + rns_tools::init_tracing( + level, + rns_tools::config_log_timestamps(&config_dir), + true, + std::io::stderr, + ); // Python truthiness: empty path lists (`-s` with no values) and an empty // `-S ""` message do not activate their operation. diff --git a/crates/rns-tools/src/commands/rnpath.rs b/crates/rns-tools/src/commands/rnpath.rs index 2624be1..22eea9a 100644 --- a/crates/rns-tools/src/commands/rnpath.rs +++ b/crates/rns-tools/src/commands/rnpath.rs @@ -139,7 +139,13 @@ pub(crate) async fn main() -> ExitCode { 1 => tracing::Level::INFO, _ => tracing::Level::DEBUG, }; - tracing_subscriber::fmt().with_max_level(level).init(); + let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref()); + rns_tools::init_tracing( + level, + rns_tools::config_log_timestamps(&config_dir), + true, + std::io::stdout, + ); if args.blackholed_list { return run_remote_blackhole_list(args).await; diff --git a/crates/rns-tools/src/commands/rnprobe.rs b/crates/rns-tools/src/commands/rnprobe.rs index 90d4531..ce16111 100644 --- a/crates/rns-tools/src/commands/rnprobe.rs +++ b/crates/rns-tools/src/commands/rnprobe.rs @@ -81,10 +81,13 @@ pub(crate) async fn main() { 1 => tracing::Level::INFO, _ => tracing::Level::DEBUG, }; - tracing_subscriber::fmt() - .with_max_level(level) - .with_writer(std::io::stderr) - .init(); + let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref()); + rns_tools::init_tracing( + level, + rns_tools::config_log_timestamps(&config_dir), + true, + std::io::stderr, + ); let full_name = args .full_name diff --git a/crates/rns-tools/src/commands/rnsd.rs b/crates/rns-tools/src/commands/rnsd.rs index 68019b6..7735ce4 100644 --- a/crates/rns-tools/src/commands/rnsd.rs +++ b/crates/rns-tools/src/commands/rnsd.rs @@ -164,6 +164,7 @@ pub(crate) async fn main() { config_loglevel + args.verbose as i32 - args.quiet as i32 }; let level = tracing_level(verbosity); + let log_timestamps = rns_tools::config_log_timestamps(&config_dir); if args.service { if let Err(e) = fs::create_dir_all(&config_dir) { @@ -181,13 +182,9 @@ pub(crate) async fn main() { ); std::process::exit(1); } - tracing_subscriber::fmt() - .with_max_level(level) - .with_writer(LogFileWriter::new(log_path)) - .with_ansi(false) - .init(); + rns_tools::init_tracing(level, log_timestamps, false, LogFileWriter::new(log_path)); } else { - tracing_subscriber::fmt().with_max_level(level).init(); + rns_tools::init_tracing(level, log_timestamps, true, std::io::stdout); } tracing::info!("rnsd-rs {RS_RETICULUM_VERSION} starting"); diff --git a/crates/rns-tools/src/commands/rnsh.rs b/crates/rns-tools/src/commands/rnsh.rs index 107b775..3cb5962 100644 --- a/crates/rns-tools/src/commands/rnsh.rs +++ b/crates/rns-tools/src/commands/rnsh.rs @@ -124,7 +124,7 @@ async fn run_listener(args: Args) -> ExitCode { // Register before any slow init so an early SIGINT exits cleanly. let shutdown = ShutdownSignal::new(); let _signal_rx = install_signal_handlers(shutdown.clone()); - init_logging(args.verbose, args.quiet); + init_logging(args.verbose, args.quiet, args.config.as_deref()); let handle = match start_reticulum(args.config.as_deref(), shutdown.clone()).await { Ok(handle) => handle, @@ -179,7 +179,7 @@ async fn run_initiator(args: Args) -> ExitCode { // Register before any slow init so an early SIGINT exits cleanly. let shutdown = ShutdownSignal::new(); let _signal_rx = install_signal_handlers(shutdown.clone()); - init_logging(args.verbose, args.quiet); + init_logging(args.verbose, args.quiet, args.config.as_deref()); let destination = match args.destination.as_deref().and_then(parse_hash16) { Some(hash) => hash, @@ -267,17 +267,20 @@ async fn start_reticulum( rns_runtime::reticulum::init(config, None, shutdown, is_foreground).await } -fn init_logging(verbose: u8, quiet: u8) { +fn init_logging(verbose: u8, quiet: u8, config_dir: Option<&Path>) { let level = match (verbose as i32) - (quiet as i32) { n if n >= 2 => tracing::Level::DEBUG, 1 => tracing::Level::INFO, 0 => tracing::Level::WARN, _ => tracing::Level::ERROR, }; - let _ = tracing_subscriber::fmt() - .with_max_level(level) - .with_writer(std::io::stderr) - .try_init(); + let resolved = resolve_config_dir(config_dir.and_then(|path| path.to_str())); + rns_tools::init_tracing( + level, + rns_tools::config_log_timestamps(&resolved), + true, + std::io::stderr, + ); } fn terminal_window_size() -> (Option, Option, Option, Option) { diff --git a/crates/rns-tools/src/commands/rnstatus.rs b/crates/rns-tools/src/commands/rnstatus.rs index 29a614e..955763f 100644 --- a/crates/rns-tools/src/commands/rnstatus.rs +++ b/crates/rns-tools/src/commands/rnstatus.rs @@ -140,7 +140,13 @@ pub(crate) async fn main() -> ExitCode { 1 => tracing::Level::INFO, _ => tracing::Level::DEBUG, }; - tracing_subscriber::fmt().with_max_level(level).init(); + let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref()); + rns_tools::init_tracing( + level, + rns_tools::config_log_timestamps(&config_dir), + true, + std::io::stdout, + ); if args.monitor { run_monitor(args).await diff --git a/crates/rns-tools/src/lib.rs b/crates/rns-tools/src/lib.rs index 4dadb23..48851b5 100644 --- a/crates/rns-tools/src/lib.rs +++ b/crates/rns-tools/src/lib.rs @@ -8,3 +8,30 @@ pub const RS_RETICULUM_VERSION: &str = env!("CARGO_PKG_VERSION"); /// Python Reticulum version these tools track for CLI/protocol parity. pub const RETICULUM_COMPAT_VERSION: &str = "1.2.5"; + +/// Python 1.3.2 `[logging] logtimestamps` (Reticulum.py:459-461, +/// RNS/__init__.py:85 default True): whether log lines carry a timestamp +/// prefix. Read pre-init from the config file, like the loglevel. +pub fn config_log_timestamps(config_dir: &std::path::Path) -> bool { + rns_runtime::config::Config::from_file(&config_dir.join("config")) + .ok() + .and_then(|config| config.section("logging")?.get_bool("logtimestamps")) + .unwrap_or(true) +} + +/// Shared tracing-subscriber setup for the CLI binaries; omits the timestamp +/// field when `logtimestamps` is disabled (Python RNS.log parity). +pub fn init_tracing(level: tracing::Level, timestamps: bool, ansi: bool, writer: W) +where + W: for<'a> tracing_subscriber::fmt::MakeWriter<'a> + Send + Sync + 'static, +{ + let builder = tracing_subscriber::fmt() + .with_max_level(level) + .with_ansi(ansi) + .with_writer(writer); + if timestamps { + let _ = builder.try_init(); + } else { + let _ = builder.without_time().try_init(); + } +} diff --git a/crates/rns-transport/src/actor/inbound.rs b/crates/rns-transport/src/actor/inbound.rs index 778a6a6..3b0b7f8 100644 --- a/crates/rns-transport/src/actor/inbound.rs +++ b/crates/rns-transport/src/actor/inbound.rs @@ -625,6 +625,13 @@ impl TransportActor { .path_table .get_live(&header.destination_hash) .is_some_and(|path| self.is_local_client_interface(path.interface_id)); + // Python 1.3.8 Transport.py:1550-1551: to_local_client also covers + // proofs whose reverse entry came in from a local client. + let proof_for_local_client = self + .reverse_table + .get(&header.destination_hash) + .is_some_and(|entry| self.is_local_client_interface(entry.receiving_interface)); + let to_local_client = for_local_client || proof_for_local_client; let path_request_dest = Self::path_request_dest_hash(); let tunnel_synth_dest = Self::tunnel_synthesize_dest_hash(); @@ -747,6 +754,7 @@ impl TransportActor { interface_id, from_local_client, for_local_client, + to_local_client, ) { let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type); self.reverse_table.insert_with_outbound( @@ -778,6 +786,11 @@ impl TransportActor { .path_table .get_live(&header.destination_hash) .is_some_and(|path| self.is_local_client_interface(path.interface_id)); + let proof_for_local_client = self + .reverse_table + .get(&header.destination_hash) + .is_some_and(|entry| self.is_local_client_interface(entry.receiving_interface)); + let to_local_client = for_local_client || proof_for_local_client; let link_request_for_this_instance = header.transport_id.is_none() || header @@ -809,6 +822,7 @@ impl TransportActor { interface_id, from_local_client, for_local_client, + to_local_client, ) { let Some(path) = self.path_table.get_live(&header.destination_hash) else { return; @@ -872,6 +886,7 @@ impl TransportActor { interface_id: InterfaceId, from_local_client: bool, for_local_client: bool, + to_local_client: bool, ) -> Option<(InterfaceId, Vec)> { let path = self.path_table.get_live(&header.destination_hash)?; if path.interface_id == interface_id && !for_local_client { @@ -898,7 +913,13 @@ impl TransportActor { return None; } - let forwarded = self.rewrite_forwarded_transport_packet(raw, header, path)?; + let mut forwarded = + self.rewrite_forwarded_transport_packet(raw, header, path, to_local_client)?; + // Python 1.3.8 Transport.py:1687: substitute the delta for + // local-client-originated packets leaving the shared instance. + if self.local_hops_delta != 0 && from_local_client && !to_local_client { + forwarded[1] = self.local_hops_delta; + } Some((path.interface_id, forwarded)) } @@ -907,6 +928,7 @@ impl TransportActor { raw: &[u8], header: &rns_wire::header::PacketHeader, path: &crate::path_table::PathEntry, + to_local_client: bool, ) -> Option> { let payload_offset = header.size(); if raw.len() < payload_offset { @@ -928,7 +950,14 @@ impl TransportActor { let mut forwarded = new_header.pack(); forwarded.extend_from_slice(&raw[payload_offset..]); Some(forwarded) - } else if path.hops == 1 { + } else if path.hops == 1 + || (to_local_client + && self.local_hops_delta != 0 + && header.flags.header_type == rns_wire::flags::HeaderType::Header2) + { + // Python 1.3.8 Transport.py:1613-1619: with the delta active, + // HEADER_2 frames delivered to local shared clients get their + // transport headers stripped, same as the one-hop case. let mut flags = header.flags; flags.header_type = rns_wire::flags::HeaderType::Header1; flags.transport_type = rns_wire::flags::TransportType::Broadcast; @@ -1018,6 +1047,11 @@ impl TransportActor { let outbound_interface = link_entry.interface_id; let target_interface = link_entry.receiving_interface; let destination_hash = link_entry.destination_hash; + // Python 1.3.8 Transport.py:1552/2222: instance-local + // links are exempt from delta mangling (1.3.7 eacff56f). + let instance_local_link = self + .is_local_client_interface(link_entry.interface_id) + && self.is_local_client_interface(link_entry.receiving_interface); // Require that the proof arrived on the same interface we // forwarded the request to; a mismatch is either a routing @@ -1037,7 +1071,14 @@ impl TransportActor { } let mut forwarded = raw.to_vec(); if forwarded.len() >= 2 { - forwarded[1] = header.hops; + forwarded[1] = if !from_local_client + || instance_local_link + || self.local_hops_delta == 0 + { + header.hops + } else { + self.local_hops_delta + }; } if let Some(entry) = self.link_table.get_mut(&header.destination_hash) { entry.validated = true; @@ -1100,6 +1141,14 @@ impl TransportActor { // match — a proof on the wrong interface means a routing change or // a spoof. Older entries without that field route unconditionally. if self.is_transport_enabled || from_local_client || proof_for_local_client { + // Python 1.3.8 Transport.py:2287: delta for local-client-origin + // proofs; proofs headed to local clients exempt (1.3.7 eacff56f). + let proof_hops = + if !from_local_client || proof_for_local_client || self.local_hops_delta == 0 { + header.hops + } else { + self.local_hops_delta + }; if let Some(reverse_entry) = self.reverse_table.remove(&header.destination_hash) { if let Some(expected_outbound) = reverse_entry.outbound_interface { if _interface_id != expected_outbound { @@ -1113,7 +1162,7 @@ impl TransportActor { let target_interface = reverse_entry.receiving_interface; let mut forwarded = raw.to_vec(); if forwarded.len() >= 2 { - forwarded[1] = header.hops; + forwarded[1] = proof_hops; } self.send_to_interface(target_interface, &forwarded); trace!( @@ -1127,7 +1176,7 @@ impl TransportActor { let target_interface = reverse_entry.receiving_interface; let mut forwarded = raw.to_vec(); if forwarded.len() >= 2 { - forwarded[1] = header.hops; + forwarded[1] = proof_hops; } self.send_to_interface(target_interface, &forwarded); trace!( @@ -1169,7 +1218,13 @@ impl TransportActor { return false; }; - let shared_client_path = self.is_local_client_interface(interface_id) + let from_local_client = self.is_local_client_interface(interface_id); + // Python 1.3.8 Transport.py:1548-1553 (the 1.3.7 eacff56f fix): links + // between two local clients of this shared instance are exempt from + // delta mangling. + let instance_local_link = self.is_local_client_interface(entry.interface_id) + && self.is_local_client_interface(entry.receiving_interface); + let shared_client_path = from_local_client || self.is_local_client_interface(entry.receiving_interface) || self.is_local_client_interface(entry.interface_id); if !self.is_transport_enabled && !shared_client_path { @@ -1226,7 +1281,14 @@ impl TransportActor { let mut forwarded = raw.to_vec(); if forwarded.len() >= 2 { - forwarded[1] = header.hops; + // Python 1.3.8 Transport.py:1731: delta for local-client link + // traffic leaving the instance; instance-local links exempt. + forwarded[1] = if !from_local_client || instance_local_link || self.local_hops_delta == 0 + { + header.hops + } else { + self.local_hops_delta + }; } let skip_hashlist = matches!( header.context, diff --git a/crates/rns-transport/src/actor/mod.rs b/crates/rns-transport/src/actor/mod.rs index e6b5026..8a9ca49 100644 --- a/crates/rns-transport/src/actor/mod.rs +++ b/crates/rns-transport/src/actor/mod.rs @@ -121,6 +121,12 @@ pub struct TransportActor { /// default false): opts a non-transport node out of the per-boot ephemeral /// transport identity. Set by the runtime before spawn. pub static_transport_identity: bool, + /// Python 1.3.8 `Transport.local_hops_delta` (Transport.py:167,240): when + /// the `local_hops_delta` config key is set, a per-boot random 2..=7 + /// replaces the hops byte of locally-originated packets at egress + /// (`should_apply_delta`/`mangle_hops`). 0 = disabled (the default). Set + /// by the runtime before spawn. + pub local_hops_delta: u8, pub blackhole_sources: Vec<[u8; 16]>, /// Live snapshot of currently blackholed identity hashes, shared with the /// runtime's link layer so the LINKIDENTIFY handler can tear down links @@ -289,6 +295,7 @@ impl TransportActor { internal_identity_hash: None, ephemeral_identity_hash: None, static_transport_identity: false, + local_hops_delta: 0, blackhole_sources: Vec::new(), blackholed_snapshot: Arc::new(std::sync::RwLock::new(HashSet::new())), is_shared_instance: false, @@ -676,6 +683,54 @@ impl TransportActor { .is_some_and(|entry| entry.role == InterfaceRole::SharedInstancePeer) } + /// Python 1.3.8 Transport.should_apply_delta (Transport.py:1356-1359): + /// mangle only locally-originated (hops==0) non-PLAIN/GROUP packets, never + /// when this node is itself a shared-instance client, and never on + /// local-client / shared-instance edges. + fn should_apply_delta( + &self, + header: &rns_wire::header::PacketHeader, + interface_id: InterfaceId, + ) -> bool { + self.local_hops_delta != 0 + && !self.is_shared_instance + && header.hops == 0 + && header.flags.destination_type != rns_wire::flags::DestinationType::Plain + && header.flags.destination_type != rns_wire::flags::DestinationType::Group + && !self.is_local_client_interface(interface_id) + && !self.is_shared_instance_peer_interface(interface_id) + } + + /// Python 1.3.8 Transport.mangle_hops (Transport.py:1362-1365): rewrite + /// the hops byte to the per-boot delta. `transport_insert` additionally + /// re-frames a HEADER_1 announce as HEADER_2|TRANSPORT carrying this + /// node's transport identity hash (packet grows by 17 bytes). + fn mangle_hops( + &self, + raw: &[u8], + header: &rns_wire::header::PacketHeader, + transport_insert: bool, + ) -> Vec { + if transport_insert && let Some(transport_id) = self.transport_identity_hash { + let mut flags = header.flags; + flags.header_type = rns_wire::flags::HeaderType::Header2; + flags.transport_type = rns_wire::flags::TransportType::Transport; + let new_header = rns_wire::header::PacketHeader { + flags, + hops: self.local_hops_delta, + transport_id: Some(transport_id), + destination_hash: header.destination_hash, + context: header.context, + }; + let mut out = new_header.pack(); + out.extend_from_slice(&raw[header.size()..]); + return out; + } + let mut out = raw.to_vec(); + out[1] = self.local_hops_delta; + out + } + fn adjusted_inbound_hops(&self, raw_hops: u8, interface_id: InterfaceId) -> u8 { let mut hops = raw_hops.saturating_add(1); @@ -1121,8 +1176,20 @@ impl TransportActor { } }) .collect(); + // Python 1.3.8 Transport.py:1342-1344: locally-originated non-announce + // packets get the per-boot hops delta, decided per egress interface. + let delta_header = (self.local_hops_delta != 0) + .then(|| rns_wire::header::PacketHeader::unpack(raw).ok()) + .flatten() + .map(|(header, _)| header); for id in ids { - self.send_to_interface(id, raw); + match &delta_header { + Some(header) if self.should_apply_delta(header, id) => { + let mangled = self.mangle_hops(raw, header, false); + self.send_to_interface(id, &mangled); + } + _ => self.send_to_interface(id, raw), + } } } @@ -1214,9 +1281,12 @@ impl TransportActor { } fn broadcast_local_announce_on_interfaces(&mut self, raw: &[u8], except: Option) { - let destination_hash = rns_wire::header::PacketHeader::unpack(raw) + let header = rns_wire::header::PacketHeader::unpack(raw) .ok() - .map(|(h, _)| h.destination_hash) + .map(|(h, _)| h); + let destination_hash = header + .as_ref() + .map(|h| h.destination_hash) .unwrap_or([0u8; 16]); let ids: Vec = self .interfaces @@ -1225,7 +1295,17 @@ impl TransportActor { .filter(|id| self.interface_allows_announce(*id, &destination_hash, except)) .collect(); for id in ids { - self.send_to_interface(id, raw); + // Python 1.3.8 Transport.py:1345: delta-mangled HEADER_1 announces + // are re-framed as HEADER_2|TRANSPORT with our transport identity. + match &header { + Some(h) if self.should_apply_delta(h, id) => { + let transport_insert = + h.flags.header_type == rns_wire::flags::HeaderType::Header1; + let mangled = self.mangle_hops(raw, h, transport_insert); + self.send_to_interface(id, &mangled); + } + _ => self.send_to_interface(id, raw), + } if let Some(entry) = self.interfaces.get_mut(&id) { entry.ingress.sent_announce(); } @@ -5980,6 +6060,481 @@ mod tests { assert_eq!(actor.ephemeral_identity_hash, None); } + // ---- local_hops_delta (Python 1.3.8 Transport.py:1356-1365, 1.3.7 + // eacff56f instance-local exclusions) ---- + + fn make_data_packet_with_dest_type( + dest_hash: [u8; 16], + destination_type: rns_wire::flags::DestinationType, + ) -> Bytes { + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type, + packet_type: rns_wire::flags::PacketType::Data, + }; + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&[0xDD; 32]); + Bytes::from(raw) + } + + #[test] + fn local_hops_delta_disabled_by_default_is_noop() { + let (mut actor, _tx) = TransportActor::new(); + assert_eq!(actor.local_hops_delta, 0); + let (entry, mut rx) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry); + + let raw = make_data_packet([0x21; 16], 0); + actor.on_outbound(OutboundRequest { + raw: raw.clone(), + destination_hash: [0x21; 16], + }); + let sent = rx.try_recv().unwrap(); + assert_eq!(&sent[..], &raw[..], "disabled delta must not touch bytes"); + } + + #[test] + fn local_hops_delta_mangles_outbound_by_destination_type() { + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 5; + let (entry, mut rx) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry); + + // SINGLE data: hops byte rewritten to the delta, rest untouched. + let raw = make_data_packet_with_dest_type([0x21; 16], rns_wire::flags::DestinationType::Single); + actor.on_outbound(OutboundRequest { + raw: raw.clone(), + destination_hash: [0x21; 16], + }); + let sent = rx.try_recv().unwrap(); + assert_eq!(sent[1], 5); + assert_eq!(sent[0], raw[0]); + assert_eq!(&sent[2..], &raw[2..]); + while rx.try_recv().is_ok() {} // drain the automatic path request + + // PLAIN and GROUP destinations are excluded (Transport.py:1358). + for dest_type in [ + rns_wire::flags::DestinationType::Plain, + rns_wire::flags::DestinationType::Group, + ] { + let raw = make_data_packet_with_dest_type([0x22; 16], dest_type); + actor.on_outbound(OutboundRequest { + raw: raw.clone(), + destination_hash: [0x22; 16], + }); + let sent = rx.try_recv().unwrap(); + assert_eq!(&sent[..], &raw[..], "{dest_type:?} must not be mangled"); + } + } + + #[test] + fn local_hops_delta_announce_transport_insert() { + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 4; + let transport_id = [0x77; 16]; + actor.transport_identity_hash = Some(transport_id); + let (entry, mut rx) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry); + + let (raw, dest_hash) = make_valid_announce("delta.announce", 0); + actor.local_destinations.insert(dest_hash); + actor.on_outbound(OutboundRequest { + raw: raw.clone(), + destination_hash: dest_hash, + }); + + let sent = rx.try_recv().unwrap(); + let (header, offset) = rns_wire::header::PacketHeader::unpack(&sent).unwrap(); + assert_eq!( + header.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!( + header.flags.transport_type, + rns_wire::flags::TransportType::Transport + ); + assert_eq!(header.flags.packet_type, rns_wire::flags::PacketType::Announce); + assert_eq!(header.transport_id, Some(transport_id)); + assert_eq!(header.destination_hash, dest_hash); + assert_eq!(header.hops, 4); + assert_eq!( + sent.len(), + raw.len() + 16, + "HEADER_2 insert adds the 16-byte transport_id" + ); + assert_eq!( + &sent[offset..], + &raw[rns_wire::constants::HEADER_MINSIZE..], + "announce payload must be preserved" + ); + // The hashable part skips hops/transport bits, so the packet hash is + // stable across the mangle (Python Packet.get_hashable_part). + assert_eq!( + rns_wire::hash::packet_hash(&sent, rns_wire::flags::HeaderType::Header2), + rns_wire::hash::packet_hash(&raw, rns_wire::flags::HeaderType::Header1), + ); + } + + #[test] + fn local_hops_delta_applies_on_known_path_sends() { + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 3; + let (entry, mut rx) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry); + + // Transport-wrapped send (Transport.py:1153): hops byte = delta. + let dest_a = [0x31; 16]; + actor.path_table.insert( + dest_a, + crate::path_table::PathEntry::new(Some([0xBB; 16]), 2, 1, InterfaceMode::Gateway), + ); + actor.on_outbound(OutboundRequest { + raw: make_data_packet(dest_a, 0), + destination_hash: dest_a, + }); + let sent = rx.try_recv().unwrap(); + let (header, _) = rns_wire::header::PacketHeader::unpack(&sent).unwrap(); + assert_eq!( + header.flags.header_type, + rns_wire::flags::HeaderType::Header2 + ); + assert_eq!(header.transport_id, Some([0xBB; 16])); + assert_eq!(header.hops, 3, "wrapped send must carry the delta"); + + // Direct send (Transport.py:1186-1187): mangle_hops. + let dest_b = [0x32; 16]; + actor.path_table.insert( + dest_b, + crate::path_table::PathEntry::new(None, 1, 1, InterfaceMode::Gateway), + ); + actor.on_outbound(OutboundRequest { + raw: make_data_packet(dest_b, 0), + destination_hash: dest_b, + }); + let sent = rx.try_recv().unwrap(); + assert_eq!(sent[1], 3, "direct send must carry the delta"); + } + + #[test] + fn local_hops_delta_skips_local_client_and_shared_peer_interfaces() { + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 6; + + let (mut client, mut client_rx) = make_test_interface("local_client"); + client.role = InterfaceRole::LocalClient; + let (mut peer, mut peer_rx) = make_test_interface("shared_peer"); + peer.role = InterfaceRole::SharedInstancePeer; + let (normal, mut normal_rx) = make_test_interface("external"); + actor.interfaces.insert(1, client); + actor.interfaces.insert(2, peer); + actor.interfaces.insert(3, normal); + + actor.on_outbound(OutboundRequest { + raw: make_data_packet([0x41; 16], 0), + destination_hash: [0x41; 16], + }); + + assert_eq!(client_rx.try_recv().unwrap()[1], 0, "local client exempt"); + assert_eq!(peer_rx.try_recv().unwrap()[1], 0, "shared peer exempt"); + assert_eq!(normal_rx.try_recv().unwrap()[1], 6, "external mangled"); + } + + #[test] + fn local_hops_delta_suppressed_when_connected_to_shared_instance() { + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 6; + actor.is_shared_instance = true; + let (entry, mut rx) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry); + + actor.on_outbound(OutboundRequest { + raw: make_data_packet([0x42; 16], 0), + destination_hash: [0x42; 16], + }); + assert_eq!( + rx.try_recv().unwrap()[1], + 0, + "shared-instance clients never apply the delta themselves" + ); + } + + #[test] + fn local_hops_delta_link_table_substitution_and_instance_local_exemption() { + // Shared-instance host forwarding link traffic for a local client + // (Transport.py:1731). + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 6; + + let (mut client, _client_rx) = make_test_interface("local_client"); + client.role = InterfaceRole::LocalClient; + let (external, mut external_rx) = make_test_interface("external"); + actor.interfaces.insert(1, client); + actor.interfaces.insert(2, external); + + let link_id = [0x51; 16]; + actor.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 1, + destination_hash: [0xC1; 16], + established: true, + validated: true, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + actor.on_inbound(InboundPacket { + raw: make_link_data_packet(link_id, 0), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + let forwarded = external_rx.try_recv().unwrap(); + assert_eq!(forwarded[1], 6, "local-client link traffic gets the delta"); + + // Instance-local link (both sides local clients): exempt — this is + // the 1.3.6 regression fixed in 1.3.7 (eacff56f). + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 6; + let (mut client_a, _rx_a) = make_test_interface("client_a"); + client_a.role = InterfaceRole::LocalClient; + let (mut client_b, mut rx_b) = make_test_interface("client_b"); + client_b.role = InterfaceRole::LocalClient; + actor.interfaces.insert(1, client_a); + actor.interfaces.insert(2, client_b); + + let link_id = [0x52; 16]; + actor.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 0, + destination_hash: [0xC2; 16], + established: true, + validated: true, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + actor.on_inbound(InboundPacket { + raw: make_link_data_packet(link_id, 0), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + let forwarded = rx_b.try_recv().unwrap(); + assert_eq!( + forwarded[1], 0, + "instance-local link traffic must keep its true hop count" + ); + } + + #[test] + fn local_hops_delta_lrproof_transit_exclusions() { + // Destination is a local client, initiator is external: the proof + // leaving the instance gets the delta (Transport.py:2222). + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 6; + actor.is_transport_enabled = true; + + let (external, mut external_rx) = make_test_interface("to_initiator"); + let (mut client, _client_rx) = make_test_interface("local_client"); + client.role = InterfaceRole::LocalClient; + actor.interfaces.insert(1, external); + actor.interfaces.insert(2, client); + + let link_id = [0x61; 16]; + let destination_hash = [0xC3; 16]; + let destination_identity = rns_identity::identity::Identity::new(); + insert_announce_for(&mut actor, destination_hash, &destination_identity); + actor.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 0, + destination_hash, + established: false, + validated: false, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 1, + }, + ); + let proof = make_lrproof_packet(link_id, 0, &destination_identity, None); + actor.on_inbound(InboundPacket { + raw: proof, + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + let routed = external_rx.try_recv().unwrap(); + assert_eq!(routed[1], 6, "proof leaving the instance gets the delta"); + + // Instance-local link: proof between two local clients is exempt. + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 6; + let (mut client_a, mut rx_a) = make_test_interface("client_a"); + client_a.role = InterfaceRole::LocalClient; + let (mut client_b, _rx_b) = make_test_interface("client_b"); + client_b.role = InterfaceRole::LocalClient; + actor.interfaces.insert(1, client_a); + actor.interfaces.insert(2, client_b); + + let link_id = [0x62; 16]; + let destination_hash = [0xC4; 16]; + let destination_identity = rns_identity::identity::Identity::new(); + insert_announce_for(&mut actor, destination_hash, &destination_identity); + actor.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 0, + destination_hash, + established: false, + validated: false, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + let proof = make_lrproof_packet(link_id, 0, &destination_identity, None); + actor.on_inbound(InboundPacket { + raw: proof, + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + let routed = rx_a.try_recv().unwrap(); + assert_eq!( + routed[1], 0, + "instance-local link proof must keep its true hop count" + ); + } + + #[test] + fn local_hops_delta_reverse_proof_exclusions() { + // Proof originated by a local client heading to an external requester + // gets the delta (Transport.py:2287). + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 6; + actor.is_transport_enabled = true; + + let (external, mut external_rx) = make_test_interface("external"); + let (mut client, _client_rx) = make_test_interface("local_client"); + client.role = InterfaceRole::LocalClient; + actor.interfaces.insert(1, external); + actor.interfaces.insert(2, client); + + let proof_hash = [0x71; 16]; + actor.reverse_table.insert(proof_hash, 1, 1); + actor.on_inbound(InboundPacket { + raw: make_proof_packet(proof_hash, 0), + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + let routed = external_rx.try_recv().unwrap(); + assert_eq!(routed[1], 6, "local-client proof gets the delta"); + + // Proof heading back to a local client is exempt (1.3.7 eacff56f). + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 6; + actor.is_transport_enabled = true; + let (mut client_a, mut rx_a) = make_test_interface("client_a"); + client_a.role = InterfaceRole::LocalClient; + let (mut client_b, _rx_b) = make_test_interface("client_b"); + client_b.role = InterfaceRole::LocalClient; + actor.interfaces.insert(1, client_a); + actor.interfaces.insert(2, client_b); + + let proof_hash = [0x72; 16]; + actor.reverse_table.insert(proof_hash, 1, 0); + actor.on_inbound(InboundPacket { + raw: make_proof_packet(proof_hash, 0), + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + let routed = rx_a.try_recv().unwrap(); + assert_eq!( + routed[1], 0, + "proof to a local client must keep its true hop count" + ); + } + + #[test] + fn local_hops_delta_strips_transport_header_on_local_client_delivery() { + // Transport.py:1613-1619: with the delta active, HEADER_2 frames + // delivered to a local shared client lose their transport headers. + let (mut actor, _tx) = TransportActor::new(); + actor.local_hops_delta = 6; + actor.is_transport_enabled = true; + let transport_id = [0x88; 16]; + actor.transport_identity_hash = Some(transport_id); + + let (external, _external_rx) = make_test_interface("external"); + let (mut client, mut client_rx) = make_test_interface("local_client"); + client.role = InterfaceRole::LocalClient; + actor.interfaces.insert(1, external); + actor.interfaces.insert(2, client); + + let dest_hash = [0x81; 16]; + actor.path_table.insert( + dest_hash, + crate::path_table::PathEntry::new(None, 0, 2, InterfaceMode::Gateway), + ); + + let raw = make_header2_data_packet(transport_id, dest_hash, 1, b"to_local_client"); + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + let delivered = client_rx.try_recv().unwrap(); + let (header, offset) = rns_wire::header::PacketHeader::unpack(&delivered).unwrap(); + assert_eq!( + header.flags.header_type, + rns_wire::flags::HeaderType::Header1, + "transport headers must be stripped for local-client delivery" + ); + assert_eq!( + header.flags.transport_type, + rns_wire::flags::TransportType::Broadcast + ); + assert_eq!(header.transport_id, None); + assert_eq!(header.hops, 2, "raw 1 -> inbound-adjusted 2"); + assert_eq!(&delivered[offset..], b"to_local_client"); + } + // Shared snapshot consumed by the runtime link layer for the Python 1.3.8 // Link.py:966-968 blackholed-identity link teardown. #[test] diff --git a/crates/rns-transport/src/actor/outbound.rs b/crates/rns-transport/src/actor/outbound.rs index c272e17..7d33f55 100644 --- a/crates/rns-transport/src/actor/outbound.rs +++ b/crates/rns-transport/src/actor/outbound.rs @@ -88,6 +88,10 @@ impl TransportActor { "outbound: routed via path" ); + // Python 1.3.8 Transport.py:1153/1186: local_hops_delta + // replaces the zero hops byte on the way out. + let apply_delta = self.should_apply_delta(&parsed, target_interface); + // Transport nodes only forward Header2 packets whose transport_id // matches their identity — Python hubs silently drop Header1 — // so every directed send through a relay must be wrapped. @@ -100,7 +104,11 @@ impl TransportActor { }; let new_header = rns_wire::header::PacketHeader { flags: new_flags, - hops: parsed.hops, + hops: if apply_delta { + self.local_hops_delta + } else { + parsed.hops + }, transport_id: Some(next_hop), destination_hash: parsed.destination_hash, context: parsed.context, @@ -116,9 +124,15 @@ impl TransportActor { "outbound: wrapped Header1 -> Header2 for transport" ); self.send_to_interface(target_interface, &new_raw); + } else if apply_delta { + let mangled = self.mangle_hops(&request.raw, &parsed, false); + self.send_to_interface(target_interface, &mangled); } else { self.send_to_interface(target_interface, &request.raw); } + } else if apply_delta { + let mangled = self.mangle_hops(&request.raw, &parsed, false); + self.send_to_interface(target_interface, &mangled); } else { self.send_to_interface(target_interface, &request.raw); } @@ -159,7 +173,17 @@ impl TransportActor { if let Ok((parsed, _)) = rns_wire::header::PacketHeader::unpack(&request.raw) { let pkt_hash = rns_wire::hash::packet_hash(&request.raw, parsed.flags.header_type); self.packet_hashlist.insert(pkt_hash); - self.send_to_interface(interface_id, &request.raw); + // Python's outbound applies should_apply_delta on attached- + // interface sends too (Transport.py:1342-1345). + if self.should_apply_delta(&parsed, interface_id) { + let transport_insert = parsed.flags.packet_type + == rns_wire::flags::PacketType::Announce + && parsed.flags.header_type == rns_wire::flags::HeaderType::Header1; + let mangled = self.mangle_hops(&request.raw, &parsed, transport_insert); + self.send_to_interface(interface_id, &mangled); + } else { + self.send_to_interface(interface_id, &request.raw); + } if parsed.flags.packet_type == rns_wire::flags::PacketType::Announce { if let Some(entry) = self.interfaces.get_mut(&interface_id) { entry.ingress.sent_announce();