peat-mesh 0.8.2

Peat mesh networking library with CRDT sync, transport security, and topology management
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
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
//! UDP Bypass Channel for ephemeral data
//!
//! Provides a direct UDP pathway that bypasses the CRDT sync engine for
//! high-frequency, low-latency, or bandwidth-constrained scenarios.
//!
//! ## Use Cases
//!
//! - High-frequency telemetry (10-100 Hz position updates)
//! - Low-latency commands (<50ms delivery)
//! - Bandwidth-constrained links (9.6kbps tactical radio)
//! - Multicast/broadcast to cell members
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │                   Data Flow with Bypass                          │
//! │                                                                  │
//! │   Application                                                    │
//! │       │                                                          │
//! │       ├──────────────────────────┐                               │
//! │       ▼                          ▼                               │
//! │   ┌─────────────┐          ┌─────────────┐                       │
//! │   │ CRDT Store  │          │  UDP Bypass │ ◄── Ephemeral data    │
//! │   │ (Automerge) │          │   Channel   │                       │
//! │   └──────┬──────┘          └──────┬──────┘                       │
//! │          │                        │                              │
//! │          ▼                        ▼                              │
//! │   ┌─────────────┐          ┌─────────────┐                       │
//! │   │   Iroh      │          │    Raw      │                       │
//! │   │  Transport  │          │    UDP      │                       │
//! │   └─────────────┘          └─────────────┘                       │
//! │                                                                  │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Example
//!
//! ```ignore
//! use peat_mesh::transport::bypass::{UdpBypassChannel, BypassChannelConfig};
//!
//! // Create bypass channel
//! let config = BypassChannelConfig::default();
//! let channel = UdpBypassChannel::new(config).await?;
//!
//! // Send position update via bypass (no CRDT overhead)
//! channel.send(
//!     BypassTarget::Multicast { group: "239.1.1.100".parse()?, port: 5150 },
//!     "position_updates",
//!     &position_bytes,
//! ).await?;
//!
//! // Subscribe to incoming bypass messages
//! let mut rx = channel.subscribe("position_updates");
//! while let Some(msg) = rx.recv().await {
//!     println!("Received from {}: {:?}", msg.source, msg.data);
//! }
//! ```

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

use chacha20poly1305::{
    aead::{Aead, KeyInit},
    ChaCha20Poly1305, Nonce,
};
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};
use tokio::net::UdpSocket;
use tokio::sync::broadcast;
use tracing::{debug, info};

use super::MessagePriority;

// =============================================================================
// Error Types
// =============================================================================

/// Error type for bypass channel operations
#[derive(Debug)]
pub enum BypassError {
    /// IO error (socket operations)
    Io(std::io::Error),
    /// Encoding error
    Encode(String),
    /// Decoding error
    Decode(String),
    /// Invalid configuration
    Config(String),
    /// Channel not started
    NotStarted,
    /// Message too large
    MessageTooLarge { size: usize, max: usize },
    /// Invalid header
    InvalidHeader,
    /// Message is stale (past TTL)
    StaleMessage,
    /// Signature verification failed
    InvalidSignature,
    /// Decryption failed
    DecryptionFailed,
    /// Source IP not in allowlist
    UnauthorizedSource(IpAddr),
    /// Replay attack detected (duplicate sequence)
    ReplayDetected { sequence: u8 },
    /// Missing security credential (key not configured)
    MissingCredential(String),
}

impl std::fmt::Display for BypassError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BypassError::Io(e) => write!(f, "IO error: {}", e),
            BypassError::Encode(msg) => write!(f, "Encode error: {}", msg),
            BypassError::Decode(msg) => write!(f, "Decode error: {}", msg),
            BypassError::Config(msg) => write!(f, "Config error: {}", msg),
            BypassError::NotStarted => write!(f, "Bypass channel not started"),
            BypassError::MessageTooLarge { size, max } => {
                write!(f, "Message too large: {} bytes (max {})", size, max)
            }
            BypassError::InvalidHeader => write!(f, "Invalid bypass header"),
            BypassError::StaleMessage => write!(f, "Message is stale (past TTL)"),
            BypassError::InvalidSignature => write!(f, "Invalid message signature"),
            BypassError::DecryptionFailed => write!(f, "Message decryption failed"),
            BypassError::UnauthorizedSource(ip) => {
                write!(f, "Unauthorized source IP: {}", ip)
            }
            BypassError::ReplayDetected { sequence } => {
                write!(f, "Replay attack detected (sequence {})", sequence)
            }
            BypassError::MissingCredential(what) => {
                write!(f, "Missing security credential: {}", what)
            }
        }
    }
}

impl std::error::Error for BypassError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            BypassError::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for BypassError {
    fn from(err: std::io::Error) -> Self {
        BypassError::Io(err)
    }
}

pub type Result<T> = std::result::Result<T, BypassError>;

// =============================================================================
// Configuration Types
// =============================================================================

/// Transport mode for bypass messages
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum BypassTransport {
    /// UDP unicast to specific peer
    #[default]
    Unicast,
    /// UDP multicast to group
    Multicast {
        /// Multicast group address
        group: IpAddr,
        /// Port number
        port: u16,
    },
    /// UDP broadcast on subnet
    Broadcast,
}

/// Message encoding format
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageEncoding {
    /// Protobuf (recommended - compact)
    #[default]
    Protobuf,
    /// JSON (debugging)
    Json,
    /// Raw bytes (minimal overhead)
    Raw,
    /// CBOR (compact binary)
    Cbor,
}

impl std::fmt::Display for MessageEncoding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MessageEncoding::Protobuf => write!(f, "protobuf"),
            MessageEncoding::Json => write!(f, "json"),
            MessageEncoding::Raw => write!(f, "raw"),
            MessageEncoding::Cbor => write!(f, "cbor"),
        }
    }
}

/// Configuration for a bypass collection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BypassCollectionConfig {
    /// Collection name
    pub collection: String,
    /// Transport mode for this collection
    pub transport: BypassTransport,
    /// Message encoding format
    pub encoding: MessageEncoding,
    /// Time-to-live for messages in milliseconds
    #[serde(default = "default_ttl_ms")]
    pub ttl_ms: u64,
    /// QoS priority for bandwidth allocation
    #[serde(default)]
    pub priority: MessagePriority,
}

fn default_ttl_ms() -> u64 {
    5000
}

impl BypassCollectionConfig {
    /// Get TTL as Duration
    pub fn ttl(&self) -> Duration {
        Duration::from_millis(self.ttl_ms)
    }
}

impl Default for BypassCollectionConfig {
    fn default() -> Self {
        Self {
            collection: String::new(),
            transport: BypassTransport::Unicast,
            encoding: MessageEncoding::Protobuf,
            ttl_ms: 5000,
            priority: MessagePriority::Normal,
        }
    }
}

/// UDP configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UdpConfig {
    /// Bind port (0 = ephemeral)
    pub bind_port: u16,
    /// Buffer size for receiving
    pub buffer_size: usize,
    /// Multicast TTL (hop count)
    pub multicast_ttl: u32,
}

impl Default for UdpConfig {
    fn default() -> Self {
        Self {
            bind_port: 5150,
            buffer_size: 65536,
            multicast_ttl: 32,
        }
    }
}

/// Configuration for bypass channel
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BypassChannelConfig {
    /// UDP configuration
    pub udp: UdpConfig,
    /// Collections that use bypass
    pub collections: Vec<BypassCollectionConfig>,
    /// Enable multicast support
    pub multicast_enabled: bool,
    /// Maximum message size
    pub max_message_size: usize,
}

impl BypassChannelConfig {
    /// Create new configuration with defaults
    pub fn new() -> Self {
        Self {
            udp: UdpConfig::default(),
            collections: Vec::new(),
            multicast_enabled: true,
            max_message_size: 65000, // Leave room for header
        }
    }

    /// Add a collection to bypass
    pub fn with_collection(mut self, config: BypassCollectionConfig) -> Self {
        self.collections.push(config);
        self
    }

    /// Get configuration for a collection
    pub fn get_collection(&self, name: &str) -> Option<&BypassCollectionConfig> {
        self.collections.iter().find(|c| c.collection == name)
    }

    /// Check if a collection uses bypass
    pub fn is_bypass_collection(&self, name: &str) -> bool {
        self.collections.iter().any(|c| c.collection == name)
    }
}

// =============================================================================
// Security Configuration (ADR-042 Phase 5)
// =============================================================================

/// Security configuration for bypass channel
///
/// Since bypass messages don't go through Iroh's authenticated QUIC transport,
/// optional security features can be enabled to protect against:
/// - Message forgery (signing)
/// - Eavesdropping (encryption)
/// - Unauthorized sources (allowlisting)
/// - Replay attacks (sequence window)
///
/// ## Security Tradeoffs
///
/// | Feature | Overhead | Latency Impact | Protection |
/// |---------|----------|----------------|------------|
/// | Signing | +64 bytes | +0.1-0.5ms | Authenticity |
/// | Encryption | +16 bytes | +0.1-0.3ms | Confidentiality |
/// | Allowlist | 0 bytes | ~0ms | Source filtering |
/// | Replay | 0 bytes | ~0ms | Freshness |
///
/// ## When to Use
///
/// - **High-frequency telemetry**: Signing only (authenticity without encryption overhead)
/// - **Sensitive commands**: Full encryption + signing
/// - **Trusted network**: Allowlist only (minimal overhead)
/// - **Untrusted network**: All features enabled
///
/// ## Example
///
/// ```rust
/// use peat_mesh::transport::bypass::BypassSecurityConfig;
///
/// // Minimal security for high-frequency telemetry
/// let config = BypassSecurityConfig {
///     require_signature: true,
///     encrypt_payload: false,
///     ..Default::default()
/// };
///
/// // Full security for sensitive commands
/// let config = BypassSecurityConfig::full_security();
/// ```
#[derive(Debug, Clone, Default)]
pub struct BypassSecurityConfig {
    /// Require Ed25519 signature on all messages
    ///
    /// When enabled:
    /// - Outgoing messages are signed with the node's signing key
    /// - Incoming messages without valid signatures are rejected
    /// - Adds ~64 bytes overhead per message
    pub require_signature: bool,

    /// Encrypt payload with formation key (ChaCha20-Poly1305)
    ///
    /// When enabled:
    /// - Payload is encrypted before sending
    /// - Header remains unencrypted for routing
    /// - Adds ~16 bytes overhead (Poly1305 auth tag)
    pub encrypt_payload: bool,

    /// Filter sources by known peer addresses
    ///
    /// When Some:
    /// - Only accept messages from listed IP addresses
    /// - Messages from unknown IPs are rejected
    /// - Useful for trusted network segments
    pub source_allowlist: Option<Vec<IpAddr>>,

    /// Enable replay protection
    ///
    /// When enabled:
    /// - Track seen sequence numbers per source
    /// - Reject duplicate sequence numbers within window
    /// - Window size: 64 sequences (covers ~1 minute at 1 Hz)
    pub replay_protection: bool,

    /// Replay window size (default: 64)
    ///
    /// Number of sequence numbers to track per source.
    /// Larger windows use more memory but handle more reordering.
    pub replay_window_size: usize,
}

impl BypassSecurityConfig {
    /// Create configuration with no security (fastest)
    pub fn none() -> Self {
        Self::default()
    }

    /// Create configuration with signature only (authenticity)
    pub fn signed() -> Self {
        Self {
            require_signature: true,
            ..Default::default()
        }
    }

    /// Create configuration with full security (all features)
    pub fn full_security() -> Self {
        Self {
            require_signature: true,
            encrypt_payload: true,
            source_allowlist: None, // Set separately based on known peers
            replay_protection: true,
            replay_window_size: 64,
        }
    }

    /// Check if any security features are enabled
    pub fn is_enabled(&self) -> bool {
        self.require_signature
            || self.encrypt_payload
            || self.source_allowlist.is_some()
            || self.replay_protection
    }

    /// Check if source IP is allowed
    pub fn is_source_allowed(&self, ip: &IpAddr) -> bool {
        match &self.source_allowlist {
            Some(list) => list.contains(ip),
            None => true, // No allowlist = all sources allowed
        }
    }
}

/// Security credentials for bypass channel
///
/// Contains the cryptographic keys needed for signing and encryption.
#[derive(Clone, Default)]
pub struct BypassSecurityCredentials {
    /// Ed25519 signing key (private)
    signing_key: Option<SigningKey>,

    /// Ed25519 verifying keys for known peers (public)
    /// Maps peer ID or IP to their public key
    peer_keys: HashMap<String, VerifyingKey>,

    /// ChaCha20-Poly1305 encryption key (shared formation key)
    /// 256-bit key shared among formation members
    encryption_key: Option<[u8; 32]>,
}

impl std::fmt::Debug for BypassSecurityCredentials {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BypassSecurityCredentials")
            .field("has_signing_key", &self.signing_key.is_some())
            .field("peer_keys_count", &self.peer_keys.len())
            .field("has_encryption_key", &self.encryption_key.is_some())
            .finish()
    }
}

impl BypassSecurityCredentials {
    /// Create new empty credentials
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the signing key
    pub fn with_signing_key(mut self, key: SigningKey) -> Self {
        self.signing_key = Some(key);
        self
    }

    /// Add a peer's verifying key
    pub fn with_peer_key(mut self, peer_id: impl Into<String>, key: VerifyingKey) -> Self {
        self.peer_keys.insert(peer_id.into(), key);
        self
    }

    /// Set the encryption key
    pub fn with_encryption_key(mut self, key: [u8; 32]) -> Self {
        self.encryption_key = Some(key);
        self
    }

    /// Get the verifying key for our signing key
    pub fn verifying_key(&self) -> Option<VerifyingKey> {
        self.signing_key.as_ref().map(|k| k.verifying_key())
    }

    /// Sign a message
    pub fn sign(&self, message: &[u8]) -> Result<Signature> {
        let key = self
            .signing_key
            .as_ref()
            .ok_or_else(|| BypassError::MissingCredential("signing key".into()))?;
        Ok(key.sign(message))
    }

    /// Verify a signature from a known peer
    pub fn verify(&self, peer_id: &str, message: &[u8], signature: &Signature) -> Result<()> {
        let key = self
            .peer_keys
            .get(peer_id)
            .ok_or_else(|| BypassError::MissingCredential(format!("peer key for {}", peer_id)))?;
        key.verify(message, signature)
            .map_err(|_| BypassError::InvalidSignature)
    }

    /// Verify a signature using IP address as peer identifier
    pub fn verify_by_ip(&self, ip: &IpAddr, message: &[u8], signature: &Signature) -> Result<()> {
        self.verify(&ip.to_string(), message, signature)
    }

    /// Encrypt payload
    pub fn encrypt(&self, plaintext: &[u8], nonce: &[u8; 12]) -> Result<Vec<u8>> {
        let key = self
            .encryption_key
            .as_ref()
            .ok_or_else(|| BypassError::MissingCredential("encryption key".into()))?;

        let cipher = ChaCha20Poly1305::new_from_slice(key)
            .map_err(|_| BypassError::Config("Invalid encryption key".into()))?;

        let nonce = Nonce::from_slice(nonce);
        cipher
            .encrypt(nonce, plaintext)
            .map_err(|_| BypassError::Encode("Encryption failed".into()))
    }

    /// Decrypt payload
    pub fn decrypt(&self, ciphertext: &[u8], nonce: &[u8; 12]) -> Result<Vec<u8>> {
        let key = self
            .encryption_key
            .as_ref()
            .ok_or_else(|| BypassError::MissingCredential("encryption key".into()))?;

        let cipher = ChaCha20Poly1305::new_from_slice(key)
            .map_err(|_| BypassError::Config("Invalid encryption key".into()))?;

        let nonce = Nonce::from_slice(nonce);
        cipher
            .decrypt(nonce, ciphertext)
            .map_err(|_| BypassError::DecryptionFailed)
    }
}

/// Replay protection tracker
///
/// Tracks seen sequence numbers per source to detect replay attacks.
/// Uses a sliding window to handle out-of-order delivery.
#[derive(Debug, Default)]
pub struct ReplayTracker {
    /// Seen sequences per source IP
    /// Each entry is a bitset representing seen sequences
    windows: RwLock<HashMap<IpAddr, ReplayWindow>>,

    /// Window size
    window_size: usize,
}

/// Sliding window for replay detection
#[derive(Debug)]
struct ReplayWindow {
    /// Highest sequence seen
    highest_seq: u8,
    /// Bitmap of seen sequences (relative to highest)
    seen: u64,
}

impl ReplayWindow {
    fn new() -> Self {
        Self {
            highest_seq: 0,
            seen: 0,
        }
    }

    /// Check if sequence is valid (not a replay)
    /// Returns true if valid, false if replay
    fn check_and_update(&mut self, seq: u8, window_size: usize) -> bool {
        let window_size = window_size.min(64) as u8;

        // Calculate distance from highest seen
        let diff = self.highest_seq.wrapping_sub(seq);

        if diff == 0 && self.seen == 0 {
            // First packet
            self.highest_seq = seq;
            self.seen = 1;
            return true;
        }

        if seq == self.highest_seq {
            // Exact replay of highest
            return false;
        }

        // Check if seq is ahead of highest
        let ahead = seq.wrapping_sub(self.highest_seq);
        if ahead > 0 && ahead < 128 {
            // New highest sequence
            let shift = ahead as u32;
            if shift < 64 {
                self.seen = (self.seen << shift) | 1;
            } else {
                self.seen = 1;
            }
            self.highest_seq = seq;
            return true;
        }

        // Check if seq is within window
        if diff < window_size && diff < 64 {
            let bit = 1u64 << diff;
            if self.seen & bit != 0 {
                // Already seen
                return false;
            }
            self.seen |= bit;
            return true;
        }

        // Too old
        false
    }
}

impl ReplayTracker {
    /// Create new replay tracker
    pub fn new(window_size: usize) -> Self {
        Self {
            windows: RwLock::new(HashMap::new()),
            window_size: window_size.min(64),
        }
    }

    /// Check if message is valid (not a replay)
    /// Returns Ok(()) if valid, Err if replay detected
    pub fn check(&self, source: &IpAddr, sequence: u8) -> Result<()> {
        let mut windows = self.windows.write().unwrap_or_else(|e| e.into_inner());
        let window = windows.entry(*source).or_insert_with(ReplayWindow::new);

        if window.check_and_update(sequence, self.window_size) {
            Ok(())
        } else {
            Err(BypassError::ReplayDetected { sequence })
        }
    }

    /// Clear tracking for a source
    pub fn clear_source(&self, source: &IpAddr) {
        self.windows
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .remove(source);
    }

    /// Clear all tracking
    pub fn clear_all(&self) {
        self.windows
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
    }
}

// =============================================================================
// Bypass Header (12 bytes)
// =============================================================================

/// Bypass message header
///
/// Compact 12-byte header for bypass messages:
/// - Magic: 4 bytes ("PEAT")
/// - Collection hash: 4 bytes (FNV-1a hash of collection name)
/// - TTL: 2 bytes (milliseconds, max ~65s)
/// - Flags: 1 byte
/// - Sequence: 1 byte (wrapping counter)
#[derive(Debug, Clone, Copy)]
pub struct BypassHeader {
    /// Magic number (0x50454154 = "PEAT")
    pub magic: [u8; 4],
    /// Collection name hash (FNV-1a)
    pub collection_hash: u32,
    /// TTL in milliseconds
    pub ttl_ms: u16,
    /// Flags
    pub flags: u8,
    /// Sequence number
    pub sequence: u8,
}

impl BypassHeader {
    /// Magic bytes: "PEAT"
    pub const MAGIC: [u8; 4] = [0x45, 0x43, 0x48, 0x45];

    /// Header size in bytes
    pub const SIZE: usize = 12;

    /// Flag: message is compressed
    pub const FLAG_COMPRESSED: u8 = 0x01;
    /// Flag: message is encrypted
    pub const FLAG_ENCRYPTED: u8 = 0x02;
    /// Flag: message is signed
    pub const FLAG_SIGNED: u8 = 0x04;

    /// Create a new header
    pub fn new(collection: &str, ttl: Duration, sequence: u8) -> Self {
        Self {
            magic: Self::MAGIC,
            collection_hash: Self::hash_collection(collection),
            ttl_ms: ttl.as_millis().min(u16::MAX as u128) as u16,
            flags: 0,
            sequence,
        }
    }

    /// Hash a collection name using FNV-1a
    pub fn hash_collection(name: &str) -> u32 {
        let mut hasher = fnv::FnvHasher::default();
        name.hash(&mut hasher);
        hasher.finish() as u32
    }

    /// Check if header has valid magic
    pub fn is_valid(&self) -> bool {
        self.magic == Self::MAGIC
    }

    /// Encode header to bytes
    pub fn encode(&self) -> [u8; Self::SIZE] {
        let mut buf = [0u8; Self::SIZE];
        buf[0..4].copy_from_slice(&self.magic);
        buf[4..8].copy_from_slice(&self.collection_hash.to_be_bytes());
        buf[8..10].copy_from_slice(&self.ttl_ms.to_be_bytes());
        buf[10] = self.flags;
        buf[11] = self.sequence;
        buf
    }

    /// Decode header from bytes
    pub fn decode(buf: &[u8]) -> Result<Self> {
        if buf.len() < Self::SIZE {
            return Err(BypassError::InvalidHeader);
        }

        let mut magic = [0u8; 4];
        magic.copy_from_slice(&buf[0..4]);

        if magic != Self::MAGIC {
            return Err(BypassError::InvalidHeader);
        }

        let collection_hash = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]);
        let ttl_ms = u16::from_be_bytes([buf[8], buf[9]]);
        let flags = buf[10];
        let sequence = buf[11];

        Ok(Self {
            magic,
            collection_hash,
            ttl_ms,
            flags,
            sequence,
        })
    }

    /// Check if message is stale based on TTL
    pub fn is_stale(&self, received_at: Instant, sent_at: Instant) -> bool {
        let elapsed = received_at.duration_since(sent_at);
        elapsed > Duration::from_millis(self.ttl_ms as u64)
    }
}

// =============================================================================
// FNV-1a Hasher (simple, fast hash for collection names)
// =============================================================================

mod fnv {
    use std::hash::Hasher;

    const FNV_OFFSET_BASIS: u64 = 14695981039346656037;
    const FNV_PRIME: u64 = 1099511628211;

    #[derive(Default)]
    pub struct FnvHasher(u64);

    impl Hasher for FnvHasher {
        fn write(&mut self, bytes: &[u8]) {
            for byte in bytes {
                self.0 ^= *byte as u64;
                self.0 = self.0.wrapping_mul(FNV_PRIME);
            }
        }

        fn finish(&self) -> u64 {
            self.0
        }
    }

    impl FnvHasher {
        pub fn default() -> Self {
            Self(FNV_OFFSET_BASIS)
        }
    }
}

// =============================================================================
// Bypass Message
// =============================================================================

/// Incoming bypass message
#[derive(Debug, Clone)]
pub struct BypassMessage {
    /// Source address
    pub source: SocketAddr,
    /// Collection hash (from header)
    pub collection_hash: u32,
    /// Message payload (decoded)
    pub data: Vec<u8>,
    /// When message was received
    pub received_at: Instant,
    /// Sequence number
    pub sequence: u8,
    /// Message priority (inferred from collection config)
    pub priority: MessagePriority,
}

/// Target for bypass send
#[derive(Debug, Clone)]
pub enum BypassTarget {
    /// Unicast to specific address
    Unicast(SocketAddr),
    /// Multicast to group
    Multicast { group: IpAddr, port: u16 },
    /// Broadcast on subnet
    Broadcast { port: u16 },
}

// =============================================================================
// Bypass Metrics
// =============================================================================

/// Metrics for bypass channel
#[derive(Debug, Default)]
pub struct BypassMetrics {
    /// Messages sent
    pub messages_sent: AtomicU64,
    /// Messages received
    pub messages_received: AtomicU64,
    /// Bytes sent
    pub bytes_sent: AtomicU64,
    /// Bytes received
    pub bytes_received: AtomicU64,
    /// Messages dropped (stale)
    pub stale_dropped: AtomicU64,
    /// Messages dropped (invalid header)
    pub invalid_dropped: AtomicU64,
    /// Send errors
    pub send_errors: AtomicU64,
    /// Receive errors
    pub receive_errors: AtomicU64,

    // Security metrics (ADR-042 Phase 5)
    /// Messages rejected due to invalid signature
    pub signature_rejected: AtomicU64,
    /// Messages rejected due to decryption failure
    pub decryption_failed: AtomicU64,
    /// Messages rejected due to unauthorized source
    pub unauthorized_source: AtomicU64,
    /// Messages rejected due to replay detection
    pub replay_rejected: AtomicU64,
}

impl BypassMetrics {
    /// Create snapshot of current metrics
    pub fn snapshot(&self) -> BypassMetricsSnapshot {
        BypassMetricsSnapshot {
            messages_sent: self.messages_sent.load(Ordering::Relaxed),
            messages_received: self.messages_received.load(Ordering::Relaxed),
            bytes_sent: self.bytes_sent.load(Ordering::Relaxed),
            bytes_received: self.bytes_received.load(Ordering::Relaxed),
            stale_dropped: self.stale_dropped.load(Ordering::Relaxed),
            invalid_dropped: self.invalid_dropped.load(Ordering::Relaxed),
            send_errors: self.send_errors.load(Ordering::Relaxed),
            receive_errors: self.receive_errors.load(Ordering::Relaxed),
            signature_rejected: self.signature_rejected.load(Ordering::Relaxed),
            decryption_failed: self.decryption_failed.load(Ordering::Relaxed),
            unauthorized_source: self.unauthorized_source.load(Ordering::Relaxed),
            replay_rejected: self.replay_rejected.load(Ordering::Relaxed),
        }
    }
}

/// Snapshot of bypass metrics
#[derive(Debug, Clone, Default)]
pub struct BypassMetricsSnapshot {
    pub messages_sent: u64,
    pub messages_received: u64,
    pub bytes_sent: u64,
    pub bytes_received: u64,
    pub stale_dropped: u64,
    pub invalid_dropped: u64,
    pub send_errors: u64,
    pub receive_errors: u64,

    // Security metrics (ADR-042 Phase 5)
    /// Messages rejected due to invalid signature
    pub signature_rejected: u64,
    /// Messages rejected due to decryption failure
    pub decryption_failed: u64,
    /// Messages rejected due to unauthorized source
    pub unauthorized_source: u64,
    /// Messages rejected due to replay detection
    pub replay_rejected: u64,
}

// =============================================================================
// UDP Bypass Channel
// =============================================================================

/// UDP Bypass Channel for ephemeral data
///
/// Provides direct UDP messaging that bypasses CRDT sync for
/// low-latency, high-frequency data.
pub struct UdpBypassChannel {
    /// Configuration
    config: BypassChannelConfig,

    /// UDP socket for unicast/broadcast
    socket: Option<Arc<UdpSocket>>,

    /// Multicast sockets per group
    multicast_sockets: RwLock<HashMap<IpAddr, Arc<UdpSocket>>>,

    /// Collection hash to config mapping
    collection_map: HashMap<u32, BypassCollectionConfig>,

    /// Sequence counter
    sequence: AtomicU8,

    /// Metrics
    metrics: Arc<BypassMetrics>,

    /// Broadcast sender for incoming messages
    incoming_tx: broadcast::Sender<BypassMessage>,

    /// Running flag
    running: Arc<AtomicBool>,
}

impl UdpBypassChannel {
    /// Create a new bypass channel
    pub async fn new(config: BypassChannelConfig) -> Result<Self> {
        // Build collection hash map
        let collection_map: HashMap<u32, BypassCollectionConfig> = config
            .collections
            .iter()
            .map(|c| (BypassHeader::hash_collection(&c.collection), c.clone()))
            .collect();

        let (incoming_tx, _) = broadcast::channel(1024);

        Ok(Self {
            config,
            socket: None,
            multicast_sockets: RwLock::new(HashMap::new()),
            collection_map,
            sequence: AtomicU8::new(0),
            metrics: Arc::new(BypassMetrics::default()),
            incoming_tx,
            running: Arc::new(AtomicBool::new(false)),
        })
    }

    /// Start the bypass channel
    pub async fn start(&mut self) -> Result<()> {
        if self.running.load(Ordering::SeqCst) {
            return Ok(());
        }

        // Bind UDP socket
        let bind_addr = format!("0.0.0.0:{}", self.config.udp.bind_port);
        let socket = UdpSocket::bind(&bind_addr).await?;
        socket.set_broadcast(true)?;

        let socket = Arc::new(socket);
        self.socket = Some(socket.clone());

        // Start receiver loop
        let incoming_tx = self.incoming_tx.clone();
        let metrics = self.metrics.clone();
        let collection_map = self.collection_map.clone();
        let buffer_size = self.config.udp.buffer_size;
        let running = self.running.clone();

        running.store(true, Ordering::SeqCst);

        tokio::spawn(async move {
            let mut buf = vec![0u8; buffer_size];

            while running.load(Ordering::SeqCst) {
                match tokio::time::timeout(Duration::from_millis(100), socket.recv_from(&mut buf))
                    .await
                {
                    Ok(Ok((len, src))) => {
                        let received_at = Instant::now();

                        // Parse header
                        if len < BypassHeader::SIZE {
                            metrics.invalid_dropped.fetch_add(1, Ordering::Relaxed);
                            continue;
                        }

                        let header = match BypassHeader::decode(&buf[..BypassHeader::SIZE]) {
                            Ok(h) => h,
                            Err(_) => {
                                metrics.invalid_dropped.fetch_add(1, Ordering::Relaxed);
                                continue;
                            }
                        };

                        // Extract payload
                        let payload = buf[BypassHeader::SIZE..len].to_vec();

                        // Look up collection config for priority
                        let priority = collection_map
                            .get(&header.collection_hash)
                            .map(|c| c.priority)
                            .unwrap_or(MessagePriority::Normal);

                        let message = BypassMessage {
                            source: src,
                            collection_hash: header.collection_hash,
                            data: payload,
                            received_at,
                            sequence: header.sequence,
                            priority,
                        };

                        metrics.messages_received.fetch_add(1, Ordering::Relaxed);
                        metrics
                            .bytes_received
                            .fetch_add(len as u64, Ordering::Relaxed);

                        // Broadcast to subscribers (ignore if no subscribers)
                        let _ = incoming_tx.send(message);
                    }
                    Ok(Err(_e)) => {
                        metrics.receive_errors.fetch_add(1, Ordering::Relaxed);
                    }
                    Err(_) => {
                        // Timeout, just continue
                    }
                }
            }
        });

        info!(
            "Bypass channel started on port {}",
            self.config.udp.bind_port
        );
        Ok(())
    }

    /// Stop the bypass channel
    pub fn stop(&mut self) {
        self.running.store(false, Ordering::SeqCst);
        self.socket = None;
        self.multicast_sockets
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
        info!("Bypass channel stopped");
    }

    /// Check if channel is running
    pub fn is_running(&self) -> bool {
        self.running.load(Ordering::SeqCst)
    }

    /// Get the next sequence number
    fn next_sequence(&self) -> u8 {
        self.sequence.fetch_add(1, Ordering::Relaxed)
    }

    /// Send a message via bypass channel
    pub async fn send(&self, target: BypassTarget, collection: &str, data: &[u8]) -> Result<()> {
        let socket = self.socket.as_ref().ok_or(BypassError::NotStarted)?;

        // Check message size (0 = unlimited)
        if self.config.max_message_size > 0 && data.len() > self.config.max_message_size {
            return Err(BypassError::MessageTooLarge {
                size: data.len(),
                max: self.config.max_message_size,
            });
        }

        // Get TTL from collection config or use default
        let ttl = self
            .config
            .get_collection(collection)
            .map(|c| c.ttl())
            .unwrap_or(Duration::from_secs(5));

        // Create header
        let header = BypassHeader::new(collection, ttl, self.next_sequence());
        let header_bytes = header.encode();

        // Build frame
        let mut frame = Vec::with_capacity(BypassHeader::SIZE + data.len());
        frame.extend_from_slice(&header_bytes);
        frame.extend_from_slice(data);

        // Send based on target
        let bytes_sent = match target {
            BypassTarget::Unicast(addr) => socket.send_to(&frame, addr).await?,
            BypassTarget::Multicast { group, port } => {
                let mcast_socket = self.get_or_create_multicast(group).await?;
                mcast_socket.send_to(&frame, (group, port)).await?
            }
            BypassTarget::Broadcast { port } => {
                let broadcast_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::BROADCAST), port);
                socket.send_to(&frame, broadcast_addr).await?
            }
        };

        self.metrics.messages_sent.fetch_add(1, Ordering::Relaxed);
        self.metrics
            .bytes_sent
            .fetch_add(bytes_sent as u64, Ordering::Relaxed);

        Ok(())
    }

    /// Send with collection config (uses config's transport settings)
    pub async fn send_to_collection(
        &self,
        collection: &str,
        target_addr: Option<SocketAddr>,
        data: &[u8],
    ) -> Result<()> {
        let config = self
            .config
            .get_collection(collection)
            .ok_or_else(|| BypassError::Config(format!("Unknown collection: {}", collection)))?;

        let target = match &config.transport {
            BypassTransport::Unicast => {
                let addr = target_addr.ok_or_else(|| {
                    BypassError::Config("Unicast requires target address".to_string())
                })?;
                BypassTarget::Unicast(addr)
            }
            BypassTransport::Multicast { group, port } => BypassTarget::Multicast {
                group: *group,
                port: *port,
            },
            BypassTransport::Broadcast => BypassTarget::Broadcast {
                port: self.config.udp.bind_port,
            },
        };

        self.send(target, collection, data).await
    }

    /// Subscribe to incoming bypass messages
    pub fn subscribe(&self) -> broadcast::Receiver<BypassMessage> {
        self.incoming_tx.subscribe()
    }

    /// Subscribe to messages for a specific collection
    pub fn subscribe_collection(
        &self,
        collection: &str,
    ) -> (u32, broadcast::Receiver<BypassMessage>) {
        let hash = BypassHeader::hash_collection(collection);
        (hash, self.incoming_tx.subscribe())
    }

    /// Get or create a multicast socket for a group
    async fn get_or_create_multicast(&self, group: IpAddr) -> Result<Arc<UdpSocket>> {
        // Check if already exists
        {
            let sockets = self
                .multicast_sockets
                .read()
                .unwrap_or_else(|e| e.into_inner());
            if let Some(socket) = sockets.get(&group) {
                return Ok(socket.clone());
            }
        }

        // Create new multicast socket
        let socket = UdpSocket::bind("0.0.0.0:0").await?;

        match group {
            IpAddr::V4(addr) => {
                socket.join_multicast_v4(addr, Ipv4Addr::UNSPECIFIED)?;
                socket.set_multicast_ttl_v4(self.config.udp.multicast_ttl)?;
            }
            IpAddr::V6(addr) => {
                socket.join_multicast_v6(&addr, 0)?;
            }
        }

        let socket = Arc::new(socket);
        self.multicast_sockets
            .write()
            .unwrap()
            .insert(group, socket.clone());

        debug!("Joined multicast group: {}", group);
        Ok(socket)
    }

    /// Leave a multicast group
    pub fn leave_multicast(&self, group: IpAddr) -> Result<()> {
        if let Some(socket) = self
            .multicast_sockets
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .remove(&group)
        {
            match group {
                IpAddr::V4(addr) => {
                    // Note: socket drop will leave the group, but explicit leave is cleaner
                    if let Ok(socket) = Arc::try_unwrap(socket) {
                        let _ = socket.leave_multicast_v4(addr, Ipv4Addr::UNSPECIFIED);
                    }
                }
                IpAddr::V6(addr) => {
                    if let Ok(socket) = Arc::try_unwrap(socket) {
                        let _ = socket.leave_multicast_v6(&addr, 0);
                    }
                }
            }
            debug!("Left multicast group: {}", group);
        }
        Ok(())
    }

    /// Get current metrics
    pub fn metrics(&self) -> BypassMetricsSnapshot {
        self.metrics.snapshot()
    }

    /// Get configuration
    pub fn config(&self) -> &BypassChannelConfig {
        &self.config
    }

    /// Check if a collection is configured for bypass
    pub fn is_bypass_collection(&self, name: &str) -> bool {
        self.config.is_bypass_collection(name)
    }

    /// Get collection config by hash
    pub fn get_collection_by_hash(&self, hash: u32) -> Option<&BypassCollectionConfig> {
        self.collection_map.get(&hash)
    }
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_bypass_header_encode_decode() {
        let header = BypassHeader::new("test_collection", Duration::from_millis(1000), 42);
        let encoded = header.encode();
        let decoded = BypassHeader::decode(&encoded).unwrap();

        assert_eq!(decoded.magic, BypassHeader::MAGIC);
        assert_eq!(decoded.collection_hash, header.collection_hash);
        assert_eq!(decoded.ttl_ms, 1000);
        assert_eq!(decoded.sequence, 42);
        assert!(decoded.is_valid());
    }

    #[test]
    fn test_bypass_header_invalid_magic() {
        let mut data = [0u8; 12];
        data[0..4].copy_from_slice(&[0, 0, 0, 0]);
        let result = BypassHeader::decode(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_bypass_header_too_short() {
        let data = [0u8; 8];
        let result = BypassHeader::decode(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_collection_hash_consistency() {
        let hash1 = BypassHeader::hash_collection("position_updates");
        let hash2 = BypassHeader::hash_collection("position_updates");
        let hash3 = BypassHeader::hash_collection("sensor_data");

        assert_eq!(hash1, hash2);
        assert_ne!(hash1, hash3);
    }

    #[test]
    fn test_bypass_config() {
        let config = BypassChannelConfig::new()
            .with_collection(BypassCollectionConfig {
                collection: "positions".into(),
                transport: BypassTransport::Multicast {
                    group: "239.1.1.100".parse().unwrap(),
                    port: 5150,
                },
                encoding: MessageEncoding::Protobuf,
                ttl_ms: 200,
                priority: MessagePriority::High,
            })
            .with_collection(BypassCollectionConfig {
                collection: "telemetry".into(),
                transport: BypassTransport::Unicast,
                encoding: MessageEncoding::Cbor,
                ttl_ms: 5000,
                priority: MessagePriority::Normal,
            });

        assert!(config.is_bypass_collection("positions"));
        assert!(config.is_bypass_collection("telemetry"));
        assert!(!config.is_bypass_collection("unknown"));

        let pos_config = config.get_collection("positions").unwrap();
        assert_eq!(pos_config.priority, MessagePriority::High);
    }

    #[test]
    fn test_ttl_clamping() {
        // TTL greater than u16::MAX should be clamped
        let header = BypassHeader::new("test", Duration::from_secs(1000), 0);
        assert_eq!(header.ttl_ms, u16::MAX);
    }

    #[tokio::test]
    async fn test_bypass_channel_creation() {
        let config = BypassChannelConfig::new().with_collection(BypassCollectionConfig {
            collection: "test".into(),
            ..Default::default()
        });

        let channel = UdpBypassChannel::new(config).await.unwrap();
        assert!(!channel.is_running());
        assert!(channel.is_bypass_collection("test"));
    }

    #[tokio::test]
    async fn test_bypass_channel_start_stop() {
        let config = BypassChannelConfig {
            udp: UdpConfig {
                bind_port: 0, // Ephemeral port
                ..Default::default()
            },
            ..Default::default()
        };

        let mut channel = UdpBypassChannel::new(config).await.unwrap();

        channel.start().await.unwrap();
        assert!(channel.is_running());

        channel.stop();
        assert!(!channel.is_running());
    }

    #[tokio::test]
    async fn test_bypass_send_receive() {
        // Create two channels on different ports
        let config1 = BypassChannelConfig {
            udp: UdpConfig {
                bind_port: 0,
                ..Default::default()
            },
            collections: vec![BypassCollectionConfig {
                collection: "test".into(),
                ttl_ms: 5000,
                ..Default::default()
            }],
            ..Default::default()
        };

        let config2 = BypassChannelConfig {
            udp: UdpConfig {
                bind_port: 0,
                ..Default::default()
            },
            collections: vec![BypassCollectionConfig {
                collection: "test".into(),
                ttl_ms: 5000,
                ..Default::default()
            }],
            ..Default::default()
        };

        let mut channel1 = UdpBypassChannel::new(config1).await.unwrap();
        let mut channel2 = UdpBypassChannel::new(config2).await.unwrap();

        channel1.start().await.unwrap();
        channel2.start().await.unwrap();

        // Get channel2's port and construct localhost address
        let socket2_port = channel2
            .socket
            .as_ref()
            .unwrap()
            .local_addr()
            .unwrap()
            .port();
        let socket2_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), socket2_port);

        // Subscribe to messages on channel2
        let mut rx = channel2.subscribe();

        // Send from channel1 to channel2
        let test_data = b"Hello, bypass!";
        channel1
            .send(BypassTarget::Unicast(socket2_addr), "test", test_data)
            .await
            .unwrap();

        // Receive on channel2
        let msg = tokio::time::timeout(Duration::from_millis(500), rx.recv())
            .await
            .expect("timeout")
            .expect("receive error");

        assert_eq!(msg.data, test_data);
        assert_eq!(msg.collection_hash, BypassHeader::hash_collection("test"));

        // Check metrics
        let metrics1 = channel1.metrics();
        assert_eq!(metrics1.messages_sent, 1);
        assert!(metrics1.bytes_sent > 0);

        let metrics2 = channel2.metrics();
        assert_eq!(metrics2.messages_received, 1);
        assert!(metrics2.bytes_received > 0);

        channel1.stop();
        channel2.stop();
    }

    #[test]
    fn test_message_too_large() {
        // This test doesn't need async since we're just testing the error condition
        let _config = BypassChannelConfig {
            max_message_size: 100,
            ..Default::default()
        };

        // Create error manually since we can't easily test async in sync context
        let err = BypassError::MessageTooLarge {
            size: 200,
            max: 100,
        };
        assert!(err.to_string().contains("200"));
        assert!(err.to_string().contains("100"));
    }

    // =========================================================================
    // Security Tests (ADR-042 Phase 5)
    // =========================================================================

    #[test]
    fn test_security_config_none() {
        let config = BypassSecurityConfig::none();
        assert!(!config.require_signature);
        assert!(!config.encrypt_payload);
        assert!(config.source_allowlist.is_none());
        assert!(!config.replay_protection);
        assert!(!config.is_enabled());
    }

    #[test]
    fn test_security_config_signed() {
        let config = BypassSecurityConfig::signed();
        assert!(config.require_signature);
        assert!(!config.encrypt_payload);
        assert!(config.is_enabled());
    }

    #[test]
    fn test_security_config_full() {
        let config = BypassSecurityConfig::full_security();
        assert!(config.require_signature);
        assert!(config.encrypt_payload);
        assert!(config.replay_protection);
        assert_eq!(config.replay_window_size, 64);
        assert!(config.is_enabled());
    }

    #[test]
    fn test_security_config_allowlist() {
        let ip1: IpAddr = "192.168.1.1".parse().unwrap();
        let ip2: IpAddr = "192.168.1.2".parse().unwrap();
        let ip3: IpAddr = "10.0.0.1".parse().unwrap();

        // No allowlist - all allowed
        let config = BypassSecurityConfig::none();
        assert!(config.is_source_allowed(&ip1));
        assert!(config.is_source_allowed(&ip2));
        assert!(config.is_source_allowed(&ip3));

        // With allowlist - only listed IPs allowed
        let config = BypassSecurityConfig {
            source_allowlist: Some(vec![ip1, ip2]),
            ..Default::default()
        };
        assert!(config.is_source_allowed(&ip1));
        assert!(config.is_source_allowed(&ip2));
        assert!(!config.is_source_allowed(&ip3));
    }

    #[test]
    fn test_credentials_signing() {
        use ed25519_dalek::SigningKey;

        // Use fixed seed for deterministic testing
        let seed: [u8; 32] = [1u8; 32];
        let signing_key = SigningKey::from_bytes(&seed);
        let verifying_key = signing_key.verifying_key();

        // Create credentials
        let peer_ip: IpAddr = "192.168.1.1".parse().unwrap();
        let creds = BypassSecurityCredentials::new()
            .with_signing_key(signing_key)
            .with_peer_key(peer_ip.to_string(), verifying_key);

        // Sign a message
        let message = b"test message for signing";
        let signature = creds.sign(message).expect("signing should succeed");

        // Verify the signature
        creds
            .verify_by_ip(&peer_ip, message, &signature)
            .expect("verification should succeed");
    }

    #[test]
    fn test_credentials_invalid_signature() {
        use ed25519_dalek::SigningKey;

        // Use different fixed seeds for two key pairs
        let seed1: [u8; 32] = [1u8; 32];
        let seed2: [u8; 32] = [2u8; 32];
        let signing_key1 = SigningKey::from_bytes(&seed1);
        let signing_key2 = SigningKey::from_bytes(&seed2);
        let verifying_key2 = signing_key2.verifying_key();

        // Create credentials with mismatched keys
        let peer_ip: IpAddr = "192.168.1.1".parse().unwrap();
        let creds = BypassSecurityCredentials::new()
            .with_signing_key(signing_key1)
            .with_peer_key(peer_ip.to_string(), verifying_key2);

        // Sign with key1
        let message = b"test message";
        let signature = creds.sign(message).expect("signing should succeed");

        // Verification with key2 should fail
        let result = creds.verify_by_ip(&peer_ip, message, &signature);
        assert!(matches!(result, Err(BypassError::InvalidSignature)));
    }

    #[test]
    fn test_credentials_encryption() {
        let encryption_key = [42u8; 32];
        let creds = BypassSecurityCredentials::new().with_encryption_key(encryption_key);

        let plaintext = b"secret message for encryption";
        let nonce = [0u8; 12];

        // Encrypt
        let ciphertext = creds
            .encrypt(plaintext, &nonce)
            .expect("encryption should succeed");
        assert_ne!(ciphertext.as_slice(), plaintext);
        // Ciphertext should be plaintext + 16 bytes (Poly1305 tag)
        assert_eq!(ciphertext.len(), plaintext.len() + 16);

        // Decrypt
        let decrypted = creds
            .decrypt(&ciphertext, &nonce)
            .expect("decryption should succeed");
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_credentials_decryption_wrong_key() {
        let key1 = [1u8; 32];
        let key2 = [2u8; 32];

        let creds1 = BypassSecurityCredentials::new().with_encryption_key(key1);
        let creds2 = BypassSecurityCredentials::new().with_encryption_key(key2);

        let plaintext = b"secret message";
        let nonce = [0u8; 12];

        // Encrypt with key1
        let ciphertext = creds1
            .encrypt(plaintext, &nonce)
            .expect("encryption should succeed");

        // Decrypt with key2 should fail
        let result = creds2.decrypt(&ciphertext, &nonce);
        assert!(matches!(result, Err(BypassError::DecryptionFailed)));
    }

    #[test]
    fn test_credentials_missing_signing_key() {
        let creds = BypassSecurityCredentials::new();
        let result = creds.sign(b"message");
        assert!(matches!(result, Err(BypassError::MissingCredential(_))));
    }

    #[test]
    fn test_credentials_missing_encryption_key() {
        let creds = BypassSecurityCredentials::new();
        let result = creds.encrypt(b"message", &[0u8; 12]);
        assert!(matches!(result, Err(BypassError::MissingCredential(_))));
    }

    #[test]
    fn test_replay_tracker_first_message() {
        let tracker = ReplayTracker::new(64);
        let source: IpAddr = "192.168.1.1".parse().unwrap();

        // First message should always succeed
        tracker
            .check(&source, 0)
            .expect("first message should succeed");
    }

    #[test]
    fn test_replay_tracker_sequential() {
        let tracker = ReplayTracker::new(64);
        let source: IpAddr = "192.168.1.1".parse().unwrap();

        // Sequential messages should all succeed
        for seq in 0..10u8 {
            tracker
                .check(&source, seq)
                .unwrap_or_else(|_| panic!("sequence {} should succeed", seq));
        }
    }

    #[test]
    fn test_replay_tracker_replay_detected() {
        let tracker = ReplayTracker::new(64);
        let source: IpAddr = "192.168.1.1".parse().unwrap();

        // First message succeeds
        tracker.check(&source, 5).expect("first should succeed");

        // Replay should be detected
        let result = tracker.check(&source, 5);
        assert!(matches!(
            result,
            Err(BypassError::ReplayDetected { sequence: 5 })
        ));
    }

    #[test]
    fn test_replay_tracker_out_of_order() {
        let tracker = ReplayTracker::new(64);
        let source: IpAddr = "192.168.1.1".parse().unwrap();

        // Messages can arrive out of order within window
        tracker.check(&source, 10).expect("10 should succeed");
        tracker
            .check(&source, 8)
            .expect("8 should succeed (within window)");
        tracker.check(&source, 12).expect("12 should succeed");
        tracker
            .check(&source, 9)
            .expect("9 should succeed (within window)");

        // But not replayed
        let result = tracker.check(&source, 8);
        assert!(matches!(
            result,
            Err(BypassError::ReplayDetected { sequence: 8 })
        ));
    }

    #[test]
    fn test_replay_tracker_multiple_sources() {
        let tracker = ReplayTracker::new(64);
        let source1: IpAddr = "192.168.1.1".parse().unwrap();
        let source2: IpAddr = "192.168.1.2".parse().unwrap();

        // Same sequence from different sources should both succeed
        tracker
            .check(&source1, 5)
            .expect("source1 seq 5 should succeed");
        tracker
            .check(&source2, 5)
            .expect("source2 seq 5 should succeed");

        // Replay from same source should fail
        let result = tracker.check(&source1, 5);
        assert!(matches!(result, Err(BypassError::ReplayDetected { .. })));

        // But different sequence should work
        tracker
            .check(&source1, 6)
            .expect("source1 seq 6 should succeed");
    }

    #[test]
    fn test_replay_tracker_window_advance() {
        let tracker = ReplayTracker::new(64);
        let source: IpAddr = "192.168.1.1".parse().unwrap();

        // Start with a sequence in the middle of the range
        tracker.check(&source, 100).expect("100 should succeed");
        tracker.check(&source, 110).expect("110 should succeed");
        tracker.check(&source, 120).expect("120 should succeed");

        // Much later sequence should succeed and advance the window
        tracker.check(&source, 200).expect("200 should succeed");

        // Sequence 100 is now outside the window (more than 64 behind)
        // But we already marked it, so this tests window advancement
        tracker.check(&source, 201).expect("201 should succeed");
    }

    #[test]
    fn test_replay_tracker_clear() {
        let tracker = ReplayTracker::new(64);
        let source: IpAddr = "192.168.1.1".parse().unwrap();

        tracker.check(&source, 5).expect("initial should succeed");

        // Clear and replay should now succeed
        tracker.clear_source(&source);
        tracker
            .check(&source, 5)
            .expect("after clear should succeed");
    }

    #[test]
    fn test_metrics_snapshot_includes_security() {
        let metrics = BypassMetrics::default();

        // Increment security metrics
        metrics.signature_rejected.fetch_add(1, Ordering::Relaxed);
        metrics.decryption_failed.fetch_add(2, Ordering::Relaxed);
        metrics.unauthorized_source.fetch_add(3, Ordering::Relaxed);
        metrics.replay_rejected.fetch_add(4, Ordering::Relaxed);

        // Snapshot should include them
        let snapshot = metrics.snapshot();
        assert_eq!(snapshot.signature_rejected, 1);
        assert_eq!(snapshot.decryption_failed, 2);
        assert_eq!(snapshot.unauthorized_source, 3);
        assert_eq!(snapshot.replay_rejected, 4);
    }

    #[test]
    fn test_bypass_error_display_all_variants() {
        let io_err = BypassError::Io(std::io::Error::new(std::io::ErrorKind::Other, "test io"));
        assert!(io_err.to_string().contains("IO error"));
        assert!(io_err.to_string().contains("test io"));

        let encode_err = BypassError::Encode("bad data".to_string());
        assert!(encode_err.to_string().contains("Encode error"));

        let decode_err = BypassError::Decode("corrupt".to_string());
        assert!(decode_err.to_string().contains("Decode error"));

        let config_err = BypassError::Config("bad config".to_string());
        assert!(config_err.to_string().contains("Config error"));

        let not_started = BypassError::NotStarted;
        assert!(not_started.to_string().contains("not started"));

        let invalid_header = BypassError::InvalidHeader;
        assert!(invalid_header.to_string().contains("Invalid bypass header"));

        let stale = BypassError::StaleMessage;
        assert!(stale.to_string().contains("stale"));

        let sig_err = BypassError::InvalidSignature;
        assert!(sig_err.to_string().contains("Invalid message signature"));

        let decrypt_err = BypassError::DecryptionFailed;
        assert!(decrypt_err.to_string().contains("decryption failed"));

        let unauth = BypassError::UnauthorizedSource("10.0.0.1".parse().unwrap());
        assert!(unauth.to_string().contains("10.0.0.1"));

        let replay = BypassError::ReplayDetected { sequence: 42 };
        assert!(replay.to_string().contains("42"));

        let missing = BypassError::MissingCredential("encryption key".to_string());
        assert!(missing.to_string().contains("encryption key"));
    }

    #[test]
    fn test_bypass_error_source() {
        let io_err = BypassError::Io(std::io::Error::new(std::io::ErrorKind::Other, "test"));
        assert!(std::error::Error::source(&io_err).is_some());

        let encode_err = BypassError::Encode("test".into());
        assert!(std::error::Error::source(&encode_err).is_none());

        let not_started = BypassError::NotStarted;
        assert!(std::error::Error::source(&not_started).is_none());
    }

    #[test]
    fn test_bypass_error_from_io() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
        let bypass_err: BypassError = io_err.into();
        assert!(bypass_err.to_string().contains("gone"));
    }

    #[test]
    fn test_message_encoding_display() {
        assert_eq!(MessageEncoding::Protobuf.to_string(), "protobuf");
        assert_eq!(MessageEncoding::Json.to_string(), "json");
        assert_eq!(MessageEncoding::Raw.to_string(), "raw");
        assert_eq!(MessageEncoding::Cbor.to_string(), "cbor");
    }

    #[test]
    fn test_bypass_collection_config_ttl() {
        let config = BypassCollectionConfig {
            ttl_ms: 200,
            ..Default::default()
        };
        assert_eq!(config.ttl(), Duration::from_millis(200));
    }

    #[test]
    fn test_bypass_collection_config_default() {
        let config = BypassCollectionConfig::default();
        assert!(config.collection.is_empty());
        assert_eq!(config.transport, BypassTransport::Unicast);
        assert_eq!(config.encoding, MessageEncoding::Protobuf);
        assert_eq!(config.ttl_ms, 5000);
        assert_eq!(config.priority, MessagePriority::Normal);
    }

    #[test]
    fn test_udp_config_default() {
        let config = UdpConfig::default();
        assert_eq!(config.bind_port, 5150);
        assert_eq!(config.buffer_size, 65536);
        assert_eq!(config.multicast_ttl, 32);
    }

    #[test]
    fn test_bypass_channel_config_default() {
        let config = BypassChannelConfig::default();
        assert!(config.collections.is_empty());
        assert!(!config.multicast_enabled);
        assert_eq!(config.max_message_size, 0);
    }

    #[test]
    fn test_bypass_channel_config_new() {
        let config = BypassChannelConfig::new();
        assert!(config.multicast_enabled);
        assert_eq!(config.max_message_size, 65000);
    }

    #[test]
    fn test_bypass_security_config_is_enabled_allowlist() {
        let config = BypassSecurityConfig {
            source_allowlist: Some(vec!["10.0.0.1".parse().unwrap()]),
            ..Default::default()
        };
        assert!(config.is_enabled());
    }

    #[test]
    fn test_bypass_security_config_is_enabled_replay() {
        let config = BypassSecurityConfig {
            replay_protection: true,
            ..Default::default()
        };
        assert!(config.is_enabled());
    }

    #[test]
    fn test_bypass_security_credentials_debug() {
        let creds = BypassSecurityCredentials::new();
        let debug = format!("{:?}", creds);
        assert!(debug.contains("has_signing_key"));
        assert!(debug.contains("false"));
        assert!(debug.contains("peer_keys_count"));
    }

    #[test]
    fn test_bypass_security_credentials_verifying_key() {
        // Without signing key
        let creds = BypassSecurityCredentials::new();
        assert!(creds.verifying_key().is_none());

        // With signing key
        let seed: [u8; 32] = [42u8; 32];
        let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed);
        let creds = BypassSecurityCredentials::new().with_signing_key(signing_key.clone());
        let vk = creds.verifying_key();
        assert!(vk.is_some());
        assert_eq!(vk.unwrap(), signing_key.verifying_key());
    }

    #[test]
    fn test_bypass_security_credentials_verify_unknown_peer() {
        let creds = BypassSecurityCredentials::new();
        let sig = ed25519_dalek::Signature::from_bytes(&[0u8; 64]);
        let result = creds.verify("unknown-peer", b"message", &sig);
        assert!(matches!(result, Err(BypassError::MissingCredential(_))));
    }

    #[test]
    fn test_bypass_security_credentials_decrypt_no_key() {
        let creds = BypassSecurityCredentials::new();
        let result = creds.decrypt(b"ciphertext", &[0u8; 12]);
        assert!(matches!(result, Err(BypassError::MissingCredential(_))));
    }

    #[test]
    fn test_replay_tracker_clear_all() {
        let tracker = ReplayTracker::new(64);
        let source1: IpAddr = "192.168.1.1".parse().unwrap();
        let source2: IpAddr = "192.168.1.2".parse().unwrap();

        tracker.check(&source1, 1).unwrap();
        tracker.check(&source2, 1).unwrap();

        tracker.clear_all();

        // After clear_all, same sequences should succeed
        tracker.check(&source1, 1).unwrap();
        tracker.check(&source2, 1).unwrap();
    }

    #[test]
    fn test_bypass_header_is_stale() {
        let header = BypassHeader::new("test", Duration::from_millis(100), 0);
        let now = Instant::now();

        // Not stale: sent_at = now, received_at = now
        assert!(!header.is_stale(now, now));

        // Stale: sent 1 second ago, TTL is 100ms
        let sent_at = now - Duration::from_secs(1);
        assert!(header.is_stale(now, sent_at));
    }

    #[test]
    fn test_bypass_metrics_snapshot_default() {
        let snapshot = BypassMetricsSnapshot::default();
        assert_eq!(snapshot.messages_sent, 0);
        assert_eq!(snapshot.messages_received, 0);
        assert_eq!(snapshot.bytes_sent, 0);
        assert_eq!(snapshot.bytes_received, 0);
        assert_eq!(snapshot.stale_dropped, 0);
        assert_eq!(snapshot.invalid_dropped, 0);
        assert_eq!(snapshot.send_errors, 0);
        assert_eq!(snapshot.receive_errors, 0);
    }

    #[tokio::test]
    async fn test_bypass_channel_subscribe_collection() {
        let config = BypassChannelConfig::new().with_collection(BypassCollectionConfig {
            collection: "positions".into(),
            ..Default::default()
        });

        let channel = UdpBypassChannel::new(config).await.unwrap();
        let (hash, _rx) = channel.subscribe_collection("positions");
        assert_eq!(hash, BypassHeader::hash_collection("positions"));
    }

    #[tokio::test]
    async fn test_bypass_channel_get_collection_by_hash() {
        let config = BypassChannelConfig::new().with_collection(BypassCollectionConfig {
            collection: "telemetry".into(),
            ttl_ms: 200,
            ..Default::default()
        });

        let channel = UdpBypassChannel::new(config).await.unwrap();
        let hash = BypassHeader::hash_collection("telemetry");
        let col_config = channel.get_collection_by_hash(hash);
        assert!(col_config.is_some());
        assert_eq!(col_config.unwrap().ttl_ms, 200);

        // Unknown hash
        assert!(channel.get_collection_by_hash(12345).is_none());
    }

    #[tokio::test]
    async fn test_bypass_channel_config_accessor() {
        let config = BypassChannelConfig {
            max_message_size: 1024,
            ..BypassChannelConfig::new()
        };
        let channel = UdpBypassChannel::new(config).await.unwrap();
        assert_eq!(channel.config().max_message_size, 1024);
    }

    #[tokio::test]
    async fn test_bypass_send_not_started() {
        let config = BypassChannelConfig::new();
        let channel = UdpBypassChannel::new(config).await.unwrap();

        let result = channel
            .send(
                BypassTarget::Unicast("127.0.0.1:5000".parse().unwrap()),
                "test",
                b"data",
            )
            .await;
        assert!(matches!(result, Err(BypassError::NotStarted)));
    }

    #[tokio::test]
    async fn test_bypass_send_message_too_large() {
        let config = BypassChannelConfig {
            max_message_size: 10,
            udp: UdpConfig {
                bind_port: 0,
                ..Default::default()
            },
            ..BypassChannelConfig::new()
        };
        let mut channel = UdpBypassChannel::new(config).await.unwrap();
        channel.start().await.unwrap();

        let big_data = vec![0u8; 100];
        let result = channel
            .send(
                BypassTarget::Unicast("127.0.0.1:5000".parse().unwrap()),
                "test",
                &big_data,
            )
            .await;
        assert!(matches!(
            result,
            Err(BypassError::MessageTooLarge { size: 100, max: 10 })
        ));

        channel.stop();
    }

    #[tokio::test]
    async fn test_bypass_send_to_collection_unknown() {
        let config = BypassChannelConfig {
            udp: UdpConfig {
                bind_port: 0,
                ..Default::default()
            },
            ..BypassChannelConfig::new()
        };
        let mut channel = UdpBypassChannel::new(config).await.unwrap();
        channel.start().await.unwrap();

        let result = channel.send_to_collection("unknown", None, b"data").await;
        assert!(matches!(result, Err(BypassError::Config(_))));

        channel.stop();
    }

    #[tokio::test]
    async fn test_bypass_send_to_collection_unicast_no_addr() {
        let config = BypassChannelConfig {
            udp: UdpConfig {
                bind_port: 0,
                ..Default::default()
            },
            collections: vec![BypassCollectionConfig {
                collection: "test".into(),
                transport: BypassTransport::Unicast,
                ..Default::default()
            }],
            ..BypassChannelConfig::new()
        };
        let mut channel = UdpBypassChannel::new(config).await.unwrap();
        channel.start().await.unwrap();

        // Unicast without target address should error
        let result = channel.send_to_collection("test", None, b"data").await;
        assert!(matches!(result, Err(BypassError::Config(_))));

        channel.stop();
    }

    #[tokio::test]
    async fn test_bypass_send_to_collection_broadcast() {
        let config = BypassChannelConfig {
            udp: UdpConfig {
                bind_port: 0,
                ..Default::default()
            },
            collections: vec![BypassCollectionConfig {
                collection: "bcast".into(),
                transport: BypassTransport::Broadcast,
                ..Default::default()
            }],
            ..BypassChannelConfig::new()
        };
        let mut channel = UdpBypassChannel::new(config).await.unwrap();
        channel.start().await.unwrap();

        // Broadcast should work without target address
        // Note: actual broadcast send may fail on some systems, but the path is exercised
        let _result = channel.send_to_collection("bcast", None, b"data").await;

        channel.stop();
    }

    #[tokio::test]
    async fn test_bypass_leave_multicast_no_socket() {
        let config = BypassChannelConfig::new();
        let channel = UdpBypassChannel::new(config).await.unwrap();

        // Leaving a group we never joined should be ok
        let result = channel.leave_multicast("239.1.1.1".parse().unwrap());
        assert!(result.is_ok());
    }

    #[test]
    fn test_bypass_transport_serde() {
        let unicast = BypassTransport::Unicast;
        let json = serde_json::to_string(&unicast).unwrap();
        let parsed: BypassTransport = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, BypassTransport::Unicast);

        let multicast = BypassTransport::Multicast {
            group: "239.1.1.100".parse().unwrap(),
            port: 5150,
        };
        let json = serde_json::to_string(&multicast).unwrap();
        let parsed: BypassTransport = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, multicast);
    }

    #[test]
    fn test_message_encoding_serde() {
        for encoding in &[
            MessageEncoding::Protobuf,
            MessageEncoding::Json,
            MessageEncoding::Raw,
            MessageEncoding::Cbor,
        ] {
            let json = serde_json::to_string(encoding).unwrap();
            let parsed: MessageEncoding = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, *encoding);
        }
    }

    #[test]
    fn test_bypass_header_flags() {
        let mut header = BypassHeader::new("test", Duration::from_millis(1000), 0);

        // No flags by default
        assert_eq!(header.flags, 0);
        assert_eq!(header.flags & BypassHeader::FLAG_SIGNED, 0);
        assert_eq!(header.flags & BypassHeader::FLAG_ENCRYPTED, 0);

        // Set signed flag
        header.flags |= BypassHeader::FLAG_SIGNED;
        assert_ne!(header.flags & BypassHeader::FLAG_SIGNED, 0);
        assert_eq!(header.flags & BypassHeader::FLAG_ENCRYPTED, 0);

        // Set encrypted flag
        header.flags |= BypassHeader::FLAG_ENCRYPTED;
        assert_ne!(header.flags & BypassHeader::FLAG_SIGNED, 0);
        assert_ne!(header.flags & BypassHeader::FLAG_ENCRYPTED, 0);

        // Encode/decode preserves flags
        let encoded = header.encode();
        let decoded = BypassHeader::decode(&encoded).unwrap();
        assert_eq!(decoded.flags, header.flags);
    }
}