Skip to main content

rns_net/
discovery.rs

1//! Interface Discovery protocol implementation.
2//!
3//! Handles receiving, validating, and storing discovered interface announcements
4//! from other Reticulum nodes on the network.
5//!
6//! Pure types and parsing live in `common::discovery`; this module contains
7//! I/O storage and background-threaded stamp generation / announcing.
8//!
9//! Python reference: RNS/Discovery.py
10
11// Re-export everything from common::discovery so existing `crate::discovery::X` paths work.
12pub use crate::common::discovery::*;
13
14use std::fs;
15use std::io;
16use std::path::PathBuf;
17
18use rns_core::msgpack::{self, Value};
19use rns_core::stamp::{stamp_valid, stamp_workblock};
20use rns_crypto::sha256::sha256;
21
22use crate::time;
23
24// ============================================================================
25// Storage
26// ============================================================================
27
28/// Persistent storage for discovered interfaces
29pub struct DiscoveredInterfaceStorage {
30    base_path: PathBuf,
31}
32
33impl DiscoveredInterfaceStorage {
34    /// Create a new storage instance
35    pub fn new(base_path: PathBuf) -> Self {
36        Self { base_path }
37    }
38
39    /// Store a discovered interface
40    pub fn store(&self, iface: &DiscoveredInterface) -> io::Result<()> {
41        let filename = hex_encode(&iface.discovery_hash);
42        let filepath = self.base_path.join(filename);
43
44        let data = self.serialize_interface(iface)?;
45        fs::write(&filepath, &data)
46    }
47
48    /// Load a discovered interface by its discovery hash
49    pub fn load(&self, discovery_hash: &[u8; 32]) -> io::Result<Option<DiscoveredInterface>> {
50        let filename = hex_encode(discovery_hash);
51        let filepath = self.base_path.join(filename);
52
53        if !filepath.exists() {
54            return Ok(None);
55        }
56
57        let data = fs::read(&filepath)?;
58        self.deserialize_interface(&data).map(Some)
59    }
60
61    /// List all discovered interfaces
62    pub fn list(&self) -> io::Result<Vec<DiscoveredInterface>> {
63        let mut interfaces = Vec::new();
64
65        let entries = match fs::read_dir(&self.base_path) {
66            Ok(e) => e,
67            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(interfaces),
68            Err(e) => return Err(e),
69        };
70
71        for entry in entries {
72            let entry = entry?;
73            let path = entry.path();
74
75            if !path.is_file() {
76                continue;
77            }
78
79            match fs::read(&path) {
80                Ok(data) => {
81                    if let Ok(iface) = self.deserialize_interface(&data) {
82                        interfaces.push(iface);
83                    }
84                }
85                Err(_) => continue,
86            }
87        }
88
89        Ok(interfaces)
90    }
91
92    /// Remove a discovered interface by its discovery hash
93    pub fn remove(&self, discovery_hash: &[u8; 32]) -> io::Result<()> {
94        let filename = hex_encode(discovery_hash);
95        let filepath = self.base_path.join(filename);
96
97        if filepath.exists() {
98            fs::remove_file(&filepath)?;
99        }
100        Ok(())
101    }
102
103    /// Clean up stale entries (older than THRESHOLD_REMOVE)
104    /// Returns the number of entries removed
105    pub fn cleanup(&self) -> io::Result<usize> {
106        let mut removed = 0;
107        let now = time::now();
108
109        let interfaces = self.list()?;
110        for iface in interfaces {
111            let invalid_reachable_on = iface
112                .reachable_on
113                .as_ref()
114                .map(|reachable_on| !(is_ip_address(reachable_on) || is_hostname(reachable_on)))
115                .unwrap_or(false);
116
117            if !is_discoverable_type(&iface.interface_type)
118                || invalid_reachable_on
119                || now - iface.last_heard > THRESHOLD_REMOVE
120            {
121                self.remove(&iface.discovery_hash)?;
122                removed += 1;
123            }
124        }
125
126        Ok(removed)
127    }
128
129    /// Serialize an interface to msgpack
130    fn serialize_interface(&self, iface: &DiscoveredInterface) -> io::Result<Vec<u8>> {
131        let mut entries: Vec<(Value, Value)> = Vec::new();
132
133        entries.push((
134            Value::Str("type".into()),
135            Value::Str(iface.interface_type.clone()),
136        ));
137        entries.push((Value::Str("transport".into()), Value::Bool(iface.transport)));
138        entries.push((Value::Str("name".into()), Value::Str(iface.name.clone())));
139        entries.push((
140            Value::Str("discovered".into()),
141            Value::Float(iface.discovered),
142        ));
143        entries.push((
144            Value::Str("last_heard".into()),
145            Value::Float(iface.last_heard),
146        ));
147        entries.push((
148            Value::Str("heard_count".into()),
149            Value::UInt(iface.heard_count as u64),
150        ));
151        entries.push((
152            Value::Str("status".into()),
153            Value::Str(iface.status.as_str().into()),
154        ));
155        entries.push((Value::Str("stamp".into()), Value::Bin(iface.stamp.clone())));
156        entries.push((
157            Value::Str("value".into()),
158            Value::UInt(iface.stamp_value as u64),
159        ));
160        entries.push((
161            Value::Str("transport_id".into()),
162            Value::Bin(iface.transport_id.to_vec()),
163        ));
164        entries.push((
165            Value::Str("network_id".into()),
166            Value::Bin(iface.network_id.to_vec()),
167        ));
168        entries.push((Value::Str("hops".into()), Value::UInt(iface.hops as u64)));
169
170        if let Some(v) = iface.latitude {
171            entries.push((Value::Str("latitude".into()), Value::Float(v)));
172        }
173        if let Some(v) = iface.longitude {
174            entries.push((Value::Str("longitude".into()), Value::Float(v)));
175        }
176        if let Some(v) = iface.height {
177            entries.push((Value::Str("height".into()), Value::Float(v)));
178        }
179        if let Some(ref v) = iface.reachable_on {
180            entries.push((Value::Str("reachable_on".into()), Value::Str(v.clone())));
181        }
182        if let Some(v) = iface.port {
183            entries.push((Value::Str("port".into()), Value::UInt(v as u64)));
184        }
185        if let Some(v) = iface.frequency {
186            entries.push((Value::Str("frequency".into()), Value::UInt(v as u64)));
187        }
188        if let Some(v) = iface.bandwidth {
189            entries.push((Value::Str("bandwidth".into()), Value::UInt(v as u64)));
190        }
191        if let Some(v) = iface.spreading_factor {
192            entries.push((Value::Str("sf".into()), Value::UInt(v as u64)));
193        }
194        if let Some(v) = iface.coding_rate {
195            entries.push((Value::Str("cr".into()), Value::UInt(v as u64)));
196        }
197        if let Some(ref v) = iface.modulation {
198            entries.push((Value::Str("modulation".into()), Value::Str(v.clone())));
199        }
200        if let Some(v) = iface.channel {
201            entries.push((Value::Str("channel".into()), Value::UInt(v as u64)));
202        }
203        if let Some(ref v) = iface.ifac_netname {
204            entries.push((Value::Str("ifac_netname".into()), Value::Str(v.clone())));
205        }
206        if let Some(ref v) = iface.ifac_netkey {
207            entries.push((Value::Str("ifac_netkey".into()), Value::Str(v.clone())));
208        }
209        if let Some(ref v) = iface.config_entry {
210            entries.push((Value::Str("config_entry".into()), Value::Str(v.clone())));
211        }
212
213        entries.push((
214            Value::Str("discovery_hash".into()),
215            Value::Bin(iface.discovery_hash.to_vec()),
216        ));
217
218        Ok(msgpack::pack(&Value::Map(entries)))
219    }
220
221    /// Deserialize an interface from msgpack
222    fn deserialize_interface(&self, data: &[u8]) -> io::Result<DiscoveredInterface> {
223        let (value, _) = msgpack::unpack(data).map_err(|e| {
224            io::Error::new(io::ErrorKind::InvalidData, format!("msgpack error: {}", e))
225        })?;
226
227        // Helper functions using map_get
228        let get_str = |v: &Value, key: &str| -> io::Result<String> {
229            v.map_get(key)
230                .and_then(|val| val.as_str())
231                .map(|s| s.to_string())
232                .ok_or_else(|| {
233                    io::Error::new(io::ErrorKind::InvalidData, format!("{} not a string", key))
234                })
235        };
236
237        let get_opt_str = |v: &Value, key: &str| -> Option<String> {
238            v.map_get(key)
239                .and_then(|val| val.as_str().map(|s| s.to_string()))
240        };
241
242        let get_bool = |v: &Value, key: &str| -> io::Result<bool> {
243            v.map_get(key).and_then(|val| val.as_bool()).ok_or_else(|| {
244                io::Error::new(io::ErrorKind::InvalidData, format!("{} not a bool", key))
245            })
246        };
247
248        let get_float = |v: &Value, key: &str| -> io::Result<f64> {
249            v.map_get(key)
250                .and_then(|val| val.as_float())
251                .ok_or_else(|| {
252                    io::Error::new(io::ErrorKind::InvalidData, format!("{} not a float", key))
253                })
254        };
255
256        let get_opt_float =
257            |v: &Value, key: &str| -> Option<f64> { v.map_get(key).and_then(|val| val.as_float()) };
258
259        let get_uint = |v: &Value, key: &str| -> io::Result<u64> {
260            v.map_get(key).and_then(|val| val.as_uint()).ok_or_else(|| {
261                io::Error::new(io::ErrorKind::InvalidData, format!("{} not a uint", key))
262            })
263        };
264
265        let get_opt_uint =
266            |v: &Value, key: &str| -> Option<u64> { v.map_get(key).and_then(|val| val.as_uint()) };
267
268        let get_bytes = |v: &Value, key: &str| -> io::Result<Vec<u8>> {
269            v.map_get(key)
270                .and_then(|val| val.as_bin())
271                .map(|b| b.to_vec())
272                .ok_or_else(|| {
273                    io::Error::new(io::ErrorKind::InvalidData, format!("{} not bytes", key))
274                })
275        };
276
277        let transport_id_bytes = get_bytes(&value, "transport_id")?;
278        let mut transport_id = [0u8; 16];
279        if transport_id_bytes.len() == 16 {
280            transport_id.copy_from_slice(&transport_id_bytes);
281        }
282
283        let network_id_bytes = get_bytes(&value, "network_id")?;
284        let mut network_id = [0u8; 16];
285        if network_id_bytes.len() == 16 {
286            network_id.copy_from_slice(&network_id_bytes);
287        }
288
289        let discovery_hash_bytes = get_bytes(&value, "discovery_hash")?;
290        let mut discovery_hash = [0u8; 32];
291        if discovery_hash_bytes.len() == 32 {
292            discovery_hash.copy_from_slice(&discovery_hash_bytes);
293        }
294
295        let status_str = get_str(&value, "status")?;
296        let status = match status_str.as_str() {
297            "available" => DiscoveredStatus::Available,
298            "unknown" => DiscoveredStatus::Unknown,
299            "stale" => DiscoveredStatus::Stale,
300            _ => DiscoveredStatus::Unknown,
301        };
302
303        Ok(DiscoveredInterface {
304            interface_type: get_str(&value, "type")?,
305            transport: get_bool(&value, "transport")?,
306            name: get_str(&value, "name")?,
307            discovered: get_float(&value, "discovered")?,
308            last_heard: get_float(&value, "last_heard")?,
309            heard_count: get_uint(&value, "heard_count")? as u32,
310            status,
311            stamp: get_bytes(&value, "stamp")?,
312            stamp_value: get_uint(&value, "value")? as u32,
313            transport_id,
314            network_id,
315            hops: get_uint(&value, "hops")? as u8,
316            latitude: get_opt_float(&value, "latitude"),
317            longitude: get_opt_float(&value, "longitude"),
318            height: get_opt_float(&value, "height"),
319            reachable_on: get_opt_str(&value, "reachable_on"),
320            port: get_opt_uint(&value, "port").map(|v| v as u16),
321            frequency: get_opt_uint(&value, "frequency").map(|v| v as u32),
322            bandwidth: get_opt_uint(&value, "bandwidth").map(|v| v as u32),
323            spreading_factor: get_opt_uint(&value, "sf").map(|v| v as u8),
324            coding_rate: get_opt_uint(&value, "cr").map(|v| v as u8),
325            modulation: get_opt_str(&value, "modulation"),
326            channel: get_opt_uint(&value, "channel").map(|v| v as u8),
327            ifac_netname: get_opt_str(&value, "ifac_netname"),
328            ifac_netkey: get_opt_str(&value, "ifac_netkey"),
329            config_entry: get_opt_str(&value, "config_entry"),
330            discovery_hash,
331        })
332    }
333}
334
335// ============================================================================
336// Stamp Generation (parallel PoW search)
337// ============================================================================
338
339/// Generate a discovery stamp with the given cost using rayon parallel iterators.
340///
341/// Returns `(stamp, value)` on success. This is a blocking, CPU-intensive operation.
342pub fn generate_discovery_stamp(packed_data: &[u8], stamp_cost: u8) -> ([u8; STAMP_SIZE], u32) {
343    use rns_crypto::{OsRng, Rng};
344    use std::sync::atomic::{AtomicBool, Ordering};
345    use std::sync::{Arc, Mutex};
346
347    let infohash = sha256(packed_data);
348    let workblock = stamp_workblock(&infohash, WORKBLOCK_EXPAND_ROUNDS);
349
350    let found: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
351    let result: Arc<Mutex<Option<[u8; STAMP_SIZE]>>> = Arc::new(Mutex::new(None));
352
353    let num_threads = rayon::current_num_threads();
354
355    rayon::scope(|s| {
356        for _ in 0..num_threads {
357            let found = found.clone();
358            let result = result.clone();
359            let workblock = &workblock;
360            s.spawn(move |_| {
361                let mut rng = OsRng;
362                let mut nonce = [0u8; STAMP_SIZE];
363                loop {
364                    if found.load(Ordering::Relaxed) {
365                        return;
366                    }
367                    rng.fill_bytes(&mut nonce);
368                    if stamp_valid(&nonce, stamp_cost, workblock) {
369                        let mut r = result.lock().unwrap();
370                        if r.is_none() {
371                            *r = Some(nonce);
372                        }
373                        found.store(true, Ordering::Relaxed);
374                        return;
375                    }
376                }
377            });
378        }
379    });
380
381    let stamp = result
382        .lock()
383        .unwrap()
384        .take()
385        .expect("stamp search must find result");
386    let value = rns_core::stamp::stamp_value(&workblock, &stamp);
387    (stamp, value)
388}
389
390// ============================================================================
391// Interface Announcer
392// ============================================================================
393
394/// Info about a single discoverable interface, ready for announcing.
395#[derive(Debug, Clone)]
396pub struct DiscoverableInterface {
397    /// Configured interface name used for runtime targeting.
398    pub interface_name: String,
399    pub config: DiscoveryConfig,
400    /// Whether the node has transport enabled.
401    pub transport_enabled: bool,
402    /// IFAC network name, if configured.
403    pub ifac_netname: Option<String>,
404    /// IFAC passphrase, if configured.
405    pub ifac_netkey: Option<String>,
406}
407
408/// Result of a completed background stamp generation.
409pub struct StampResult {
410    /// Configured interface name this stamp was generated for.
411    pub interface_name: String,
412    /// The complete app_data: [flags][packed][stamp].
413    pub app_data: Vec<u8>,
414}
415
416/// Manages periodic announcing of discoverable interfaces.
417///
418/// Stamp generation (PoW) runs on a background thread so it never blocks the
419/// driver event loop.  The driver calls `poll_ready()` each tick to collect
420/// finished results.
421pub struct InterfaceAnnouncer {
422    /// Transport identity hash (16 bytes).
423    transport_id: [u8; 16],
424    /// Discoverable interfaces with their configs.
425    interfaces: Vec<DiscoverableInterface>,
426    /// Last announce time per interface (indexed same as `interfaces`).
427    last_announced: Vec<f64>,
428    /// Receiver for completed stamp results from background threads.
429    stamp_rx: std::sync::mpsc::Receiver<StampResult>,
430    /// Sender cloned into background threads.
431    stamp_tx: std::sync::mpsc::Sender<StampResult>,
432    /// Whether a background stamp job is currently running.
433    stamp_pending: bool,
434}
435
436impl InterfaceAnnouncer {
437    /// Create a new announcer.
438    pub fn new(transport_id: [u8; 16], interfaces: Vec<DiscoverableInterface>) -> Self {
439        let n = interfaces.len();
440        let (stamp_tx, stamp_rx) = std::sync::mpsc::channel();
441        InterfaceAnnouncer {
442            transport_id,
443            interfaces,
444            last_announced: vec![0.0; n],
445            stamp_rx,
446            stamp_tx,
447            stamp_pending: false,
448        }
449    }
450
451    /// If any interface is due for an announce and no stamp job is already
452    /// running, spawns a background thread for PoW.  The result will be
453    /// available via `poll_ready()`.
454    pub fn maybe_start(&mut self, now: f64) {
455        if self.stamp_pending {
456            return;
457        }
458        let due_index = self.interfaces.iter().enumerate().find_map(|(i, iface)| {
459            let elapsed = now - self.last_announced[i];
460            if elapsed >= iface.config.announce_interval as f64 {
461                Some(i)
462            } else {
463                None
464            }
465        });
466
467        if let Some(idx) = due_index {
468            let packed = self.pack_interface_info(idx);
469            let stamp_cost = self.interfaces[idx].config.stamp_value;
470            let name = self.interfaces[idx].config.discovery_name.clone();
471            let interface_name = self.interfaces[idx].interface_name.clone();
472            let tx = self.stamp_tx.clone();
473
474            log::info!(
475                "Spawning discovery stamp generation (cost={}) for '{}'...",
476                stamp_cost,
477                name,
478            );
479
480            self.stamp_pending = true;
481            self.last_announced[idx] = now;
482
483            std::thread::spawn(move || {
484                let (stamp, value) = generate_discovery_stamp(&packed, stamp_cost);
485                log::info!("Discovery stamp generated (value={}) for '{}'", value, name,);
486
487                let flags: u8 = 0x00; // no encryption
488                let mut app_data = Vec::with_capacity(1 + packed.len() + STAMP_SIZE);
489                app_data.push(flags);
490                app_data.extend_from_slice(&packed);
491                app_data.extend_from_slice(&stamp);
492
493                let _ = tx.send(StampResult {
494                    interface_name,
495                    app_data,
496                });
497            });
498        }
499    }
500
501    /// Non-blocking poll: returns completed app_data if a background stamp
502    /// job has finished.
503    pub fn poll_ready(&mut self) -> Option<StampResult> {
504        match self.stamp_rx.try_recv() {
505            Ok(result) => {
506                self.stamp_pending = false;
507                Some(result)
508            }
509            Err(_) => None,
510        }
511    }
512
513    /// Returns true if the announcer currently tracks a discoverable interface by name.
514    pub fn contains_interface(&self, interface_name: &str) -> bool {
515        self.interfaces
516            .iter()
517            .any(|iface| iface.interface_name == interface_name)
518    }
519
520    /// Insert or update a discoverable interface by configured name.
521    pub fn upsert_interface(&mut self, iface: DiscoverableInterface) {
522        if let Some(index) = self
523            .interfaces
524            .iter()
525            .position(|existing| existing.interface_name == iface.interface_name)
526        {
527            self.interfaces[index] = iface;
528            return;
529        }
530        self.interfaces.push(iface);
531        self.last_announced.push(0.0);
532    }
533
534    /// Remove a discoverable interface by configured name.
535    pub fn remove_interface(&mut self, interface_name: &str) -> bool {
536        if let Some(index) = self
537            .interfaces
538            .iter()
539            .position(|iface| iface.interface_name == interface_name)
540        {
541            self.interfaces.remove(index);
542            self.last_announced.remove(index);
543            true
544        } else {
545            false
546        }
547    }
548
549    /// Returns true if no discoverable interfaces remain.
550    pub fn is_empty(&self) -> bool {
551        self.interfaces.is_empty()
552    }
553
554    /// Pack interface metadata as msgpack map with integer keys.
555    fn pack_interface_info(&self, index: usize) -> Vec<u8> {
556        let iface = &self.interfaces[index];
557        let mut entries: Vec<(msgpack::Value, msgpack::Value)> = Vec::new();
558
559        entries.push((
560            msgpack::Value::UInt(INTERFACE_TYPE as u64),
561            msgpack::Value::Str(iface.config.interface_type.clone()),
562        ));
563        entries.push((
564            msgpack::Value::UInt(TRANSPORT as u64),
565            msgpack::Value::Bool(iface.transport_enabled),
566        ));
567        entries.push((
568            msgpack::Value::UInt(NAME as u64),
569            msgpack::Value::Str(iface.config.discovery_name.clone()),
570        ));
571        entries.push((
572            msgpack::Value::UInt(TRANSPORT_ID as u64),
573            msgpack::Value::Bin(self.transport_id.to_vec()),
574        ));
575        if let Some(ref reachable) = iface.config.reachable_on {
576            entries.push((
577                msgpack::Value::UInt(REACHABLE_ON as u64),
578                msgpack::Value::Str(reachable.clone()),
579            ));
580        }
581        if let Some(port) = iface.config.listen_port {
582            entries.push((
583                msgpack::Value::UInt(PORT as u64),
584                msgpack::Value::UInt(port as u64),
585            ));
586        }
587        if let Some(lat) = iface.config.latitude {
588            entries.push((
589                msgpack::Value::UInt(LATITUDE as u64),
590                msgpack::Value::Float(lat),
591            ));
592        }
593        if let Some(lon) = iface.config.longitude {
594            entries.push((
595                msgpack::Value::UInt(LONGITUDE as u64),
596                msgpack::Value::Float(lon),
597            ));
598        }
599        if let Some(h) = iface.config.height {
600            entries.push((
601                msgpack::Value::UInt(HEIGHT as u64),
602                msgpack::Value::Float(h),
603            ));
604        }
605        if let Some(ref netname) = iface.ifac_netname {
606            entries.push((
607                msgpack::Value::UInt(IFAC_NETNAME as u64),
608                msgpack::Value::Str(netname.clone()),
609            ));
610        }
611        if let Some(ref netkey) = iface.ifac_netkey {
612            entries.push((
613                msgpack::Value::UInt(IFAC_NETKEY as u64),
614                msgpack::Value::Str(netkey.clone()),
615            ));
616        }
617
618        msgpack::pack(&msgpack::Value::Map(entries))
619    }
620}
621
622// ============================================================================
623// Tests
624// ============================================================================
625
626#[cfg(test)]
627mod tests {
628    use super::*;
629
630    #[test]
631    fn test_hex_encode() {
632        assert_eq!(hex_encode(&[0x00, 0xff, 0x12]), "00ff12");
633        assert_eq!(hex_encode(&[]), "");
634    }
635
636    #[test]
637    fn test_compute_discovery_hash() {
638        let transport_id = [0x42u8; 16];
639        let name = "TestInterface";
640        let hash = compute_discovery_hash(&transport_id, name);
641
642        // Should be deterministic
643        let hash2 = compute_discovery_hash(&transport_id, name);
644        assert_eq!(hash, hash2);
645
646        // Different name should give different hash
647        let hash3 = compute_discovery_hash(&transport_id, "OtherInterface");
648        assert_ne!(hash, hash3);
649    }
650
651    #[test]
652    fn test_is_ip_address() {
653        assert!(is_ip_address("192.168.1.1"));
654        assert!(is_ip_address("::1"));
655        assert!(is_ip_address("2001:db8::1"));
656        assert!(!is_ip_address("not-an-ip"));
657        assert!(!is_ip_address("hostname.example.com"));
658    }
659
660    #[test]
661    fn test_is_hostname() {
662        assert!(is_hostname("example.com"));
663        assert!(is_hostname("sub.example.com"));
664        assert!(is_hostname("my-node"));
665        assert!(is_hostname("my-node.example.com"));
666        assert!(!is_hostname(""));
667        assert!(!is_hostname("-invalid"));
668        assert!(!is_hostname("invalid-"));
669        assert!(!is_hostname("a".repeat(300).as_str()));
670    }
671
672    #[test]
673    fn test_discovered_status() {
674        let now = time::now();
675
676        let mut iface = DiscoveredInterface {
677            interface_type: "TestInterface".into(),
678            transport: true,
679            name: "Test".into(),
680            discovered: now,
681            last_heard: now,
682            heard_count: 0,
683            status: DiscoveredStatus::Available,
684            stamp: vec![],
685            stamp_value: 14,
686            transport_id: [0u8; 16],
687            network_id: [0u8; 16],
688            hops: 0,
689            latitude: None,
690            longitude: None,
691            height: None,
692            reachable_on: None,
693            port: None,
694            frequency: None,
695            bandwidth: None,
696            spreading_factor: None,
697            coding_rate: None,
698            modulation: None,
699            channel: None,
700            ifac_netname: None,
701            ifac_netkey: None,
702            config_entry: None,
703            discovery_hash: [0u8; 32],
704        };
705
706        // Fresh interface should be available
707        assert_eq!(iface.compute_status(), DiscoveredStatus::Available);
708
709        // 25 hours old should be unknown
710        iface.last_heard = now - THRESHOLD_UNKNOWN - 3600.0;
711        assert_eq!(iface.compute_status(), DiscoveredStatus::Unknown);
712
713        // 4 days old should be stale
714        iface.last_heard = now - THRESHOLD_STALE - 3600.0;
715        assert_eq!(iface.compute_status(), DiscoveredStatus::Stale);
716    }
717
718    #[test]
719    fn test_storage_roundtrip() {
720        use std::sync::atomic::{AtomicU64, Ordering};
721        static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);
722
723        let id = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
724        let dir =
725            std::env::temp_dir().join(format!("rns-discovery-test-{}-{}", std::process::id(), id));
726        let _ = fs::remove_dir_all(&dir);
727        fs::create_dir_all(&dir).unwrap();
728
729        let storage = DiscoveredInterfaceStorage::new(dir.clone());
730
731        let iface = DiscoveredInterface {
732            interface_type: "BackboneInterface".into(),
733            transport: true,
734            name: "TestNode".into(),
735            discovered: 1700000000.0,
736            last_heard: 1700001000.0,
737            heard_count: 5,
738            status: DiscoveredStatus::Available,
739            stamp: vec![0x42u8; 64],
740            stamp_value: 18,
741            transport_id: [0x01u8; 16],
742            network_id: [0x02u8; 16],
743            hops: 2,
744            latitude: Some(45.0),
745            longitude: Some(9.0),
746            height: Some(100.0),
747            reachable_on: Some("example.com".into()),
748            port: Some(4242),
749            frequency: None,
750            bandwidth: None,
751            spreading_factor: None,
752            coding_rate: None,
753            modulation: None,
754            channel: None,
755            ifac_netname: Some("mynetwork".into()),
756            ifac_netkey: Some("secretkey".into()),
757            config_entry: Some("test config".into()),
758            discovery_hash: compute_discovery_hash(&[0x01u8; 16], "TestNode"),
759        };
760
761        // Store
762        storage.store(&iface).unwrap();
763
764        // Load
765        let loaded = storage.load(&iface.discovery_hash).unwrap().unwrap();
766
767        assert_eq!(loaded.interface_type, iface.interface_type);
768        assert_eq!(loaded.name, iface.name);
769        assert_eq!(loaded.stamp_value, iface.stamp_value);
770        assert_eq!(loaded.transport_id, iface.transport_id);
771        assert_eq!(loaded.hops, iface.hops);
772        assert_eq!(loaded.latitude, iface.latitude);
773        assert_eq!(loaded.reachable_on, iface.reachable_on);
774        assert_eq!(loaded.port, iface.port);
775
776        // List
777        let list = storage.list().unwrap();
778        assert_eq!(list.len(), 1);
779
780        // Remove
781        storage.remove(&iface.discovery_hash).unwrap();
782        let list = storage.list().unwrap();
783        assert!(list.is_empty());
784
785        let _ = fs::remove_dir_all(&dir);
786    }
787
788    #[test]
789    fn test_filter_and_sort() {
790        let now = time::now();
791
792        let ifaces = vec![
793            DiscoveredInterface {
794                interface_type: "BackboneInterface".into(),
795                transport: true,
796                name: "high-value-stale".into(),
797                discovered: now,
798                last_heard: now - THRESHOLD_STALE - 100.0, // Stale
799                heard_count: 0,
800                status: DiscoveredStatus::Stale,
801                stamp: vec![],
802                stamp_value: 20,
803                transport_id: [0u8; 16],
804                network_id: [0u8; 16],
805                hops: 0,
806                latitude: None,
807                longitude: None,
808                height: None,
809                reachable_on: None,
810                port: None,
811                frequency: None,
812                bandwidth: None,
813                spreading_factor: None,
814                coding_rate: None,
815                modulation: None,
816                channel: None,
817                ifac_netname: None,
818                ifac_netkey: None,
819                config_entry: None,
820                discovery_hash: [0u8; 32],
821            },
822            DiscoveredInterface {
823                interface_type: "TCPServerInterface".into(),
824                transport: true,
825                name: "low-value-available".into(),
826                discovered: now,
827                last_heard: now - 10.0, // Available
828                heard_count: 0,
829                status: DiscoveredStatus::Available,
830                stamp: vec![],
831                stamp_value: 10,
832                transport_id: [0u8; 16],
833                network_id: [0u8; 16],
834                hops: 0,
835                latitude: None,
836                longitude: None,
837                height: None,
838                reachable_on: None,
839                port: None,
840                frequency: None,
841                bandwidth: None,
842                spreading_factor: None,
843                coding_rate: None,
844                modulation: None,
845                channel: None,
846                ifac_netname: None,
847                ifac_netkey: None,
848                config_entry: None,
849                discovery_hash: [1u8; 32],
850            },
851            DiscoveredInterface {
852                interface_type: "I2PInterface".into(),
853                transport: false,
854                name: "high-value-available".into(),
855                discovered: now,
856                last_heard: now - 10.0, // Available
857                heard_count: 0,
858                status: DiscoveredStatus::Available,
859                stamp: vec![],
860                stamp_value: 20,
861                transport_id: [0u8; 16],
862                network_id: [0u8; 16],
863                hops: 0,
864                latitude: None,
865                longitude: None,
866                height: None,
867                reachable_on: None,
868                port: None,
869                frequency: None,
870                bandwidth: None,
871                spreading_factor: None,
872                coding_rate: None,
873                modulation: None,
874                channel: None,
875                ifac_netname: None,
876                ifac_netkey: None,
877                config_entry: None,
878                discovery_hash: [2u8; 32],
879            },
880        ];
881
882        // Test no filter — all included, sorted by status then value
883        let mut result = ifaces.clone();
884        filter_and_sort_interfaces(&mut result, false, false);
885        assert_eq!(result.len(), 3);
886        // Available ones should come first (higher status code)
887        assert_eq!(result[0].name, "high-value-available");
888        assert_eq!(result[1].name, "low-value-available");
889        assert_eq!(result[2].name, "high-value-stale");
890
891        // Test only_available filter
892        let mut result = ifaces.clone();
893        filter_and_sort_interfaces(&mut result, true, false);
894        assert_eq!(result.len(), 2); // stale one filtered out
895
896        // Test only_transport filter
897        let mut result = ifaces.clone();
898        filter_and_sort_interfaces(&mut result, false, true);
899        assert_eq!(result.len(), 2); // non-transport one filtered out
900    }
901
902    #[test]
903    fn test_discovery_name_hash_deterministic() {
904        let h1 = discovery_name_hash();
905        let h2 = discovery_name_hash();
906        assert_eq!(h1, h2);
907        assert_ne!(h1, [0u8; 10]); // not all zeros
908    }
909}