1pub 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
24pub struct DiscoveredInterfaceStorage {
30 base_path: PathBuf,
31}
32
33impl DiscoveredInterfaceStorage {
34 pub fn new(base_path: PathBuf) -> Self {
36 Self { base_path }
37 }
38
39 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 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 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 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 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 if now - iface.last_heard > THRESHOLD_REMOVE {
112 self.remove(&iface.discovery_hash)?;
113 removed += 1;
114 }
115 }
116
117 Ok(removed)
118 }
119
120 fn serialize_interface(&self, iface: &DiscoveredInterface) -> io::Result<Vec<u8>> {
122 let mut entries: Vec<(Value, Value)> = Vec::new();
123
124 entries.push((
125 Value::Str("type".into()),
126 Value::Str(iface.interface_type.clone()),
127 ));
128 entries.push((Value::Str("transport".into()), Value::Bool(iface.transport)));
129 entries.push((Value::Str("name".into()), Value::Str(iface.name.clone())));
130 entries.push((
131 Value::Str("discovered".into()),
132 Value::Float(iface.discovered),
133 ));
134 entries.push((
135 Value::Str("last_heard".into()),
136 Value::Float(iface.last_heard),
137 ));
138 entries.push((
139 Value::Str("heard_count".into()),
140 Value::UInt(iface.heard_count as u64),
141 ));
142 entries.push((
143 Value::Str("status".into()),
144 Value::Str(iface.status.as_str().into()),
145 ));
146 entries.push((Value::Str("stamp".into()), Value::Bin(iface.stamp.clone())));
147 entries.push((
148 Value::Str("value".into()),
149 Value::UInt(iface.stamp_value as u64),
150 ));
151 entries.push((
152 Value::Str("transport_id".into()),
153 Value::Bin(iface.transport_id.to_vec()),
154 ));
155 entries.push((
156 Value::Str("network_id".into()),
157 Value::Bin(iface.network_id.to_vec()),
158 ));
159 entries.push((Value::Str("hops".into()), Value::UInt(iface.hops as u64)));
160
161 if let Some(v) = iface.latitude {
162 entries.push((Value::Str("latitude".into()), Value::Float(v)));
163 }
164 if let Some(v) = iface.longitude {
165 entries.push((Value::Str("longitude".into()), Value::Float(v)));
166 }
167 if let Some(v) = iface.height {
168 entries.push((Value::Str("height".into()), Value::Float(v)));
169 }
170 if let Some(ref v) = iface.reachable_on {
171 entries.push((Value::Str("reachable_on".into()), Value::Str(v.clone())));
172 }
173 if let Some(v) = iface.port {
174 entries.push((Value::Str("port".into()), Value::UInt(v as u64)));
175 }
176 if let Some(v) = iface.frequency {
177 entries.push((Value::Str("frequency".into()), Value::UInt(v as u64)));
178 }
179 if let Some(v) = iface.bandwidth {
180 entries.push((Value::Str("bandwidth".into()), Value::UInt(v as u64)));
181 }
182 if let Some(v) = iface.spreading_factor {
183 entries.push((Value::Str("sf".into()), Value::UInt(v as u64)));
184 }
185 if let Some(v) = iface.coding_rate {
186 entries.push((Value::Str("cr".into()), Value::UInt(v as u64)));
187 }
188 if let Some(ref v) = iface.modulation {
189 entries.push((Value::Str("modulation".into()), Value::Str(v.clone())));
190 }
191 if let Some(v) = iface.channel {
192 entries.push((Value::Str("channel".into()), Value::UInt(v as u64)));
193 }
194 if let Some(ref v) = iface.ifac_netname {
195 entries.push((Value::Str("ifac_netname".into()), Value::Str(v.clone())));
196 }
197 if let Some(ref v) = iface.ifac_netkey {
198 entries.push((Value::Str("ifac_netkey".into()), Value::Str(v.clone())));
199 }
200 if let Some(ref v) = iface.config_entry {
201 entries.push((Value::Str("config_entry".into()), Value::Str(v.clone())));
202 }
203
204 entries.push((
205 Value::Str("discovery_hash".into()),
206 Value::Bin(iface.discovery_hash.to_vec()),
207 ));
208
209 Ok(msgpack::pack(&Value::Map(entries)))
210 }
211
212 fn deserialize_interface(&self, data: &[u8]) -> io::Result<DiscoveredInterface> {
214 let (value, _) = msgpack::unpack(data).map_err(|e| {
215 io::Error::new(io::ErrorKind::InvalidData, format!("msgpack error: {}", e))
216 })?;
217
218 let get_str = |v: &Value, key: &str| -> io::Result<String> {
220 v.map_get(key)
221 .and_then(|val| val.as_str())
222 .map(|s| s.to_string())
223 .ok_or_else(|| {
224 io::Error::new(io::ErrorKind::InvalidData, format!("{} not a string", key))
225 })
226 };
227
228 let get_opt_str = |v: &Value, key: &str| -> Option<String> {
229 v.map_get(key)
230 .and_then(|val| val.as_str().map(|s| s.to_string()))
231 };
232
233 let get_bool = |v: &Value, key: &str| -> io::Result<bool> {
234 v.map_get(key).and_then(|val| val.as_bool()).ok_or_else(|| {
235 io::Error::new(io::ErrorKind::InvalidData, format!("{} not a bool", key))
236 })
237 };
238
239 let get_float = |v: &Value, key: &str| -> io::Result<f64> {
240 v.map_get(key)
241 .and_then(|val| val.as_float())
242 .ok_or_else(|| {
243 io::Error::new(io::ErrorKind::InvalidData, format!("{} not a float", key))
244 })
245 };
246
247 let get_opt_float =
248 |v: &Value, key: &str| -> Option<f64> { v.map_get(key).and_then(|val| val.as_float()) };
249
250 let get_uint = |v: &Value, key: &str| -> io::Result<u64> {
251 v.map_get(key).and_then(|val| val.as_uint()).ok_or_else(|| {
252 io::Error::new(io::ErrorKind::InvalidData, format!("{} not a uint", key))
253 })
254 };
255
256 let get_opt_uint =
257 |v: &Value, key: &str| -> Option<u64> { v.map_get(key).and_then(|val| val.as_uint()) };
258
259 let get_bytes = |v: &Value, key: &str| -> io::Result<Vec<u8>> {
260 v.map_get(key)
261 .and_then(|val| val.as_bin())
262 .map(|b| b.to_vec())
263 .ok_or_else(|| {
264 io::Error::new(io::ErrorKind::InvalidData, format!("{} not bytes", key))
265 })
266 };
267
268 let transport_id_bytes = get_bytes(&value, "transport_id")?;
269 let mut transport_id = [0u8; 16];
270 if transport_id_bytes.len() == 16 {
271 transport_id.copy_from_slice(&transport_id_bytes);
272 }
273
274 let network_id_bytes = get_bytes(&value, "network_id")?;
275 let mut network_id = [0u8; 16];
276 if network_id_bytes.len() == 16 {
277 network_id.copy_from_slice(&network_id_bytes);
278 }
279
280 let discovery_hash_bytes = get_bytes(&value, "discovery_hash")?;
281 let mut discovery_hash = [0u8; 32];
282 if discovery_hash_bytes.len() == 32 {
283 discovery_hash.copy_from_slice(&discovery_hash_bytes);
284 }
285
286 let status_str = get_str(&value, "status")?;
287 let status = match status_str.as_str() {
288 "available" => DiscoveredStatus::Available,
289 "unknown" => DiscoveredStatus::Unknown,
290 "stale" => DiscoveredStatus::Stale,
291 _ => DiscoveredStatus::Unknown,
292 };
293
294 Ok(DiscoveredInterface {
295 interface_type: get_str(&value, "type")?,
296 transport: get_bool(&value, "transport")?,
297 name: get_str(&value, "name")?,
298 discovered: get_float(&value, "discovered")?,
299 last_heard: get_float(&value, "last_heard")?,
300 heard_count: get_uint(&value, "heard_count")? as u32,
301 status,
302 stamp: get_bytes(&value, "stamp")?,
303 stamp_value: get_uint(&value, "value")? as u32,
304 transport_id,
305 network_id,
306 hops: get_uint(&value, "hops")? as u8,
307 latitude: get_opt_float(&value, "latitude"),
308 longitude: get_opt_float(&value, "longitude"),
309 height: get_opt_float(&value, "height"),
310 reachable_on: get_opt_str(&value, "reachable_on"),
311 port: get_opt_uint(&value, "port").map(|v| v as u16),
312 frequency: get_opt_uint(&value, "frequency").map(|v| v as u32),
313 bandwidth: get_opt_uint(&value, "bandwidth").map(|v| v as u32),
314 spreading_factor: get_opt_uint(&value, "sf").map(|v| v as u8),
315 coding_rate: get_opt_uint(&value, "cr").map(|v| v as u8),
316 modulation: get_opt_str(&value, "modulation"),
317 channel: get_opt_uint(&value, "channel").map(|v| v as u8),
318 ifac_netname: get_opt_str(&value, "ifac_netname"),
319 ifac_netkey: get_opt_str(&value, "ifac_netkey"),
320 config_entry: get_opt_str(&value, "config_entry"),
321 discovery_hash,
322 })
323 }
324}
325
326pub fn generate_discovery_stamp(packed_data: &[u8], stamp_cost: u8) -> ([u8; STAMP_SIZE], u32) {
334 use rns_crypto::{OsRng, Rng};
335 use std::sync::atomic::{AtomicBool, Ordering};
336 use std::sync::{Arc, Mutex};
337
338 let infohash = sha256(packed_data);
339 let workblock = stamp_workblock(&infohash, WORKBLOCK_EXPAND_ROUNDS);
340
341 let found: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
342 let result: Arc<Mutex<Option<[u8; STAMP_SIZE]>>> = Arc::new(Mutex::new(None));
343
344 let num_threads = rayon::current_num_threads();
345
346 rayon::scope(|s| {
347 for _ in 0..num_threads {
348 let found = found.clone();
349 let result = result.clone();
350 let workblock = &workblock;
351 s.spawn(move |_| {
352 let mut rng = OsRng;
353 let mut nonce = [0u8; STAMP_SIZE];
354 loop {
355 if found.load(Ordering::Relaxed) {
356 return;
357 }
358 rng.fill_bytes(&mut nonce);
359 if stamp_valid(&nonce, stamp_cost, workblock) {
360 let mut r = result.lock().unwrap();
361 if r.is_none() {
362 *r = Some(nonce);
363 }
364 found.store(true, Ordering::Relaxed);
365 return;
366 }
367 }
368 });
369 }
370 });
371
372 let stamp = result
373 .lock()
374 .unwrap()
375 .take()
376 .expect("stamp search must find result");
377 let value = rns_core::stamp::stamp_value(&workblock, &stamp);
378 (stamp, value)
379}
380
381#[derive(Debug, Clone)]
387pub struct DiscoverableInterface {
388 pub config: DiscoveryConfig,
389 pub transport_enabled: bool,
391 pub ifac_netname: Option<String>,
393 pub ifac_netkey: Option<String>,
395}
396
397pub struct StampResult {
399 pub index: usize,
401 pub app_data: Vec<u8>,
403}
404
405pub struct InterfaceAnnouncer {
411 transport_id: [u8; 16],
413 interfaces: Vec<DiscoverableInterface>,
415 last_announced: Vec<f64>,
417 stamp_rx: std::sync::mpsc::Receiver<StampResult>,
419 stamp_tx: std::sync::mpsc::Sender<StampResult>,
421 stamp_pending: bool,
423}
424
425impl InterfaceAnnouncer {
426 pub fn new(transport_id: [u8; 16], interfaces: Vec<DiscoverableInterface>) -> Self {
428 let n = interfaces.len();
429 let (stamp_tx, stamp_rx) = std::sync::mpsc::channel();
430 InterfaceAnnouncer {
431 transport_id,
432 interfaces,
433 last_announced: vec![0.0; n],
434 stamp_rx,
435 stamp_tx,
436 stamp_pending: false,
437 }
438 }
439
440 pub fn maybe_start(&mut self, now: f64) {
444 if self.stamp_pending {
445 return;
446 }
447 let due_index = self.interfaces.iter().enumerate().find_map(|(i, iface)| {
448 let elapsed = now - self.last_announced[i];
449 if elapsed >= iface.config.announce_interval as f64 {
450 Some(i)
451 } else {
452 None
453 }
454 });
455
456 if let Some(idx) = due_index {
457 let packed = self.pack_interface_info(idx);
458 let stamp_cost = self.interfaces[idx].config.stamp_value;
459 let name = self.interfaces[idx].config.discovery_name.clone();
460 let tx = self.stamp_tx.clone();
461
462 log::info!(
463 "Spawning discovery stamp generation (cost={}) for '{}'...",
464 stamp_cost,
465 name,
466 );
467
468 self.stamp_pending = true;
469 self.last_announced[idx] = now;
470
471 std::thread::spawn(move || {
472 let (stamp, value) = generate_discovery_stamp(&packed, stamp_cost);
473 log::info!("Discovery stamp generated (value={}) for '{}'", value, name,);
474
475 let flags: u8 = 0x00; let mut app_data = Vec::with_capacity(1 + packed.len() + STAMP_SIZE);
477 app_data.push(flags);
478 app_data.extend_from_slice(&packed);
479 app_data.extend_from_slice(&stamp);
480
481 let _ = tx.send(StampResult {
482 index: idx,
483 app_data,
484 });
485 });
486 }
487 }
488
489 pub fn poll_ready(&mut self) -> Option<StampResult> {
492 match self.stamp_rx.try_recv() {
493 Ok(result) => {
494 self.stamp_pending = false;
495 Some(result)
496 }
497 Err(_) => None,
498 }
499 }
500
501 fn pack_interface_info(&self, index: usize) -> Vec<u8> {
503 let iface = &self.interfaces[index];
504 let mut entries: Vec<(msgpack::Value, msgpack::Value)> = Vec::new();
505
506 entries.push((
507 msgpack::Value::UInt(INTERFACE_TYPE as u64),
508 msgpack::Value::Str(iface.config.interface_type.clone()),
509 ));
510 entries.push((
511 msgpack::Value::UInt(TRANSPORT as u64),
512 msgpack::Value::Bool(iface.transport_enabled),
513 ));
514 entries.push((
515 msgpack::Value::UInt(NAME as u64),
516 msgpack::Value::Str(iface.config.discovery_name.clone()),
517 ));
518 entries.push((
519 msgpack::Value::UInt(TRANSPORT_ID as u64),
520 msgpack::Value::Bin(self.transport_id.to_vec()),
521 ));
522 if let Some(ref reachable) = iface.config.reachable_on {
523 entries.push((
524 msgpack::Value::UInt(REACHABLE_ON as u64),
525 msgpack::Value::Str(reachable.clone()),
526 ));
527 }
528 if let Some(port) = iface.config.listen_port {
529 entries.push((
530 msgpack::Value::UInt(PORT as u64),
531 msgpack::Value::UInt(port as u64),
532 ));
533 }
534 if let Some(lat) = iface.config.latitude {
535 entries.push((
536 msgpack::Value::UInt(LATITUDE as u64),
537 msgpack::Value::Float(lat),
538 ));
539 }
540 if let Some(lon) = iface.config.longitude {
541 entries.push((
542 msgpack::Value::UInt(LONGITUDE as u64),
543 msgpack::Value::Float(lon),
544 ));
545 }
546 if let Some(h) = iface.config.height {
547 entries.push((
548 msgpack::Value::UInt(HEIGHT as u64),
549 msgpack::Value::Float(h),
550 ));
551 }
552 if let Some(ref netname) = iface.ifac_netname {
553 entries.push((
554 msgpack::Value::UInt(IFAC_NETNAME as u64),
555 msgpack::Value::Str(netname.clone()),
556 ));
557 }
558 if let Some(ref netkey) = iface.ifac_netkey {
559 entries.push((
560 msgpack::Value::UInt(IFAC_NETKEY as u64),
561 msgpack::Value::Str(netkey.clone()),
562 ));
563 }
564
565 msgpack::pack(&msgpack::Value::Map(entries))
566 }
567}
568
569#[cfg(test)]
574mod tests {
575 use super::*;
576
577 #[test]
578 fn test_hex_encode() {
579 assert_eq!(hex_encode(&[0x00, 0xff, 0x12]), "00ff12");
580 assert_eq!(hex_encode(&[]), "");
581 }
582
583 #[test]
584 fn test_compute_discovery_hash() {
585 let transport_id = [0x42u8; 16];
586 let name = "TestInterface";
587 let hash = compute_discovery_hash(&transport_id, name);
588
589 let hash2 = compute_discovery_hash(&transport_id, name);
591 assert_eq!(hash, hash2);
592
593 let hash3 = compute_discovery_hash(&transport_id, "OtherInterface");
595 assert_ne!(hash, hash3);
596 }
597
598 #[test]
599 fn test_is_ip_address() {
600 assert!(is_ip_address("192.168.1.1"));
601 assert!(is_ip_address("::1"));
602 assert!(is_ip_address("2001:db8::1"));
603 assert!(!is_ip_address("not-an-ip"));
604 assert!(!is_ip_address("hostname.example.com"));
605 }
606
607 #[test]
608 fn test_is_hostname() {
609 assert!(is_hostname("example.com"));
610 assert!(is_hostname("sub.example.com"));
611 assert!(is_hostname("my-node"));
612 assert!(is_hostname("my-node.example.com"));
613 assert!(!is_hostname(""));
614 assert!(!is_hostname("-invalid"));
615 assert!(!is_hostname("invalid-"));
616 assert!(!is_hostname("a".repeat(300).as_str()));
617 }
618
619 #[test]
620 fn test_discovered_status() {
621 let now = time::now();
622
623 let mut iface = DiscoveredInterface {
624 interface_type: "TestInterface".into(),
625 transport: true,
626 name: "Test".into(),
627 discovered: now,
628 last_heard: now,
629 heard_count: 0,
630 status: DiscoveredStatus::Available,
631 stamp: vec![],
632 stamp_value: 14,
633 transport_id: [0u8; 16],
634 network_id: [0u8; 16],
635 hops: 0,
636 latitude: None,
637 longitude: None,
638 height: None,
639 reachable_on: None,
640 port: None,
641 frequency: None,
642 bandwidth: None,
643 spreading_factor: None,
644 coding_rate: None,
645 modulation: None,
646 channel: None,
647 ifac_netname: None,
648 ifac_netkey: None,
649 config_entry: None,
650 discovery_hash: [0u8; 32],
651 };
652
653 assert_eq!(iface.compute_status(), DiscoveredStatus::Available);
655
656 iface.last_heard = now - THRESHOLD_UNKNOWN - 3600.0;
658 assert_eq!(iface.compute_status(), DiscoveredStatus::Unknown);
659
660 iface.last_heard = now - THRESHOLD_STALE - 3600.0;
662 assert_eq!(iface.compute_status(), DiscoveredStatus::Stale);
663 }
664
665 #[test]
666 fn test_storage_roundtrip() {
667 use std::sync::atomic::{AtomicU64, Ordering};
668 static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);
669
670 let id = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
671 let dir =
672 std::env::temp_dir().join(format!("rns-discovery-test-{}-{}", std::process::id(), id));
673 let _ = fs::remove_dir_all(&dir);
674 fs::create_dir_all(&dir).unwrap();
675
676 let storage = DiscoveredInterfaceStorage::new(dir.clone());
677
678 let iface = DiscoveredInterface {
679 interface_type: "BackboneInterface".into(),
680 transport: true,
681 name: "TestNode".into(),
682 discovered: 1700000000.0,
683 last_heard: 1700001000.0,
684 heard_count: 5,
685 status: DiscoveredStatus::Available,
686 stamp: vec![0x42u8; 64],
687 stamp_value: 18,
688 transport_id: [0x01u8; 16],
689 network_id: [0x02u8; 16],
690 hops: 2,
691 latitude: Some(45.0),
692 longitude: Some(9.0),
693 height: Some(100.0),
694 reachable_on: Some("example.com".into()),
695 port: Some(4242),
696 frequency: None,
697 bandwidth: None,
698 spreading_factor: None,
699 coding_rate: None,
700 modulation: None,
701 channel: None,
702 ifac_netname: Some("mynetwork".into()),
703 ifac_netkey: Some("secretkey".into()),
704 config_entry: Some("test config".into()),
705 discovery_hash: compute_discovery_hash(&[0x01u8; 16], "TestNode"),
706 };
707
708 storage.store(&iface).unwrap();
710
711 let loaded = storage.load(&iface.discovery_hash).unwrap().unwrap();
713
714 assert_eq!(loaded.interface_type, iface.interface_type);
715 assert_eq!(loaded.name, iface.name);
716 assert_eq!(loaded.stamp_value, iface.stamp_value);
717 assert_eq!(loaded.transport_id, iface.transport_id);
718 assert_eq!(loaded.hops, iface.hops);
719 assert_eq!(loaded.latitude, iface.latitude);
720 assert_eq!(loaded.reachable_on, iface.reachable_on);
721 assert_eq!(loaded.port, iface.port);
722
723 let list = storage.list().unwrap();
725 assert_eq!(list.len(), 1);
726
727 storage.remove(&iface.discovery_hash).unwrap();
729 let list = storage.list().unwrap();
730 assert!(list.is_empty());
731
732 let _ = fs::remove_dir_all(&dir);
733 }
734
735 #[test]
736 fn test_filter_and_sort() {
737 let now = time::now();
738
739 let ifaces = vec![
740 DiscoveredInterface {
741 interface_type: "A".into(),
742 transport: true,
743 name: "high-value-stale".into(),
744 discovered: now,
745 last_heard: now - THRESHOLD_STALE - 100.0, heard_count: 0,
747 status: DiscoveredStatus::Stale,
748 stamp: vec![],
749 stamp_value: 20,
750 transport_id: [0u8; 16],
751 network_id: [0u8; 16],
752 hops: 0,
753 latitude: None,
754 longitude: None,
755 height: None,
756 reachable_on: None,
757 port: None,
758 frequency: None,
759 bandwidth: None,
760 spreading_factor: None,
761 coding_rate: None,
762 modulation: None,
763 channel: None,
764 ifac_netname: None,
765 ifac_netkey: None,
766 config_entry: None,
767 discovery_hash: [0u8; 32],
768 },
769 DiscoveredInterface {
770 interface_type: "B".into(),
771 transport: true,
772 name: "low-value-available".into(),
773 discovered: now,
774 last_heard: now - 10.0, heard_count: 0,
776 status: DiscoveredStatus::Available,
777 stamp: vec![],
778 stamp_value: 10,
779 transport_id: [0u8; 16],
780 network_id: [0u8; 16],
781 hops: 0,
782 latitude: None,
783 longitude: None,
784 height: None,
785 reachable_on: None,
786 port: None,
787 frequency: None,
788 bandwidth: None,
789 spreading_factor: None,
790 coding_rate: None,
791 modulation: None,
792 channel: None,
793 ifac_netname: None,
794 ifac_netkey: None,
795 config_entry: None,
796 discovery_hash: [1u8; 32],
797 },
798 DiscoveredInterface {
799 interface_type: "C".into(),
800 transport: false,
801 name: "high-value-available".into(),
802 discovered: now,
803 last_heard: now - 10.0, heard_count: 0,
805 status: DiscoveredStatus::Available,
806 stamp: vec![],
807 stamp_value: 20,
808 transport_id: [0u8; 16],
809 network_id: [0u8; 16],
810 hops: 0,
811 latitude: None,
812 longitude: None,
813 height: None,
814 reachable_on: None,
815 port: None,
816 frequency: None,
817 bandwidth: None,
818 spreading_factor: None,
819 coding_rate: None,
820 modulation: None,
821 channel: None,
822 ifac_netname: None,
823 ifac_netkey: None,
824 config_entry: None,
825 discovery_hash: [2u8; 32],
826 },
827 ];
828
829 let mut result = ifaces.clone();
831 filter_and_sort_interfaces(&mut result, false, false);
832 assert_eq!(result.len(), 3);
833 assert_eq!(result[0].name, "high-value-available");
835 assert_eq!(result[1].name, "low-value-available");
836 assert_eq!(result[2].name, "high-value-stale");
837
838 let mut result = ifaces.clone();
840 filter_and_sort_interfaces(&mut result, true, false);
841 assert_eq!(result.len(), 2); let mut result = ifaces.clone();
845 filter_and_sort_interfaces(&mut result, false, true);
846 assert_eq!(result.len(), 2); }
848
849 #[test]
850 fn test_discovery_name_hash_deterministic() {
851 let h1 = discovery_name_hash();
852 let h2 = discovery_name_hash();
853 assert_eq!(h1, h2);
854 assert_ne!(h1, [0u8; 10]); }
856}