From feb11b00898a742ce87c5a042ea5ec9e4cdba582 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Sun, 25 Oct 2026 02:51:31 -0600 Subject: [PATCH] discovery: name rsRNS and auto-connect only to the stacks Python 1.5 trusts --- CHANGELOG.md | 1 + README.md | 6 + api/migrations/1.4.md | 7 ++ api/snapshots/rns-runtime.txt | 1 + api/snapshots/rns-transport.txt | 18 +++ api/stability.json | 8 +- crates/rns-runtime/src/reticulum.rs | 102 ++++++++++++++-- .../rns-transport/src/discovery/announcer.rs | 22 +++- .../rns-transport/src/discovery/app_data.rs | 60 +++++++++- .../src/discovery/autoconnect.rs | 110 ++++++++++++++++++ .../rns-transport/src/discovery/constants.rs | 33 +++++- crates/rns-transport/src/discovery/mod.rs | 1 + .../rns-transport/src/discovery/receiver.rs | 39 ++++++- crates/rns-transport/src/discovery/storage.rs | 80 ++++++++++++- 14 files changed, 466 insertions(+), 22 deletions(-) create mode 100644 crates/rns-transport/src/discovery/autoconnect.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index f27b4b8..2828255 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ - 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. - Python Reticulum 1.5 `rnstatus` and `rnpath` work against `rnsd-rs`, locally and with `-R`: interface stats carry every field they read, including announce and path request counts, violation counters and the transport instance, and remote management answers on the transport identity, as in Python Reticulum. - Announces held during an ingress burst on an IFAC interface are processed when released instead of being dropped, and released or replayed announces no longer count as received traffic again, as in Python Reticulum. +- Interface discovery announces name this stack, `rsRNS`, and its version. `rnsd-rs` auto-connects only to Backbone interfaces announced by Python Reticulum 1.5.2 or later, or to any announced Backbone interface with `autoconnect_unverified_implementations`, and no longer stores or lists discovered TCP client interfaces, as in Python Reticulum. ## 1.4.0 - 2026-10-12 diff --git a/README.md b/README.md index c541dce..e678c6a 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,12 @@ Known gaps and intentional limits: - `rnpath-rs` remote mode is read-only for table/rates, including destination filters, apart from the remote blackhole-list query path. Remote mutations and remote active path requests are full gaps. +- Interface discovery announces name this stack `rsRNS` and its version. Python + Reticulum 1.5.2 and later auto-connects only to Backbone interfaces + announced by Python Reticulum 1.5.2 or later, so a Python node auto-connects + to an `rsRNS` interface only with `autoconnect_unverified_implementations = + yes` in its `[reticulum]` section. `rnsd-rs` follows the same rule, and the + same option lets it auto-connect to any announced Backbone interface. - `rncp-rs` implements the listener `-b` announce interval. `-P/--phy-rates` is not supported for the time being. - `rns-ratkey` hardware identity support is feature-gated and still has known diff --git a/api/migrations/1.4.md b/api/migrations/1.4.md index 99f4b78..d003348 100644 --- a/api/migrations/1.4.md +++ b/api/migrations/1.4.md @@ -73,6 +73,13 @@ decode a `/status` answer as `[stats, link_count?]`, and a `/path` answer with `rpc::decode_response_for_request`. Remote management answers on the transport identity, so `rnstatus -R` and `rnpath -R` take its hash. +Interface discovery carries Python 1.5's implementation keys. +`DiscoveryInfo` gains `impl_name` and `impl_version`; build it with +`..Default::default()`. `discovery::autoconnect::qualifies` applies Python's +auto-connect rule, with `ReticulumConfig::autoconnect_unverified_implementations` +as its opt-in. The receiver no longer stores types that are never listed, so +`discovery::Reason` gains `UnlistedType`; exhaustive matches need the arm. + 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 diff --git a/api/snapshots/rns-runtime.txt b/api/snapshots/rns-runtime.txt index 49a5b2a..d12f141 100644 --- a/api/snapshots/rns-runtime.txt +++ b/api/snapshots/rns-runtime.txt @@ -1632,6 +1632,7 @@ impl core::fmt::Debug for rns_runtime::reticulum::RecalledDestination pub fn rns_runtime::reticulum::RecalledDestination::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct rns_runtime::reticulum::ReticulumConfig pub rns_runtime::reticulum::ReticulumConfig::autoconnect_discovered_interfaces: usize +pub rns_runtime::reticulum::ReticulumConfig::autoconnect_unverified_implementations: bool pub rns_runtime::reticulum::ReticulumConfig::blackhole_sources: alloc::vec::Vec<[u8; 16]> pub rns_runtime::reticulum::ReticulumConfig::blackhole_update_interval: f64 pub rns_runtime::reticulum::ReticulumConfig::bootstrap_configs: alloc::vec::Vec diff --git a/api/snapshots/rns-transport.txt b/api/snapshots/rns-transport.txt index 6dc5395..c5df9d7 100644 --- a/api/snapshots/rns-transport.txt +++ b/api/snapshots/rns-transport.txt @@ -359,6 +359,8 @@ pub rns_transport::discovery::app_data::DiscoveryInfo::frequency: core::option:: pub rns_transport::discovery::app_data::DiscoveryInfo::height: core::option::Option pub rns_transport::discovery::app_data::DiscoveryInfo::ifac_netkey: core::option::Option pub rns_transport::discovery::app_data::DiscoveryInfo::ifac_netname: core::option::Option +pub rns_transport::discovery::app_data::DiscoveryInfo::impl_name: core::option::Option +pub rns_transport::discovery::app_data::DiscoveryInfo::impl_version: core::option::Option pub rns_transport::discovery::app_data::DiscoveryInfo::interface_type: alloc::string::String pub rns_transport::discovery::app_data::DiscoveryInfo::latitude: core::option::Option pub rns_transport::discovery::app_data::DiscoveryInfo::longitude: core::option::Option @@ -380,6 +382,8 @@ pub fn rns_transport::discovery::app_data::sanitize_name(&str) -> alloc::string: pub fn rns_transport::discovery::app_data::split_flags(&[u8]) -> core::result::Result<(u8, &[u8]), rns_transport::discovery::app_data::AppDataError> pub fn rns_transport::discovery::app_data::split_stamp(&[u8]) -> core::result::Result<(&[u8], &[u8]), rns_transport::discovery::app_data::AppDataError> pub type rns_transport::discovery::app_data::DiscoveryEncryptor<'a> = (dyn core::ops::function::Fn(&[u8]) -> core::option::Option> + 'a) +pub mod rns_transport::discovery::autoconnect +pub fn rns_transport::discovery::autoconnect::qualifies(&rns_transport::discovery::app_data::DiscoveryInfo, bool) -> bool pub mod rns_transport::discovery::blackhole_manifest pub enum rns_transport::discovery::blackhole_manifest::ManifestError pub rns_transport::discovery::blackhole_manifest::ManifestError::BadField(&'static str) @@ -431,9 +435,12 @@ pub const rns_transport::discovery::constants::key::REACHABLE_ON: u8 pub const rns_transport::discovery::constants::key::SPREADING_FACTOR: u8 pub const rns_transport::discovery::constants::key::TRANSPORT: u8 pub const rns_transport::discovery::constants::key::TRANSPORT_ID: u8 +pub const rns_transport::discovery::constants::key::TRANSPORT_IMPL: u8 +pub const rns_transport::discovery::constants::key::TRANSPORT_VERS: u8 pub const rns_transport::discovery::constants::ANNOUNCE_JOB_INTERVAL_SECS: u64 pub const rns_transport::discovery::constants::APP_NAME: &str pub const rns_transport::discovery::constants::AUTOCONNECT_INTERFACE_TYPES: &[&str] +pub const rns_transport::discovery::constants::AUTOCONNECT_MINIMUM_VERSIONS: &[(&str, core::option::Option<&str>)] pub const rns_transport::discovery::constants::BLACKHOLE_ASPECTS: &[&str] pub const rns_transport::discovery::constants::BLACKHOLE_ASPECT_FILTER: &str pub const rns_transport::discovery::constants::BLACKHOLE_INITIAL_WAIT_SECS: u64 @@ -443,10 +450,13 @@ pub const rns_transport::discovery::constants::BLACKHOLE_UPDATE_INTERVAL_SECS: u pub const rns_transport::discovery::constants::DEFAULT_STAMP_VALUE: u8 pub const rns_transport::discovery::constants::DETACH_THRESHOLD_TICKS: u64 pub const rns_transport::discovery::constants::DISCOVERABLE_INTERFACE_TYPES: &[&str] +pub const rns_transport::discovery::constants::DISCOVERED_INTERFACE_TYPES: &[&str] pub const rns_transport::discovery::constants::DISCOVERY_ASPECTS: &[&str] pub const rns_transport::discovery::constants::DISCOVERY_ASPECT_FILTER: &str pub const rns_transport::discovery::constants::FLAG_ENCRYPTED: u8 pub const rns_transport::discovery::constants::FLAG_SIGNED: u8 +pub const rns_transport::discovery::constants::IMPLEMENTATION_NAME: &str +pub const rns_transport::discovery::constants::IMPLEMENTATION_VERSION: &str pub const rns_transport::discovery::constants::MONITOR_INTERVAL_SECS: u64 pub const rns_transport::discovery::constants::STAMP_SIZE: usize pub const rns_transport::discovery::constants::THRESHOLD_REMOVE_SECS: u64 @@ -471,6 +481,8 @@ pub const rns_transport::discovery::key::REACHABLE_ON: u8 pub const rns_transport::discovery::key::SPREADING_FACTOR: u8 pub const rns_transport::discovery::key::TRANSPORT: u8 pub const rns_transport::discovery::key::TRANSPORT_ID: u8 +pub const rns_transport::discovery::key::TRANSPORT_IMPL: u8 +pub const rns_transport::discovery::key::TRANSPORT_VERS: u8 pub mod rns_transport::discovery::receiver pub enum rns_transport::discovery::receiver::Outcome pub rns_transport::discovery::receiver::Outcome::Accepted @@ -484,6 +496,7 @@ pub rns_transport::discovery::receiver::Reason::MissingAppData pub rns_transport::discovery::receiver::Reason::StampInvalid pub rns_transport::discovery::receiver::Reason::StorageFailed pub rns_transport::discovery::receiver::Reason::UnauthorizedSource +pub rns_transport::discovery::receiver::Reason::UnlistedType pub rns_transport::discovery::receiver::Reason::ValidationBusy pub struct rns_transport::discovery::receiver::ReceiverConfig pub rns_transport::discovery::receiver::ReceiverConfig::decryptor: core::option::Option> @@ -583,6 +596,7 @@ pub rns_transport::discovery::Reason::MissingAppData pub rns_transport::discovery::Reason::StampInvalid pub rns_transport::discovery::Reason::StorageFailed pub rns_transport::discovery::Reason::UnauthorizedSource +pub rns_transport::discovery::Reason::UnlistedType pub rns_transport::discovery::Reason::ValidationBusy pub enum rns_transport::discovery::SkipReason pub rns_transport::discovery::SkipReason::EncryptionFailed @@ -683,6 +697,7 @@ pub fn rns_transport::discovery::receiver::ReceiverConfig::process_event(&self, pub const rns_transport::discovery::ANNOUNCE_JOB_INTERVAL_SECS: u64 pub const rns_transport::discovery::APP_NAME: &str pub const rns_transport::discovery::AUTOCONNECT_INTERFACE_TYPES: &[&str] +pub const rns_transport::discovery::AUTOCONNECT_MINIMUM_VERSIONS: &[(&str, core::option::Option<&str>)] pub const rns_transport::discovery::BLACKHOLE_ASPECTS: &[&str] pub const rns_transport::discovery::BLACKHOLE_ASPECT_FILTER: &str pub const rns_transport::discovery::BLACKHOLE_INITIAL_WAIT: core::time::Duration @@ -696,10 +711,13 @@ pub const rns_transport::discovery::BLACKHOLE_UPDATE_INTERVAL_SECS: u64 pub const rns_transport::discovery::DEFAULT_STAMP_VALUE: u8 pub const rns_transport::discovery::DETACH_THRESHOLD_TICKS: u64 pub const rns_transport::discovery::DISCOVERABLE_INTERFACE_TYPES: &[&str] +pub const rns_transport::discovery::DISCOVERED_INTERFACE_TYPES: &[&str] pub const rns_transport::discovery::DISCOVERY_ASPECTS: &[&str] pub const rns_transport::discovery::DISCOVERY_ASPECT_FILTER: &str pub const rns_transport::discovery::FLAG_ENCRYPTED: u8 pub const rns_transport::discovery::FLAG_SIGNED: u8 +pub const rns_transport::discovery::IMPLEMENTATION_NAME: &str +pub const rns_transport::discovery::IMPLEMENTATION_VERSION: &str pub const rns_transport::discovery::MONITOR_INTERVAL_SECS: u64 pub const rns_transport::discovery::STAMP_SIZE: usize pub const rns_transport::discovery::THRESHOLD_REMOVE_SECS: u64 diff --git a/api/stability.json b/api/stability.json index 9bdd25f..46566f7 100644 --- a/api/stability.json +++ b/api/stability.json @@ -51,8 +51,8 @@ "tier": "provisional", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/rns-transport.txt", - "itemCount": 1926, - "sha256": "b65cf06367ee67949ee563ad43dc62414628d6243bc3ce44d93c10db54e44aca" + "itemCount": 1944, + "sha256": "17482aaa9841b518a977d549534c7328ca73aec60e6dc1b977d6e54c246c1cb7" }, { "name": "rns-link", @@ -87,8 +87,8 @@ "tier": "provisional", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/rns-runtime.txt", - "itemCount": 2141, - "sha256": "3efb385cf4664b63a80f8c9eb3f02c1a390fd97734a263fbaa3690fd1e61e1d8" + "itemCount": 2142, + "sha256": "a318326e7ce8e7bace2e2bcb3299e96cd18a8eb89d3f0703921ea12712fb3bc0" }, { "name": "rns-tools", diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index cfcc938..fb69842 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -2407,6 +2407,9 @@ pub struct ReticulumConfig { /// Maximum number of discovered interfaces to auto-connect to. Python /// `autoconnect_discovered_interfaces`. pub autoconnect_discovered_interfaces: usize, + /// Python `autoconnect_unverified_implementations`: also auto-connect + /// interfaces whose stack is not a trusted release, rsRNS included. + pub autoconnect_unverified_implementations: bool, /// Minimum stamp value (leading-zero bits). Default 16 (LXStamper /// `DEFAULT_STAMP_VALUE`). Python `required_discovery_value`. pub discover_interfaces_required_value: u8, @@ -2459,6 +2462,7 @@ impl Default for ReticulumConfig { network_identity_path: None, discover_interfaces: false, autoconnect_discovered_interfaces: 0, + autoconnect_unverified_implementations: false, discover_interfaces_required_value: rns_transport::discovery::DEFAULT_STAMP_VALUE, interface_discovery_sources: Vec::new(), blackhole_sources: Vec::new(), @@ -2737,6 +2741,11 @@ impl ReticulumConfig { } rc.autoconnect_discovered_interfaces = parse_autoconnect_limit(sec)?.unwrap_or(rc.autoconnect_discovered_interfaces); + if let Some(value) = + config_bool("reticulum", sec, "autoconnect_unverified_implementations")? + { + rc.autoconnect_unverified_implementations = value; + } if let Some(v) = config_uint("reticulum", sec, "required_discovery_value")?.or( config_uint("reticulum", sec, "discover_interfaces_required_value")?, ) { @@ -6370,13 +6379,7 @@ async fn maybe_autoconnect_discovered(handle: &ReticulumHandle, record: Discover return; } let limit = handle.config.autoconnect_discovered_interfaces; - if limit == 0 { - return; - } - if !matches!( - record.info.interface_type.as_str(), - "BackboneInterface" | "TCPServerInterface" - ) { + if limit == 0 || !autoconnect_admits(&record, &handle.config) { return; } let Some(host) = record.info.reachable_on.clone() else { @@ -6416,6 +6419,25 @@ async fn maybe_autoconnect_discovered(handle: &ReticulumHandle, record: Discover } } +/// Python auto-connects only Backbone interfaces of a trusted stack and +/// release, unless unverified stacks are allowed (Discovery.py:782-798). +fn autoconnect_admits(record: &DiscoveredInterface, config: &ReticulumConfig) -> bool { + let admitted = rns_transport::discovery::autoconnect::qualifies( + &record.info, + config.autoconnect_unverified_implementations, + ); + if !admitted { + tracing::debug!( + name = %record.info.name, + interface_type = %record.info.interface_type, + implementation = ?record.info.impl_name, + version = ?record.info.impl_version, + "not auto-connecting discovered interface, auto-connect criteria not satisfied" + ); + } + admitted +} + async fn spawn_discovered_backbone_client( handle: &ReticulumHandle, record: &DiscoveredInterface, @@ -12163,6 +12185,72 @@ loglevel = 7 assert_eq!(h.blackhole_sources()[0], [0xAA; 16]); } + /// Python's `autoconnect_unverified_implementations` (Reticulum.py:632-634). + #[test] + fn autoconnect_unverified_implementations_is_parsed_and_off_by_default() { + assert!(!ReticulumConfig::default().autoconnect_unverified_implementations); + let rc = ReticulumConfig::from_config( + &Config::parse("[reticulum]\nautoconnect_unverified_implementations = Yes\n").unwrap(), + ); + assert!(rc.autoconnect_unverified_implementations); + } + + /// Only Backbone interfaces from Python 1.5.2 or later, unless unverified + /// stacks are allowed (Discovery.py:782-798). + #[test] + fn discovered_interfaces_auto_connect_like_python() { + let record = |interface_type: &str, impl_name: Option<&str>, version: Option<&str>| { + DiscoveredInterface { + info: rns_transport::discovery::app_data::DiscoveryInfo { + interface_type: interface_type.into(), + impl_name: impl_name.map(str::to_string), + impl_version: version.map(str::to_string), + reachable_on: Some("192.0.2.10".into()), + port: Some(4242), + ..Default::default() + }, + network_id: [0x51; 16], + hops: 1, + stamp_value: 16, + stamp: vec![0; 32], + discovered: 0, + last_heard: 0, + heard_count: 1, + status: None, + } + }; + let mut config = ReticulumConfig::default(); + assert!(autoconnect_admits( + &record("BackboneInterface", Some("RNS"), Some("1.5.2")), + &config + )); + for rejected in [ + record("TCPServerInterface", Some("RNS"), Some("1.5.5")), + record("BackboneInterface", Some("RNS"), Some("1.5.1")), + record( + "BackboneInterface", + Some("rsRNS"), + Some(env!("CARGO_PKG_VERSION")), + ), + record("BackboneInterface", None, None), + ] { + assert!( + !autoconnect_admits(&rejected, &config), + "{:?}", + rejected.info + ); + } + config.autoconnect_unverified_implementations = true; + assert!(autoconnect_admits( + &record("BackboneInterface", Some("rsRNS"), Some("1.4.0")), + &config + )); + assert!(!autoconnect_admits( + &record("TCPServerInterface", None, None), + &config + )); + } + #[test] fn test_discovery_defaults_are_off() { let rc = ReticulumConfig::default(); diff --git a/crates/rns-transport/src/discovery/announcer.rs b/crates/rns-transport/src/discovery/announcer.rs index 188c376..05f8d6f 100644 --- a/crates/rns-transport/src/discovery/announcer.rs +++ b/crates/rns-transport/src/discovery/announcer.rs @@ -13,7 +13,8 @@ use crate::messages::InterfaceId; use super::app_data::{self, DiscoveryInfo, Encoded}; use super::constants::{ - ANNOUNCE_JOB_INTERVAL_SECS, DEFAULT_STAMP_VALUE, DISCOVERABLE_INTERFACE_TYPES, STAMP_SIZE, + ANNOUNCE_JOB_INTERVAL_SECS, DEFAULT_STAMP_VALUE, DISCOVERABLE_INTERFACE_TYPES, + IMPLEMENTATION_NAME, IMPLEMENTATION_VERSION, STAMP_SIZE, }; use super::stamper::DiscoveryStamper; @@ -368,6 +369,8 @@ fn config_to_info(cfg: &DiscoveryInterfaceConfig, transport_id: [u8; 16]) -> Dis DiscoveryInfo { name: cfg.name.clone(), transport_id, + impl_name: Some(IMPLEMENTATION_NAME.to_string()), + impl_version: Some(IMPLEMENTATION_VERSION.to_string()), interface_type: cfg.interface_type.clone(), transport_enabled: cfg.transport_enabled, reachable_on: cfg.reachable_on.clone(), @@ -504,6 +507,23 @@ mod tests { assert_eq!(info.port, Some(4965)); } + /// D12: the announcer names its own stack and version, as Python names + /// "RNS" and its `__version__` (Discovery.py:46-47, :173-174). + #[test] + fn announces_name_the_rust_implementation_and_its_version() { + let mut a = Announcer::new(static_stamper()); + a.register(1, [0x11; 16], sample_backbone()); + let (requests, _) = a.tick(1000.0, None); + let (_, body) = app_data::split_flags(&requests[0].app_data).unwrap(); + let (info_bytes, _) = app_data::split_stamp(body).unwrap(); + let info = app_data::decode_info(info_bytes).unwrap(); + assert_eq!(info.impl_name.as_deref(), Some("rsRNS")); + assert_eq!( + info.impl_version.as_deref(), + Some(env!("CARGO_PKG_VERSION")) + ); + } + #[test] fn subsequent_tick_within_interval_skips() { let mut a = Announcer::new(static_stamper()); diff --git a/crates/rns-transport/src/discovery/app_data.rs b/crates/rns-transport/src/discovery/app_data.rs index 96e475a..589d794 100644 --- a/crates/rns-transport/src/discovery/app_data.rs +++ b/crates/rns-transport/src/discovery/app_data.rs @@ -35,6 +35,10 @@ pub struct DiscoveryInfo { pub name: String, /// Transport identity hash of the announcer (key `0xFE`, 16 bytes). pub transport_id: [u8; 16], + /// The announcing stack and its version (keys `0xFD` / `0xFC`), when it + /// names them as strings. + pub impl_name: Option, + pub impl_version: Option, /// Interface type string, e.g. `"BackboneInterface"` (key `0x00`). pub interface_type: String, /// Whether the announcer has transport (routing) enabled (key `0x01`). @@ -167,6 +171,17 @@ fn info_to_map(info: &DiscoveryInfo) -> Vec<(Value, Value)> { u8_key(key::TRANSPORT_ID), Value::Binary(info.transport_id.to_vec()), ), + ]; + if let Some(impl_name) = &info.impl_name { + entries.push((u8_key(key::TRANSPORT_IMPL), Value::from(impl_name.clone()))); + } + if let Some(impl_version) = &info.impl_version { + entries.push(( + u8_key(key::TRANSPORT_VERS), + Value::from(impl_version.clone()), + )); + } + entries.extend([ (u8_key(key::NAME), Value::from(info.name.clone())), ( u8_key(key::LATITUDE), @@ -180,7 +195,7 @@ fn info_to_map(info: &DiscoveryInfo) -> Vec<(Value, Value)> { u8_key(key::HEIGHT), info.height.map_or(Value::Nil, Value::F64), ), - ]; + ]); if let Some(addr) = &info.reachable_on { entries.push((u8_key(key::REACHABLE_ON), Value::from(addr.clone()))); @@ -274,6 +289,8 @@ pub fn decode_info(packed: &[u8]) -> Result { info.interface_type = value_as_string(&v, kb)?; saw_interface_type = true; } + key::TRANSPORT_IMPL => info.impl_name = v.as_str().map(str::to_string), + key::TRANSPORT_VERS => info.impl_version = v.as_str().map(str::to_string), key::TRANSPORT => { info.transport_enabled = value_as_bool(&v, kb)?; } @@ -453,6 +470,47 @@ mod tests { } } + /// Python 1.5.5 packs the implementation name and version right after + /// the transport id (Discovery.py:170-178). + #[test] + fn implementation_keys_follow_the_transport_id_as_python_packs_them() { + let mut info = sample_backbone(); + info.impl_name = Some("rsRNS".into()); + info.impl_version = Some("1.4.0".into()); + let encoded = encode_info(&info).unwrap(); + let Value::Map(map) = rmpv::decode::read_value(&mut Cursor::new(&encoded.packed)).unwrap() + else { + panic!("info is a map"); + }; + let keys: Vec = map.iter().map(|(k, _)| value_as_u8(k).unwrap()).collect(); + assert_eq!( + keys[..6], + [ + key::INTERFACE_TYPE, + key::TRANSPORT, + key::TRANSPORT_ID, + key::TRANSPORT_IMPL, + key::TRANSPORT_VERS, + key::NAME + ] + ); + assert_eq!(map[3].1.as_str(), Some("rsRNS")); + assert_eq!(map[4].1.as_str(), Some("1.4.0")); + assert_eq!(decode_info(&encoded.packed).unwrap(), info); + } + + /// Python reads the keys without checking their type (Discovery.py:348-349). + #[test] + fn an_implementation_that_is_not_a_string_is_ignored() { + let mut map = info_to_map(&sample_backbone()); + map.push((u8_key(key::TRANSPORT_IMPL), Value::from(7u64))); + map.push((u8_key(key::TRANSPORT_VERS), Value::Nil)); + let mut packed = Vec::new(); + rmpv::encode::write_value(&mut packed, &Value::Map(map)).unwrap(); + let decoded = decode_info(&packed).unwrap(); + assert_eq!((decoded.impl_name, decoded.impl_version), (None, None)); + } + #[test] fn independent_nullable_coordinates_preserve_zero_and_hash() { let mut hashes = std::collections::HashSet::new(); diff --git a/crates/rns-transport/src/discovery/autoconnect.rs b/crates/rns-transport/src/discovery/autoconnect.rs new file mode 100644 index 0000000..23d901c --- /dev/null +++ b/crates/rns-transport/src/discovery/autoconnect.rs @@ -0,0 +1,110 @@ +//! Which discovered interfaces may be auto-connected +//! (`InterfaceDiscovery.autoconnect_qualified`, Discovery.py:782-798). + +use super::app_data::DiscoveryInfo; +use super::constants::{AUTOCONNECT_INTERFACE_TYPES, AUTOCONNECT_MINIMUM_VERSIONS}; + +/// A Backbone interface whose stack is at least the trusted release of its +/// implementation, or any Backbone interface when `allow_unverified` +/// (`autoconnect_unverified_implementations`) is set. +pub fn qualifies(info: &DiscoveryInfo, allow_unverified: bool) -> bool { + if !AUTOCONNECT_INTERFACE_TYPES.contains(&info.interface_type.as_str()) { + return false; + } + if allow_unverified { + return true; + } + let (Some(name), Some(version)) = (info.impl_name.as_deref(), info.impl_version.as_deref()) + else { + return false; + }; + let Some(minimum) = AUTOCONNECT_MINIMUM_VERSIONS + .iter() + .find(|(implementation, _)| *implementation == name) + .and_then(|(_, minimum)| minimum.and_then(version_tuple)) + else { + return false; + }; + version_tuple(version).is_some_and(|version| version >= minimum) +} + +/// Python's `version_tuple`: the leading digits of each dot-separated +/// component, up to the first without any (Discovery.py:995-1005). +fn version_tuple(version: &str) -> Option> { + let components: Vec = version + .trim() + .split('.') + .map_while(|component| { + let digits = component + .find(|c: char| !c.is_ascii_digit()) + .map_or(component, |end| &component[..end]); + (!digits.is_empty()).then(|| digits.parse().unwrap_or(u64::MAX)) + }) + .collect(); + (!components.is_empty()).then_some(components) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn backbone(impl_name: Option<&str>, impl_version: Option<&str>) -> DiscoveryInfo { + DiscoveryInfo { + interface_type: "BackboneInterface".into(), + impl_name: impl_name.map(str::to_string), + impl_version: impl_version.map(str::to_string), + ..Default::default() + } + } + + /// Python 1.5.5 auto-connects only to "RNS" 1.5.2 or later + /// (Discovery.py:486-487, :782-790). + #[test] + fn python_backbones_qualify_from_1_5_2() { + assert!(qualifies(&backbone(Some("RNS"), Some("1.5.2")), false)); + assert!(qualifies(&backbone(Some("RNS"), Some("1.5.10")), false)); + assert!(qualifies(&backbone(Some("RNS"), Some("1.6")), false)); + assert!(qualifies(&backbone(Some("RNS"), Some("1.5.2rc1")), false)); + assert!(!qualifies(&backbone(Some("RNS"), Some("1.5.1")), false)); + assert!(!qualifies(&backbone(Some("RNS"), Some("1.5")), false)); + assert!(!qualifies(&backbone(Some("RNS"), Some("")), false)); + assert!(!qualifies(&backbone(Some("RNS"), Some("next")), false)); + assert!(!qualifies(&backbone(Some("RNS"), None), false)); + } + + /// No rsRNS release has Backbone egress control yet, so rsRNS hubs need + /// the unverified opt-in, as unknown stacks and announces without an + /// implementation do. + #[test] + fn rust_and_unknown_stacks_need_the_unverified_opt_in() { + for info in [ + backbone(Some("rsRNS"), Some(env!("CARGO_PKG_VERSION"))), + backbone(Some("rsRNS"), Some("99.0.0")), + backbone(Some("OtherRNS"), Some("9.9.9")), + backbone(None, Some("1.5.5")), + backbone(None, None), + ] { + assert!(!qualifies(&info, false), "{info:?}"); + assert!(qualifies(&info, true), "{info:?}"); + } + } + + /// Python auto-connects only Backbone interfaces (Discovery.py:483, :798). + #[test] + fn only_backbone_interfaces_are_auto_connected() { + assert_eq!(AUTOCONNECT_INTERFACE_TYPES, &["BackboneInterface"]); + let mut server = backbone(Some("RNS"), Some("1.5.5")); + server.interface_type = "TCPServerInterface".into(); + assert!(!qualifies(&server, true)); + } + + #[test] + fn versions_parse_like_python_version_tuple() { + assert_eq!(version_tuple("1.5.2"), Some(vec![1, 5, 2])); + assert_eq!(version_tuple(" 1.5.2 "), Some(vec![1, 5, 2])); + assert_eq!(version_tuple("1.5.2rc1"), Some(vec![1, 5, 2])); + assert_eq!(version_tuple("1.x.2"), Some(vec![1])); + assert_eq!(version_tuple("v1.5"), None); + assert_eq!(version_tuple(""), None); + } +} diff --git a/crates/rns-transport/src/discovery/constants.rs b/crates/rns-transport/src/discovery/constants.rs index 662629c..db07e8e 100644 --- a/crates/rns-transport/src/discovery/constants.rs +++ b/crates/rns-transport/src/discovery/constants.rs @@ -37,8 +37,8 @@ pub const STAMP_SIZE: usize = 32; pub const FLAG_SIGNED: u8 = 0b0000_0001; pub const FLAG_ENCRYPTED: u8 = 0b0000_0010; -/// Interface types that announce themselves via discovery. Mirrors -/// `InterfaceAnnouncer.DISCOVERABLE_INTERFACE_TYPES`. +/// Interface types that announce themselves via discovery, and that a +/// receiver accepts. Mirrors `InterfaceAnnouncer.DISCOVERABLE_INTERFACE_TYPES`. pub const DISCOVERABLE_INTERFACE_TYPES: &[&str] = &[ "BackboneInterface", "TCPServerInterface", @@ -49,9 +49,34 @@ pub const DISCOVERABLE_INTERFACE_TYPES: &[&str] = &[ "KISSInterface", ]; +/// Discovered interface types that are listed; stored records of other types +/// are removed. Mirrors `InterfaceDiscovery.DISCOVERABLE_TYPES`. +pub const DISCOVERED_INTERFACE_TYPES: &[&str] = &[ + "BackboneInterface", + "TCPServerInterface", + "I2PInterface", + "RNodeInterface", + "WeaveInterface", + "KISSInterface", +]; + /// Interface types eligible for auto-connect. Mirrors /// `InterfaceDiscovery.AUTOCONNECT_TYPES`. -pub const AUTOCONNECT_INTERFACE_TYPES: &[&str] = &["BackboneInterface", "TCPServerInterface"]; +pub const AUTOCONNECT_INTERFACE_TYPES: &[&str] = &["BackboneInterface"]; + +/// The implementation name this stack announces (`0xFD`); Python announces +/// "RNS" (`IMPLEMENTATION_NAME`). +pub const IMPLEMENTATION_NAME: &str = "rsRNS"; + +/// The version this stack announces (`0xFC`): its own, never Python's. +pub const IMPLEMENTATION_VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// The oldest release of each implementation that auto-connect trusts. +/// Python's 1.5.2 floor is its Backbone flow control; no rsRNS release has +/// Backbone egress control yet, so none qualifies without +/// `autoconnect_unverified_implementations`. +pub const AUTOCONNECT_MINIMUM_VERSIONS: &[(&str, Option<&str>)] = + &[("RNS", Some("1.5.2")), (IMPLEMENTATION_NAME, None)]; /// Freshness tiers for discovered interfaces (seconds). Match /// `InterfaceDiscovery.THRESHOLD_*`. @@ -75,6 +100,8 @@ pub const BLACKHOLE_SOURCE_TIMEOUT_SECS: u64 = 25; pub mod key { pub const NAME: u8 = 0xFF; pub const TRANSPORT_ID: u8 = 0xFE; + pub const TRANSPORT_IMPL: u8 = 0xFD; + pub const TRANSPORT_VERS: u8 = 0xFC; pub const INTERFACE_TYPE: u8 = 0x00; pub const TRANSPORT: u8 = 0x01; pub const REACHABLE_ON: u8 = 0x02; diff --git a/crates/rns-transport/src/discovery/mod.rs b/crates/rns-transport/src/discovery/mod.rs index 9b282bd..a78ce00 100644 --- a/crates/rns-transport/src/discovery/mod.rs +++ b/crates/rns-transport/src/discovery/mod.rs @@ -15,6 +15,7 @@ pub mod announcer; pub mod app_data; +pub mod autoconnect; pub mod blackhole_manifest; pub mod blackhole_subscriber; pub mod constants; diff --git a/crates/rns-transport/src/discovery/receiver.rs b/crates/rns-transport/src/discovery/receiver.rs index 2a36fd1..30d6545 100644 --- a/crates/rns-transport/src/discovery/receiver.rs +++ b/crates/rns-transport/src/discovery/receiver.rs @@ -6,7 +6,8 @@ //! 1. split the `app_data` payload into flags / body / stamp, //! 2. (optionally) decrypt the body using a shared-network decryptor, //! 3. validate the stamp against a [`DiscoveryStamper`], -//! 4. decode the info map, filter by `discovery_sources` if configured, +//! 4. decode the info map, filter by `discovery_sources` if configured, and +//! drop types that are never listed, //! 5. upsert into [`DiscoveryStore`] and notify any observer. //! //! Mirrors Python `Discovery.InterfaceAnnounceHandler.received_announce`. @@ -25,7 +26,7 @@ use tracing::{debug, trace, warn}; use crate::messages::AnnounceHandlerEvent; use super::app_data::{self, DiscoveryInfo}; -use super::constants::FLAG_ENCRYPTED; +use super::constants::{DISCOVERED_INTERFACE_TYPES, FLAG_ENCRYPTED}; use super::stamper::DiscoveryStamper; use super::storage::{DiscoveredInterface, DiscoveryStore}; @@ -93,6 +94,8 @@ pub enum Reason { DecodeFailed, /// Source (transport_id) not in the configured discovery_sources list. UnauthorizedSource, + /// An announceable type that is never listed ([`DISCOVERED_INTERFACE_TYPES`]). + UnlistedType, /// Upsert into the on-disk store failed (io error). StorageFailed, } @@ -416,6 +419,9 @@ impl ReceiverConfig { { return Outcome::Rejected(Reason::UnauthorizedSource); } + if !DISCOVERED_INTERFACE_TYPES.contains(&info.interface_type.as_str()) { + return Outcome::Rejected(Reason::UnlistedType); + } let now = now_unix(); let record = DiscoveredInterface { @@ -1038,6 +1044,35 @@ mod tests { assert_eq!(received.info.name, "unit-test-iface"); } + /// Python validates TCPClientInterface announces but neither stores nor + /// reports them (Discovery.py:354, :596). + #[test] + fn client_interfaces_are_validated_but_not_stored() { + let dir = tmpdir("client"); + let store = Arc::new(DiscoveryStore::open(&dir).unwrap()); + let stamp = vec![0xAB; STAMP_SIZE]; + let stamper = Arc::new(MockStamper::new(stamp.clone(), 20)); + let mut info = sample_info(); + info.interface_type = "TCPClientInterface".into(); + let (blob, _) = stamped_blob(&info, &stamp); + + let (obs_tx, mut obs_rx) = mpsc::channel::(4); + let cfg = ReceiverConfig { + stamper, + store: store.clone(), + required_value: 14, + discovery_sources: None, + decryptor: None, + observer: Some(obs_tx), + }; + assert_eq!( + cfg.process_event(&event_with(blob)), + Outcome::Rejected(Reason::UnlistedType) + ); + assert!(obs_rx.try_recv().is_err()); + assert_eq!(std::fs::read_dir(store.root()).unwrap().count(), 0); + } + #[test] fn valid_cache_hit_runs_stamper_once() { let dir = tmpdir("valid-cache"); diff --git a/crates/rns-transport/src/discovery/storage.rs b/crates/rns-transport/src/discovery/storage.rs index 1df9958..a578461 100644 --- a/crates/rns-transport/src/discovery/storage.rs +++ b/crates/rns-transport/src/discovery/storage.rs @@ -9,7 +9,8 @@ use thiserror::Error; use super::app_data::DiscoveryInfo; use super::constants::{ - STAMP_SIZE, THRESHOLD_REMOVE_SECS, THRESHOLD_STALE_SECS, THRESHOLD_UNKNOWN_SECS, + DISCOVERED_INTERFACE_TYPES, STAMP_SIZE, THRESHOLD_REMOVE_SECS, THRESHOLD_STALE_SECS, + THRESHOLD_UNKNOWN_SECS, }; /// Freshness status for a learned interface. @@ -148,8 +149,9 @@ impl DiscoveryStore { } /// List records sorted desc by `(status_code, stamp_value, last_heard)`. - /// Expired entries are culled from disk; `discovery_sources` (when set) - /// filters out records whose `network_id` is not in the set. + /// Expired records, records of a type Python does not list, and records + /// whose `network_id` is not in `discovery_sources` (when set) are culled + /// from disk (Discovery.py:536-547). pub fn list( &self, discovery_sources: Option<&[[u8; 16]]>, @@ -183,7 +185,8 @@ impl DiscoveryStore { }; let heard_delta = now.saturating_sub(rec.last_heard); - let mut should_remove = heard_delta > THRESHOLD_REMOVE_SECS; + let mut should_remove = heard_delta > THRESHOLD_REMOVE_SECS + || !DISCOVERED_INTERFACE_TYPES.contains(&rec.info.interface_type.as_str()); if let Some(sources) = discovery_sources && !sources.iter().any(|s| s == &rec.network_id) { @@ -240,6 +243,12 @@ fn encode_record(rec: &DiscoveredInterface) -> Result, StorageError> { let i = &rec.info; map.push((s("type"), Value::from(i.interface_type.clone()))); + if let Some(impl_name) = &i.impl_name { + map.push((s("impl_name"), Value::from(impl_name.clone()))); + } + if let Some(impl_version) = &i.impl_version { + map.push((s("version"), Value::from(impl_version.clone()))); + } map.push((s("transport"), Value::from(i.transport_enabled))); map.push((s("name"), Value::from(i.name.clone()))); map.push((s("transport_id"), Value::from(hex::encode(i.transport_id)))); @@ -311,6 +320,8 @@ fn decode_record(bytes: &[u8]) -> Result { let info = DiscoveryInfo { interface_type: str_or_default(&lookup, "type"), + impl_name: str_opt(&lookup, "impl_name"), + impl_version: str_opt(&lookup, "version"), transport_enabled: bool_or_default(&lookup, "transport"), transport_id: hex16(&lookup, "transport_id").unwrap_or([0; 16]), name: str_or_default(&lookup, "name"), @@ -575,6 +586,67 @@ mod tests { assert_eq!(listed_again.len(), 1); } + /// Python stores the announcer's stack as `impl_name` and `version` + /// (Discovery.py:364-365). + #[test] + fn records_keep_the_announcing_implementation() { + let dir = tmpdir("implementation"); + let store = DiscoveryStore::open(&dir).unwrap(); + let mut r = record("versioned", [0x31; 16]); + r.last_heard = unix_now(); + r.info.impl_name = Some("RNS".into()); + r.info.impl_version = Some("1.5.5".into()); + store.upsert(r).unwrap(); + + let listed = store.list(None).unwrap(); + assert_eq!(listed[0].info.impl_name.as_deref(), Some("RNS")); + assert_eq!(listed[0].info.impl_version.as_deref(), Some("1.5.5")); + let raw = std::fs::read(store.root().join(listed[0].filename())).unwrap(); + let Value::Map(map) = rmpv::decode::read_value(&mut raw.as_slice()).unwrap() else { + panic!("record is a map"); + }; + let field = |name: &str| { + map.iter() + .find(|(k, _)| k.as_str() == Some(name)) + .and_then(|(_, v)| v.as_str().map(str::to_string)) + }; + assert_eq!(field("impl_name").as_deref(), Some("RNS")); + assert_eq!(field("version").as_deref(), Some("1.5.5")); + } + + /// Python lists only `InterfaceDiscovery.DISCOVERABLE_TYPES` and removes + /// other records, such as a KISS TCP client's (Discovery.py:484, :542). + #[test] + fn listing_removes_types_python_does_not_list() { + let dir = tmpdir("listed_types"); + let store = DiscoveryStore::open(&dir).unwrap(); + let now = unix_now(); + for (id, name, interface_type) in [ + (1, "backbone", "BackboneInterface"), + (2, "kiss-tcp", "TCPClientInterface"), + (3, "rnode", "RNodeInterface"), + ] { + let mut r = record(name, [id; 16]); + r.info.interface_type = interface_type.into(); + r.last_heard = now; + store.upsert(r).unwrap(); + } + + let listed: Vec = store + .list(None) + .unwrap() + .into_iter() + .map(|r| r.info.name) + .collect(); + assert_eq!(listed.len(), 2); + assert!(!listed.contains(&"kiss-tcp".to_string())); + assert_eq!( + std::fs::read_dir(store.root()).unwrap().count(), + 2, + "the unlisted record is removed from disk" + ); + } + #[test] fn list_removes_expired() { let dir = tmpdir("expired");