From 4845bc1f93d74385fdbe0929d6d878bdcb773a2c Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:39:26 -0700 Subject: [PATCH] filter: hash entries, flagged names and the config-dir type lists --- crates/rns-runtime/src/config.rs | 42 +++++ crates/rns-runtime/src/reticulum.rs | 20 +++ .../src/reticulum/tests/paths_and_filters.rs | 23 +++ crates/rns-transport/src/actor/inbound.rs | 2 +- .../rns-transport/src/destination_filter.rs | 151 ++++++++++++++++-- 5 files changed, 225 insertions(+), 13 deletions(-) create mode 100644 crates/rns-runtime/src/reticulum/tests/paths_and_filters.rs diff --git a/crates/rns-runtime/src/config.rs b/crates/rns-runtime/src/config.rs index f093607..db50b1a 100644 --- a/crates/rns-runtime/src/config.rs +++ b/crates/rns-runtime/src/config.rs @@ -796,6 +796,32 @@ const DEFAULT_CONFIG: &str = r#"################################################ enabled = Yes "#; +/// A list file in the config directory as Reticulum.py reads one: the whole +/// text stripped and split into lines, each line stripped, `#` lines skipped. +/// `None` when the file is absent. +pub(crate) fn read_list_file(path: &Path) -> std::io::Result>> { + if !path.is_file() { + return Ok(None); + } + Ok(Some(list_file_lines(&std::fs::read_to_string(path)?))) +} + +/// Python `str.strip().splitlines()`, then per-line `strip()`. +fn list_file_lines(text: &str) -> Vec { + let text = text.trim(); + if text.is_empty() { + return Vec::new(); + } + text.replace("\r\n", "\n") + .split([ + '\n', '\r', '\x0b', '\x0c', '\x1c', '\x1d', '\x1e', '\u{85}', '\u{2028}', '\u{2029}', + ]) + .map(str::trim) + .filter(|line| !line.starts_with('#')) + .map(String::from) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -831,6 +857,22 @@ mod tests { assert!(config.sections.is_empty()); } + #[test] + fn list_files_read_like_upstream() { + assert_eq!( + list_file_lines("\n# names\n lxmf.delivery \r\n\n#x\nnomadnetwork.node\n\n"), + ["lxmf.delivery", "", "nomadnetwork.node"] + ); + assert!(list_file_lines(" \n\t").is_empty()); + let dir = std::env::temp_dir().join(format!("rns-list-file-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("known_destination_types"); + assert!(read_list_file(&path).unwrap().is_none()); + std::fs::write(&path, "a.b\n#c.d\n").unwrap(); + assert_eq!(read_list_file(&path).unwrap().unwrap(), ["a.b"]); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn filter_section_follows_upstream_keys() { let config = Config::parse( diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index fd809d8..225d39f 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -3861,6 +3861,7 @@ pub async fn init_with_policy( } let mut rc = ReticulumConfig::try_from_config(&config).map_err(ReticulumError::Config)?; rc.apply_init_options(&options); + load_config_dir_lists(&config_dir, &mut rc); match &policy { InstancePolicy::Configured => {} InstancePolicy::Standalone => rc.share_instance = false, @@ -11029,6 +11030,24 @@ pub fn get_instance() -> Option<&'static ReticulumHandle> { INSTANCE.get() } +/// The list files beside `config` (Reticulum.py); a file that cannot be read +/// is logged and skipped, as upstream does. +fn load_config_dir_lists(config_dir: &Path, rc: &mut ReticulumConfig) { + let read = |name: &str| match crate::config::read_list_file(&config_dir.join(name)) { + Ok(lines) => lines, + Err(error) => { + tracing::error!(file = name, %error, "could not load config directory list"); + None + } + }; + if let Some(names) = read("known_destination_types") { + rc.filter.known_types = names; + } + if let Some(names) = read("flagged_destination_types") { + rc.filter.flagged_types = names; + } +} + fn load_or_create_config(path: &Path) -> Result<(Config, bool), ReticulumError> { if path.exists() { Config::from_file(path) @@ -11251,6 +11270,7 @@ mod tests { mod concurrent_start; mod interface_stats; mod manage_interfaces; + mod paths_and_filters; mod tunnels; #[test] diff --git a/crates/rns-runtime/src/reticulum/tests/paths_and_filters.rs b/crates/rns-runtime/src/reticulum/tests/paths_and_filters.rs new file mode 100644 index 0000000..3f8b4fb --- /dev/null +++ b/crates/rns-runtime/src/reticulum/tests/paths_and_filters.rs @@ -0,0 +1,23 @@ +//! Runtime wiring for the path table and traffic filters: the config +//! directory's list files, per-interface hop limits and filter registrations. +use super::*; + +#[test] +fn config_dir_type_lists_fill_the_filter_policy() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("known_destination_types"), + "# known\nlxmf.delivery\n", + ) + .unwrap(); + std::fs::write(dir.path().join("flagged_destination_types"), "spam.type\n").unwrap(); + let mut rc = ReticulumConfig::default(); + load_config_dir_lists(dir.path(), &mut rc); + assert_eq!(rc.filter.known_types, ["lxmf.delivery"]); + assert_eq!(rc.filter.flagged_types, ["spam.type"]); + + let empty = tempfile::tempdir().unwrap(); + let mut rc = ReticulumConfig::default(); + load_config_dir_lists(empty.path(), &mut rc); + assert!(rc.filter.known_types.is_empty() && rc.filter.flagged_types.is_empty()); +} diff --git a/crates/rns-transport/src/actor/inbound.rs b/crates/rns-transport/src/actor/inbound.rs index d33f516..bbbf0ae 100644 --- a/crates/rns-transport/src/actor/inbound.rs +++ b/crates/rns-transport/src/actor/inbound.rs @@ -531,7 +531,7 @@ impl TransportActor { { trace!( interface_id, - destination_type = self.destination_filter.type_name(&name_hash), + destination_type = self.destination_filter.pretty_name(&name_hash), "announce filtered as not required" ); self.filtered_announce(interface_id); diff --git a/crates/rns-transport/src/destination_filter.rs b/crates/rns-transport/src/destination_filter.rs index 361436f..786fc67 100644 --- a/crates/rns-transport/src/destination_filter.rs +++ b/crates/rns-transport/src/destination_filter.rs @@ -11,16 +11,21 @@ pub const NAME_HASH_LEN: usize = 10; pub type NameHash = [u8; NAME_HASH_LEN]; -/// The `[filter]` configuration (Reticulum.py). +/// The `[filter]` configuration and the config directory's type-name files +/// (Reticulum.py). #[derive(Debug, Clone, PartialEq, Eq)] pub struct FilterPolicy { pub required_only: bool, - /// Full destination names, Python `ignored_types`. + /// Python `ignored_types`: full destination names, or `` name hashes. pub ignored_types: Vec, - /// Full destination names, Python `allowed_types`. + /// Python `allowed_types`: full destination names, or `` name hashes. pub allowed_types: Vec, /// Packets arriving with this many wire hops or more are dropped. pub hop_limiter: u8, + /// Full names from `known_destination_types`, for logs only. + pub known_types: Vec, + /// Full names from `flagged_destination_types`, for logs only. + pub flagged_types: Vec, } impl Default for FilterPolicy { @@ -30,6 +35,8 @@ impl Default for FilterPolicy { ignored_types: Vec::new(), allowed_types: Vec::new(), hop_limiter: crate::constants::PATHFINDER_M, + known_types: Vec::new(), + flagged_types: Vec::new(), } } } @@ -55,12 +62,51 @@ pub(crate) struct DestinationTypeFilter { allowed: HashSet, client: HashMap>>, names: HashMap, + flagged: HashMap, required_only: bool, } +/// A type-filter entry as Python's `block_destination_type` and +/// `allow_destination_type` read it: `<…>` takes the next 20 characters as a +/// hex name hash, else hashes those characters as a name. `None` for an empty +/// entry, or hex that is not one name hash long, which upstream stores but can +/// never match. +fn parse_type_entry(full_name: &str) -> Option<(NameHash, String)> { + if full_name.is_empty() { + return None; + } + if !(full_name.starts_with('<') && full_name.ends_with('>')) { + return Some((name_hash(full_name), full_name.to_string())); + } + let sliced: String = full_name.chars().skip(1).take(NAME_HASH_LEN * 2).collect(); + match py_fromhex(&sliced) { + Some(bytes) if bytes.len() == NAME_HASH_LEN => { + Some((bytes.try_into().expect("checked length"), sliced)) + } + Some(bytes) if !bytes.is_empty() => None, + _ => Some((name_hash(&sliced), sliced)), + } +} + +/// Python `bytes.fromhex`: hex pairs, with ASCII whitespace allowed between them. +fn py_fromhex(text: &str) -> Option> { + let digit = |c: char| c.to_digit(16).filter(|_| c.is_ascii()); + let mut out = Vec::new(); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + if matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r') { + continue; + } + let high = digit(c)?; + let low = digit(chars.next()?)?; + out.push((high * 16 + low) as u8); + } + Some(out) +} + impl DestinationTypeFilter { /// Apply a configuration: `ignored_types` through `block`, `allowed_types` - /// through `allow`, in Python's order. + /// through `allow`, then the type-name files, in Python's order. pub fn apply_policy(&mut self, policy: &FilterPolicy) { self.required_only = policy.required_only; for name in &policy.ignored_types { @@ -69,25 +115,37 @@ impl DestinationTypeFilter { for name in &policy.allowed_types { self.allow(name); } + for name in &policy.known_types { + self.names.insert(name_hash(name), name.clone()); + } + for name in &policy.flagged_types { + self.flagged.insert(name_hash(name), name.clone()); + } } pub fn set_required_only(&mut self, enabled: bool) { self.required_only = enabled; } - /// Python `block_destination_type`: a blocked type is no longer wanted. + /// Python `block_destination_type`: a blocked type is no longer wanted, + /// and its name is flagged. pub fn block(&mut self, full_name: &str) { - let hash = name_hash(full_name); + let Some((hash, name)) = parse_type_entry(full_name) else { + return; + }; self.blocked.insert(hash); self.client.remove(&hash); - self.names.insert(hash, full_name.to_string()); + self.names.insert(hash, name.clone()); + self.flagged.insert(hash, name); } /// Python `allow_destination_type`. pub fn allow(&mut self, full_name: &str) { - let hash = name_hash(full_name); + let Some((hash, name)) = parse_type_entry(full_name) else { + return; + }; self.allowed.insert(hash); - self.names.insert(hash, full_name.to_string()); + self.names.insert(hash, name); } /// Python `_wants_destination_type`: false only for a blocked type. @@ -132,9 +190,19 @@ impl DestinationTypeFilter { self.client.contains_key(hash) } - /// Python `destination_type_name`. - pub fn type_name(&self, hash: &NameHash) -> &str { - self.names.get(hash).map_or("unknown", String::as_str) + /// Python `destination_type_name`: the known name, else the flagged + /// name, else the hash in hex. + pub fn type_name(&self, hash: &NameHash) -> String { + self.names + .get(hash) + .or_else(|| self.flagged.get(hash)) + .cloned() + .unwrap_or_else(|| hex::encode(hash)) + } + + /// Python `prettynamehash`. + pub fn pretty_name(&self, hash: &NameHash) -> String { + format!("<{}>", self.type_name(hash)) } /// Python drops a blocked type silently, ahead of the required-only check. @@ -174,6 +242,65 @@ mod tests { assert!(!f.wants("a.b", vec![1])); } + /// Transport.py 1.6.1 (e96c81c3): `` is a name hash; anything else + /// in angle brackets is hashed as the 20 characters after `<`. + #[test] + fn angle_bracket_entries_are_name_hashes() { + let hash: NameHash = hex::decode("c4ace368262d845c9dd3") + .unwrap() + .try_into() + .unwrap(); + for entry in [ + "", + "", + "", + ] { + let mut f = DestinationTypeFilter::default(); + f.block(entry); + assert!(!f.admits(&hash, AnnounceSource::Other, 0), "{entry}"); + assert_eq!(f.type_name(&hash).to_lowercase(), "c4ace368262d845c9dd3"); + } + let mut f = DestinationTypeFilter::default(); + f.block(""); + assert!(!f.admits(&name_hash("abcd>"), AnnounceSource::Other, 0)); + f.set_required_only(true); + f.allow("<0123456789abcdef0123>"); + let allowed: NameHash = hex::decode("0123456789abcdef0123") + .unwrap() + .try_into() + .unwrap(); + assert!(f.admits(&allowed, AnnounceSource::Other, 0)); + // A client registration hashes the literal text. + assert!(f.wants("<0011223344556677889a>", vec![1])); + assert!(f.is_wanted(&name_hash("<0011223344556677889a>"))); + // Whitespace between pairs is skipped, as `bytes.fromhex` does; a + // short result matches nothing. + assert_eq!(parse_type_entry(""), None); + assert_eq!(parse_type_entry(""), None); + } + + /// Transport.py 1.6.1: known name, else flagged name, else bare hex; a + /// blocked type is flagged, and the name files apply after `[filter]`. + #[test] + fn type_names_fall_back_to_flagged_then_hex() { + let mut f = DestinationTypeFilter::default(); + f.apply_policy(&FilterPolicy { + ignored_types: vec!["spam.type".into()], + known_types: vec!["lxmf.delivery".into(), "spam.type".into()], + flagged_types: vec!["bad.type".into()], + ..Default::default() + }); + assert_eq!(f.type_name(&name_hash("lxmf.delivery")), "lxmf.delivery"); + assert_eq!(f.type_name(&name_hash("bad.type")), "bad.type"); + assert_eq!(f.flagged.get(&name_hash("spam.type")).unwrap(), "spam.type"); + let unknown = name_hash("other.type"); + assert_eq!(f.type_name(&unknown), hex::encode(unknown)); + assert_eq!( + f.pretty_name(&unknown), + format!("<{}>", hex::encode(unknown)) + ); + } + #[test] fn unwants_reports_registration_and_last_requester_drops_type() { let mut f = DestinationTypeFilter::default();