crafter 0.3.0

Packet-level network interaction for Rust tools and agents.
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
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
//! OSPF (Open Shortest Path First) protocol support.
//!
//! This module provides wire-level OSPF: protocol-correct construction, decode,
//! and inspection of OSPF packets within the typed [`Packet`] abstraction. It
//! covers the full OSPFv2 (RFC 2328) packet set and an OSPFv3 (RFC 5340) base
//! layer:
//!
//! - [`Ospfv2`]: the OSPFv2 packet layer — the shared 24-octet common header
//!   (RFC 2328 §A.3.1) plus a typed [`OspfBody`] for the five packet types
//!   (Hello, Database Description, Link State Request, Link State Update, Link
//!   State Acknowledgment). It carries the standard link-state advertisements
//!   ([`OspfLsa`](crate::protocols::ospf::lsa::OspfLsa): Router, Network, Summary,
//!   AS-External, NSSA, and Opaque) and supports null, simple-password, and
//!   cryptographic (keyed-MD5 / HMAC-SHA) authentication.
//! - [`Ospfv3`]: the OSPFv3 base packet layer — the 16-octet common header
//!   (RFC 5340 §A.3.1) plus the v3 Hello and request/update/ack framing.
//!
//! OSPF runs directly over IP (protocol 89): OSPFv2 over IPv4 and OSPFv3 over
//! IPv6 (next header 89). `compile()` writes each header, appends the body, and
//! auto-fills the Packet Length, the common-header Checksum, the per-LSA length,
//! and the Fletcher-16 LSA checksum unless the caller pinned them — so a packet
//! built with the crate is protocol-correct by default while deliberately
//! malformed values survive untouched. Decoding through the protocol registry
//! recognizes OSPF from IPv4/IPv6 and preserves unknown packet, LSA, and opaque
//! types verbatim so they round-trip byte-for-byte. The curated exports include
//! the deprecated neutral `Ospf` alias for the OSPFv2 layer.
//!
//! This is a wire primitive, not a router: there is no neighbor/adjacency state
//! machine, SPF/Dijkstra computation, link-state database, flooding, or
//! routing-table construction. The module builds and decodes packets; protocol
//! behavior is left to generated tools that build on it.
//!
//! The example below builds an OSPFv2 Hello over IPv4, compiles it, decodes it
//! back through the default registry, and confirms the typed [`Ospfv2`] layer is
//! present and the bytes round-trip exactly. It uses documentation address space
//! (RFC 5737) and the OSPF AllSPFRouters multicast group.
//!
//! ```rust
//! use crafter::prelude::*;
//! use std::net::Ipv4Addr;
//!
//! # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
//! // OSPFv2 Hello (RFC 2328 §A.3.2) over IPv4, addressed to AllSPFRouters.
//! let packet = Ipv4::new()
//!     .src(Ipv4Addr::new(192, 0, 2, 1))
//!     .dst(Ipv4Addr::new(224, 0, 0, 5))
//!     / Ospfv2::hello()
//!         .router_id(Ipv4Addr::new(192, 0, 2, 1))
//!         .area_id(Ipv4Addr::new(0, 0, 0, 0))
//!         .with_hello(|hello| {
//!             *hello = hello
//!                 .clone()
//!                 .network_mask(Ipv4Addr::new(255, 255, 255, 0))
//!                 .hello_interval(10)
//!                 .router_dead_interval(40);
//!         });
//!
//! // `compile()` fills the OSPF Packet Length and Checksum (and the IPv4 header).
//! let compiled = packet.compile()?;
//! println!("{}", packet.summary());
//!
//! // Decode the IPv4 payload back through the default registry (protocol 89).
//! let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes())?;
//! let ospf = decoded.layer::<Ospfv2>().expect("typed OSPFv2 layer present");
//! assert_eq!(ospf.packet_type_value(), OSPF_TYPE_HELLO);
//! assert_eq!(ospf.router_id_value(), Ipv4Addr::new(192, 0, 2, 1));
//!
//! // A decoded OSPF packet recompiles byte-for-byte.
//! let recompiled = decoded.compile()?;
//! assert_eq!(recompiled.as_bytes(), compiled.as_bytes());
//! # Ok(())
//! # }
//! ```
//!
//! The OSPFv3 base layer follows the same shape over IPv6:
//!
//! ```rust
//! use crafter::prelude::*;
//! use std::net::{Ipv4Addr, Ipv6Addr};
//!
//! # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
//! // OSPFv3 Hello (RFC 5340 §A.3.2) over IPv6, addressed to AllSPFRouters.
//! let packet = Ipv6::new()
//!     .src("2001:db8::1".parse::<Ipv6Addr>()?)
//!     .dst("ff02::5".parse::<Ipv6Addr>()?)
//!     / Ospfv3::hello().router_id(Ipv4Addr::new(192, 0, 2, 1));
//!
//! let compiled = packet.compile()?;
//! let decoded = Packet::decode_from_l3(NetworkLayer::Ipv6, compiled.as_bytes())?;
//! assert!(decoded.layer::<Ospfv3>().is_some());
//! assert_eq!(decoded.compile()?.as_bytes(), compiled.as_bytes());
//! # Ok(())
//! # }
//! ```

use core::any::Any;
use core::net::Ipv4Addr;
use core::ops::Div;

use crate::checksum::internet_checksum_chunks;
use crate::field::Field;
use crate::packet::{IntoPacket, Layer, LayerContext, Packet};
use crate::Result;

pub mod auth;

#[allow(unused_imports)]
pub mod constants;

pub(crate) mod decode;

pub mod lsa;

pub mod packet;

pub mod v3;

#[allow(unused_imports)]
pub use auth::{
    OspfCryptoAlgorithm, OspfCryptoAuth, OSPF_HMAC_SHA1_DIGEST_LEN, OSPF_HMAC_SHA256_DIGEST_LEN,
    OSPF_HMAC_SHA384_DIGEST_LEN, OSPF_HMAC_SHA512_DIGEST_LEN, OSPF_MD5_DIGEST_LEN,
};
#[allow(unused_imports)]
pub use constants::*;
pub use packet::{
    OspfDatabaseDescription, OspfHello, OspfLinkStateAck, OspfLinkStateRequest,
    OspfLinkStateRequestEntry, OspfLinkStateUpdate,
};
pub use v3::{
    Ospfv3, Ospfv3Body, Ospfv3DatabaseDescription, Ospfv3Hello, Ospfv3LinkStateAck,
    Ospfv3LinkStateRequest, Ospfv3LinkStateRequestEntry, Ospfv3LinkStateUpdate, Ospfv3Lsa,
    Ospfv3LsaBody, Ospfv3LsaHeader, Ospfv3NetworkLsa, Ospfv3RouterInterface, Ospfv3RouterLsa,
    OSPFV3_DD_FLAG_I, OSPFV3_DD_FLAG_M, OSPFV3_DD_FLAG_MS, OSPFV3_HEADER_LEN,
    OSPFV3_LSA_HEADER_LEN, OSPFV3_TYPE_DATABASE_DESCRIPTION, OSPFV3_TYPE_HELLO,
    OSPFV3_TYPE_LINK_STATE_ACK, OSPFV3_TYPE_LINK_STATE_REQUEST, OSPFV3_TYPE_LINK_STATE_UPDATE,
    OSPF_VERSION_3,
};

macro_rules! impl_layer_object {
    ($type:ty) => {
        fn clone_layer(&self) -> Box<dyn Layer> {
            Box::new(self.clone())
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn as_any_mut(&mut self) -> &mut dyn Any {
            self
        }

        fn into_any(self: Box<Self>) -> Box<dyn Any> {
            self
        }
    };
}

macro_rules! impl_layer_div {
    ($type:ty) => {
        impl<R> Div<R> for $type
        where
            R: IntoPacket,
        {
            type Output = Packet;

            fn div(self, rhs: R) -> Self::Output {
                Packet::from_layer(self).concat(rhs)
            }
        }
    };
}

/// Decode-time validation status for the OSPF common-header checksum.
///
/// Set during decode and gated by
/// [`ProtocolRegistry::validates_checksums`](crate::ProtocolRegistry); mirrors
/// [`Ipv4ChecksumStatus`](crate::Ipv4ChecksumStatus) and
/// [`UdpChecksumStatus`](crate::UdpChecksumStatus). The OSPF checksum is the
/// standard Internet checksum over the whole OSPF packet excluding the 8-octet
/// authentication field, and is zero for cryptographic authentication
/// (AuType 2, [`OSPF_AUTYPE_CRYPTOGRAPHIC`]); cryptographic-auth packets are
/// therefore reported as [`OspfChecksumStatus::NotChecked`] rather than checked.
///
/// This is decode metadata only: it never affects compiled bytes,
/// `clone_layer`, or round-trip equality.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OspfChecksumStatus {
    /// The decoded OSPF checksum validates.
    Valid,
    /// The decoded OSPF checksum failed validation.
    Invalid,
    /// Checksum validation was not attempted (validation disabled or the packet
    /// uses cryptographic authentication, where the checksum field is zero).
    NotChecked,
}

/// The body of an OSPFv2 packet (RFC 2328 §A.3), following the shared 24-octet
/// common header.
///
/// This block models the typed [`OspfBody::Hello`] body (RFC 2328 §A.3.2), the
/// [`OspfBody::DatabaseDescription`] body (RFC 2328 §A.3.3), the
/// [`OspfBody::LinkStateRequest`] body (RFC 2328 §A.3.4), the
/// [`OspfBody::LinkStateUpdate`] body (RFC 2328 §A.3.5), the
/// [`OspfBody::LinkStateAck`] body (RFC 2328 §A.3.6), and the
/// [`OspfBody::Unknown`] variant, which preserves the raw body bytes of a
/// packet type the builder/decoder does not (yet) model so the bytes round-trip
/// verbatim.
#[derive(Debug, Clone)]
pub enum OspfBody {
    /// The OSPFv2 Hello packet body (RFC 2328 §A.3.2).
    Hello(OspfHello),
    /// The OSPFv2 Database Description packet body (RFC 2328 §A.3.3).
    DatabaseDescription(OspfDatabaseDescription),
    /// The OSPFv2 Link State Request packet body (RFC 2328 §A.3.4).
    LinkStateRequest(OspfLinkStateRequest),
    /// The OSPFv2 Link State Update packet body (RFC 2328 §A.3.5).
    LinkStateUpdate(OspfLinkStateUpdate),
    /// The OSPFv2 Link State Acknowledgment packet body (RFC 2328 §A.3.6).
    LinkStateAck(OspfLinkStateAck),
    /// A packet body the layer does not (yet) model, preserved verbatim.
    Unknown {
        /// The OSPF packet Type code this body belongs to.
        type_code: u8,
        /// The raw body bytes following the 24-octet common header.
        body: Vec<u8>,
    },
}

impl OspfBody {
    /// The on-wire length of this body, in octets (the bytes after the header).
    fn encoded_len(&self) -> usize {
        match self {
            OspfBody::Hello(hello) => hello.encoded_len(),
            OspfBody::DatabaseDescription(dd) => dd.encoded_len(),
            OspfBody::LinkStateRequest(lsr) => lsr.encoded_len(),
            OspfBody::LinkStateUpdate(lsu) => lsu.encoded_len(),
            OspfBody::LinkStateAck(ack) => ack.encoded_len(),
            OspfBody::Unknown { body, .. } => body.len(),
        }
    }

    /// Append this body's bytes to `out`.
    fn encode(&self, out: &mut Vec<u8>) {
        match self {
            OspfBody::Hello(hello) => hello.encode(out),
            OspfBody::DatabaseDescription(dd) => dd.encode(out),
            OspfBody::LinkStateRequest(lsr) => lsr.encode(out),
            OspfBody::LinkStateUpdate(lsu) => lsu.encode(out),
            OspfBody::LinkStateAck(ack) => ack.encode(out),
            OspfBody::Unknown { body, .. } => out.extend_from_slice(body),
        }
    }

    /// The OSPF packet Type code this body carries.
    fn type_code(&self) -> u8 {
        match self {
            OspfBody::Hello(_) => OSPF_TYPE_HELLO,
            OspfBody::DatabaseDescription(_) => OSPF_TYPE_DATABASE_DESCRIPTION,
            OspfBody::LinkStateRequest(_) => OSPF_TYPE_LINK_STATE_REQUEST,
            OspfBody::LinkStateUpdate(_) => OSPF_TYPE_LINK_STATE_UPDATE,
            OspfBody::LinkStateAck(_) => OSPF_TYPE_LINK_STATE_ACK,
            OspfBody::Unknown { type_code, .. } => *type_code,
        }
    }

    /// Track the OSPF packet Type code on the body so the header and body agree
    /// by default.
    ///
    /// The typed bodies own their packet type (Hello, Database Description, Link
    /// State Request, Link State Acknowledgment) and so ignore type-code changes;
    /// only the opaque [`OspfBody::Unknown`] body tracks the header's type.
    fn set_type_code(&mut self, type_code: u8) {
        match self {
            OspfBody::Hello(_) => {}
            OspfBody::DatabaseDescription(_) => {}
            OspfBody::LinkStateRequest(_) => {}
            OspfBody::LinkStateUpdate(_) => {}
            OspfBody::LinkStateAck(_) => {}
            OspfBody::Unknown { type_code: tc, .. } => *tc = type_code,
        }
    }
}

/// OSPFv2 packet layer (RFC 2328).
///
/// An `Ospfv2` layer is the shared 24-octet common header (Version, Type, Packet
/// Length, Router ID, Area ID, Checksum, AuType, Authentication) followed by a
/// typed [`OspfBody`]. `compile()` writes the header — auto-filling the Packet
/// Length from the total OSPF byte count and the Checksum (the standard Internet
/// checksum over the whole packet excluding the 8-octet authentication field)
/// unless the caller pinned them — then the body bytes.
///
/// Per the repo's version-suffix naming convention the layer is named `Ospfv2`;
/// the deprecated neutral `Ospf` alias is added in a later step.
#[derive(Debug, Clone)]
pub struct Ospfv2 {
    /// OSPF version (RFC 2328 §A.3.1); defaults to [`OSPF_VERSION_2`].
    version: Field<u8>,
    /// OSPF packet Type code (RFC 2328 §A.3.1).
    packet_type: Field<u8>,
    /// Packet Length, in octets, of the OSPF packet (RFC 2328 §A.3.1).
    packet_length: Field<u16>,
    /// Router ID of the originating router (RFC 2328 §A.3.1).
    router_id: Field<Ipv4Addr>,
    /// Area ID this packet belongs to (RFC 2328 §A.3.1).
    area_id: Field<Ipv4Addr>,
    /// Standard Internet checksum over the packet excluding the auth field.
    checksum: Field<u16>,
    /// Authentication type (RFC 2328 §A.3.1); defaults to [`OSPF_AUTYPE_NULL`].
    autype: Field<u16>,
    /// 8-octet authentication field (RFC 2328 §A.3.1); defaults to all zeros.
    authentication: Field<[u8; OSPF_AUTH_LEN]>,
    /// Decode-time checksum validation status. This is metadata only: it is not
    /// serialized, does not affect compiled bytes, and defaults to
    /// [`OspfChecksumStatus::NotChecked`] on builder-constructed packets.
    checksum_status: OspfChecksumStatus,
    /// Cryptographic-authentication parameters (AuType 2, keyed-MD5, RFC 2328
    /// §D.3) installed by [`Ospfv2::crypto_md5_auth`]. This is `compile()`
    /// metadata: when present (and the AuType is cryptographic) it drives the
    /// appended message-digest trailer; the secret key it holds never appears on
    /// the wire. `None` for null and simple-password authentication.
    crypto_auth: Option<OspfCryptoAuth>,
    /// The appended cryptographic-authentication message-digest trailer recovered
    /// on decode (AuType 2, RFC 2328 §D.3). The OSPF Packet Length covers only the
    /// header and body, so the trailing `available - packet_length` octets of a
    /// cryptographically authenticated packet are this digest trailer, captured
    /// here so the packet re-compiles byte-for-byte even though the decoder does
    /// not hold the secret key. This is `compile()` metadata: when no recorded
    /// [`crypto_auth`](Ospfv2::crypto_auth) parameters are present to recompute a
    /// digest, a non-empty trailer is re-emitted verbatim after the body. Empty
    /// for builder-constructed packets and for non-cryptographic authentication.
    auth_trailer: Vec<u8>,
    /// The typed packet body following the common header.
    body: OspfBody,
}

impl Ospfv2 {
    /// Build a new OSPFv2 packet with default common-header values and an empty
    /// opaque body.
    ///
    /// Version defaults to [`OSPF_VERSION_2`], AuType to [`OSPF_AUTYPE_NULL`],
    /// and the authentication field to all zeros. The Packet Length and Checksum
    /// are left unset so `compile()` fills them. The body defaults to an empty
    /// [`OspfBody::Unknown`] with a zero type code; set the packet type with
    /// [`Ospfv2::packet_type`] and the body with [`Ospfv2::raw_body`].
    pub fn new() -> Self {
        Self {
            version: Field::defaulted(OSPF_VERSION_2),
            packet_type: Field::unset(),
            packet_length: Field::unset(),
            router_id: Field::unset(),
            area_id: Field::unset(),
            checksum: Field::unset(),
            autype: Field::defaulted(OSPF_AUTYPE_NULL),
            authentication: Field::defaulted([0; OSPF_AUTH_LEN]),
            checksum_status: OspfChecksumStatus::NotChecked,
            crypto_auth: None,
            auth_trailer: Vec::new(),
            body: OspfBody::Unknown {
                type_code: 0,
                body: Vec::new(),
            },
        }
    }

    /// Force the OSPF Version field.
    pub fn version(mut self, version: u8) -> Self {
        self.version.set_user(version);
        self
    }

    /// Set the OSPF packet Type code (RFC 2328 §A.3.1).
    ///
    /// The opaque body's type code tracks this value so the body and header
    /// agree by default.
    pub fn packet_type(mut self, packet_type: u8) -> Self {
        self.packet_type.set_user(packet_type);
        self.body.set_type_code(packet_type);
        self
    }

    /// Force the OSPF Packet Length field.
    ///
    /// This preserves malformed-on-purpose packets whose declared length differs
    /// from the emitted byte count.
    pub fn packet_length(mut self, packet_length: u16) -> Self {
        self.packet_length.set_user(packet_length);
        self
    }

    /// Set the originating Router ID field.
    pub fn router_id(mut self, router_id: impl Into<Ipv4Addr>) -> Self {
        self.router_id.set_user(router_id.into());
        self
    }

    /// Set the Area ID field.
    pub fn area_id(mut self, area_id: impl Into<Ipv4Addr>) -> Self {
        self.area_id.set_user(area_id.into());
        self
    }

    /// Force the OSPF Checksum field.
    ///
    /// This preserves malformed-on-purpose packets whose checksum is not the
    /// computed Internet checksum.
    pub fn checksum(mut self, checksum: u16) -> Self {
        self.checksum.set_user(checksum);
        self
    }

    /// Set the Authentication Type (AuType) field (RFC 2328 §A.3.1).
    pub fn autype(mut self, autype: u16) -> Self {
        self.autype.set_user(autype);
        self
    }

    /// Set the 8-octet Authentication field (RFC 2328 §A.3.1).
    pub fn authentication(mut self, authentication: [u8; OSPF_AUTH_LEN]) -> Self {
        self.authentication.set_user(authentication);
        self
    }

    /// Configure null authentication (AuType 0, RFC 2328 §D.1).
    ///
    /// Sets the AuType field to [`OSPF_AUTYPE_NULL`] and the 8-octet
    /// authentication field to all zeros. The standard Internet checksum (which
    /// excludes the authentication field) still protects the packet. This is an
    /// ergonomic shorthand over [`Ospfv2::autype`] / [`Ospfv2::authentication`].
    pub fn null_auth(mut self) -> Self {
        self.autype.set_user(OSPF_AUTYPE_NULL);
        self.authentication.set_user([0; OSPF_AUTH_LEN]);
        self
    }

    /// Configure simple-password authentication (AuType 1, RFC 2328 §D.2).
    ///
    /// Sets the AuType field to [`OSPF_AUTYPE_SIMPLE`] and copies up to 8 octets
    /// of the cleartext `password` into the 8-octet authentication field,
    /// right-padded with zeros. A password longer than 8 octets is truncated to
    /// its first 8 octets — the only 8 the field can carry. The checksum
    /// auto-fill excludes the authentication field, so setting a password never
    /// changes the computed checksum. Use [`Ospfv2::authentication`] directly to
    /// pin a deliberately malformed 8-octet authentication value.
    pub fn simple_password(mut self, password: &[u8]) -> Self {
        self.autype.set_user(OSPF_AUTYPE_SIMPLE);
        self.authentication
            .set_user(auth::simple_password_field(password));
        self
    }

    /// Configure cryptographic authentication (AuType 2) with a chosen digest
    /// `algorithm` — keyed-MD5 (RFC 2328 §D.3) or an HMAC-SHA variant (RFC 5709).
    ///
    /// Sets the AuType field to [`OSPF_AUTYPE_CRYPTOGRAPHIC`], encodes the
    /// structured 8-octet authentication field — Reserved (2 octets, zero),
    /// Key ID, Authentication Data Length (the algorithm's digest size: 16 for
    /// keyed-MD5, 20/32/48/64 for HMAC-SHA-1/256/384/512), and the Cryptographic
    /// sequence number — and records the secret `key` so `compile()` can append
    /// the message-digest trailer. For keyed-MD5 the trailer is
    /// `MD5(ospf_packet_with_structured_auth || key_padded_to_16)` (RFC 1321);
    /// for the HMAC-SHA variants it is `HMAC(key, ospf_packet_with_structured_auth)`
    /// (RFC 5709 §3.3).
    ///
    /// For cryptographic authentication `compile()` writes the header Checksum as
    /// zero (RFC 2328 §D.3), the OSPF Packet Length covers only the header and
    /// body (the digest trailer is excluded but is still part of the IP payload),
    /// and the digest is appended after the packet bytes. The secret key never
    /// appears on the wire — only the digest derived from it does.
    ///
    /// Caller overrides are honored: pin the [`authentication`](Ospfv2::authentication)
    /// field to install a deliberately malformed structured auth field, or pin the
    /// [`checksum`](Ospfv2::checksum) to override the zero checksum; the recorded
    /// key still drives the appended trailer.
    pub fn crypto_auth(
        mut self,
        algorithm: OspfCryptoAlgorithm,
        key_id: u8,
        sequence_number: u32,
        key: impl Into<Vec<u8>>,
    ) -> Self {
        let crypto = OspfCryptoAuth::with_algorithm(algorithm, key_id, sequence_number, key);
        self.autype.set_user(OSPF_AUTYPE_CRYPTOGRAPHIC);
        self.authentication.set_user(crypto.structured_auth_field());
        self.crypto_auth = Some(crypto);
        self
    }

    /// Configure cryptographic (keyed-MD5) authentication (AuType 2, RFC 2328
    /// §D.3).
    ///
    /// A thin wrapper over [`Ospfv2::crypto_auth`] fixing the algorithm to
    /// [`OspfCryptoAlgorithm::KeyedMd5`]: the structured authentication field's
    /// Authentication Data Length is 16 (the MD5 digest length) and the appended
    /// trailer is `MD5(ospf_packet_with_structured_auth || key_padded_to_16)`
    /// (RFC 1321). See [`Ospfv2::crypto_auth`] for the checksum, Packet Length,
    /// and override semantics.
    pub fn crypto_md5_auth(
        self,
        key_id: u8,
        sequence_number: u32,
        key: impl Into<Vec<u8>>,
    ) -> Self {
        self.crypto_auth(OspfCryptoAlgorithm::KeyedMd5, key_id, sequence_number, key)
    }

    /// Replace the opaque body bytes that follow the common header.
    ///
    /// The body's stored type code tracks the current packet type so the header
    /// and body agree by default.
    pub fn raw_body(mut self, body: impl Into<Vec<u8>>) -> Self {
        let type_code = self.packet_type.value().copied().unwrap_or(0);
        self.body = OspfBody::Unknown {
            type_code,
            body: body.into(),
        };
        self
    }

    /// Build an OSPFv2 Hello packet (RFC 2328 §A.3.2).
    ///
    /// Sets the packet Type to [`OSPF_TYPE_HELLO`] and installs a default
    /// [`OspfHello`] body. Set the Hello fields fluently with
    /// [`Ospfv2::with_hello`] or replace the whole body with
    /// [`Ospfv2::hello_body`].
    pub fn hello() -> Self {
        Self::new()
            .packet_type(OSPF_TYPE_HELLO)
            .hello_body(OspfHello::new())
    }

    /// Replace the packet body with the given [`OspfHello`] body and set the
    /// packet Type to [`OSPF_TYPE_HELLO`].
    pub fn hello_body(mut self, hello: OspfHello) -> Self {
        self.packet_type.set_user(OSPF_TYPE_HELLO);
        self.body = OspfBody::Hello(hello);
        self
    }

    /// Mutate the Hello body in place through a closure, returning `self` for
    /// fluent chaining (e.g. `Ospfv2::hello().with_hello(|h| ...)`).
    ///
    /// If the current body is not a Hello it is replaced with a default one
    /// (and the packet Type set to [`OSPF_TYPE_HELLO`]) before the closure runs,
    /// so the accessor always yields a Hello body to configure.
    pub fn with_hello(mut self, configure: impl FnOnce(&mut OspfHello)) -> Self {
        configure(self.hello_mut());
        self
    }

    /// Borrow the Hello body mutably, installing a default Hello body (and
    /// setting the packet Type to [`OSPF_TYPE_HELLO`]) when the current body is
    /// not already a Hello.
    pub fn hello_mut(&mut self) -> &mut OspfHello {
        if !matches!(self.body, OspfBody::Hello(_)) {
            self.packet_type.set_user(OSPF_TYPE_HELLO);
            self.body = OspfBody::Hello(OspfHello::new());
        }
        match &mut self.body {
            OspfBody::Hello(hello) => hello,
            // Unreachable: the body was just normalized to a Hello above.
            _ => unreachable!("hello body installed above"),
        }
    }

    /// Build an OSPFv2 Database Description packet (RFC 2328 §A.3.3).
    ///
    /// Sets the packet Type to [`OSPF_TYPE_DATABASE_DESCRIPTION`] and installs a
    /// default [`OspfDatabaseDescription`] body. Set the DD fields fluently with
    /// [`Ospfv2::with_database_description`] or replace the whole body with
    /// [`Ospfv2::database_description_body`].
    pub fn database_description() -> Self {
        Self::new()
            .packet_type(OSPF_TYPE_DATABASE_DESCRIPTION)
            .database_description_body(OspfDatabaseDescription::new())
    }

    /// Replace the packet body with the given [`OspfDatabaseDescription`] body
    /// and set the packet Type to [`OSPF_TYPE_DATABASE_DESCRIPTION`].
    pub fn database_description_body(mut self, dd: OspfDatabaseDescription) -> Self {
        self.packet_type.set_user(OSPF_TYPE_DATABASE_DESCRIPTION);
        self.body = OspfBody::DatabaseDescription(dd);
        self
    }

    /// Mutate the Database Description body in place through a closure, returning
    /// `self` for fluent chaining (e.g.
    /// `Ospfv2::database_description().with_database_description(|d| ...)`).
    ///
    /// If the current body is not a Database Description it is replaced with a
    /// default one (and the packet Type set to
    /// [`OSPF_TYPE_DATABASE_DESCRIPTION`]) before the closure runs, so the
    /// accessor always yields a Database Description body to configure.
    pub fn with_database_description(
        mut self,
        configure: impl FnOnce(&mut OspfDatabaseDescription),
    ) -> Self {
        configure(self.database_description_mut());
        self
    }

    /// Borrow the Database Description body mutably, installing a default
    /// Database Description body (and setting the packet Type to
    /// [`OSPF_TYPE_DATABASE_DESCRIPTION`]) when the current body is not already
    /// a Database Description.
    pub fn database_description_mut(&mut self) -> &mut OspfDatabaseDescription {
        if !matches!(self.body, OspfBody::DatabaseDescription(_)) {
            self.packet_type.set_user(OSPF_TYPE_DATABASE_DESCRIPTION);
            self.body = OspfBody::DatabaseDescription(OspfDatabaseDescription::new());
        }
        match &mut self.body {
            OspfBody::DatabaseDescription(dd) => dd,
            // Unreachable: the body was just normalized to a DD above.
            _ => unreachable!("database description body installed above"),
        }
    }

    /// Build an OSPFv2 Link State Request packet (RFC 2328 §A.3.4).
    ///
    /// Sets the packet Type to [`OSPF_TYPE_LINK_STATE_REQUEST`] and installs a
    /// default (empty) [`OspfLinkStateRequest`] body. Add request entries
    /// fluently with [`Ospfv2::with_link_state_request`] or replace the whole
    /// body with [`Ospfv2::link_state_request_body`].
    pub fn link_state_request() -> Self {
        Self::new()
            .packet_type(OSPF_TYPE_LINK_STATE_REQUEST)
            .link_state_request_body(OspfLinkStateRequest::new())
    }

    /// Replace the packet body with the given [`OspfLinkStateRequest`] body and
    /// set the packet Type to [`OSPF_TYPE_LINK_STATE_REQUEST`].
    pub fn link_state_request_body(mut self, lsr: OspfLinkStateRequest) -> Self {
        self.packet_type.set_user(OSPF_TYPE_LINK_STATE_REQUEST);
        self.body = OspfBody::LinkStateRequest(lsr);
        self
    }

    /// Mutate the Link State Request body in place through a closure, returning
    /// `self` for fluent chaining (e.g.
    /// `Ospfv2::link_state_request().with_link_state_request(|r| ...)`).
    ///
    /// If the current body is not a Link State Request it is replaced with a
    /// default one (and the packet Type set to
    /// [`OSPF_TYPE_LINK_STATE_REQUEST`]) before the closure runs, so the
    /// accessor always yields a Link State Request body to configure.
    pub fn with_link_state_request(
        mut self,
        configure: impl FnOnce(&mut OspfLinkStateRequest),
    ) -> Self {
        configure(self.link_state_request_mut());
        self
    }

    /// Borrow the Link State Request body mutably, installing a default Link
    /// State Request body (and setting the packet Type to
    /// [`OSPF_TYPE_LINK_STATE_REQUEST`]) when the current body is not already a
    /// Link State Request.
    pub fn link_state_request_mut(&mut self) -> &mut OspfLinkStateRequest {
        if !matches!(self.body, OspfBody::LinkStateRequest(_)) {
            self.packet_type.set_user(OSPF_TYPE_LINK_STATE_REQUEST);
            self.body = OspfBody::LinkStateRequest(OspfLinkStateRequest::new());
        }
        match &mut self.body {
            OspfBody::LinkStateRequest(lsr) => lsr,
            // Unreachable: the body was just normalized to an LSR above.
            _ => unreachable!("link state request body installed above"),
        }
    }

    /// Build an OSPFv2 Link State Update packet (RFC 2328 §A.3.5).
    ///
    /// Sets the packet Type to [`OSPF_TYPE_LINK_STATE_UPDATE`] and installs a
    /// default (empty) [`OspfLinkStateUpdate`] body. Add LSAs fluently with
    /// [`Ospfv2::with_link_state_update`] or replace the whole body with
    /// [`Ospfv2::link_state_update_body`].
    pub fn link_state_update() -> Self {
        Self::new()
            .packet_type(OSPF_TYPE_LINK_STATE_UPDATE)
            .link_state_update_body(OspfLinkStateUpdate::new())
    }

    /// Replace the packet body with the given [`OspfLinkStateUpdate`] body and
    /// set the packet Type to [`OSPF_TYPE_LINK_STATE_UPDATE`].
    pub fn link_state_update_body(mut self, lsu: OspfLinkStateUpdate) -> Self {
        self.packet_type.set_user(OSPF_TYPE_LINK_STATE_UPDATE);
        self.body = OspfBody::LinkStateUpdate(lsu);
        self
    }

    /// Mutate the Link State Update body in place through a closure, returning
    /// `self` for fluent chaining (e.g.
    /// `Ospfv2::link_state_update().with_link_state_update(|u| ...)`).
    ///
    /// If the current body is not a Link State Update it is replaced with a
    /// default one (and the packet Type set to [`OSPF_TYPE_LINK_STATE_UPDATE`])
    /// before the closure runs, so the accessor always yields a Link State Update
    /// body to configure.
    pub fn with_link_state_update(
        mut self,
        configure: impl FnOnce(&mut OspfLinkStateUpdate),
    ) -> Self {
        configure(self.link_state_update_mut());
        self
    }

    /// Borrow the Link State Update body mutably, installing a default Link State
    /// Update body (and setting the packet Type to
    /// [`OSPF_TYPE_LINK_STATE_UPDATE`]) when the current body is not already a
    /// Link State Update.
    pub fn link_state_update_mut(&mut self) -> &mut OspfLinkStateUpdate {
        if !matches!(self.body, OspfBody::LinkStateUpdate(_)) {
            self.packet_type.set_user(OSPF_TYPE_LINK_STATE_UPDATE);
            self.body = OspfBody::LinkStateUpdate(OspfLinkStateUpdate::new());
        }
        match &mut self.body {
            OspfBody::LinkStateUpdate(lsu) => lsu,
            // Unreachable: the body was just normalized to an LSU above.
            _ => unreachable!("link state update body installed above"),
        }
    }

    /// Build an OSPFv2 Link State Acknowledgment packet (RFC 2328 §A.3.6).
    ///
    /// Sets the packet Type to [`OSPF_TYPE_LINK_STATE_ACK`] and installs a
    /// default (empty) [`OspfLinkStateAck`] body. Add LSA headers fluently with
    /// [`Ospfv2::with_link_state_ack`] or replace the whole body with
    /// [`Ospfv2::link_state_ack_body`].
    pub fn link_state_ack() -> Self {
        Self::new()
            .packet_type(OSPF_TYPE_LINK_STATE_ACK)
            .link_state_ack_body(OspfLinkStateAck::new())
    }

    /// Replace the packet body with the given [`OspfLinkStateAck`] body and set
    /// the packet Type to [`OSPF_TYPE_LINK_STATE_ACK`].
    pub fn link_state_ack_body(mut self, ack: OspfLinkStateAck) -> Self {
        self.packet_type.set_user(OSPF_TYPE_LINK_STATE_ACK);
        self.body = OspfBody::LinkStateAck(ack);
        self
    }

    /// Mutate the Link State Acknowledgment body in place through a closure,
    /// returning `self` for fluent chaining (e.g.
    /// `Ospfv2::link_state_ack().with_link_state_ack(|a| ...)`).
    ///
    /// If the current body is not a Link State Acknowledgment it is replaced with
    /// a default one (and the packet Type set to [`OSPF_TYPE_LINK_STATE_ACK`])
    /// before the closure runs, so the accessor always yields a Link State
    /// Acknowledgment body to configure.
    pub fn with_link_state_ack(mut self, configure: impl FnOnce(&mut OspfLinkStateAck)) -> Self {
        configure(self.link_state_ack_mut());
        self
    }

    /// Borrow the Link State Acknowledgment body mutably, installing a default
    /// Link State Acknowledgment body (and setting the packet Type to
    /// [`OSPF_TYPE_LINK_STATE_ACK`]) when the current body is not already a Link
    /// State Acknowledgment.
    pub fn link_state_ack_mut(&mut self) -> &mut OspfLinkStateAck {
        if !matches!(self.body, OspfBody::LinkStateAck(_)) {
            self.packet_type.set_user(OSPF_TYPE_LINK_STATE_ACK);
            self.body = OspfBody::LinkStateAck(OspfLinkStateAck::new());
        }
        match &mut self.body {
            OspfBody::LinkStateAck(ack) => ack,
            // Unreachable: the body was just normalized to an LSAck above.
            _ => unreachable!("link state ack body installed above"),
        }
    }

    /// The effective OSPF Version (the caller value, else [`OSPF_VERSION_2`]).
    pub fn version_value(&self) -> u8 {
        self.version.value().copied().unwrap_or(OSPF_VERSION_2)
    }

    /// The effective OSPF packet Type code (the caller value, else the body's).
    pub fn packet_type_value(&self) -> u8 {
        self.packet_type
            .value()
            .copied()
            .unwrap_or_else(|| self.body.type_code())
    }

    /// The pinned Packet Length, if the caller set it.
    pub fn packet_length_value(&self) -> Option<u16> {
        self.packet_length.value().copied()
    }

    /// The effective Router ID (the caller value, else the unspecified address).
    pub fn router_id_value(&self) -> Ipv4Addr {
        self.router_id
            .value()
            .copied()
            .unwrap_or(Ipv4Addr::UNSPECIFIED)
    }

    /// The effective Area ID (the caller value, else the unspecified address).
    pub fn area_id_value(&self) -> Ipv4Addr {
        self.area_id
            .value()
            .copied()
            .unwrap_or(Ipv4Addr::UNSPECIFIED)
    }

    /// The pinned Checksum, if the caller set it.
    pub fn checksum_value(&self) -> Option<u16> {
        self.checksum.value().copied()
    }

    /// The effective AuType (the caller value, else [`OSPF_AUTYPE_NULL`]).
    pub fn autype_value(&self) -> u16 {
        self.autype.value().copied().unwrap_or(OSPF_AUTYPE_NULL)
    }

    /// The effective Authentication field (the caller value, else all zeros).
    pub fn authentication_value(&self) -> [u8; OSPF_AUTH_LEN] {
        self.authentication
            .value()
            .copied()
            .unwrap_or([0; OSPF_AUTH_LEN])
    }

    /// Decode-time checksum validation status (RFC 2328 §A.3.1).
    ///
    /// Builder-constructed packets report [`OspfChecksumStatus::NotChecked`].
    /// On decode this is set to [`OspfChecksumStatus::Valid`] or
    /// [`OspfChecksumStatus::Invalid`] when checksum validation is enabled and
    /// the packet does not use cryptographic authentication; it stays
    /// [`OspfChecksumStatus::NotChecked`] when validation is disabled or the
    /// AuType is [`OSPF_AUTYPE_CRYPTOGRAPHIC`] (whose checksum field is zero).
    /// This is decode metadata only and does not affect compiled bytes.
    pub fn checksum_status(&self) -> OspfChecksumStatus {
        self.checksum_status
    }

    /// The cryptographic-authentication parameters (AuType 2) recorded by
    /// [`Ospfv2::crypto_auth`] or [`Ospfv2::crypto_md5_auth`], if any.
    ///
    /// Present only when cryptographic authentication was configured through the
    /// builder; `None` for null, simple-password, and decoded packets. When
    /// present, `compile()` appends the message-digest trailer after the OSPF
    /// packet (RFC 2328 §D.3 keyed-MD5 or an RFC 5709 HMAC-SHA variant, as
    /// selected by [`OspfCryptoAuth::algorithm`]). The secret key it holds never
    /// appears on the wire.
    pub fn crypto_auth_params(&self) -> Option<&OspfCryptoAuth> {
        self.crypto_auth.as_ref()
    }

    /// The Key ID from the structured 8-octet authentication field, when the
    /// AuType is cryptographic (AuType 2, RFC 2328 §D.3).
    ///
    /// For cryptographic authentication the 8-octet authentication field is
    /// reinterpreted as Reserved(2), Key ID(1), Auth Data Length(1), and the
    /// Cryptographic sequence number(4). The Key ID is octet 2 of that field.
    /// Returns `None` for any non-cryptographic AuType, where the field is a raw
    /// 8-octet value rather than the structured form.
    pub fn crypto_key_id(&self) -> Option<u8> {
        if self.autype_value() == OSPF_AUTYPE_CRYPTOGRAPHIC {
            Some(self.authentication_value()[2])
        } else {
            None
        }
    }

    /// The Authentication Data Length from the structured 8-octet authentication
    /// field, when the AuType is cryptographic (AuType 2, RFC 2328 §D.3).
    ///
    /// This is octet 3 of the structured authentication field and records the
    /// length, in octets, of the appended message-digest trailer (16 for
    /// keyed-MD5). Returns `None` for any non-cryptographic AuType.
    pub fn crypto_auth_data_length(&self) -> Option<u8> {
        if self.autype_value() == OSPF_AUTYPE_CRYPTOGRAPHIC {
            Some(self.authentication_value()[3])
        } else {
            None
        }
    }

    /// The Cryptographic sequence number from the structured 8-octet
    /// authentication field, when the AuType is cryptographic (AuType 2, RFC 2328
    /// §D.3).
    ///
    /// This is the trailing 4-octet (big-endian) field of the structured
    /// authentication field (octets 4..8). Returns `None` for any
    /// non-cryptographic AuType.
    pub fn crypto_sequence_number(&self) -> Option<u32> {
        if self.autype_value() == OSPF_AUTYPE_CRYPTOGRAPHIC {
            let field = self.authentication_value();
            Some(u32::from_be_bytes([field[4], field[5], field[6], field[7]]))
        } else {
            None
        }
    }

    /// The appended cryptographic-authentication message-digest trailer recovered
    /// on decode (AuType 2, RFC 2328 §D.3), or an empty slice when none was
    /// captured.
    ///
    /// The OSPF Packet Length covers only the header and body, so a
    /// cryptographically authenticated packet's appended digest occupies the
    /// trailing `available - packet_length` octets of the IP payload. Decoding
    /// captures those octets here so the packet re-compiles byte-for-byte even
    /// without the secret key. Empty for builder-constructed packets (whose
    /// trailer is recomputed from the recorded [`crypto_auth`](Ospfv2::crypto_auth)
    /// key on `compile()`) and for non-cryptographic authentication.
    pub fn auth_trailer(&self) -> &[u8] {
        &self.auth_trailer
    }

    /// The recorded cryptographic-authentication parameters that `compile()`
    /// should use to append a keyed-MD5 trailer, if any.
    ///
    /// A trailer is appended only when both the recorded parameters are present
    /// (set via [`Ospfv2::crypto_md5_auth`]) and the effective AuType is
    /// [`OSPF_AUTYPE_CRYPTOGRAPHIC`]. Overriding the AuType away from
    /// cryptographic after configuring crypto auth therefore suppresses the
    /// trailer, keeping the AuType field authoritative.
    fn crypto_auth_for_trailer(&self) -> Option<&OspfCryptoAuth> {
        match &self.crypto_auth {
            Some(crypto) if self.autype_value() == OSPF_AUTYPE_CRYPTOGRAPHIC => Some(crypto),
            _ => None,
        }
    }

    /// The length, in octets, of the cryptographic message-digest trailer
    /// `compile()` appends after the OSPF packet body (RFC 2328 §D.3), so length
    /// accounting can include it.
    ///
    /// When recorded [`crypto_auth`](Ospfv2::crypto_auth) parameters are present
    /// (and the AuType is cryptographic) the trailer is the freshly recomputed
    /// digest, whose length is the recorded algorithm's digest size (16 for
    /// keyed-MD5, 20/32/48/64 for the RFC 5709 HMAC-SHA variants). Otherwise a
    /// non-empty decoded [`auth_trailer`](Ospfv2::auth_trailer) is re-emitted
    /// verbatim, so its captured length applies. Zero when neither is present.
    fn crypto_trailer_len(&self) -> usize {
        if let Some(crypto) = self.crypto_auth_for_trailer() {
            usize::from(crypto.digest_len())
        } else {
            self.auth_trailer.len()
        }
    }
}

impl Default for Ospfv2 {
    fn default() -> Self {
        Self::new()
    }
}

impl Layer for Ospfv2 {
    fn name(&self) -> &'static str {
        "Ospf"
    }

    fn summary(&self) -> String {
        // The effective Packet Length is the caller value, else the total OSPF
        // byte count (24-octet header + body) that `compile()` would emit.
        let len = self
            .packet_length_value()
            .map(usize::from)
            .unwrap_or(OSPF_HEADER_LEN + self.body.encoded_len());
        // Dispatch on the body variant so each typed body extends the header
        // one-liner with its own at-a-glance detail (mirroring BGP). The Hello
        // body reports the network mask, DR/BDR, and neighbor count; other
        // bodies fall back to the common-header summary with the Packet Length.
        match &self.body {
            OspfBody::Hello(hello) => format!(
                "Ospf(type={}, rid={}, area={}, mask={}, dr={}, bdr={}, neighbors={})",
                ospf_type_name(self.packet_type_value()),
                self.router_id_value(),
                self.area_id_value(),
                hello.network_mask_value(),
                hello.designated_router_value(),
                hello.backup_designated_router_value(),
                hello.neighbors_value().len()
            ),
            OspfBody::DatabaseDescription(dd) => format!(
                "Ospf(type={}, rid={}, area={}, mtu={}, seq=0x{:08x}, flags=0x{:02x}, lsa_headers={})",
                ospf_type_name(self.packet_type_value()),
                self.router_id_value(),
                self.area_id_value(),
                dd.interface_mtu_value(),
                dd.dd_sequence_number_value(),
                dd.flags_value(),
                dd.lsa_headers_value().len()
            ),
            OspfBody::LinkStateRequest(lsr) => format!(
                "Ospf(type={}, rid={}, area={}, requests={})",
                ospf_type_name(self.packet_type_value()),
                self.router_id_value(),
                self.area_id_value(),
                lsr.entries_value().len()
            ),
            OspfBody::LinkStateUpdate(lsu) => format!(
                "Ospf(type={}, rid={}, area={}, num_lsas={}, lsas={})",
                ospf_type_name(self.packet_type_value()),
                self.router_id_value(),
                self.area_id_value(),
                lsu.num_lsas_value(),
                lsu.lsas_value().len()
            ),
            OspfBody::LinkStateAck(ack) => format!(
                "Ospf(type={}, rid={}, area={}, lsa_headers={})",
                ospf_type_name(self.packet_type_value()),
                self.router_id_value(),
                self.area_id_value(),
                ack.lsa_headers_value().len()
            ),
            OspfBody::Unknown { .. } => format!(
                "Ospf(type={}, rid={}, area={}, len={})",
                ospf_type_name(self.packet_type_value()),
                self.router_id_value(),
                self.area_id_value(),
                len
            ),
        }
    }

    fn inspection_fields(&self) -> Vec<(&'static str, String)> {
        // Stable field/value pairs for `show()`. Auto-filled Packet Length and
        // Checksum print as `auto` when the caller left them unset; the checksum
        // and authentication fields print as hex.
        let mut fields = vec![
            ("version", self.version_value().to_string()),
            ("type", ospf_type_name(self.packet_type_value()).to_string()),
            (
                "length",
                self.packet_length_value()
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "auto".to_string()),
            ),
            ("router_id", self.router_id_value().to_string()),
            ("area_id", self.area_id_value().to_string()),
            (
                "checksum",
                self.checksum_value()
                    .map(|value| format!("0x{value:04x}"))
                    .unwrap_or_else(|| "auto".to_string()),
            ),
            (
                "autype",
                format!(
                    "{} ({})",
                    self.autype_value(),
                    ospf_autype_name(self.autype_value())
                ),
            ),
            (
                "authentication",
                format!("0x{}", hex_bytes(&self.authentication_value())),
            ),
        ];

        // Each typed body contributes its own stable pairs after the common
        // header (mirroring BGP). The Hello body adds its intervals, options,
        // priority, mask, DR/BDR, neighbor count, and one `neighbor` per
        // neighbor Router ID.
        if let OspfBody::Hello(hello) = &self.body {
            fields.push(("hello_interval", hello.hello_interval_value().to_string()));
            fields.push((
                "dead_interval",
                hello.router_dead_interval_value().to_string(),
            ));
            fields.push(("options", format_options(hello.options_value())));
            fields.push(("priority", hello.router_priority_value().to_string()));
            fields.push(("network_mask", hello.network_mask_value().to_string()));
            fields.push((
                "designated_router",
                hello.designated_router_value().to_string(),
            ));
            fields.push((
                "backup_designated_router",
                hello.backup_designated_router_value().to_string(),
            ));
            fields.push(("neighbor_count", hello.neighbors_value().len().to_string()));
            for neighbor in hello.neighbors_value() {
                fields.push(("neighbor", neighbor.to_string()));
            }
        }

        // The Database Description body adds its MTU, options, flags, DD
        // sequence number, and one `lsa_header` summary per carried LSA header.
        if let OspfBody::DatabaseDescription(dd) = &self.body {
            fields.push(("interface_mtu", dd.interface_mtu_value().to_string()));
            fields.push(("options", format_options(dd.options_value())));
            fields.push(("dd_flags", format_dd_flags(dd)));
            fields.push((
                "dd_sequence_number",
                format!("0x{:08x}", dd.dd_sequence_number_value()),
            ));
            fields.push(("lsa_header_count", dd.lsa_headers_value().len().to_string()));
            for header in dd.lsa_headers_value() {
                fields.push(("lsa_header", header.summary()));
            }
        }

        // The Link State Request body adds its request count and one `request`
        // line per entry (LS type, Link State ID, Advertising Router).
        if let OspfBody::LinkStateRequest(lsr) = &self.body {
            fields.push(("request_count", lsr.entries_value().len().to_string()));
            for entry in lsr.entries_value() {
                fields.push((
                    "request",
                    format!(
                        "ls_type=0x{:08x}, id={}, adv={}",
                        entry.ls_type_value(),
                        entry.link_state_id_value(),
                        entry.advertising_router_value()
                    ),
                ));
            }
        }

        // The Link State Update body adds its `# LSAs` count, its carried-LSA
        // count, and one `lsa` line per carried LSA: the LSA header summary plus
        // the body byte length (e.g. `LSA(...) body=12B`). The body is still
        // `Raw` here, so its length is the byte count after the 20-octet header;
        // typed bodies (added in later steps) keep the same `body=NB` suffix.
        if let OspfBody::LinkStateUpdate(lsu) = &self.body {
            fields.push(("num_lsas", lsu.num_lsas_value().to_string()));
            fields.push(("lsa_count", lsu.lsas_value().len().to_string()));
            for lsa in lsu.lsas_value() {
                fields.push((
                    "lsa",
                    format!("{} body={}B", lsa.header.summary(), lsa.body.encoded_len()),
                ));
                // A typed Router-LSA body (RFC 2328 §A.4.2) adds a `router_lsa`
                // pair (the V/E/B flags and link count) followed by one
                // `router_link` pair per link (type name, Link ID, Link Data,
                // metric). Other LSA body variants contribute only the `lsa`
                // header summary above.
                if let crate::protocols::ospf::lsa::OspfLsaBody::Router(router) = &lsa.body {
                    fields.push(("router_lsa", router.summary()));
                    for link in router.links_value() {
                        fields.push(("router_link", link.summary()));
                    }
                }
                // A typed Network-LSA body (RFC 2328 §A.4.3) adds a `network_lsa`
                // pair (the network mask and attached-router count) followed by
                // one `attached_router` pair per attached Router ID. Other LSA
                // body variants contribute only the `lsa` header summary above.
                if let crate::protocols::ospf::lsa::OspfLsaBody::Network(network) = &lsa.body {
                    fields.push(("network_lsa", network.summary()));
                    for router in network.attached_routers_value() {
                        fields.push(("attached_router", router.to_string()));
                    }
                }
                // A typed Summary-LSA body (RFC 2328 §A.4.4, LS type 3 and 4)
                // adds a `summary_lsa` pair (the network mask and TOS/metric-entry
                // count) followed by one `summary_tos` pair per TOS/metric entry
                // (the TOS code and its 24-bit metric). Other LSA body variants
                // contribute only the `lsa` header summary above.
                if let crate::protocols::ospf::lsa::OspfLsaBody::Summary(summary) = &lsa.body {
                    fields.push(("summary_lsa", summary.summary()));
                    for entry in summary.entries_value() {
                        fields.push((
                            "summary_tos",
                            format!("tos={} metric={}", entry.tos_value(), entry.metric_value()),
                        ));
                    }
                }
                // A typed AS-External-LSA body (RFC 2328 §A.4.5, LS type 5) adds
                // an `as_external_lsa` pair (the network mask and a summary of the
                // mandatory TOS 0 entry) followed by one `as_external_tos` pair per
                // external metric entry (the E bit / external metric type, 24-bit
                // metric, forwarding address, and external route tag). Other LSA
                // body variants contribute only the `lsa` header summary above.
                if let crate::protocols::ospf::lsa::OspfLsaBody::AsExternal(external) = &lsa.body {
                    fields.push(("as_external_lsa", external.summary()));
                    for entry in external.entries_value() {
                        fields.push((
                            "as_external_tos",
                            format!(
                                "type={} metric={} fwd={} tag=0x{:08x}",
                                if entry.e_bit_value() { "E2" } else { "E1" },
                                entry.metric_value(),
                                entry.forwarding_address_value(),
                                entry.external_route_tag_value()
                            ),
                        ));
                    }
                }
                // A typed NSSA-LSA body (RFC 3101 §2.2, LS type 7) adds an
                // `nssa_lsa` pair (the P-bit translation flag read from the
                // enclosing LSA header Options field, plus the network mask and a
                // summary of the mandatory TOS 0 entry) followed by one `nssa_tos`
                // pair per external metric entry (the E bit / external metric
                // type, 24-bit metric, forwarding address, and external route
                // tag). The NSSA body shares the AS-External-LSA layout; the P-bit
                // lives on the LSA header, not in the body, so it is read from the
                // header Options octet here. Other LSA body variants contribute
                // only the `lsa` header summary above.
                if let crate::protocols::ospf::lsa::OspfLsaBody::Nssa(nssa) = &lsa.body {
                    let p_bit = lsa.header.options_value()
                        & crate::protocols::ospf::lsa::OSPF_OPTIONS_NP
                        != 0;
                    fields.push((
                        "nssa_lsa",
                        format!(
                            "P={} {}",
                            if p_bit { "set" } else { "clear" },
                            nssa.summary()
                        ),
                    ));
                    for entry in nssa.entries_value() {
                        fields.push((
                            "nssa_tos",
                            format!(
                                "type={} metric={} fwd={} tag=0x{:08x}",
                                if entry.e_bit_value() { "E2" } else { "E1" },
                                entry.metric_value(),
                                entry.forwarding_address_value(),
                                entry.external_route_tag_value()
                            ),
                        ));
                    }
                }
                // A typed Opaque-LSA body (RFC 5250 §3, LS type 9 link-local, 10
                // area, or 11 AS) adds an `opaque_lsa` pair (the Opaque Type read
                // from the enclosing LSA header Link State ID, plus the TLV count)
                // followed by one `opaque_tlv` pair per TLV (the TLV type and its
                // value byte length). The Opaque Type/Opaque ID live in the LSA
                // header Link State ID, not in the body, so the Opaque Type is read
                // from the header here. Other LSA body variants contribute only the
                // `lsa` header summary above.
                if let crate::protocols::ospf::lsa::OspfLsaBody::Opaque(opaque) = &lsa.body {
                    fields.push((
                        "opaque_lsa",
                        format!(
                            "type={} {}",
                            crate::protocols::ospf::lsa::opaque_type(&lsa.header),
                            opaque.summary()
                        ),
                    ));
                    for tlv in opaque.tlvs_value() {
                        fields.push((
                            "opaque_tlv",
                            format!("type={} value={}B", tlv.tlv_type(), tlv.value().len()),
                        ));
                    }
                }
            }
        }

        // The Link State Acknowledgment body adds its acknowledged-header count
        // and one `lsa_header` summary per carried LSA header.
        if let OspfBody::LinkStateAck(ack) = &self.body {
            fields.push((
                "lsa_header_count",
                ack.lsa_headers_value().len().to_string(),
            ));
            for header in ack.lsa_headers_value() {
                fields.push(("lsa_header", header.summary()));
            }
        }

        fields
    }

    fn encoded_len(&self) -> usize {
        // The OSPF packet is the 24-octet common header plus the body. When
        // cryptographic authentication is active, `compile()` also appends a
        // message-digest trailer after the packet (RFC 2328 §D.3): the trailer is
        // excluded from the OSPF Packet Length field but is part of the emitted
        // bytes, so the enclosing IP payload length must count it. The trailer is
        // either a freshly recomputed keyed-MD5 digest (from recorded crypto-auth
        // parameters) or a verbatim decoded `auth_trailer`.
        OSPF_HEADER_LEN + self.body.encoded_len() + self.crypto_trailer_len()
    }

    fn compile(&self, _ctx: &LayerContext<'_>, out: &mut Vec<u8>) -> Result<()> {
        let start = out.len();
        // The OSPF Packet Length field covers the common header plus the body. The
        // cryptographic message-digest trailer (if any) is appended after the
        // packet and is deliberately NOT counted here (RFC 2328 §D.3).
        let total_len = OSPF_HEADER_LEN + self.body.encoded_len();

        // Cryptographic authentication (AuType 2, RFC 2328 §D.3) zeroes the header
        // Checksum and appends a keyed-MD5 trailer; null/simple authentication use
        // the standard Internet checksum.
        let crypto = self.crypto_auth_for_trailer();

        // Common header (RFC 2328 §A.3.1). The Packet Length and Checksum are
        // written as placeholders first, then back-filled below unless pinned.
        out.push(self.version_value());
        out.push(self.packet_type_value());

        // Packet Length placeholder (octets 2..4).
        let packet_length = self
            .packet_length
            .value()
            .copied()
            .unwrap_or(total_len as u16);
        out.extend_from_slice(&packet_length.to_be_bytes());

        out.extend_from_slice(&self.router_id_value().octets());
        out.extend_from_slice(&self.area_id_value().octets());

        // Checksum placeholder (octets 12..14): zeroed so the auto-fill below can
        // compute over the header-with-hole; a pinned checksum is written verbatim.
        // For cryptographic authentication the checksum field is left zero and is
        // never auto-filled (RFC 2328 §D.3).
        let pinned_checksum = self.checksum.value().copied();
        out.extend_from_slice(&pinned_checksum.unwrap_or(0).to_be_bytes());

        out.extend_from_slice(&self.autype_value().to_be_bytes());
        out.extend_from_slice(&self.authentication_value());

        // Body bytes follow the 24-octet common header.
        self.body.encode(out);

        if let Some(crypto) = crypto {
            // Cryptographic authentication: the header Checksum stays zero unless
            // the caller pinned a (deliberately malformed) value, and the
            // message-digest trailer over the packet-so-far is appended after the
            // OSPF packet. For keyed-MD5 it is `MD5(packet || key_padded_to_16)`
            // (RFC 2328 §D.3); for the RFC 5709 HMAC-SHA variants it is
            // `HMAC(key, packet)` (RFC 5709 §3.3). The trailer is excluded from the
            // Packet Length but is part of the emitted bytes, so the enclosing IP
            // payload counts it. Its length is the algorithm's digest size.
            let digest = crypto.digest(&out[start..]);
            out.extend_from_slice(&digest);
        } else if !self.auth_trailer.is_empty() {
            // A decoded cryptographically authenticated packet carries no secret
            // key, so its appended digest trailer (RFC 2328 §D.3) was captured
            // verbatim on decode. Re-emit it unchanged so the packet re-compiles
            // byte-for-byte without re-deriving a digest. The header Checksum is
            // preserved as the decoded (zero) value because it was recovered
            // user-set, so the Internet-checksum auto-fill below is not reached.
            out.extend_from_slice(&self.auth_trailer);
        } else if pinned_checksum.is_none() {
            // Null/simple authentication: auto-fill the standard Internet checksum
            // over the whole packet EXCLUDING the 8-octet authentication field
            // (octets 16..24), computed with the checksum field itself zeroed
            // (RFC 2328 §A.3.1). The placeholder above already wrote zero.
            let checksum = internet_checksum_chunks([&out[start..start + 16], &out[start + 24..]]);
            out[start + 12..start + 14].copy_from_slice(&checksum.to_be_bytes());
        }

        Ok(())
    }

    impl_layer_object!(Ospfv2);
}

impl_layer_div!(Ospfv2);

/// Deprecated neutral alias for the OSPFv2 layer struct, renamed to [`Ospfv2`].
///
/// Per the repo's version-suffix naming convention (mirroring `Icmp` ->
/// `Icmpv4`), the OSPF layer is the version-explicit [`Ospfv2`]. This alias is
/// kept so downstream code that imported the neutral `Ospf` name keeps compiling
/// (with a deprecation warning). Prefer the version-explicit [`Ospfv2`] name; a
/// distinct `Ospfv3` layer is added in a later block.
#[deprecated(note = "renamed to Ospfv2")]
pub type Ospf = Ospfv2;

/// Render bytes as a continuous lowercase hex string (no separators), used for
/// the authentication field in `inspection_fields()`.
fn hex_bytes(bytes: &[u8]) -> String {
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push_str(&format!("{byte:02x}"));
    }
    output
}

/// Render an OSPFv2 Options octet (RFC 2328 §A.2) for `inspection_fields()`: the
/// raw hex value, with the decoded capability labels in parentheses when any
/// recognized bit is set (e.g. `0x42 (E|O)`). A value with no recognized bits
/// (including `0x00`) renders as the bare hex value.
fn format_options(options: u8) -> String {
    let labels = ospf_options_summary(options);
    if labels.is_empty() {
        format!("0x{options:02x}")
    } else {
        format!("0x{options:02x} ({labels})")
    }
}

/// Render a Database Description flags octet (RFC 2328 §A.3.3) for
/// `inspection_fields()`: the raw hex value, with the decoded `I|M|MS` labels in
/// parentheses when any recognized bit is set (e.g. `0x07 (I|M|MS)`). A value
/// with no recognized bits (including `0x00`) renders as the bare hex value.
fn format_dd_flags(dd: &OspfDatabaseDescription) -> String {
    let flags = dd.flags_value();
    let labels = dd.dd_flags_summary();
    if labels.is_empty() {
        format!("0x{flags:02x}")
    } else {
        format!("0x{flags:02x} ({labels})")
    }
}

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

    #[test]
    fn ospf_new_defaults_common_header() {
        let ospf = Ospfv2::new();
        assert_eq!(ospf.name(), "Ospf");
        assert_eq!(ospf.version_value(), OSPF_VERSION_2);
        assert_eq!(ospf.autype_value(), OSPF_AUTYPE_NULL);
        assert_eq!(ospf.authentication_value(), [0; OSPF_AUTH_LEN]);
        assert_eq!(ospf.checksum_value(), None);
        assert_eq!(ospf.packet_length_value(), None);
        assert_eq!(ospf.encoded_len(), OSPF_HEADER_LEN);
    }

    #[test]
    fn ospf_common_header_compiles_with_auto_length_and_checksum() {
        let body = [0xde, 0xad, 0xbe, 0xef];
        let ospf = Ospfv2::new()
            .packet_type(OSPF_TYPE_HELLO)
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .raw_body(body);

        let bytes = Packet::from_layer(ospf).compile().unwrap();

        // 24-octet header + 4-octet body.
        let total = OSPF_HEADER_LEN + body.len();
        assert_eq!(bytes.len(), total);

        // Version octet (RFC 2328 §A.3.1) defaults to 2.
        assert_eq!(bytes[0], OSPF_VERSION_2);
        // Type octet carries the requested packet type.
        assert_eq!(bytes[1], OSPF_TYPE_HELLO);
        // Packet Length field (octets 2..4) auto-fills to the total OSPF length.
        assert_eq!(&bytes[2..4], &(total as u16).to_be_bytes());
        // Router ID (octets 4..8) and Area ID (octets 8..12).
        assert_eq!(&bytes[4..8], &[192, 0, 2, 1]);
        assert_eq!(&bytes[8..12], &[0, 0, 0, 0]);
        // AuType (octets 14..16) defaults to null.
        assert_eq!(&bytes[14..16], &OSPF_AUTYPE_NULL.to_be_bytes());
        // Authentication field (octets 16..24) defaults to zeros.
        assert_eq!(&bytes[16..24], &[0u8; OSPF_AUTH_LEN]);
        // Body bytes follow the header verbatim.
        assert_eq!(&bytes[OSPF_HEADER_LEN..], &body);

        // The auto-filled checksum is the Internet checksum over the packet with
        // the 8-octet auth field excluded and the checksum field zeroed; verify it
        // by recomputing the same way (over a copy with the checksum field zeroed)
        // and confirming the field matches.
        let mut zeroed = bytes.as_bytes().to_vec();
        zeroed[12] = 0;
        zeroed[13] = 0;
        let expected = internet_checksum_chunks([&zeroed[0..16], &zeroed[24..]]);
        assert_eq!(&bytes[12..14], &expected.to_be_bytes());
        // The auto-filled checksum is nonzero for this packet.
        assert_ne!(&bytes[12..14], &[0, 0]);
    }

    #[test]
    fn ospf_caller_set_checksum_survives_compile() {
        let ospf = Ospfv2::new()
            .packet_type(OSPF_TYPE_HELLO)
            .raw_body([0x01, 0x02])
            .checksum(0x1234);

        let bytes = Packet::from_layer(ospf).compile().unwrap();

        // The pinned checksum is written verbatim, not recomputed.
        assert_eq!(&bytes[12..14], &0x1234u16.to_be_bytes());
        // The packet type still rides in the Type octet.
        assert_eq!(bytes[1], OSPF_TYPE_HELLO);
        // Version octet is still the default.
        assert_eq!(bytes[0], OSPF_VERSION_2);
    }

    #[test]
    fn ospf_caller_set_packet_length_survives_compile() {
        let ospf = Ospfv2::new()
            .packet_type(OSPF_TYPE_HELLO)
            .raw_body([0x00])
            .packet_length(0xbeef);

        let bytes = Packet::from_layer(ospf).compile().unwrap();
        assert_eq!(&bytes[2..4], &0xbeefu16.to_be_bytes());
    }

    /// `summary()` reads the header at a glance and `inspection_fields()`
    /// exposes a stable `type` entry equal to the type name, so the OSPF common
    /// header is inspectable through `Packet::summary()` and `Packet::show()`.
    #[test]
    fn ospf_summary_and_inspection_expose_the_common_header() {
        let ospf = Ospfv2::new()
            .packet_type(OSPF_TYPE_HELLO)
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0]);

        // The one-line summary carries the type name and router id.
        let summary = ospf.summary();
        assert!(
            summary.contains("Hello"),
            "summary missing type name: {summary}"
        );
        assert!(
            summary.contains("192.0.2.1"),
            "summary missing router id: {summary}"
        );

        // `inspection_fields` carries a `type` entry equal to the expected name.
        let fields = ospf.inspection_fields();
        let type_field = fields
            .iter()
            .find(|(name, _)| *name == "type")
            .map(|(_, value)| value.as_str());
        assert_eq!(type_field, Some(ospf_type_name(OSPF_TYPE_HELLO)));
        assert_eq!(type_field, Some("Hello"));

        // Unset length/checksum print as `auto`.
        let length = fields.iter().find(|(name, _)| *name == "length");
        assert_eq!(length.map(|(_, v)| v.as_str()), Some("auto"));
        let checksum = fields.iter().find(|(name, _)| *name == "checksum");
        assert_eq!(checksum.map(|(_, v)| v.as_str()), Some("auto"));
    }

    /// A Hello packet's `summary()` extends the common-header one-liner with the
    /// network mask, DR/BDR, and `neighbors=` count, and `inspection_fields()`
    /// contributes one stable `neighbor` pair per neighbor Router ID, so the
    /// Hello body is inspectable through `Packet::summary()` / `Packet::show()`.
    #[test]
    fn ospf_hello_summary_and_inspection_describe_the_body() {
        let ospf = Ospfv2::hello()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .with_hello(|h| {
                *h = OspfHello::new()
                    .network_mask(Ipv4Addr::new(255, 255, 255, 0))
                    .designated_router(Ipv4Addr::new(192, 0, 2, 1))
                    .backup_designated_router(Ipv4Addr::new(192, 0, 2, 2))
                    .neighbor(Ipv4Addr::new(192, 0, 2, 3))
                    .neighbor(Ipv4Addr::new(192, 0, 2, 4))
                    .neighbor(Ipv4Addr::new(192, 0, 2, 5));
            });

        // The one-line summary carries the Hello detail: type, mask, DR/BDR, and
        // the neighbor count.
        let summary = ospf.summary();
        assert!(
            summary.contains("type=Hello"),
            "summary missing type: {summary}"
        );
        assert!(
            summary.contains("mask=255.255.255.0"),
            "summary missing network mask: {summary}"
        );
        assert!(
            summary.contains("dr=192.0.2.1"),
            "summary missing DR: {summary}"
        );
        assert!(
            summary.contains("bdr=192.0.2.2"),
            "summary missing BDR: {summary}"
        );
        assert!(
            summary.contains("neighbors=3"),
            "summary missing neighbor count: {summary}"
        );

        // `inspection_fields` carries the stable Hello pairs, including the
        // neighbor count and one `neighbor` entry per neighbor Router ID.
        let fields = ospf.inspection_fields();
        let value_of = |name: &str| {
            fields
                .iter()
                .find(|(field, _)| *field == name)
                .map(|(_, value)| value.as_str())
        };
        assert_eq!(value_of("network_mask"), Some("255.255.255.0"));
        assert_eq!(value_of("designated_router"), Some("192.0.2.1"));
        assert_eq!(value_of("backup_designated_router"), Some("192.0.2.2"));
        assert_eq!(value_of("hello_interval"), Some("10"));
        assert_eq!(value_of("dead_interval"), Some("40"));
        assert_eq!(value_of("priority"), Some("0"));
        assert_eq!(value_of("options"), Some("0x00"));
        assert_eq!(value_of("neighbor_count"), Some("3"));

        // Every neighbor Router ID appears as its own `neighbor` pair.
        let neighbors: Vec<&str> = fields
            .iter()
            .filter(|(field, _)| *field == "neighbor")
            .map(|(_, value)| value.as_str())
            .collect();
        assert_eq!(neighbors, vec!["192.0.2.3", "192.0.2.4", "192.0.2.5"]);
    }

    /// A Link State Update packet's `summary()` reports the carried-LSA count
    /// (`lsas=`), and `inspection_fields()` contributes a `lsa_count` pair plus
    /// one `lsa` entry per carried LSA, each combining the LSA header summary with
    /// the body byte length (`body=NB`), so the LSU and its LSAs are inspectable
    /// through `Packet::summary()` / `Packet::show()`.
    #[test]
    fn ospf_link_state_update_summary_and_inspection_describe_each_lsa() {
        use crate::protocols::ospf::lsa::{
            OspfLsa, OspfLsaBody, OspfLsaHeader, OSPF_LSA_NETWORK, OSPF_LSA_ROUTER,
        };

        let router_lsa = OspfLsa::new(
            OspfLsaHeader::new()
                .ls_type(OSPF_LSA_ROUTER)
                .link_state_id(Ipv4Addr::new(192, 0, 2, 1))
                .advertising_router(Ipv4Addr::new(192, 0, 2, 1)),
            // Six body octets after the 20-octet header.
            OspfLsaBody::Raw(vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06]),
        );
        let network_lsa = OspfLsa::new(
            OspfLsaHeader::new()
                .ls_type(OSPF_LSA_NETWORK)
                .link_state_id(Ipv4Addr::new(192, 0, 2, 2))
                .advertising_router(Ipv4Addr::new(198, 51, 100, 7)),
            // Four body octets after the 20-octet header.
            OspfLsaBody::Raw(vec![0xaa, 0xbb, 0xcc, 0xdd]),
        );

        let ospf = Ospfv2::link_state_update()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .with_link_state_update(|u| {
                *u = OspfLinkStateUpdate::new().lsa(router_lsa).lsa(network_lsa);
            });

        // The one-line summary reports the carried-LSA count via `lsas=`.
        let summary = ospf.summary();
        assert!(
            summary.contains("type=LSUpdate"),
            "summary missing type: {summary}"
        );
        assert!(
            summary.contains("lsas=2"),
            "summary missing carried-LSA count: {summary}"
        );

        // `inspection_fields` carries the `lsa_count` pair and one `lsa` entry per
        // carried LSA.
        let fields = ospf.inspection_fields();
        let lsa_count = fields
            .iter()
            .find(|(field, _)| *field == "lsa_count")
            .map(|(_, value)| value.as_str());
        assert_eq!(lsa_count, Some("2"));

        let lsa_entries: Vec<&str> = fields
            .iter()
            .filter(|(field, _)| *field == "lsa")
            .map(|(_, value)| value.as_str())
            .collect();
        // One `lsa` entry per carried LSA.
        assert_eq!(lsa_entries.len(), 2);

        // Each entry combines the LSA header summary with the body byte length.
        assert!(
            lsa_entries[0].contains("type=Router"),
            "first lsa entry missing header summary: {}",
            lsa_entries[0]
        );
        assert!(
            lsa_entries[0].contains("body=6B"),
            "first lsa entry missing body byte length: {}",
            lsa_entries[0]
        );
        assert!(
            lsa_entries[1].contains("type=Network"),
            "second lsa entry missing header summary: {}",
            lsa_entries[1]
        );
        assert!(
            lsa_entries[1].contains("body=4B"),
            "second lsa entry missing body byte length: {}",
            lsa_entries[1]
        );
    }

    /// The `Ospfv2` layer, `OspfBody`, and the OSPF constants are reachable
    /// through the curated `crafter::prelude` exports (the crate's public
    /// surface), not just the crate-internal module path.
    #[test]
    fn ospf_types_and_constants_reach_the_prelude() {
        use crate::prelude::*;

        // Build an OSPF Hello using only prelude-surfaced symbols and confirm the
        // constants are reachable as named values.
        let ospf = Ospfv2::new()
            .packet_type(OSPF_TYPE_HELLO)
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .autype(OSPF_AUTYPE_NULL);

        assert_eq!(ospf.version_value(), OSPF_VERSION_2);
        assert_eq!(ospf.packet_type_value(), OSPF_TYPE_HELLO);
        assert_eq!(ospf.autype_value(), OSPF_AUTYPE_NULL);

        // The remaining packet-type, length, and AuType constants are reachable.
        let _ = (
            OSPF_TYPE_DATABASE_DESCRIPTION,
            OSPF_TYPE_LINK_STATE_REQUEST,
            OSPF_TYPE_LINK_STATE_UPDATE,
            OSPF_TYPE_LINK_STATE_ACK,
            OSPF_HEADER_LEN,
            OSPF_AUTH_LEN,
            OSPF_AUTYPE_SIMPLE,
            OSPF_AUTYPE_CRYPTOGRAPHIC,
        );

        // The `OspfBody` enum and the deprecated neutral `Ospf` alias surface too.
        let body = OspfBody::Unknown {
            type_code: OSPF_TYPE_HELLO,
            body: Vec::new(),
        };
        assert_eq!(body.type_code(), OSPF_TYPE_HELLO);
        #[allow(deprecated)]
        let _alias: Ospf = Ospfv2::new();

        // The packet compiles through the public `Packet` surface.
        let bytes = Packet::from_layer(ospf).compile().unwrap();
        assert_eq!(bytes[1], OSPF_TYPE_HELLO);
    }

    /// A well-formed OSPF Hello wrapped in IPv4 (protocol 89), decoded through
    /// the default registry (checksum validation on), records
    /// [`OspfChecksumStatus::Valid`] and re-compiles byte-for-byte.
    #[test]
    fn ospf_decode_records_valid_checksum_status() {
        use crate::packet::NetworkLayer;
        use crate::protocols::ip::v4::Ipv4;

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(192, 0, 2, 2))
            / Ospfv2::hello()
                .router_id([192, 0, 2, 1])
                .area_id([0, 0, 0, 0]))
        .compile()
        .expect("Ipv4 / Ospfv2 Hello compiles");

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .expect("the default registry decodes OSPF over IPv4");
        let ospf = decoded
            .layer::<Ospfv2>()
            .expect("the decoded packet exposes a typed Ospfv2 layer");
        assert_eq!(ospf.checksum_status(), OspfChecksumStatus::Valid);

        // The decode-time status is metadata only; the packet still round-trips.
        let recompiled = decoded.compile().expect("decoded OSPF re-compiles");
        assert_eq!(recompiled.as_bytes(), bytes.as_bytes());
    }

    /// An OSPF packet whose checksum octet is corrupted decodes with
    /// [`OspfChecksumStatus::Invalid`] yet still re-compiles byte-for-byte
    /// (the corrupted checksum is preserved as a user-set field).
    #[test]
    fn ospf_decode_records_invalid_checksum_status() {
        use crate::packet::NetworkLayer;
        use crate::protocols::ip::v4::Ipv4;

        // Build a valid Ipv4 / Ospfv2 Hello, then corrupt one OSPF checksum
        // octet in the assembled bytes. The IPv4 header is 20 octets (no
        // options), so the OSPF checksum field sits at offsets 20+12..20+14.
        let mut raw = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(192, 0, 2, 2))
            / Ospfv2::hello().router_id([192, 0, 2, 1]))
        .compile()
        .expect("Ipv4 / Ospfv2 Hello compiles")
        .as_bytes()
        .to_vec();

        let ipv4_header_len = (raw[0] & 0x0f) as usize * 4;
        let ospf_checksum_octet = ipv4_header_len + 12;
        raw[ospf_checksum_octet] ^= 0xff;
        // Recompute the IPv4 header checksum so only the OSPF checksum is wrong:
        // re-decode then re-compile would refill it, so instead decode the
        // (IP-corrupt-tolerant) buffer directly and assert on the OSPF status.
        // The IPv4 layer reports its own checksum status independently; here we
        // only care that the OSPF layer flags the corrupted OSPF checksum.

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, &raw)
            .expect("a corrupted-OSPF-checksum buffer still decodes structurally");
        let ospf = decoded
            .layer::<Ospfv2>()
            .expect("the decoded packet exposes a typed Ospfv2 layer");
        assert_eq!(ospf.checksum_status(), OspfChecksumStatus::Invalid);

        // The corrupted checksum is a user-set field, so re-compiling the OSPF
        // layer reproduces the corrupted bytes verbatim.
        let mut ospf_only = Vec::new();
        let recompiled_ospf = Packet::from_layer(ospf.clone())
            .compile()
            .expect("the decoded OSPF layer re-compiles");
        ospf_only.extend_from_slice(recompiled_ospf.as_bytes());
        assert_eq!(&raw[ipv4_header_len..], ospf_only.as_slice());
    }

    /// Decoding through a registry with checksum validation disabled leaves the
    /// OSPF checksum status as [`OspfChecksumStatus::NotChecked`], and the
    /// packet still round-trips byte-for-byte.
    #[test]
    fn ospf_decode_skips_checksum_validation_when_disabled() {
        use crate::packet::NetworkLayer;
        use crate::protocols::ip::v4::Ipv4;
        use crate::registry::ProtocolRegistry;

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(192, 0, 2, 2))
            / Ospfv2::hello().router_id([192, 0, 2, 1]))
        .compile()
        .expect("Ipv4 / Ospfv2 Hello compiles");

        let registry = ProtocolRegistry::new().checksum_validation(false);
        let decoded = registry
            .decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .expect("the registry decodes OSPF over IPv4");
        let ospf = decoded
            .layer::<Ospfv2>()
            .expect("the decoded packet exposes a typed Ospfv2 layer");
        assert_eq!(ospf.checksum_status(), OspfChecksumStatus::NotChecked);

        let recompiled = decoded.compile().expect("decoded OSPF re-compiles");
        assert_eq!(recompiled.as_bytes(), bytes.as_bytes());
    }

    /// A Hello built with `simple_password(b"secret")` carries AuType 1 and the
    /// cleartext password right-padded into the 8-octet authentication field
    /// (RFC 2328 §D.2), round-trips byte-for-byte through IPv4 decode, and still
    /// reports a valid checksum (the auth field is excluded from the checksum).
    #[test]
    fn ospf_simple_password_encodes_into_the_auth_field_and_round_trips() {
        use crate::packet::NetworkLayer;
        use crate::protocols::ip::v4::Ipv4;

        let ospf = Ospfv2::hello()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .simple_password(b"secret");

        // AuType is simple password and the 8-octet field is the password
        // right-padded with zeros.
        assert_eq!(ospf.autype_value(), OSPF_AUTYPE_SIMPLE);
        assert_eq!(
            ospf.authentication_value(),
            [b's', b'e', b'c', b'r', b'e', b't', 0, 0]
        );

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(192, 0, 2, 2))
            / ospf)
            .compile()
            .expect("Ipv4 / simple-password Hello compiles");

        // The AuType (octets 14..16 of the OSPF header) and the authentication
        // field (octets 16..24) appear on the wire. The IPv4 header is 20 octets
        // (no options), so the OSPF header starts at offset 20.
        let raw = bytes.as_bytes();
        let ipv4_header_len = (raw[0] & 0x0f) as usize * 4;
        let ospf = ipv4_header_len;
        assert_eq!(
            &raw[ospf + 14..ospf + 16],
            &OSPF_AUTYPE_SIMPLE.to_be_bytes()
        );
        assert_eq!(
            &raw[ospf + 16..ospf + 24],
            &[b's', b'e', b'c', b'r', b'e', b't', 0, 0]
        );

        // Decoding through the default registry (checksum validation on) recovers
        // the AuType and authentication field, reports a valid checksum (the auth
        // field is excluded from the OSPF checksum), and re-compiles byte-for-byte.
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, raw)
            .expect("the default registry decodes the simple-password Hello");
        let layer = decoded
            .layer::<Ospfv2>()
            .expect("the decoded packet exposes a typed Ospfv2 layer");
        assert_eq!(layer.autype_value(), OSPF_AUTYPE_SIMPLE);
        assert_eq!(
            layer.authentication_value(),
            [b's', b'e', b'c', b'r', b'e', b't', 0, 0]
        );
        assert_eq!(layer.checksum_status(), OspfChecksumStatus::Valid);

        let recompiled = decoded.compile().expect("decoded OSPF re-compiles");
        assert_eq!(recompiled.as_bytes(), raw);
    }

    /// A Hello built with `null_auth()` carries AuType 0 and a zero 8-octet
    /// authentication field (RFC 2328 §D.1).
    #[test]
    fn ospf_null_auth_zeroes_the_auth_field() {
        let ospf = Ospfv2::hello()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .null_auth();

        assert_eq!(ospf.autype_value(), OSPF_AUTYPE_NULL);
        assert_eq!(ospf.authentication_value(), [0; OSPF_AUTH_LEN]);

        let bytes = Packet::from_layer(ospf).compile().unwrap();
        // AuType (octets 14..16) and authentication field (octets 16..24) are zero.
        assert_eq!(&bytes[14..16], &OSPF_AUTYPE_NULL.to_be_bytes());
        assert_eq!(&bytes[16..24], &[0u8; OSPF_AUTH_LEN]);
    }

    /// The `autype` inspection field surfaces the AuType name (RFC 2328 §D)
    /// alongside its numeric value, so the authentication type is inspectable
    /// through `Packet::show()`.
    #[test]
    fn ospf_inspection_surfaces_the_autype_name() {
        let ospf = Ospfv2::hello()
            .router_id([192, 0, 2, 1])
            .simple_password(b"secret");
        let fields = ospf.inspection_fields();
        let autype = fields
            .iter()
            .find(|(name, _)| *name == "autype")
            .map(|(_, value)| value.as_str());
        assert_eq!(autype, Some("1 (Simple)"));

        let null = Ospfv2::hello().router_id([192, 0, 2, 1]).null_auth();
        let null_autype = null
            .inspection_fields()
            .into_iter()
            .find(|(name, _)| *name == "autype")
            .map(|(_, value)| value);
        assert_eq!(null_autype.as_deref(), Some("0 (Null)"));
    }

    /// A Hello built with `crypto_md5_auth(...)` (AuType 2, RFC 2328 §D.3)
    /// compiles with a zero header Checksum, an OSPF Packet Length equal to the
    /// header+body (excluding the appended digest), the structured 8-octet
    /// authentication field, and a 16-octet keyed-MD5 digest trailer that
    /// recomputing with the same key reproduces.
    #[test]
    fn ospf_crypto_md5_auth_zeroes_checksum_and_appends_digest_trailer() {
        let key = b"ospf-secret-key".to_vec();
        let ospf = Ospfv2::hello()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .crypto_md5_auth(7, 0x0000_002a, key.clone());

        // The AuType is cryptographic and the structured auth field carries the
        // Reserved/Key ID/Auth Data Length/Crypto-sequence layout.
        assert_eq!(ospf.autype_value(), OSPF_AUTYPE_CRYPTOGRAPHIC);
        assert_eq!(
            ospf.authentication_value(),
            [
                0x00,
                0x00,
                0x07,
                OSPF_MD5_DIGEST_LEN,
                0x00,
                0x00,
                0x00,
                0x2a
            ]
        );

        // The body-only OSPF packet length (header + Hello body) excludes the
        // 16-octet digest trailer.
        let packet_len = OSPF_HEADER_LEN + ospf.body.encoded_len();

        let bytes = Packet::from_layer(ospf).compile().unwrap();

        // The emitted bytes are the packet plus the 16-octet digest trailer.
        assert_eq!(bytes.len(), packet_len + OSPF_MD5_DIGEST_LEN as usize);

        // The OSPF Packet Length field (octets 2..4) covers only the header+body.
        assert_eq!(&bytes[2..4], &(packet_len as u16).to_be_bytes());

        // The header Checksum field (octets 12..14) is zero for cryptographic
        // authentication (it is not the Internet checksum).
        assert_eq!(&bytes[12..14], &[0u8, 0u8]);

        // The 8-octet authentication field (octets 16..24) is the structured form.
        assert_eq!(
            &bytes[16..24],
            &[
                0x00,
                0x00,
                0x07,
                OSPF_MD5_DIGEST_LEN,
                0x00,
                0x00,
                0x00,
                0x2a
            ]
        );

        // The trailing 16 octets are the keyed-MD5 digest. Recomputing the digest
        // over the packet bytes (everything before the trailer) with the same key
        // reproduces the trailer exactly.
        let trailer = &bytes.as_bytes()[packet_len..];
        assert_eq!(trailer.len(), OSPF_MD5_DIGEST_LEN as usize);
        let recomputed =
            OspfCryptoAuth::new(7, 0x0000_002a, key).md5_digest(&bytes.as_bytes()[..packet_len]);
        assert_eq!(trailer, recomputed);
    }

    /// A crypto-authed Hello honors caller overrides: a pinned (deliberately
    /// malformed) Checksum survives instead of being zeroed, and a pinned
    /// authentication field replaces the structured form, while the recorded key
    /// still drives the appended digest trailer.
    #[test]
    fn ospf_crypto_md5_auth_honors_pinned_checksum_and_authentication() {
        let ospf = Ospfv2::hello()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .crypto_md5_auth(3, 1, b"k".to_vec())
            .checksum(0xbeef)
            .authentication([0xaa; OSPF_AUTH_LEN]);

        let packet_len = OSPF_HEADER_LEN + ospf.body.encoded_len();
        let bytes = Packet::from_layer(ospf).compile().unwrap();

        // The pinned checksum is written verbatim (not zeroed by crypto auth).
        assert_eq!(&bytes[12..14], &0xbeefu16.to_be_bytes());
        // The pinned authentication field is written verbatim.
        assert_eq!(&bytes[16..24], &[0xaau8; OSPF_AUTH_LEN]);
        // The digest trailer is still appended after the packet body.
        assert_eq!(bytes.len(), packet_len + OSPF_MD5_DIGEST_LEN as usize);
    }

    /// A crypto-authed Hello (AuType 2, RFC 2328 §D.3) wrapped in IPv4
    /// (protocol 89), once compiled, decodes through the default registry into a
    /// typed `Ospfv2` layer that exposes the structured Key ID, Auth Data Length,
    /// and Cryptographic sequence number, captures the appended 16-octet keyed-MD5
    /// digest as the `auth_trailer`, reports `NotChecked` (the checksum field is
    /// zero for crypto auth), and re-compiles byte-for-byte even though the decoder
    /// holds no secret key.
    #[test]
    fn ospf_decode_crypto_md5_auth_exposes_fields_and_round_trips_trailer() {
        use crate::packet::NetworkLayer;
        use crate::protocols::ip::v4::Ipv4;

        let key = b"ospf-secret-key".to_vec();
        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(192, 0, 2, 2))
            / Ospfv2::hello()
                .router_id([192, 0, 2, 1])
                .area_id([0, 0, 0, 0])
                .crypto_md5_auth(7, 0x0000_002a, key.clone()))
        .compile()
        .expect("Ipv4 / crypto-MD5 Hello compiles");

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .expect("the default registry decodes the crypto-MD5 Hello");
        let ospf = decoded
            .layer::<Ospfv2>()
            .expect("the decoded packet exposes a typed Ospfv2 layer");

        // The AuType is cryptographic and the structured auth fields are exposed.
        assert_eq!(ospf.autype_value(), OSPF_AUTYPE_CRYPTOGRAPHIC);
        assert_eq!(ospf.crypto_key_id(), Some(7));
        assert_eq!(ospf.crypto_auth_data_length(), Some(OSPF_MD5_DIGEST_LEN));
        assert_eq!(ospf.crypto_sequence_number(), Some(0x0000_002a));

        // The appended digest is captured as a 16-octet trailer and matches the
        // keyed-MD5 digest recomputed over the header+body (excluding the trailer).
        let trailer = ospf.auth_trailer();
        assert_eq!(trailer.len(), OSPF_MD5_DIGEST_LEN as usize);
        let packet_len = OSPF_HEADER_LEN + ospf.body.encoded_len();
        let ipv4_header_len = (bytes.as_bytes()[0] & 0x0f) as usize * 4;
        let ospf_bytes = &bytes.as_bytes()[ipv4_header_len..];
        let recomputed =
            OspfCryptoAuth::new(7, 0x0000_002a, key).md5_digest(&ospf_bytes[..packet_len]);
        assert_eq!(trailer, recomputed);

        // The checksum field is zero for cryptographic auth, so it is NotChecked.
        assert_eq!(ospf.checksum_status(), OspfChecksumStatus::NotChecked);

        // The decoded packet re-compiles byte-for-byte without the secret key:
        // the decoder records no `crypto_auth` params, only the verbatim trailer.
        assert!(ospf.crypto_auth_params().is_none());
        let recompiled = decoded.compile().expect("decoded crypto OSPF re-compiles");
        assert_eq!(recompiled.as_bytes(), bytes.as_bytes());
    }

    /// The structured cryptographic-auth accessors return `None` for a
    /// non-cryptographic AuType, where the 8-octet authentication field is a raw
    /// value rather than the RFC 2328 §D.3 structured form.
    #[test]
    fn ospf_crypto_field_accessors_are_none_for_non_cryptographic_autype() {
        let simple = Ospfv2::hello()
            .router_id([192, 0, 2, 1])
            .simple_password(b"secret");
        assert_eq!(simple.crypto_key_id(), None);
        assert_eq!(simple.crypto_auth_data_length(), None);
        assert_eq!(simple.crypto_sequence_number(), None);
        assert!(simple.auth_trailer().is_empty());
    }

    /// HMAC-SHA-256 cryptographic authentication (RFC 5709) sets the structured
    /// Auth Data Length to 32 and appends a 32-octet HMAC trailer after the OSPF
    /// packet, leaving the OSPF Packet Length covering only the header and body.
    #[test]
    fn ospf_crypto_hmac_sha256_auth_yields_a_32_octet_trailer() {
        let ospf = Ospfv2::hello()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .crypto_auth(
                OspfCryptoAlgorithm::HmacSha256,
                3,
                0x0000_0010,
                b"sha256-key",
            );

        // The structured authentication field carries Key ID 3 and Auth Data
        // Length 32 (RFC 5709 §3.1).
        assert_eq!(ospf.autype_value(), OSPF_AUTYPE_CRYPTOGRAPHIC);
        assert_eq!(ospf.crypto_key_id(), Some(3));
        assert_eq!(ospf.crypto_auth_data_length(), Some(32));
        assert_eq!(ospf.crypto_sequence_number(), Some(0x0000_0010));

        let packet_len = OSPF_HEADER_LEN + ospf.body.encoded_len();
        let bytes = Packet::from_layer(ospf).compile().unwrap();

        // The OSPF Packet Length field counts only header+body (RFC 2328 §D.3),
        // while the emitted bytes carry the extra 32-octet HMAC-SHA-256 trailer.
        assert_eq!(&bytes[2..4], &(packet_len as u16).to_be_bytes());
        assert_eq!(bytes.len(), packet_len + 32);

        // The checksum field is zero for cryptographic authentication.
        assert_eq!(&bytes[12..14], &[0, 0]);

        // The trailer is the HMAC-SHA-256 over the header+body (RFC 5709 §3.3),
        // recomputed independently here to confirm the appended bytes.
        let recomputed = OspfCryptoAuth::with_algorithm(
            OspfCryptoAlgorithm::HmacSha256,
            3,
            0x0000_0010,
            b"sha256-key".to_vec(),
        )
        .digest(&bytes[..packet_len]);
        assert_eq!(&bytes[packet_len..], recomputed.as_slice());
    }

    /// An HMAC-SHA-256 crypto-authed Hello (RFC 5709) wrapped in IPv4
    /// (protocol 89) round-trips byte-for-byte through the default registry: the
    /// decoder captures the 32-octet trailer by the Auth Data Length octet and
    /// re-emits it verbatim without the secret key.
    #[test]
    fn ospf_crypto_hmac_sha256_auth_round_trips_byte_for_byte() {
        use crate::packet::NetworkLayer;
        use crate::protocols::ip::v4::Ipv4;

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(192, 0, 2, 2))
            / Ospfv2::hello()
                .router_id([192, 0, 2, 1])
                .area_id([0, 0, 0, 0])
                .crypto_auth(
                    OspfCryptoAlgorithm::HmacSha256,
                    3,
                    0x0000_0010,
                    b"sha256-key",
                ))
        .compile()
        .expect("Ipv4 / HMAC-SHA-256 Hello compiles");

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .expect("the default registry decodes the HMAC-SHA-256 Hello");
        let ospf = decoded
            .layer::<Ospfv2>()
            .expect("the decoded packet exposes a typed Ospfv2 layer");

        // The 32-octet trailer is captured by the structured Auth Data Length.
        assert_eq!(ospf.crypto_auth_data_length(), Some(32));
        assert_eq!(ospf.auth_trailer().len(), 32);
        assert!(ospf.crypto_auth_params().is_none());

        let recompiled = decoded.compile().expect("decoded HMAC OSPF re-compiles");
        assert_eq!(recompiled.as_bytes(), bytes.as_bytes());
    }

    /// Each cryptographic-auth algorithm (RFC 2328 §D.3 keyed-MD5 and the
    /// RFC 5709 HMAC-SHA family) appends a trailer of exactly its digest length
    /// (16/20/32/48/64) and writes that length into the Auth Data Length octet.
    #[test]
    fn ospf_crypto_auth_each_algorithm_appends_its_digest_length() {
        for (algorithm, digest_len) in [
            (OspfCryptoAlgorithm::KeyedMd5, 16usize),
            (OspfCryptoAlgorithm::HmacSha1, 20),
            (OspfCryptoAlgorithm::HmacSha256, 32),
            (OspfCryptoAlgorithm::HmacSha384, 48),
            (OspfCryptoAlgorithm::HmacSha512, 64),
        ] {
            let ospf = Ospfv2::hello()
                .router_id([192, 0, 2, 1])
                .area_id([0, 0, 0, 0])
                .crypto_auth(algorithm, 1, 0x0000_0001, b"shared-secret");

            // The Auth Data Length octet records the algorithm's digest size.
            assert_eq!(ospf.crypto_auth_data_length(), Some(digest_len as u8));

            let packet_len = OSPF_HEADER_LEN + ospf.body.encoded_len();
            let bytes = Packet::from_layer(ospf).compile().unwrap();

            // The emitted bytes are the OSPF packet plus exactly the algorithm's
            // digest-length trailer (RFC 2328 §D.3 / RFC 5709 §3.1).
            assert_eq!(bytes.len(), packet_len + digest_len);
            assert_eq!(&bytes[2..4], &(packet_len as u16).to_be_bytes());
        }
    }

    /// The three RFC 2328 §D length/checksum invariants hold together for every
    /// authentication type when an OSPF Hello is wrapped in IPv4 (protocol 89):
    ///
    /// 1. the OSPF Packet Length field covers only the 24-octet common header plus
    ///    the body and excludes any appended cryptographic digest trailer;
    /// 2. the enclosing IPv4 total length covers the 20-octet IPv4 header plus the
    ///    OSPF header, body, and the digest trailer (the trailer is OSPF bytes on
    ///    the wire, just not in the OSPF Packet Length field);
    /// 3. the OSPF header Checksum is the standard Internet checksum for null and
    ///    simple-password auth (decoded as [`OspfChecksumStatus::Valid`]) and is
    ///    zero for cryptographic auth (decoded as [`OspfChecksumStatus::NotChecked`]).
    ///
    /// Every variant also round-trips byte-for-byte through the default registry.
    #[test]
    fn ospf_auth_length_and_checksum_invariants_hold_across_all_auth_types() {
        use crate::packet::NetworkLayer;
        use crate::protocols::ip::v4::Ipv4;

        // The IPv4 header is 20 octets (no options) for every case below.
        const IPV4_HEADER_LEN: usize = 20;

        // Each case: a label, the OSPF Hello layer, the expected digest-trailer
        // length (0 for non-crypto), whether the OSPF checksum is the Internet
        // checksum (so it validates) or a zeroed crypto checksum.
        enum Check {
            /// Internet-checksum auth: the decoded checksum status is `Valid`.
            Validated,
            /// Cryptographic auth: the OSPF checksum field is zero and the decoded
            /// status is `NotChecked`.
            Crypto,
        }

        let cases: Vec<(&str, Ospfv2, usize, Check)> = vec![
            (
                "null",
                Ospfv2::hello()
                    .router_id([192, 0, 2, 1])
                    .area_id([0, 0, 0, 0])
                    .null_auth(),
                0,
                Check::Validated,
            ),
            (
                "simple",
                Ospfv2::hello()
                    .router_id([192, 0, 2, 1])
                    .area_id([0, 0, 0, 0])
                    .simple_password(b"secret"),
                0,
                Check::Validated,
            ),
            (
                "keyed-md5",
                Ospfv2::hello()
                    .router_id([192, 0, 2, 1])
                    .area_id([0, 0, 0, 0])
                    .crypto_md5_auth(7, 0x0000_002a, b"ospf-secret-key".to_vec()),
                OSPF_MD5_DIGEST_LEN as usize,
                Check::Crypto,
            ),
            (
                "hmac-sha256",
                Ospfv2::hello()
                    .router_id([192, 0, 2, 1])
                    .area_id([0, 0, 0, 0])
                    .crypto_auth(
                        OspfCryptoAlgorithm::HmacSha256,
                        3,
                        0x0000_0010,
                        b"sha256-key",
                    ),
                OSPF_HMAC_SHA256_DIGEST_LEN as usize,
                Check::Crypto,
            ),
        ];

        for (label, ospf, trailer_len, check) in cases {
            // Body length is the same for every Hello here, but read it from the
            // built layer so the assertions stay independent of that detail.
            let body_len = ospf.body.encoded_len();
            // Invariant (1): OSPF Packet Length = 24-octet header + body, trailer
            // excluded.
            let ospf_packet_len = OSPF_HEADER_LEN + body_len;

            let bytes = (Ipv4::new()
                .src(Ipv4Addr::new(192, 0, 2, 1))
                .dst(Ipv4Addr::new(192, 0, 2, 2))
                / ospf)
                .compile()
                .unwrap_or_else(|e| panic!("{label}: Ipv4 / Ospfv2 Hello compiles: {e}"));
            let raw = bytes.as_bytes();

            // The OSPF layer begins right after the 20-octet IPv4 header.
            let ipv4_header_len = (raw[0] & 0x0f) as usize * 4;
            assert_eq!(ipv4_header_len, IPV4_HEADER_LEN, "{label}: IPv4 header len");

            // Invariant (1): the OSPF Packet Length field (header octets 2..4)
            // covers only header+body, never the trailer.
            assert_eq!(
                &raw[ipv4_header_len + 2..ipv4_header_len + 4],
                &(ospf_packet_len as u16).to_be_bytes(),
                "{label}: OSPF Packet Length must equal header+body"
            );

            // The on-wire OSPF region (header + body + trailer) is what IPv4 must
            // count, so the appended trailer is part of the OSPF bytes.
            let ospf_on_wire_len = ospf_packet_len + trailer_len;
            assert_eq!(
                raw.len() - ipv4_header_len,
                ospf_on_wire_len,
                "{label}: OSPF on-wire length includes the digest trailer"
            );

            // Invariant (2): the IPv4 total length field (octets 2..4) equals
            // 20 + header + body + trailer.
            let expected_ipv4_total = IPV4_HEADER_LEN + ospf_on_wire_len;
            assert_eq!(
                &raw[2..4],
                &(expected_ipv4_total as u16).to_be_bytes(),
                "{label}: IPv4 total length must include the digest trailer"
            );
            assert_eq!(
                raw.len(),
                expected_ipv4_total,
                "{label}: total emitted bytes match the IPv4 total length"
            );

            // Invariant (3): the OSPF header Checksum field (octets 12..14).
            let ospf_checksum = &raw[ipv4_header_len + 12..ipv4_header_len + 14];
            match check {
                Check::Validated => {
                    // Null/simple auth carries the (nonzero) Internet checksum.
                    assert_ne!(
                        ospf_checksum,
                        &[0u8, 0u8],
                        "{label}: Internet checksum must be filled"
                    );
                }
                Check::Crypto => {
                    // Cryptographic auth zeroes the checksum field (RFC 2328 §D.3).
                    assert_eq!(
                        ospf_checksum,
                        &[0u8, 0u8],
                        "{label}: crypto-auth checksum field must be zero"
                    );
                }
            }

            // Decode through the default registry (checksum validation on) and
            // confirm the decode-time checksum status matches the auth class.
            let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, raw)
                .unwrap_or_else(|e| panic!("{label}: default registry decodes OSPF: {e}"));
            let layer = decoded
                .layer::<Ospfv2>()
                .unwrap_or_else(|| panic!("{label}: decoded packet exposes a typed Ospfv2 layer"));
            let expected_status = match check {
                Check::Validated => OspfChecksumStatus::Valid,
                Check::Crypto => OspfChecksumStatus::NotChecked,
            };
            assert_eq!(
                layer.checksum_status(),
                expected_status,
                "{label}: decode-time checksum status"
            );

            // Every variant round-trips byte-for-byte.
            let recompiled = decoded
                .compile()
                .unwrap_or_else(|e| panic!("{label}: decoded OSPF re-compiles: {e}"));
            assert_eq!(
                recompiled.as_bytes(),
                raw,
                "{label}: OSPF re-compiles byte-for-byte"
            );
        }
    }

    /// A combined options/flags round-trip: a Hello carrying several Options bits
    /// (RFC 2328 §A.2), a Database Description carrying I+M+MS (RFC 2328 §A.3.3),
    /// and a Router-LSA carrying V+E+B (RFC 2328 §A.4.2) each compile through
    /// IPv4, decode through the default registry, round-trip byte-for-byte, and
    /// preserve every option/flag bit with its `summary()` label intact.
    #[test]
    fn ospf_combined_options_and_flags_round_trip_with_labels() {
        use crate::packet::NetworkLayer;
        use crate::protocols::ip::v4::Ipv4;
        use crate::protocols::ospf::lsa::{
            OspfLsa, OspfLsaBody, OspfLsaHeader, OspfRouterLsa, OSPF_LSA_ROUTER,
            OSPF_ROUTER_LSA_FLAG_B, OSPF_ROUTER_LSA_FLAG_E, OSPF_ROUTER_LSA_FLAG_V,
        };
        use crate::protocols::ospf::packet::database_description::{
            OSPF_DD_FLAG_I, OSPF_DD_FLAG_M, OSPF_DD_FLAG_MS,
        };

        // Helper: wrap an OSPF layer in IPv4, compile, decode via the default
        // registry, and assert a byte-for-byte round-trip, returning the decoded
        // Ospfv2 layer for further field assertions.
        fn round_trip(ospf: Ospfv2) -> Ospfv2 {
            let bytes = (Ipv4::new()
                .src(Ipv4Addr::new(192, 0, 2, 1))
                .dst(Ipv4Addr::new(192, 0, 2, 2))
                / ospf)
                .compile()
                .expect("Ipv4 / Ospfv2 compiles");
            let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
                .expect("the default registry decodes OSPF over IPv4");
            let recompiled = decoded.compile().expect("decoded OSPF re-compiles");
            assert_eq!(
                recompiled.as_bytes(),
                bytes.as_bytes(),
                "OSPF re-compiles byte-for-byte"
            );
            decoded
                .layer::<Ospfv2>()
                .expect("the decoded packet exposes a typed Ospfv2 layer")
                .clone()
        }

        // --- Hello: multiple Options bits (E | O | DC). ----------------------
        let options = OSPF_OPTIONS_E | OSPF_OPTIONS_O | OSPF_OPTIONS_DC;
        let hello = Ospfv2::hello()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .with_hello(|h| {
                *h = h.clone().options(options);
            });
        let decoded_hello = round_trip(hello);
        let hello_body = match &decoded_hello.body {
            OspfBody::Hello(hello) => hello,
            other => panic!("expected a typed Hello body, got {other:?}"),
        };
        // Every Options bit survives the round-trip.
        assert_eq!(hello_body.options_value(), options);
        assert_eq!(hello_body.options_value() & OSPF_OPTIONS_E, OSPF_OPTIONS_E);
        assert_eq!(hello_body.options_value() & OSPF_OPTIONS_O, OSPF_OPTIONS_O);
        assert_eq!(
            hello_body.options_value() & OSPF_OPTIONS_DC,
            OSPF_OPTIONS_DC
        );
        // The exported summary helper renders the bits in ascending order.
        assert_eq!(ospf_options_summary(hello_body.options_value()), "E|DC|O");

        // --- Database Description: I + M + MS flags. -------------------------
        let dd = Ospfv2::database_description()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .with_database_description(|d| {
                *d = d.clone().init(true).more(true).master(true);
            });
        let decoded_dd = round_trip(dd);
        let dd_body = match &decoded_dd.body {
            OspfBody::DatabaseDescription(dd) => dd,
            other => panic!("expected a typed Database Description body, got {other:?}"),
        };
        // Each DD flag bit round-trips.
        assert_eq!(
            dd_body.flags_value(),
            OSPF_DD_FLAG_I | OSPF_DD_FLAG_M | OSPF_DD_FLAG_MS
        );
        assert!(dd_body.is_init());
        assert!(dd_body.is_more());
        assert!(dd_body.is_master());
        // The DD flags summary renders I|M|MS.
        assert_eq!(dd_body.dd_flags_summary(), "I|M|MS");

        // --- Router-LSA: V + E + B flags. -----------------------------------
        let router = OspfRouterLsa::new().virtual_link().external().border();
        let lsa = OspfLsa::new(
            OspfLsaHeader::new()
                .ls_type(OSPF_LSA_ROUTER)
                .link_state_id(Ipv4Addr::new(192, 0, 2, 1))
                .advertising_router(Ipv4Addr::new(192, 0, 2, 1))
                .ls_sequence_number(0x8000_0001),
            OspfLsaBody::Router(router),
        );
        let lsu = Ospfv2::link_state_update()
            .router_id([192, 0, 2, 1])
            .area_id([0, 0, 0, 0])
            .with_link_state_update(|u| {
                *u = u.clone().lsa(lsa);
            });
        let decoded_lsu = round_trip(lsu);
        let lsu_body = match &decoded_lsu.body {
            OspfBody::LinkStateUpdate(lsu) => lsu,
            other => panic!("expected a typed Link State Update body, got {other:?}"),
        };
        let decoded_lsas = lsu_body.lsas_value();
        assert_eq!(decoded_lsas.len(), 1);
        let decoded_router = match &decoded_lsas[0].body {
            OspfLsaBody::Router(router) => router,
            other => panic!("expected a typed Router-LSA body, got {other:?}"),
        };
        // Each Router-LSA flag bit round-trips.
        assert_eq!(
            decoded_router.flags_value(),
            OSPF_ROUTER_LSA_FLAG_V | OSPF_ROUTER_LSA_FLAG_E | OSPF_ROUTER_LSA_FLAG_B
        );
        assert!(decoded_router.is_virtual());
        assert!(decoded_router.is_external());
        assert!(decoded_router.is_border());
        // The Router-LSA flags summary renders V|E|B.
        assert_eq!(decoded_router.router_flags_summary(), "V|E|B");
    }
}