rns-net 0.5.5

Network interfaces and node driver for the Reticulum Network Stack
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
//! AutoInterface: Zero-configuration LAN auto-discovery via IPv6 multicast.
//!
//! Matches Python `AutoInterface` from `RNS/Interfaces/AutoInterface.py`.
//!
//! Thread model (per adopted network interface):
//!   - Discovery sender: periodically sends discovery token via multicast
//!   - Discovery receiver (multicast): validates tokens, adds peers
//!   - Discovery receiver (unicast): validates reverse-peering tokens
//!   - Data receiver: UDP server receiving unicast data from peers
//!
//! Additionally one shared thread:
//!   - Peer jobs: periodically culls timed-out peers

use std::collections::{HashMap, VecDeque};
use std::io;
use std::net::{Ipv6Addr, SocketAddrV6, UdpSocket};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use rns_core::transport::types::InterfaceId;

use crate::event::{Event, EventSender};
use crate::interface::Writer;

// ── Constants (matching Python AutoInterface) ──────────────────────────────

/// Default UDP port for multicast discovery.
pub const DEFAULT_DISCOVERY_PORT: u16 = 29716;

/// Default UDP port for unicast data exchange.
pub const DEFAULT_DATA_PORT: u16 = 42671;

/// Default group identifier.
pub const DEFAULT_GROUP_ID: &[u8] = b"reticulum";

/// Default IFAC size for AutoInterface (bytes).
pub const DEFAULT_IFAC_SIZE: usize = 16;

/// Hardware MTU for AutoInterface packets.
pub const HW_MTU: usize = 1196;

/// Multicast scope: link-local.
pub const SCOPE_LINK: &str = "2";
/// Multicast scope: admin-local.
pub const SCOPE_ADMIN: &str = "4";
/// Multicast scope: site-local.
pub const SCOPE_SITE: &str = "5";
/// Multicast scope: organization-local.
pub const SCOPE_ORGANISATION: &str = "8";
/// Multicast scope: global.
pub const SCOPE_GLOBAL: &str = "e";

/// Permanent multicast address type.
pub const MULTICAST_PERMANENT_ADDRESS_TYPE: &str = "0";
/// Temporary multicast address type.
pub const MULTICAST_TEMPORARY_ADDRESS_TYPE: &str = "1";

/// How long before a peer is considered timed out (seconds).
pub const PEERING_TIMEOUT: f64 = 22.0;

/// How often to send multicast discovery announcements (seconds).
pub const ANNOUNCE_INTERVAL: f64 = 1.6;

/// How often to run peer maintenance jobs (seconds).
pub const PEER_JOB_INTERVAL: f64 = 4.0;

/// Multicast echo timeout (seconds). Used for carrier detection.
pub const MCAST_ECHO_TIMEOUT: f64 = 6.5;

/// Default bitrate guess for AutoInterface (10 Mbps).
pub const BITRATE_GUESS: u64 = 10_000_000;

/// Deduplication deque size.
pub const MULTI_IF_DEQUE_LEN: usize = 48;

/// Deduplication deque entry TTL (seconds).
pub const MULTI_IF_DEQUE_TTL: f64 = 0.75;

/// Reverse peering interval multiplier (announce_interval * 3.25).
pub const REVERSE_PEERING_MULTIPLIER: f64 = 3.25;

/// Interfaces always ignored.
pub const ALL_IGNORE_IFS: &[&str] = &["lo0"];

// ── Configuration ──────────────────────────────────────────────────────────

/// Configuration for an AutoInterface.
#[derive(Debug, Clone)]
pub struct AutoConfig {
    pub name: String,
    pub group_id: Vec<u8>,
    pub discovery_scope: String,
    pub discovery_port: u16,
    pub data_port: u16,
    pub multicast_address_type: String,
    pub allowed_interfaces: Vec<String>,
    pub ignored_interfaces: Vec<String>,
    pub configured_bitrate: u64,
    /// Base interface ID. Per-peer IDs will be assigned dynamically.
    pub interface_id: InterfaceId,
    pub ingress_control: rns_core::transport::types::IngressControlConfig,
    pub runtime: Arc<Mutex<AutoRuntime>>,
}

#[derive(Debug, Clone)]
pub struct AutoRuntime {
    pub announce_interval_secs: f64,
    pub peer_timeout_secs: f64,
    pub peer_job_interval_secs: f64,
}

impl AutoRuntime {
    pub fn from_config(_config: &AutoConfig) -> Self {
        Self {
            announce_interval_secs: ANNOUNCE_INTERVAL,
            peer_timeout_secs: PEERING_TIMEOUT,
            peer_job_interval_secs: PEER_JOB_INTERVAL,
        }
    }
}

#[derive(Debug, Clone)]
pub struct AutoRuntimeConfigHandle {
    pub interface_name: String,
    pub runtime: Arc<Mutex<AutoRuntime>>,
    pub startup: AutoRuntime,
}

impl Default for AutoConfig {
    fn default() -> Self {
        let mut config = AutoConfig {
            name: String::new(),
            group_id: DEFAULT_GROUP_ID.to_vec(),
            discovery_scope: SCOPE_LINK.to_string(),
            discovery_port: DEFAULT_DISCOVERY_PORT,
            data_port: DEFAULT_DATA_PORT,
            multicast_address_type: MULTICAST_TEMPORARY_ADDRESS_TYPE.to_string(),
            allowed_interfaces: Vec::new(),
            ignored_interfaces: Vec::new(),
            configured_bitrate: BITRATE_GUESS,
            interface_id: InterfaceId(0),
            ingress_control: rns_core::transport::types::IngressControlConfig::enabled(),
            runtime: Arc::new(Mutex::new(AutoRuntime {
                announce_interval_secs: ANNOUNCE_INTERVAL,
                peer_timeout_secs: PEERING_TIMEOUT,
                peer_job_interval_secs: PEER_JOB_INTERVAL,
            })),
        };
        let startup = AutoRuntime::from_config(&config);
        config.runtime = Arc::new(Mutex::new(startup));
        config
    }
}

// ── Multicast address derivation ───────────────────────────────────────────

/// Derive the IPv6 multicast discovery address from group_id, scope, and address type.
///
/// Algorithm (matching Python):
///   1. group_hash = SHA-256(group_id)
///   2. Build suffix from hash bytes 2..14 as 6 little-endian 16-bit words
///   3. First word is hardcoded "0"
///   4. Prefix = "ff" + address_type + scope
pub fn derive_multicast_address(group_id: &[u8], address_type: &str, scope: &str) -> String {
    let group_hash = rns_crypto::sha256::sha256(group_id);
    let g = &group_hash;

    // Build 6 LE 16-bit words from bytes 2..14
    let w1 = (g[2] as u16) << 8 | g[3] as u16;
    let w2 = (g[4] as u16) << 8 | g[5] as u16;
    let w3 = (g[6] as u16) << 8 | g[7] as u16;
    let w4 = (g[8] as u16) << 8 | g[9] as u16;
    let w5 = (g[10] as u16) << 8 | g[11] as u16;
    let w6 = (g[12] as u16) << 8 | g[13] as u16;

    format!(
        "ff{}{}:0:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
        address_type, scope, w1, w2, w3, w4, w5, w6
    )
}

/// Parse a multicast address string into an Ipv6Addr.
pub fn parse_multicast_addr(addr: &str) -> Option<Ipv6Addr> {
    addr.parse::<Ipv6Addr>().ok()
}

// ── Discovery token ────────────────────────────────────────────────────────

/// Compute the discovery token: SHA-256(group_id + link_local_address_string).
pub fn compute_discovery_token(group_id: &[u8], link_local_addr: &str) -> [u8; 32] {
    let mut input = group_id.to_vec();
    input.extend_from_slice(link_local_addr.as_bytes());
    rns_crypto::sha256::sha256(&input)
}

// ── Network interface enumeration ──────────────────────────────────────────

/// Information about a local network interface with an IPv6 link-local address.
#[derive(Debug, Clone)]
pub struct LocalInterface {
    pub name: String,
    pub link_local_addr: String,
    pub index: u32,
}

/// Enumerate network interfaces that have IPv6 link-local addresses (fe80::/10).
///
/// Uses `libc::getifaddrs()`. Filters by allowed/ignored interface lists.
pub fn enumerate_interfaces(allowed: &[String], ignored: &[String]) -> Vec<LocalInterface> {
    let mut result = Vec::new();

    unsafe {
        let mut ifaddrs: *mut libc::ifaddrs = std::ptr::null_mut();
        if libc::getifaddrs(&mut ifaddrs) != 0 {
            return result;
        }

        let mut current = ifaddrs;
        while !current.is_null() {
            let ifa = &*current;
            current = ifa.ifa_next;

            // Must have an address
            if ifa.ifa_addr.is_null() {
                continue;
            }

            // Must be AF_INET6
            if (*ifa.ifa_addr).sa_family as i32 != libc::AF_INET6 {
                continue;
            }

            // Get interface name
            let name = match std::ffi::CStr::from_ptr(ifa.ifa_name).to_str() {
                Ok(s) => s.to_string(),
                Err(_) => continue,
            };

            // Check global ignore list
            if ALL_IGNORE_IFS.iter().any(|&ig| ig == name) {
                if !allowed.iter().any(|a| a == &name) {
                    continue;
                }
            }

            // Check ignored interfaces
            if ignored.iter().any(|ig| ig == &name) {
                continue;
            }

            // Check allowed interfaces (if non-empty, only allow those)
            if !allowed.is_empty() && !allowed.iter().any(|a| a == &name) {
                continue;
            }

            // Extract IPv6 address
            let sa6 = ifa.ifa_addr as *const libc::sockaddr_in6;
            let addr_bytes = (*sa6).sin6_addr.s6_addr;
            let ipv6 = Ipv6Addr::from(addr_bytes);

            // Must be link-local (fe80::/10)
            let octets = ipv6.octets();
            if octets[0] != 0xfe || (octets[1] & 0xc0) != 0x80 {
                continue;
            }

            // Format the address (drop scope ID, matching Python's descope_linklocal)
            let addr_str = format!("{}", ipv6);

            // Get interface index
            let index = libc::if_nametoindex(ifa.ifa_name);
            if index == 0 {
                continue;
            }

            // Avoid duplicates (same interface may appear multiple times)
            if result.iter().any(|li: &LocalInterface| li.name == name) {
                continue;
            }

            result.push(LocalInterface {
                name,
                link_local_addr: addr_str,
                index,
            });
        }

        libc::freeifaddrs(ifaddrs);
    }

    result
}

// ── Peer tracking ──────────────────────────────────────────────────────────

/// A discovered peer.
struct AutoPeer {
    interface_id: InterfaceId,
    #[allow(dead_code)]
    link_local_addr: String,
    #[allow(dead_code)]
    ifname: String,
    last_heard: f64,
}

/// Writer that sends UDP unicast data to a peer.
struct UdpWriter {
    socket: UdpSocket,
    target: SocketAddrV6,
}

impl Writer for UdpWriter {
    fn send_frame(&mut self, data: &[u8]) -> io::Result<()> {
        self.socket.send_to(data, self.target)?;
        Ok(())
    }
}

/// Shared state for the AutoInterface across all threads.
struct SharedState {
    /// Known peers: link_local_addr → AutoPeer
    peers: HashMap<String, AutoPeer>,
    /// Our own link-local addresses (for echo detection)
    link_local_addresses: Vec<String>,
    /// Deduplication deque: (hash, timestamp)
    dedup_deque: VecDeque<([u8; 32], f64)>,
    /// Flag set when final_init is done
    online: bool,
    /// Next dynamic interface ID
    next_id: Arc<AtomicU64>,
}

impl SharedState {
    fn new(next_id: Arc<AtomicU64>) -> Self {
        SharedState {
            peers: HashMap::new(),
            link_local_addresses: Vec::new(),
            dedup_deque: VecDeque::new(),
            online: false,
            next_id,
        }
    }

    /// Check dedup deque for a data hash.
    fn is_duplicate(&self, hash: &[u8; 32], now: f64) -> bool {
        for (h, ts) in &self.dedup_deque {
            if h == hash && now < *ts + MULTI_IF_DEQUE_TTL {
                return true;
            }
        }
        false
    }

    /// Add to dedup deque, trimming to max length.
    fn add_dedup(&mut self, hash: [u8; 32], now: f64) {
        self.dedup_deque.push_back((hash, now));
        while self.dedup_deque.len() > MULTI_IF_DEQUE_LEN {
            self.dedup_deque.pop_front();
        }
    }

    /// Refresh a peer's last_heard timestamp.
    fn refresh_peer(&mut self, addr: &str, now: f64) {
        if let Some(peer) = self.peers.get_mut(addr) {
            peer.last_heard = now;
        }
    }
}

// ── Start function ─────────────────────────────────────────────────────────

/// Start an AutoInterface. Discovers local IPv6 link-local interfaces,
/// sets up multicast discovery, and creates UDP data servers.
///
/// Returns a vec of (InterfaceId, Writer) for each initial peer (typically empty
/// since peers are discovered dynamically via InterfaceUp events).
pub fn start(
    config: AutoConfig,
    tx: EventSender,
    next_dynamic_id: Arc<AtomicU64>,
) -> io::Result<()> {
    let interfaces = enumerate_interfaces(&config.allowed_interfaces, &config.ignored_interfaces);

    if interfaces.is_empty() {
        log::warn!(
            "[{}] No suitable IPv6 link-local interfaces found",
            config.name,
        );
        return Ok(());
    }

    let group_id = config.group_id.clone();
    let mcast_addr_str = derive_multicast_address(
        &group_id,
        &config.multicast_address_type,
        &config.discovery_scope,
    );

    let mcast_ip = match parse_multicast_addr(&mcast_addr_str) {
        Some(ip) => ip,
        None => {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Invalid multicast address: {}", mcast_addr_str),
            ));
        }
    };

    let discovery_port = config.discovery_port;
    let unicast_discovery_port = config.discovery_port + 1;
    let data_port = config.data_port;
    let name = config.name.clone();
    let configured_bitrate = config.configured_bitrate;
    let ingress_control = config.ingress_control;
    {
        let startup = AutoRuntime::from_config(&config);
        *config.runtime.lock().unwrap() = startup;
    }
    let runtime = Arc::clone(&config.runtime);

    let shared = Arc::new(Mutex::new(SharedState::new(next_dynamic_id)));
    let running = Arc::new(AtomicBool::new(true));

    // Record our own link-local addresses
    {
        let mut state = shared.lock().unwrap();
        for iface in &interfaces {
            state
                .link_local_addresses
                .push(iface.link_local_addr.clone());
        }
    }

    log::info!(
        "[{}] AutoInterface starting with {} local interfaces, multicast {}",
        name,
        interfaces.len(),
        mcast_addr_str,
    );

    // Per-interface: set up discovery sockets and threads
    for local_iface in &interfaces {
        let ifname = local_iface.name.clone();
        let link_local = local_iface.link_local_addr.clone();
        let if_index = local_iface.index;

        // ─── Multicast discovery socket ───────────────────────────────
        let mcast_socket = create_multicast_recv_socket(&mcast_ip, discovery_port, if_index)?;

        // ─── Unicast discovery socket ─────────────────────────────────
        let unicast_socket =
            create_unicast_recv_socket(&link_local, unicast_discovery_port, if_index)?;

        // ─── Discovery sender thread ──────────────────────────────────
        {
            let group_id = group_id.clone();
            let link_local = link_local.clone();
            let running = running.clone();
            let name = name.clone();
            let runtime = runtime.clone();

            thread::Builder::new()
                .name(format!("auto-disc-tx-{}", ifname))
                .spawn(move || {
                    discovery_sender_loop(
                        &group_id,
                        &link_local,
                        &mcast_ip,
                        discovery_port,
                        if_index,
                        runtime,
                        &running,
                        &name,
                    );
                })?;
        }

        // ─── Multicast discovery receiver thread ──────────────────────
        {
            let group_id = group_id.clone();
            let shared = shared.clone();
            let tx = tx.clone();
            let running = running.clone();
            let name = name.clone();
            let runtime = runtime.clone();

            thread::Builder::new()
                .name(format!("auto-disc-rx-{}", ifname))
                .spawn(move || {
                    discovery_receiver_loop(
                        mcast_socket,
                        &group_id,
                        shared,
                        tx,
                        &running,
                        &name,
                        data_port,
                        configured_bitrate,
                        ingress_control,
                        runtime,
                    );
                })?;
        }

        // ─── Unicast discovery receiver thread ────────────────────────
        {
            let group_id = group_id.clone();
            let shared = shared.clone();
            let tx = tx.clone();
            let running = running.clone();
            let name = name.clone();
            let runtime = runtime.clone();
            let ingress_control = ingress_control;

            thread::Builder::new()
                .name(format!("auto-udisc-rx-{}", ifname))
                .spawn(move || {
                    discovery_receiver_loop(
                        unicast_socket,
                        &group_id,
                        shared,
                        tx,
                        &running,
                        &name,
                        data_port,
                        configured_bitrate,
                        ingress_control,
                        runtime,
                    );
                })?;
        }

        // ─── Data receiver thread ─────────────────────────────────────
        {
            let link_local = local_iface.link_local_addr.clone();
            let shared = shared.clone();
            let tx = tx.clone();
            let running = running.clone();
            let name = name.clone();

            let data_socket = create_data_recv_socket(&link_local, data_port, if_index)?;

            thread::Builder::new()
                .name(format!("auto-data-rx-{}", local_iface.name))
                .spawn(move || {
                    data_receiver_loop(data_socket, shared, tx, &running, &name);
                })?;
        }
    }

    // ─── Peer jobs thread ─────────────────────────────────────────────
    {
        let shared = shared.clone();
        let tx = tx.clone();
        let running = running.clone();
        let name = name.clone();
        let runtime = runtime.clone();

        thread::Builder::new()
            .name(format!("auto-peer-jobs-{}", name))
            .spawn(move || {
                peer_jobs_loop(shared, tx, runtime, &running, &name);
            })?;
    }

    // Wait for initial peering
    let announce_interval = runtime.lock().unwrap().announce_interval_secs;
    let peering_wait = Duration::from_secs_f64(announce_interval * 1.2);
    thread::sleep(peering_wait);

    // Mark as online
    {
        let mut state = shared.lock().unwrap();
        state.online = true;
    }

    log::info!("[{}] AutoInterface online", config.name);

    Ok(())
}

// ── Socket creation helpers ────────────────────────────────────────────────

fn create_multicast_recv_socket(
    mcast_ip: &Ipv6Addr,
    port: u16,
    if_index: u32,
) -> io::Result<UdpSocket> {
    let socket = socket2::Socket::new(
        socket2::Domain::IPV6,
        socket2::Type::DGRAM,
        Some(socket2::Protocol::UDP),
    )?;

    socket.set_reuse_address(true)?;
    #[cfg(not(target_os = "windows"))]
    socket.set_reuse_port(true)?;

    // Bind to [::]:port on the specific interface
    let bind_addr = SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, port, 0, if_index);
    socket.bind(&bind_addr.into())?;

    // Join multicast group on the specific interface
    socket.join_multicast_v6(mcast_ip, if_index)?;

    socket.set_nonblocking(false)?;
    let std_socket: UdpSocket = socket.into();
    std_socket.set_read_timeout(Some(Duration::from_secs(2)))?;
    Ok(std_socket)
}

fn create_unicast_recv_socket(link_local: &str, port: u16, if_index: u32) -> io::Result<UdpSocket> {
    let ip: Ipv6Addr = link_local
        .parse()
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("bad IPv6: {}", e)))?;

    let socket = socket2::Socket::new(
        socket2::Domain::IPV6,
        socket2::Type::DGRAM,
        Some(socket2::Protocol::UDP),
    )?;

    socket.set_reuse_address(true)?;
    #[cfg(not(target_os = "windows"))]
    socket.set_reuse_port(true)?;

    let bind_addr = SocketAddrV6::new(ip, port, 0, if_index);
    socket.bind(&bind_addr.into())?;

    socket.set_nonblocking(false)?;
    let std_socket: UdpSocket = socket.into();
    std_socket.set_read_timeout(Some(Duration::from_secs(2)))?;
    Ok(std_socket)
}

fn create_data_recv_socket(link_local: &str, port: u16, if_index: u32) -> io::Result<UdpSocket> {
    let ip: Ipv6Addr = link_local
        .parse()
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("bad IPv6: {}", e)))?;

    let socket = socket2::Socket::new(
        socket2::Domain::IPV6,
        socket2::Type::DGRAM,
        Some(socket2::Protocol::UDP),
    )?;

    socket.set_reuse_address(true)?;
    #[cfg(not(target_os = "windows"))]
    socket.set_reuse_port(true)?;

    let bind_addr = SocketAddrV6::new(ip, port, 0, if_index);
    socket.bind(&bind_addr.into())?;

    socket.set_nonblocking(false)?;
    let std_socket: UdpSocket = socket.into();
    std_socket.set_read_timeout(Some(Duration::from_secs(2)))?;
    Ok(std_socket)
}

// ── Thread loops ───────────────────────────────────────────────────────────

/// Discovery sender: periodically sends discovery token via multicast.
fn discovery_sender_loop(
    group_id: &[u8],
    link_local_addr: &str,
    mcast_ip: &Ipv6Addr,
    discovery_port: u16,
    if_index: u32,
    runtime: Arc<Mutex<AutoRuntime>>,
    running: &AtomicBool,
    name: &str,
) {
    let token = compute_discovery_token(group_id, link_local_addr);

    while running.load(Ordering::Relaxed) {
        // Create a fresh socket for each send (matches Python)
        if let Ok(socket) = UdpSocket::bind("[::]:0") {
            // Set multicast interface
            let if_bytes = if_index.to_ne_bytes();
            unsafe {
                libc::setsockopt(
                    socket_fd(&socket),
                    libc::IPPROTO_IPV6,
                    libc::IPV6_MULTICAST_IF,
                    if_bytes.as_ptr() as *const libc::c_void,
                    4,
                );
            }

            let target = SocketAddrV6::new(*mcast_ip, discovery_port, 0, 0);
            if let Err(e) = socket.send_to(&token, target) {
                log::debug!("[{}] multicast send error: {}", name, e);
            }
        }

        let sleep_dur =
            Duration::from_secs_f64(runtime.lock().unwrap().announce_interval_secs.max(0.1));
        thread::sleep(sleep_dur);
    }
}

/// Discovery receiver: listens for discovery tokens and adds peers.
fn discovery_receiver_loop(
    socket: UdpSocket,
    group_id: &[u8],
    shared: Arc<Mutex<SharedState>>,
    tx: EventSender,
    running: &AtomicBool,
    name: &str,
    data_port: u16,
    configured_bitrate: u64,
    ingress_control: rns_core::transport::types::IngressControlConfig,
    runtime: Arc<Mutex<AutoRuntime>>,
) {
    let mut buf = [0u8; 1024];

    while running.load(Ordering::Relaxed) {
        match socket.recv_from(&mut buf) {
            Ok((n, src)) => {
                if n < 32 {
                    continue;
                }

                // Extract source IPv6 address
                let src_addr = match src {
                    std::net::SocketAddr::V6(v6) => v6,
                    _ => continue,
                };
                let src_ip = format!("{}", src_addr.ip());

                let peering_hash = &buf[..32];
                let expected = compute_discovery_token(group_id, &src_ip);

                if peering_hash != expected {
                    log::debug!("[{}] invalid peering hash from {}", name, src_ip);
                    continue;
                }

                // Check if online
                let state = shared.lock().unwrap();
                if !state.online {
                    // Not fully initialized yet, but still accept for initial peering
                    // (Python processes after final_init_done)
                }

                // Check if it's our own echo
                if state.link_local_addresses.contains(&src_ip) {
                    // Multicast echo from ourselves — just record it
                    drop(state);
                    continue;
                }

                // Check if already known
                if state.peers.contains_key(&src_ip) {
                    let now = crate::time::now();
                    drop(state);
                    let mut state = shared.lock().unwrap();
                    state.refresh_peer(&src_ip, now);
                    continue;
                }
                drop(state);

                // New peer! Create a data writer to send to them.
                add_peer(
                    &shared,
                    &tx,
                    &src_ip,
                    data_port,
                    name,
                    configured_bitrate,
                    ingress_control,
                    &runtime,
                );
            }
            Err(ref e)
                if e.kind() == io::ErrorKind::WouldBlock || e.kind() == io::ErrorKind::TimedOut =>
            {
                // Timeout, loop again
                continue;
            }
            Err(e) => {
                log::warn!("[{}] discovery recv error: {}", name, e);
                if !running.load(Ordering::Relaxed) {
                    return;
                }
                thread::sleep(Duration::from_millis(100));
            }
        }
    }
}

/// Add a new peer, creating a writer and emitting InterfaceUp.
fn add_peer(
    shared: &Arc<Mutex<SharedState>>,
    tx: &EventSender,
    peer_addr: &str,
    data_port: u16,
    name: &str,
    configured_bitrate: u64,
    ingress_control: rns_core::transport::types::IngressControlConfig,
    _runtime: &Arc<Mutex<AutoRuntime>>,
) {
    let peer_ip: Ipv6Addr = match peer_addr.parse() {
        Ok(ip) => ip,
        Err(_) => return,
    };

    // Create UDP writer to send data to this peer
    let send_socket = match UdpSocket::bind("[::]:0") {
        Ok(s) => s,
        Err(e) => {
            log::warn!(
                "[{}] failed to create writer for peer {}: {}",
                name,
                peer_addr,
                e
            );
            return;
        }
    };

    let target = SocketAddrV6::new(peer_ip, data_port, 0, 0);

    let mut state = shared.lock().unwrap();

    // Double-check not already added (race)
    if state.peers.contains_key(peer_addr) {
        state.refresh_peer(peer_addr, crate::time::now());
        return;
    }

    let peer_id = InterfaceId(state.next_id.fetch_add(1, Ordering::Relaxed));

    // Create a boxed writer for the driver
    let driver_writer: Box<dyn Writer> = Box::new(UdpWriter {
        socket: send_socket,
        target,
    });

    let peer_info = rns_core::transport::types::InterfaceInfo {
        id: peer_id,
        name: format!("{}:{}", name, peer_addr),
        mode: rns_core::constants::MODE_FULL,
        out_capable: true,
        in_capable: true,
        bitrate: Some(configured_bitrate),
        announce_rate_target: None,
        announce_rate_grace: 0,
        announce_rate_penalty: 0.0,
        announce_cap: rns_core::constants::ANNOUNCE_CAP,
        is_local_client: false,
        wants_tunnel: false,
        tunnel_id: None,
        mtu: 1400,
        ia_freq: 0.0,
        started: 0.0,
        ingress_control,
    };

    let now = crate::time::now();
    state.peers.insert(
        peer_addr.to_string(),
        AutoPeer {
            interface_id: peer_id,
            link_local_addr: peer_addr.to_string(),
            ifname: String::new(),
            last_heard: now,
        },
    );

    log::info!(
        "[{}] Peer discovered: {} (id={})",
        name,
        peer_addr,
        peer_id.0
    );

    // Notify driver of new dynamic interface
    let _ = tx.send(Event::InterfaceUp(
        peer_id,
        Some(driver_writer),
        Some(peer_info),
    ));
}

/// Data receiver: receives unicast UDP data from peers and dispatches as frames.
fn data_receiver_loop(
    socket: UdpSocket,
    shared: Arc<Mutex<SharedState>>,
    tx: EventSender,
    running: &AtomicBool,
    name: &str,
) {
    let mut buf = [0u8; HW_MTU + 64]; // a bit extra

    while running.load(Ordering::Relaxed) {
        match socket.recv_from(&mut buf) {
            Ok((n, src)) => {
                if n == 0 {
                    continue;
                }

                let src_addr = match src {
                    std::net::SocketAddr::V6(v6) => v6,
                    _ => continue,
                };
                let src_ip = format!("{}", src_addr.ip());
                let data = &buf[..n];

                let now = crate::time::now();
                let data_hash = rns_crypto::sha256::sha256(data);

                let mut state = shared.lock().unwrap();

                if !state.online {
                    continue;
                }

                // Deduplication
                if state.is_duplicate(&data_hash, now) {
                    continue;
                }
                state.add_dedup(data_hash, now);

                // Refresh peer
                state.refresh_peer(&src_ip, now);

                // Find the interface ID for this peer
                let iface_id = match state.peers.get(&src_ip) {
                    Some(peer) => peer.interface_id,
                    None => {
                        // Unknown peer, skip
                        continue;
                    }
                };

                drop(state);

                if tx
                    .send(Event::Frame {
                        interface_id: iface_id,
                        data: data.to_vec(),
                    })
                    .is_err()
                {
                    return;
                }
            }
            Err(ref e)
                if e.kind() == io::ErrorKind::WouldBlock || e.kind() == io::ErrorKind::TimedOut =>
            {
                continue;
            }
            Err(e) => {
                log::warn!("[{}] data recv error: {}", name, e);
                if !running.load(Ordering::Relaxed) {
                    return;
                }
                thread::sleep(Duration::from_millis(100));
            }
        }
    }
}

/// Peer jobs: periodically cull timed-out peers.
fn peer_jobs_loop(
    shared: Arc<Mutex<SharedState>>,
    tx: EventSender,
    runtime: Arc<Mutex<AutoRuntime>>,
    running: &AtomicBool,
    name: &str,
) {
    while running.load(Ordering::Relaxed) {
        let interval =
            Duration::from_secs_f64(runtime.lock().unwrap().peer_job_interval_secs.max(0.1));
        thread::sleep(interval);

        let now = crate::time::now();
        let mut timed_out = Vec::new();
        let peer_timeout_secs = runtime.lock().unwrap().peer_timeout_secs;

        {
            let state = shared.lock().unwrap();
            for (addr, peer) in &state.peers {
                if now > peer.last_heard + peer_timeout_secs {
                    timed_out.push((addr.clone(), peer.interface_id));
                }
            }
        }

        for (addr, iface_id) in &timed_out {
            log::info!("[{}] Peer timed out: {}", name, addr);
            let mut state = shared.lock().unwrap();
            state.peers.remove(addr.as_str());
            let _ = tx.send(Event::InterfaceDown(*iface_id));
        }
    }
}

// ── Helper ─────────────────────────────────────────────────────────────────

/// Get the raw file descriptor from a UdpSocket (for setsockopt).
#[cfg(unix)]
fn socket_fd(socket: &UdpSocket) -> i32 {
    use std::os::unix::io::AsRawFd;
    socket.as_raw_fd()
}

#[cfg(not(unix))]
fn socket_fd(_socket: &UdpSocket) -> i32 {
    0
}

// ── Factory implementation ─────────────────────────────────────────────────

use super::{InterfaceConfigData, InterfaceFactory, StartContext, StartResult};

/// Factory for `AutoInterface`.
pub struct AutoFactory;

impl InterfaceFactory for AutoFactory {
    fn type_name(&self) -> &str {
        "AutoInterface"
    }

    fn parse_config(
        &self,
        name: &str,
        id: InterfaceId,
        params: &HashMap<String, String>,
    ) -> Result<Box<dyn InterfaceConfigData>, String> {
        let group_id = params
            .get("group_id")
            .map(|v| v.as_bytes().to_vec())
            .unwrap_or_else(|| DEFAULT_GROUP_ID.to_vec());

        let discovery_scope = params
            .get("discovery_scope")
            .map(|v| match v.to_lowercase().as_str() {
                "link" => SCOPE_LINK.to_string(),
                "admin" => SCOPE_ADMIN.to_string(),
                "site" => SCOPE_SITE.to_string(),
                "organisation" | "organization" => SCOPE_ORGANISATION.to_string(),
                "global" => SCOPE_GLOBAL.to_string(),
                _ => v.clone(),
            })
            .unwrap_or_else(|| SCOPE_LINK.to_string());

        let discovery_port = params
            .get("discovery_port")
            .and_then(|v| v.parse().ok())
            .unwrap_or(DEFAULT_DISCOVERY_PORT);

        let data_port = params
            .get("data_port")
            .and_then(|v| v.parse().ok())
            .unwrap_or(DEFAULT_DATA_PORT);

        let multicast_address_type = params
            .get("multicast_address_type")
            .map(|v| match v.to_lowercase().as_str() {
                "permanent" => MULTICAST_PERMANENT_ADDRESS_TYPE.to_string(),
                "temporary" => MULTICAST_TEMPORARY_ADDRESS_TYPE.to_string(),
                _ => v.clone(),
            })
            .unwrap_or_else(|| MULTICAST_TEMPORARY_ADDRESS_TYPE.to_string());

        let configured_bitrate = params
            .get("configured_bitrate")
            .or_else(|| params.get("bitrate"))
            .and_then(|v| v.parse().ok())
            .unwrap_or(BITRATE_GUESS);

        let allowed_interfaces = params
            .get("devices")
            .or_else(|| params.get("allowed_interfaces"))
            .map(|v| {
                v.split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect()
            })
            .unwrap_or_default();

        let ignored_interfaces = params
            .get("ignored_devices")
            .or_else(|| params.get("ignored_interfaces"))
            .map(|v| {
                v.split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect()
            })
            .unwrap_or_default();

        Ok(Box::new(AutoConfig {
            name: name.to_string(),
            group_id,
            discovery_scope,
            discovery_port,
            data_port,
            multicast_address_type,
            allowed_interfaces,
            ignored_interfaces,
            configured_bitrate,
            interface_id: id,
            ingress_control: rns_core::transport::types::IngressControlConfig::enabled(),
            runtime: Arc::new(Mutex::new(AutoRuntime {
                announce_interval_secs: ANNOUNCE_INTERVAL,
                peer_timeout_secs: PEERING_TIMEOUT,
                peer_job_interval_secs: PEER_JOB_INTERVAL,
            })),
        }))
    }

    fn start(
        &self,
        config: Box<dyn InterfaceConfigData>,
        ctx: StartContext,
    ) -> std::io::Result<StartResult> {
        let mut auto_config = *config.into_any().downcast::<AutoConfig>().map_err(|_| {
            std::io::Error::new(std::io::ErrorKind::InvalidData, "wrong config type")
        })?;

        auto_config.ingress_control = ctx.ingress_control;
        start(auto_config, ctx.tx, ctx.next_dynamic_id)?;
        Ok(StartResult::Listener { control: None })
    }
}

pub(crate) fn auto_runtime_handle_from_config(config: &AutoConfig) -> AutoRuntimeConfigHandle {
    AutoRuntimeConfigHandle {
        interface_name: config.name.clone(),
        runtime: Arc::clone(&config.runtime),
        startup: AutoRuntime::from_config(config),
    }
}

// ── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── Multicast address derivation ──────────────────────────────────

    #[test]
    fn multicast_address_default_group() {
        // Python vector: ff12:0:d70b:fb1c:16e4:5e39:485e:31e1
        let addr = derive_multicast_address(
            DEFAULT_GROUP_ID,
            MULTICAST_TEMPORARY_ADDRESS_TYPE,
            SCOPE_LINK,
        );
        assert_eq!(addr, "ff12:0:d70b:fb1c:16e4:5e39:485e:31e1");
    }

    #[test]
    fn multicast_address_custom_group() {
        let addr =
            derive_multicast_address(b"testgroup", MULTICAST_TEMPORARY_ADDRESS_TYPE, SCOPE_LINK);
        // Just verify format
        assert!(addr.starts_with("ff12:0:"));
        // Must be different from default
        assert_ne!(addr, "ff12:0:d70b:fb1c:16e4:5e39:485e:31e1");
    }

    #[test]
    fn multicast_address_scope_admin() {
        let addr = derive_multicast_address(
            DEFAULT_GROUP_ID,
            MULTICAST_TEMPORARY_ADDRESS_TYPE,
            SCOPE_ADMIN,
        );
        assert!(addr.starts_with("ff14:0:"));
    }

    #[test]
    fn multicast_address_permanent_type() {
        let addr = derive_multicast_address(
            DEFAULT_GROUP_ID,
            MULTICAST_PERMANENT_ADDRESS_TYPE,
            SCOPE_LINK,
        );
        assert!(addr.starts_with("ff02:0:"));
    }

    #[test]
    fn multicast_address_parseable() {
        let addr = derive_multicast_address(
            DEFAULT_GROUP_ID,
            MULTICAST_TEMPORARY_ADDRESS_TYPE,
            SCOPE_LINK,
        );
        let ip = parse_multicast_addr(&addr);
        assert!(ip.is_some());
        assert!(ip.unwrap().is_multicast());
    }

    // ── Discovery token ──────────────────────────────────────────────

    #[test]
    fn discovery_token_interop() {
        // Python vector: fe80::1 → 97b25576749ea936b0d8a8536ffaf442d157cf47d460dcf13c48b7bd18b6c163
        let token = compute_discovery_token(DEFAULT_GROUP_ID, "fe80::1");
        let expected = "97b25576749ea936b0d8a8536ffaf442d157cf47d460dcf13c48b7bd18b6c163";
        let got = token
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>();
        assert_eq!(got, expected);
    }

    #[test]
    fn discovery_token_interop_2() {
        // Python vector: fe80::dead:beef:1234:5678
        let token = compute_discovery_token(DEFAULT_GROUP_ID, "fe80::dead:beef:1234:5678");
        let expected = "46b6ec7595504b6a35f06bd4bfff71567fb82fcf2706cd361bab20409c42d072";
        let got = token
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>();
        assert_eq!(got, expected);
    }

    #[test]
    fn discovery_token_different_groups() {
        let t1 = compute_discovery_token(b"reticulum", "fe80::1");
        let t2 = compute_discovery_token(b"othergroup", "fe80::1");
        assert_ne!(t1, t2);
    }

    #[test]
    fn discovery_token_different_addrs() {
        let t1 = compute_discovery_token(DEFAULT_GROUP_ID, "fe80::1");
        let t2 = compute_discovery_token(DEFAULT_GROUP_ID, "fe80::2");
        assert_ne!(t1, t2);
    }

    // ── Deduplication ────────────────────────────────────────────────

    #[test]
    fn dedup_basic() {
        let next_id = Arc::new(AtomicU64::new(1));
        let mut state = SharedState::new(next_id);

        let hash = [0xAA; 32];
        let now = 1000.0;

        assert!(!state.is_duplicate(&hash, now));
        state.add_dedup(hash, now);
        assert!(state.is_duplicate(&hash, now));
    }

    #[test]
    fn dedup_expired() {
        let next_id = Arc::new(AtomicU64::new(1));
        let mut state = SharedState::new(next_id);

        let hash = [0xBB; 32];
        state.add_dedup(hash, 1000.0);

        // Within TTL
        assert!(state.is_duplicate(&hash, 1000.5));
        // Expired
        assert!(!state.is_duplicate(&hash, 1001.0));
    }

    #[test]
    fn dedup_max_length() {
        let next_id = Arc::new(AtomicU64::new(1));
        let mut state = SharedState::new(next_id);

        // Fill beyond max
        for i in 0..MULTI_IF_DEQUE_LEN + 10 {
            let mut hash = [0u8; 32];
            hash[0] = (i & 0xFF) as u8;
            hash[1] = ((i >> 8) & 0xFF) as u8;
            state.add_dedup(hash, 1000.0);
        }

        assert_eq!(state.dedup_deque.len(), MULTI_IF_DEQUE_LEN);
    }

    // ── Peer tracking ────────────────────────────────────────────────

    #[test]
    fn peer_refresh() {
        let next_id = Arc::new(AtomicU64::new(100));
        let mut state = SharedState::new(next_id);

        state.peers.insert(
            "fe80::1".to_string(),
            AutoPeer {
                interface_id: InterfaceId(100),
                link_local_addr: "fe80::1".to_string(),
                ifname: "eth0".to_string(),
                last_heard: 1000.0,
            },
        );

        state.refresh_peer("fe80::1", 2000.0);
        assert_eq!(state.peers["fe80::1"].last_heard, 2000.0);
    }

    #[test]
    fn peer_not_found_refresh() {
        let next_id = Arc::new(AtomicU64::new(100));
        let mut state = SharedState::new(next_id);
        // Should not panic
        state.refresh_peer("fe80::999", 1000.0);
    }

    // ── Network interface enumeration ────────────────────────────────

    #[test]
    fn enumerate_returns_vec() {
        // This test just verifies the function runs without crashing.
        // Results depend on the system's network configuration.
        let interfaces = enumerate_interfaces(&[], &[]);
        // On CI/test machines, we may or may not have IPv6 link-local
        for iface in &interfaces {
            assert!(!iface.name.is_empty());
            assert!(iface.link_local_addr.starts_with("fe80"));
            assert!(iface.index > 0);
        }
    }

    #[test]
    fn enumerate_with_ignored() {
        // Ignore everything
        let interfaces = enumerate_interfaces(
            &[],
            &[
                "lo".to_string(),
                "eth0".to_string(),
                "wlan0".to_string(),
                "enp0s3".to_string(),
                "docker0".to_string(),
            ],
        );
        // May still have some interfaces, but known ones should be filtered
        for iface in &interfaces {
            assert_ne!(iface.name, "lo");
            assert_ne!(iface.name, "eth0");
            assert_ne!(iface.name, "wlan0");
        }
    }

    #[test]
    fn enumerate_with_allowed_nonexistent() {
        // Only allow an interface that doesn't exist
        let interfaces = enumerate_interfaces(&["nonexistent_if_12345".to_string()], &[]);
        assert!(interfaces.is_empty());
    }

    // ── Config defaults ──────────────────────────────────────────────

    #[test]
    fn config_defaults() {
        let config = AutoConfig::default();
        assert_eq!(config.group_id, DEFAULT_GROUP_ID);
        assert_eq!(config.discovery_scope, SCOPE_LINK);
        assert_eq!(config.discovery_port, DEFAULT_DISCOVERY_PORT);
        assert_eq!(config.data_port, DEFAULT_DATA_PORT);
        assert_eq!(
            config.multicast_address_type,
            MULTICAST_TEMPORARY_ADDRESS_TYPE
        );
        assert_eq!(config.configured_bitrate, BITRATE_GUESS);
        assert!(config.allowed_interfaces.is_empty());
        assert!(config.ignored_interfaces.is_empty());
    }

    // ── Constants ────────────────────────────────────────────────────

    #[test]
    fn constants_match_python() {
        assert_eq!(DEFAULT_DISCOVERY_PORT, 29716);
        assert_eq!(DEFAULT_DATA_PORT, 42671);
        assert_eq!(HW_MTU, 1196);
        assert_eq!(MULTI_IF_DEQUE_LEN, 48);
        assert!((MULTI_IF_DEQUE_TTL - 0.75).abs() < f64::EPSILON);
        assert!((PEERING_TIMEOUT - 22.0).abs() < f64::EPSILON);
        assert!((ANNOUNCE_INTERVAL - 1.6).abs() < f64::EPSILON);
        assert!((PEER_JOB_INTERVAL - 4.0).abs() < f64::EPSILON);
        assert!((MCAST_ECHO_TIMEOUT - 6.5).abs() < f64::EPSILON);
        assert_eq!(BITRATE_GUESS, 10_000_000);
    }

    #[test]
    fn unicast_discovery_port() {
        // Python: unicast_discovery_port = discovery_port + 1
        let unicast_port = DEFAULT_DISCOVERY_PORT + 1;
        assert_eq!(unicast_port, 29717);
    }

    #[test]
    fn reverse_peering_interval() {
        let interval = ANNOUNCE_INTERVAL * REVERSE_PEERING_MULTIPLIER;
        assert!((interval - 5.2).abs() < 0.01);
    }
}