blvm-node 0.1.54

Bitcoin Commons BLVM: Minimal Bitcoin node implementation using blvm-protocol and blvm-consensus
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
//! Coordinator / admit / ahead-policy tests extracted from `mod.rs`.
//! Complements `chunk_assigner_tests` (assignment) and `download_tests` (pipe).

use super::*;
use std::collections::VecDeque;

#[serial_test::serial(ibd)]
#[test]
fn a5_tip_admit_tight_aligns_ahead_cap_with_admit() {
    // SAFETY: single-threaded test; env restored before exit.
    unsafe {
        std::env::remove_var("BLVM_IBD_TIP_ADMIT_TIGHT");
        let (_, cap_default) = wan_ahead_policy(true, true, true, 2);
        assert_eq!(
            cap_default,
            wan_bulk_tip_gap_ahead_cap(),
            "default tip-starve ahead stays tip-gap cap (256)"
        );
        std::env::set_var("BLVM_IBD_TIP_ADMIT_TIGHT", "1");
        let (kind, cap) = wan_ahead_policy(true, true, true, 2);
        assert_eq!(kind, "wan_tip_tight");
        assert_eq!(
            cap,
            wan_gap_admit_window(),
            "TIGHT tip-starve ahead must match admit window (A5 KEEP; A6 tip-first REVERT)"
        );
        // Sole + GD_SLOW: do not deepen starve under wan_tip_tight.
        tip_stage::test_seed_getdata_body_ewma(1_500, 32);
        let (kind_sole, cap_sole) = wan_ahead_policy(true, true, true, 1);
        assert_eq!(kind_sole, "wan_bulk_gap_sole");
        assert_eq!(cap_sole, wan_bulk_tip_gap_ahead_cap());
        tip_stage::test_reset_getdata_body_ewma();
        std::env::remove_var("BLVM_IBD_TIP_ADMIT_TIGHT");
    }
}

#[serial_test::serial(ibd)]
#[test]
fn a4_tip_admit_tight_opt_in_ignores_bulk_catchup() {
    // SAFETY: single-threaded test; env restored before exit.
    unsafe {
        // Default (tight off): tip+bulk still selects bulk admit (pre-A4 public DNA).
        std::env::remove_var("BLVM_IBD_TIP_ADMIT_TIGHT");
        assert!(!tip_admit_tight_enabled());
        assert_eq!(
            effective_gap_admit_window(true, true),
            wan_bulk_admit_window(),
            "default tip+bulk must keep bulk admit until public confirm"
        );
        assert_eq!(
            effective_gap_admit_window(true, false),
            wan_gap_admit_window()
        );
        // Opt-in tight: tip crawl ignores bulk (archive fabric KEEP mech).
        std::env::set_var("BLVM_IBD_TIP_ADMIT_TIGHT", "1");
        assert!(tip_admit_tight_enabled());
        assert_eq!(
            effective_gap_admit_window(true, true),
            wan_gap_admit_window(),
            "TIP_ADMIT_TIGHT=1 must ignore bulk catchup"
        );
        std::env::remove_var("BLVM_IBD_TIP_ADMIT_TIGHT");
        // Pre-tip / LOCAL_GAP path unchanged.
        assert_eq!(effective_gap_admit_window(false, true), gap_admit_window());
        assert_eq!(effective_gap_admit_window(false, false), gap_admit_window());
    }
}

#[serial_test::serial(ibd)]
#[test]
fn c1f_tip_runway_mode_classifies_tip_hole_ahead() {
    assert_eq!(
        tip_runway_mode(false, 0, 64, 0, false),
        "TIP_HOLE_AHEAD",
        "holes=0 + ahead buffered + tip missing must not look like filled runway"
    );
    assert_eq!(tip_runway_mode(false, 0, 0, 0, false), "EMPTY_TIP");
    assert_eq!(tip_runway_mode(true, 32, 0, 0, false), "FILLED_RUNWAY");
    assert_eq!(tip_runway_mode(true, 8, 20, 12, false), "CHEESE");
    // C1q: tip in feeder + ahead buffered = filled runway (not TIP_HOLE_AHEAD).
    assert_eq!(
        tip_runway_mode(false, 0, 64, 0, true),
        "FILLED_RUNWAY",
        "tip in feeder must not be classified as tip hole"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn tip_nudge_skips_healthy_handoff_shapes() {
    // True TIP_HOLE_AHEAD / EMPTY_TIP — nudge allowed.
    assert!(tip_nudge_true_body_gap(false, false, false, false));
    // Healthy handoff: tip left reorder into feeder / bridge / validation.
    assert!(
        !tip_nudge_true_body_gap(false, true, false, false),
        "tip in feeder must not TIP_NUDGE"
    );
    assert!(
        !tip_nudge_true_body_gap(false, false, true, false),
        "tip in bridge pending must not TIP_NUDGE"
    );
    assert!(
        !tip_nudge_true_body_gap(false, false, false, true),
        "tip_taken must not TIP_NUDGE (dens: covering thrash)"
    );
    assert!(
        !tip_nudge_true_body_gap(true, false, false, false),
        "tip in reorder needs no nudge"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn pinned_ibd_peers_skips_archive_dns_seed() {
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _g = LOCK.lock().unwrap();
    unsafe {
        std::env::remove_var("BLVM_IBD_PEERS");
    }
    assert!(!skip_ibd_archive_dns_seed());
    unsafe {
        std::env::set_var("BLVM_IBD_PEERS", "127.0.0.1:18333");
    }
    assert!(skip_ibd_archive_dns_seed());
    unsafe {
        std::env::remove_var("BLVM_IBD_PEERS");
    }
}

#[serial_test::serial(ibd)]
#[test]
fn c1f_reorder_contig_runway_counts_from_tip() {
    use std::sync::Arc;
    let mut reorder: std::collections::BTreeMap<u64, (SharedBlock, SharedWitnesses)> =
        std::collections::BTreeMap::new();
    let tip = 100u64;
    // Tip hole, ahead present — contig=0, ahead=2
    let dummy_block = Arc::new(Block {
        header: BlockHeader {
            version: 1,
            timestamp: 1,
            ..Default::default()
        },
        transactions: vec![].into(),
    });
    let dummy_w: SharedWitnesses = Arc::new(vec![]);
    reorder.insert(tip + 2, (dummy_block.clone(), dummy_w.clone()));
    reorder.insert(tip + 3, (dummy_block.clone(), dummy_w.clone()));
    assert_eq!(reorder_contig_runway(&reorder, tip), 0);
    assert_eq!(reorder_ahead_buffered(&reorder, tip), 2);
    assert_eq!(reorder_first_ahead(&reorder, tip), Some(tip + 2));
    // Fill tip..tip+1 → contiguous through tip+3 (already buffered).
    reorder.insert(tip, (dummy_block.clone(), dummy_w.clone()));
    reorder.insert(tip + 1, (dummy_block, dummy_w));
    assert_eq!(reorder_contig_runway(&reorder, tip), 4);
}

/// Isolate tests from shell `BLVM_IBD_*` (e.g. left over from manual IBD runs).
fn with_ibd_env_cleared<F: FnOnce()>(f: F) {
    let peers = std::env::var("BLVM_IBD_PEERS").ok();
    let mode = std::env::var("BLVM_IBD_MODE").ok();
    let wan_single = std::env::var("BLVM_IBD_WAN_SINGLE_PEER").ok();
    unsafe {
        std::env::remove_var("BLVM_IBD_PEERS");
        std::env::remove_var("BLVM_IBD_MODE");
        std::env::remove_var("BLVM_IBD_WAN_SINGLE_PEER");
    }
    f();
    unsafe {
        if let Some(v) = peers {
            std::env::set_var("BLVM_IBD_PEERS", v);
        } else {
            std::env::remove_var("BLVM_IBD_PEERS");
        }
        if let Some(v) = mode {
            std::env::set_var("BLVM_IBD_MODE", v);
        } else {
            std::env::remove_var("BLVM_IBD_MODE");
        }
        if let Some(v) = wan_single {
            std::env::set_var("BLVM_IBD_WAN_SINGLE_PEER", v);
        } else {
            std::env::remove_var("BLVM_IBD_WAN_SINGLE_PEER");
        }
    }
}

/// N15: engine admit leaves tx_ids empty; legacy still fills.
#[serial_test::serial(ibd)]
#[test]
fn n15_prepare_coord_dispatch_defers_engine_txids() {
    use blvm_protocol::{Transaction, TransactionOutput};
    let block = Block {
        header: BlockHeader {
            version: 1,
            timestamp: 1,
            ..Default::default()
        },
        transactions: vec![Transaction {
            version: 1,
            inputs: blvm_protocol::tx_inputs![],
            outputs: blvm_protocol::tx_outputs![TransactionOutput {
                value: 50,
                script_pubkey: vec![0x51],
            }],
            lock_time: 0,
        }]
        .into(),
    };
    let mut tx_ids = vec![[9u8; 32]];
    let mut keys = vec![[1u8; 40]];
    prepare_coord_dispatch_bufs(true, &block, &mut tx_ids, &mut keys);
    assert!(tx_ids.is_empty(), "engine defer: no SHA on admit");
    assert!(keys.is_empty());
    // Validation-side fill matches non-empty hash count.
    compute_tx_ids_only(&block, &mut tx_ids);
    assert_eq!(tx_ids.len(), block.transactions.len());
}

#[serial_test::serial(ibd)]
#[test]
fn phase3_path_promotes_when_tip_ckpt_ready() {
    use crate::storage::ibd_engine::{Phase3Finish, phase3_path};
    assert_eq!(
        phase3_path(957_950, 957_950, 957_950, true),
        Phase3Finish::PromotedAlias
    );
}

#[serial_test::serial(ibd)]
#[test]
fn phase3_path_catchup_when_export_lags_tip() {
    use crate::storage::ibd_engine::{Phase3Finish, phase3_path};
    // Live soak: export_h=880k, tip=957950, nonempty ckpt at 880k.
    assert_eq!(
        phase3_path(880_000, 957_950, 880_000, true),
        Phase3Finish::CatchupThenAlias
    );
}

#[serial_test::serial(ibd)]
#[test]
fn phase3_path_full_when_no_ckpt() {
    use crate::storage::ibd_engine::{Phase3Finish, phase3_path};
    assert_eq!(
        phase3_path(0, 100_000, 0, false),
        Phase3Finish::FullWatermarkExport
    );
}

#[serial_test::serial(ibd)]
#[test]
fn export_isolation_inactive_when_export_not_running() {
    // Regardless of env, isolation cannot be "active" without an in-flight export.
    IBD_CHECKPOINT_EXPORT_ACTIVE.store(false, Ordering::Relaxed);
    assert!(!export_isolation_active());
}

fn engine_gap_export_defer_until_height_cases() {
    // Live zeus: wm=230k, start=230001, RAM replay cap=172791 < start → no defer.
    assert_eq!(
        engine_gap_export_defer_until_height(230_001, 172_791, 957_272),
        0
    );
    // Active local replay window: defer through min(bodies, tip).
    assert_eq!(
        engine_gap_export_defer_until_height(230_001, 657_030, 957_272),
        657_030
    );
    // Fresh start from genesis with RAM cap.
    assert_eq!(
        engine_gap_export_defer_until_height(1, 200_000, 500_000),
        200_000
    );
}

#[serial_test::serial(ibd)]
#[test]
fn bps_scaling_shrinks_interval_when_validation_is_slow() {
    let d = crate::config::ibd::IbdEngineDurabilityConfig {
        checkpoint_interval: None,
        checkpoint_min_interval: 500,
        checkpoint_max_interval: 50_000,
        checkpoint_target_secs: 60,
        muhash_persist_interval: 200,
    };
    // Cheap last export → BPS may shrink for resume tightness.
    let utxo_iv = utxo_scaled_checkpoint_interval(640_068_968, 30.0, &d);
    assert_eq!(utxo_iv, 80_000);
    let slow_cap = bps_scaled_checkpoint_interval_cap(2.0, 60, 500, utxo_iv);
    let mid_cap = bps_scaled_checkpoint_interval_cap(16.0, 60, 500, utxo_iv);
    let fast_cap = bps_scaled_checkpoint_interval_cap(80.0, 60, 500, utxo_iv);
    assert_eq!(
        slow_cap, 500,
        "2 bps × 60s = 120, clamped to min_interval 500"
    );
    assert_eq!(mid_cap, 960, "16 bps × 60s");
    assert_eq!(fast_cap, 4800, "80 bps × 60s");
    assert!(slow_cap < mid_cap && mid_cap < fast_cap && fast_cap < utxo_iv);
    assert_eq!(
        adaptive_checkpoint_interval(640_068_968, 30.0, 16.0, &d),
        960,
        "cheap export + slow BPS → resume-tight interval"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn w173_expensive_midchain_export_keeps_sparse_interval() {
    // Live W173: TARGET_SECS=300, ~50M UTXOs, 90–208s piggyback walls, tip60~80–100.
    // Old scaler: BASE*25M/count → ~5k, duration scale never fired (175 < 300),
    // BPS min() kept ~5k → 10 full exports in ~26 min.
    let d = crate::config::ibd::IbdEngineDurabilityConfig {
        checkpoint_interval: None,
        checkpoint_min_interval: 500,
        checkpoint_max_interval: 50_000,
        checkpoint_target_secs: 300,
        muhash_persist_interval: 200,
    };
    let utxo_iv = utxo_scaled_checkpoint_interval(50_000_000, 175.0, &d);
    assert_eq!(utxo_iv, 50_000, "≥40M UTXOs → high-UTXO ceiling");
    let adaptive = adaptive_checkpoint_interval(50_000_000, 175.0, 80.0, &d);
    assert_eq!(
        adaptive, 50_000,
        "expensive export must not be undercut by BPS×target (80×300=24k)"
    );
    // Below HIGH threshold: interval grows with UTXO count (never shrinks).
    let early = utxo_scaled_checkpoint_interval(30_000_000, 100.0, &d);
    assert!(
        early >= 20_000,
        "30M UTXOs + 100s export must stay sparse, got {early}"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn w175_restored_midchain_export_wall_counts_expensive() {
    // Live W174: restored last_export_wall_secs=81, utxos≈25.6M, TARGET=300.
    // Threshold was min(target,90)=90 → 81 treated cheap → BPS interval 7890.
    let d = crate::config::ibd::IbdEngineDurabilityConfig {
        checkpoint_interval: None,
        checkpoint_min_interval: 500,
        checkpoint_max_interval: 50_000,
        checkpoint_target_secs: 300,
        muhash_persist_interval: 200,
    };
    assert_eq!(export_cost_scale_threshold_secs(300), 60.0);
    let adaptive = adaptive_checkpoint_interval(25_643_324, 81.0, 26.3, &d);
    assert!(
        adaptive >= 20_000,
        "restored 81s wall must not be BPS-undercut to ~7.8k, got {adaptive}"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn aligned_checkpoint_height_steps_from_last_exported() {
    // Live soak: export_h=880000, 80k global alignment missed 931k; relative 960 iv catches up.
    assert_eq!(aligned_checkpoint_height(931_000, 880_000, 80_000), 880_000);
    assert_eq!(aligned_checkpoint_height(931_000, 880_000, 960), 930_880);
    assert_eq!(aligned_checkpoint_height(880_960, 880_000, 960), 880_960);
    assert_eq!(aligned_checkpoint_height(880_959, 880_000, 960), 880_000);
}

#[serial_test::serial(ibd)]
#[test]
fn checkpoint_export_requires_validation_caught_up() {
    // Live 2026-07-14: CL claimed 49716 while vh was ~5800 — must not export 40000.
    assert!(!checkpoint_export_validation_caught_up(40_000, 5_800));
    assert!(!checkpoint_export_validation_caught_up(40_000, 39_999));
    assert!(checkpoint_export_validation_caught_up(40_000, 40_000));
    assert!(checkpoint_export_validation_caught_up(40_000, 48_702));
    assert!(!checkpoint_export_validation_caught_up(0, 100));
}

#[serial_test::serial(ibd)]
#[test]
fn w75_tip_gap_body_in_pipeline_requires_pending_or_feeder() {
    // Live 344348: bridge_next==tip with pending=0 must fall through to Case C.
    // W78: second arg is tip_in_feeder (bool), not feeder_len.
    assert!(!tip_gap_body_in_pipeline(false, false));
    assert!(tip_gap_body_in_pipeline(true, false));
    assert!(tip_gap_body_in_pipeline(false, true));
    assert!(tip_gap_body_in_pipeline(true, true));
}

#[serial_test::serial(ibd)]
#[test]
fn w78_feeder_len_alone_is_not_in_pipeline() {
    // Live 381335: feeder=46 / gap_missing / bridge_next>>tip — must not short-circuit.
    assert!(
        !tip_gap_body_in_pipeline(false, false),
        "occupancy without tip key must fall through to Case C / TIP_REWIND"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn w79_export_gate_steady_state_ok_and_stall_defers() {
    // Live genesis→250k: gap_missing+feeder=0 forever under W75 → zero exports.
    // Single test: shared atomics race if split across threads.
    let prev_kill = std::env::var_os("BLVM_PROC_ANON_KILL_MB");
    // SAFETY: test-only env mutation; restored below.
    unsafe {
        std::env::set_var("BLVM_PROC_ANON_KILL_MB", "999999999");
    }
    IBD_TIP_GAP_MISSING.store(true, Ordering::Relaxed);
    IBD_FEEDER_BUFFER_BLOCKS.store(0, Ordering::Relaxed);
    IBD_FEEDER_BUFFER_CAP.store(128, Ordering::Relaxed);
    IBD_VALIDATION_STALL_WALL_MS.store(0, Ordering::Relaxed);
    tip_stage::clear_tip_ahead_soft_freeze();
    tip_stage::mark_needed(9_000_001);
    assert!(
        export_start_gate_allows(),
        "healthy WAN tip crawl must allow periodic checkpoint export"
    );

    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0);
    IBD_VALIDATION_STALL_WALL_MS.store(now_ms, Ordering::Relaxed);
    assert!(!export_start_gate_allows());
    IBD_VALIDATION_STALL_WALL_MS.store(0, Ordering::Relaxed);
    assert!(export_start_gate_allows());

    IBD_TIP_GAP_MISSING.store(false, Ordering::Relaxed);
    IBD_FEEDER_BUFFER_BLOCKS.store(64, Ordering::Relaxed);
    // SAFETY: restore prior test env.
    unsafe {
        match prev_kill {
            Some(v) => std::env::set_var("BLVM_PROC_ANON_KILL_MB", v),
            None => std::env::remove_var("BLVM_PROC_ANON_KILL_MB"),
        }
    }
}

#[serial_test::serial(ibd)]
#[test]
fn w174_export_gate_defers_on_severe_tip_holes() {
    let prev_kill = std::env::var_os("BLVM_PROC_ANON_KILL_MB");
    unsafe {
        std::env::set_var("BLVM_PROC_ANON_KILL_MB", "999999999");
    }
    IBD_VALIDATION_STALL_WALL_MS.store(0, Ordering::Relaxed);
    tip_stage::clear_tip_ahead_soft_freeze();
    tip_stage::mark_needed(9_000_002);
    // Fresh mark_needed → awaiting≈0 so W176 awaiting≥5 path stays off.
    IBD_TIP_GAP_MISSING.store(true, Ordering::Relaxed);
    IBD_TIP_BRIDGE_HOLES.store(15, Ordering::Relaxed);
    assert!(
        export_start_gate_allows(),
        "holes=15 must still allow export (W176 threshold 16)"
    );
    IBD_TIP_BRIDGE_HOLES.store(16, Ordering::Relaxed);
    assert!(
        !export_start_gate_allows(),
        "holes≥16 + gap_missing must defer export (W176; was 32)"
    );
    IBD_TIP_GAP_MISSING.store(false, Ordering::Relaxed);
    assert!(
        export_start_gate_allows(),
        "holes alone without gap_missing must not defer"
    );
    IBD_TIP_BRIDGE_HOLES.store(0, Ordering::Relaxed);
    unsafe {
        match prev_kill {
            Some(v) => std::env::set_var("BLVM_PROC_ANON_KILL_MB", v),
            None => std::env::remove_var("BLVM_PROC_ANON_KILL_MB"),
        }
    }
}

#[serial_test::serial(ibd)]
#[test]
fn w176_export_gate_defers_when_tip_already_awaiting() {
    let prev_kill = std::env::var_os("BLVM_PROC_ANON_KILL_MB");
    unsafe {
        std::env::set_var("BLVM_PROC_ANON_KILL_MB", "999999999");
    }
    IBD_VALIDATION_STALL_WALL_MS.store(0, Ordering::Relaxed);
    tip_stage::clear_tip_ahead_soft_freeze();
    tip_stage::mark_needed(9_000_003);
    tip_stage::test_backdate_awaiting_ms(6_000);
    IBD_TIP_GAP_MISSING.store(true, Ordering::Relaxed);
    IBD_TIP_BRIDGE_HOLES.store(0, Ordering::Relaxed);
    assert!(
        !export_start_gate_allows(),
        "gap_missing + awaiting≥5s must defer export (W176)"
    );
    // Body landed → late-body freeze clears; gap_missing false → awaiting gate off.
    tip_stage::mark_body(9_000_003);
    IBD_TIP_GAP_MISSING.store(false, Ordering::Relaxed);
    assert!(
        export_start_gate_allows(),
        "healthy tip (body landed, no gap) must allow export"
    );
    tip_stage::mark_needed(0);
    unsafe {
        match prev_kill {
            Some(v) => std::env::set_var("BLVM_PROC_ANON_KILL_MB", v),
            None => std::env::remove_var("BLVM_PROC_ANON_KILL_MB"),
        }
    }
}

#[serial_test::serial(ibd)]
#[test]
fn w177_export_gate_defers_during_local_body_ahead() {
    let prev_kill = std::env::var_os("BLVM_PROC_ANON_KILL_MB");
    unsafe {
        std::env::set_var("BLVM_PROC_ANON_KILL_MB", "999999999");
    }
    IBD_VALIDATION_STALL_WALL_MS.store(0, Ordering::Relaxed);
    tip_stage::clear_tip_ahead_soft_freeze();
    IBD_TIP_GAP_MISSING.store(false, Ordering::Relaxed);
    IBD_TIP_BRIDGE_HOLES.store(0, Ordering::Relaxed);
    IBD_LOCAL_BODY_AHEAD.store(true, Ordering::Relaxed);
    assert!(
        !export_start_gate_allows(),
        "local body ahead must defer export (W177 soft-resume)"
    );
    IBD_LOCAL_BODY_AHEAD.store(false, Ordering::Relaxed);
    assert!(
        export_start_gate_allows(),
        "past body tip must allow export when tip healthy"
    );
    unsafe {
        match prev_kill {
            Some(v) => std::env::set_var("BLVM_PROC_ANON_KILL_MB", v),
            None => std::env::remove_var("BLVM_PROC_ANON_KILL_MB"),
        }
    }
}

#[serial_test::serial(ibd)]
#[test]
fn ibd_block_flush_opts_default_enables_parallel_serialize() {
    let opts = IbdBlockFlushOpts::default();
    assert!(opts.parallel_serialize);
    assert!(!opts.log_progress);
}

#[serial_test::serial(ibd)]
#[test]
fn ibd_block_flush_opts_shutdown_sync_is_serial_with_progress() {
    let opts = IbdBlockFlushOpts::shutdown_sync();
    assert!(!opts.parallel_serialize);
    assert!(opts.log_progress);
}

#[serial_test::serial(ibd)]
#[test]
fn test_parallel_ibd_config_default() {
    let config = ParallelIBDConfig::default();
    assert!(config.num_workers > 0);
    // chunk_size: 128 default, or BLVM_IBD_CHUNK_SIZE (16-2000) if set
    assert!(
        config.chunk_size >= 16 && config.chunk_size <= 2000,
        "chunk_size={}",
        config.chunk_size
    );
    assert_eq!(config.max_concurrent_per_peer, 64);
}

#[serial_test::serial(ibd)]
#[test]
fn empty_blvm_ibd_peers_env_allows_auto_lan() {
    with_ibd_env_cleared(|| {
        unsafe {
            std::env::set_var("BLVM_IBD_PEERS", "");
        }
        let peers = vec!["192.168.2.100:8333".to_string(), "8.8.8.8:8333".to_string()];
        let config = ParallelIBDConfig::resolve_for_session(None, 0, &peers);
        assert_eq!(config.preferred_peers, vec!["192.168.2.100:8333"]);
    });
}

#[serial_test::serial(ibd)]
#[test]
fn wan_multi_peer_keeps_all_peers_by_default() {
    let peers = vec!["8.8.8.8:8333".to_string(), "1.1.1.1:8333".to_string()];
    let out = ParallelIBDConfig::collapse_wan_only_download_peers(peers);
    assert_eq!(out.len(), 2);
}

#[serial_test::serial(ibd)]
#[test]
fn collapse_keeps_multi_peer_when_lan_present() {
    let peers = vec!["192.168.1.1:8333".to_string(), "8.8.8.8:8333".to_string()];
    let out = ParallelIBDConfig::collapse_wan_only_download_peers(peers);
    assert_eq!(out.len(), 2);
}

#[serial_test::serial(ibd)]
#[test]
fn resolve_wan_only_keeps_parallel_mode() {
    with_ibd_env_cleared(|| {
        let peers = vec!["8.8.8.8:8333".to_string(), "1.1.1.1:8333".to_string()];
        let config = ParallelIBDConfig::resolve_for_session(None, 100_000, &peers);
        assert_eq!(config.mode, "parallel");
        assert!(config.preferred_peers.is_empty());
        assert_eq!(config.min_peers_for_ibd(), 1);
    });
}

#[serial_test::serial(ibd)]
#[test]
fn resolve_auto_prefers_lan_peers() {
    with_ibd_env_cleared(|| {
        let peers = vec!["192.168.2.100:8333".to_string(), "8.8.8.8:8333".to_string()];
        let config = ParallelIBDConfig::resolve_for_session(None, 100_000, &peers);
        assert_eq!(config.preferred_peers, vec!["192.168.2.100:8333"]);
        assert_eq!(config.min_peers_for_ibd(), 1);
    });
}

#[serial_test::serial(ibd)]
#[test]
fn filter_ibd_download_peers_falls_back_when_none_connected() {
    let preferred = vec!["192.168.1.10:8333".to_string()];
    let connected = vec!["8.8.8.8:8333".to_string(), "1.1.1.1:8333".to_string()];
    let out = super::filter_ibd_download_peers(&preferred, connected.clone());
    assert_eq!(out, connected);
}

#[serial_test::serial(ibd)]
#[test]
fn filter_ibd_download_peers_falls_back_when_only_one_preferred_connected() {
    let preferred = vec![
        "66.45.230.178:8333".to_string(),
        "63.254.176.191:8333".to_string(),
    ];
    let connected = vec![
        "66.45.230.178:8333".to_string(),
        "172.105.25.248:8333".to_string(),
        "99.56.151.125:8333".to_string(),
    ];
    let out = super::filter_ibd_download_peers(&preferred, connected.clone());
    assert_eq!(out, connected);
}

#[serial_test::serial(ibd)]
#[test]
fn filter_ibd_download_peers_matches_host_without_port() {
    let preferred = vec!["192.168.1.10".to_string(), "192.168.1.11".to_string()];
    let connected = vec![
        "192.168.1.10:8333".to_string(),
        "192.168.1.11:8333".to_string(),
        "8.8.8.8:8333".to_string(),
    ];
    let out = super::filter_ibd_download_peers(&preferred, connected);
    assert_eq!(
        out,
        vec![
            "192.168.1.10:8333".to_string(),
            "192.168.1.11:8333".to_string()
        ]
    );
}

#[serial_test::serial(ibd)]
#[test]
fn resolve_fresh_chain_keeps_parallel_mode() {
    with_ibd_env_cleared(|| {
        let peers = vec!["192.168.1.1:8333".to_string()];
        let config = ParallelIBDConfig::resolve_for_session(None, 0, &peers);
        assert_eq!(config.mode, "parallel");
    });
}

#[serial_test::serial(ibd)]
#[test]
fn test_create_chunks() {
    let config = ParallelIBDConfig {
        chunk_size: 100,
        ..Default::default()
    };
    let ibd = ParallelIBD::new(config);
    let peer_ids = vec!["peer1".to_string(), "peer2".to_string()];

    let chunks = ibd.create_chunks(0, 250, &peer_ids, None);

    // Bootstrap chunk is always ≥128 blocks so 99 and 100 are in same chunk (stall fix)
    assert_eq!(chunks.len(), 3); // 0-127, 128-227, 228-250
    assert_eq!(chunks[0].start_height, 0);
    assert_eq!(
        chunks[0].end_height, 127,
        "Bootstrap chunk must include 99 and 100"
    );
    assert_eq!(chunks[1].start_height, 128);
    assert_eq!(chunks[1].end_height, 227);
    assert_eq!(chunks[2].start_height, 228);
    assert_eq!(chunks[2].end_height, 250);

    // Note: With weighted assignment, peer selection depends on scores
    // All peers have equal score (1.0) by default, so they get equal chunks
    // Just verify all chunks have a valid peer assigned
    for chunk in &chunks {
        assert!(
            peer_ids.contains(&chunk.peer_id),
            "Chunk should be assigned to a valid peer, got: {}",
            chunk.peer_id
        );
    }
}

/// Ensures bootstrap chunk includes both block 99 and 100 — prevents stall at 99.
#[serial_test::serial(ibd)]
#[test]
fn test_bootstrap_chunk_includes_99_and_100() {
    let config = ParallelIBDConfig {
        chunk_size: 16, // Small chunk_size would normally put 99/100 in different chunks
        ..Default::default()
    };
    let ibd = ParallelIBD::new(config);
    let peer_ids = vec!["peer1".to_string()];
    let chunks = ibd.create_chunks(0, 500, &peer_ids, None);
    assert!(!chunks.is_empty(), "Must have at least one chunk");
    let bootstrap = &chunks[0];
    assert!(
        bootstrap.end_height >= 100,
        "Bootstrap chunk must include block 100 (end={})",
        bootstrap.end_height
    );
    assert!(
        bootstrap.start_height <= 99,
        "Bootstrap chunk must include block 99 (start={})",
        bootstrap.start_height
    );
}

// Regression: chunk queue must drain in height order (FIFO). Vec::pop would yield highest
// heights first and break sequential validation.

#[serial_test::serial(ibd)]
#[test]
fn test_work_queue_fifo_order_not_lifo() {
    // Queue uses VecDeque::pop_front — lowest-height chunk leaves first.

    // Simulate the work queue as created in sync_parallel
    let chunks: Vec<(u64, u64, Option<String>)> = vec![
        (0u64, 99u64, None),
        (100u64, 199u64, None),
        (200u64, 299u64, None),
        (931000u64, 931099u64, None),
    ];

    let mut work_queue: VecDeque<(u64, u64, Option<String>)> = chunks.into_iter().collect();

    // Verify FIFO order (first chunk in = first chunk out)
    let (s, e, _) = work_queue.pop_front().unwrap();
    assert_eq!((s, e), (0, 99), "First chunk should be (0, 99)");

    let (s, e, _) = work_queue.pop_front().unwrap();
    assert_eq!((s, e), (100, 199), "Second chunk should be (100, 199)");

    let (s, e, _) = work_queue.pop_front().unwrap();
    assert_eq!((s, e), (200, 299), "Third chunk should be (200, 299)");

    let (s, e, _) = work_queue.pop_front().unwrap();
    assert_eq!(
        (s, e),
        (931000, 931099),
        "Fourth chunk should be the high-height chunk"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn test_vec_pop_is_lifo_bug() {
    // Vec::pop takes from the end — wrong order if used as a download work queue.

    let mut vec_queue: Vec<(u64, u64)> = vec![(0, 99), (100, 199), (200, 299)];

    let popped = vec_queue.pop().unwrap();
    assert_eq!(
        popped,
        (200, 299),
        "Vec::pop() returns LAST element (LIFO behavior)"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn test_vecdeque_pop_front_is_fifo_correct() {
    let mut deque_queue: VecDeque<(u64, u64, Option<String>)> =
        VecDeque::from(vec![(0, 99, None), (100, 199, None), (200, 299, None)]);

    let (s, e, _) = deque_queue.pop_front().unwrap();
    assert_eq!(
        (s, e),
        (0, 99),
        "VecDeque::pop_front() returns FIRST element (FIFO behavior)"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn test_failed_chunk_requeue_excludes_failing_peer() {
    // Verify that failed chunks are re-queued with exclude_peer so a DIFFERENT peer retries.
    // Same peer retrying would likely fail again (e.g. disconnected).

    let mut work_queue: VecDeque<(u64, u64, Option<String>)> =
        VecDeque::from(vec![(100, 199, None), (200, 299, None)]);

    // Simulate peer "flaky:8333" failing chunk 0-99 - re-queue with exclude
    work_queue.push_front((0, 99, Some("flaky:8333".to_string())));

    let (start, end, exclude) = work_queue.pop_front().unwrap();
    assert_eq!((start, end), (0, 99));
    assert_eq!(exclude.as_deref(), Some("flaky:8333"));
    // Worker for flaky:8333 would skip this; worker for other peer would take it
}

// ============================================================
// Chunk Creation Order Tests
// ============================================================

#[serial_test::serial(ibd)]
#[test]
fn test_chunks_created_in_ascending_height_order() {
    let config = ParallelIBDConfig {
        chunk_size: 1000,
        ..Default::default()
    };
    let ibd = ParallelIBD::new(config);
    let peer_ids = vec!["peer1".to_string()];

    let chunks = ibd.create_chunks(0, 10000, &peer_ids, None);

    // Verify chunks are in ascending order
    for i in 1..chunks.len() {
        assert!(
            chunks[i].start_height > chunks[i - 1].start_height,
            "Chunk {} start ({}) should be > chunk {} start ({})",
            i,
            chunks[i].start_height,
            i - 1,
            chunks[i - 1].start_height
        );
        assert!(
            chunks[i].start_height == chunks[i - 1].end_height + 1,
            "Chunk {} start ({}) should immediately follow chunk {} end ({})",
            i,
            chunks[i].start_height,
            i - 1,
            chunks[i - 1].end_height
        );
    }

    // First chunk must start at 0
    assert_eq!(
        chunks[0].start_height, 0,
        "First chunk must start at height 0"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn test_create_chunks_covers_full_range() {
    let config = ParallelIBDConfig {
        chunk_size: 500,
        ..Default::default()
    };
    let ibd = ParallelIBD::new(config);
    let peer_ids = vec!["peer1".to_string(), "peer2".to_string()];

    let start = 0u64;
    let end = 935000u64; // Approximate mainnet height
    let chunks = ibd.create_chunks(start, end, &peer_ids, None);

    // First chunk starts at start
    assert_eq!(chunks.first().unwrap().start_height, start);

    // Last chunk ends at or after end
    assert!(chunks.last().unwrap().end_height >= end);

    // No gaps between chunks
    for i in 1..chunks.len() {
        assert_eq!(
            chunks[i].start_height,
            chunks[i - 1].end_height + 1,
            "Gap detected between chunk {} and {}",
            i - 1,
            i
        );
    }
}

// ============================================================
// Checkpoint Tests
// ============================================================

#[serial_test::serial(ibd)]
#[test]
fn test_mainnet_checkpoints_exist() {
    assert_ne!(
        checkpoints::MAINNET_CHECKPOINTS.len(),
        0,
        "Checkpoints should be defined"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn test_mainnet_checkpoints_start_at_genesis() {
    let (height, _hash) = checkpoints::MAINNET_CHECKPOINTS[0];
    assert_eq!(
        height, 0,
        "First checkpoint should be genesis block (height 0)"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn test_mainnet_checkpoints_in_ascending_order() {
    for i in 1..checkpoints::MAINNET_CHECKPOINTS.len() {
        let (prev_height, _) = checkpoints::MAINNET_CHECKPOINTS[i - 1];
        let (curr_height, _) = checkpoints::MAINNET_CHECKPOINTS[i];
        assert!(
            curr_height > prev_height,
            "Checkpoint {} (height {}) should be > checkpoint {} (height {})",
            i,
            curr_height,
            i - 1,
            prev_height
        );
    }
}

#[serial_test::serial(ibd)]
#[test]
fn test_mainnet_genesis_hash() {
    // Verify the genesis block hash is correct
    let (height, hash) = checkpoints::MAINNET_CHECKPOINTS[0];
    assert_eq!(height, 0);

    assert_eq!(
        hash,
        blvm_protocol::GENESIS_BLOCK_HASH_INTERNAL,
        "Genesis block hash should match"
    );
}

// ============================================================
// Configuration Tests
// ============================================================

#[serial_test::serial(ibd)]
#[test]
fn test_config_chunk_size_reasonable() {
    let config = ParallelIBDConfig::default();
    // 16 = Core-like minimum, 128 = default, 2000 = max (BLVM_IBD_CHUNK_SIZE override)
    assert!(
        config.chunk_size >= 16 && config.chunk_size <= 2000,
        "chunk_size={}",
        config.chunk_size
    );
}

#[serial_test::serial(ibd)]
#[test]
fn test_config_timeout_reasonable() {
    let config = ParallelIBDConfig::default();
    // Timeout should accommodate slow peers and large blocks
    assert!(
        config.download_timeout_secs >= 30,
        "Timeout too short for large blocks"
    );
    assert!(
        config.download_timeout_secs <= 300,
        "Timeout too long, will stall on dead peers"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn checkpoint_export_exits_on_validation_height_even_if_ckpt_lagging() {
    // Live hang: cl=957000, interval-aligned ckpt stuck at 880000, end=957804.
    assert!(checkpoint_export_thread_should_exit(
        957804, 957000, 957804, 880000
    ));
    assert!(checkpoint_export_thread_should_exit(957804, 0, 957804, 0));
    assert!(!checkpoint_export_thread_should_exit(
        957000, 957000, 957804, 880000
    ));
}

#[serial_test::serial(ibd)]
#[test]
fn checkpoint_export_exits_on_contiguous_length_or_ckpt() {
    assert!(checkpoint_export_thread_should_exit(0, 957804, 957804, 0));
    assert!(checkpoint_export_thread_should_exit(
        0, 957000, 957804, 957804
    ));
    assert!(!checkpoint_export_thread_should_exit(
        0, 957000, 957804, 880000
    ));
    assert!(checkpoint_export_thread_should_exit(0, 0, 0, 0)); // end_h<=0
}

#[serial_test::serial(ibd)]
#[test]
fn tip_skip_advances_near_effective_end_without_1000_boundary() {
    // Live: tip stuck 957632..957804 with no %1000 in range.
    assert!(should_advance_tip_on_skip_path(957632, 957804));
    assert!(should_advance_tip_on_skip_path(957804, 957804));
    assert!(should_advance_tip_on_skip_path(957000, 957804)); // %1000
    // Far from end and not on 1000 boundary:
    assert!(!should_advance_tip_on_skip_path(900001, 957804));
    assert!(!should_advance_tip_on_skip_path(0, 100));
}

#[serial_test::serial(ibd)]
#[test]
fn tip_follow_extends_when_peer_advances() {
    assert_eq!(
        tip_follow_new_effective_end(957_850, 957_900, 957_900),
        Some(957_900)
    );
    assert_eq!(
        tip_follow_new_effective_end(957_850, 957_900, 957_870),
        Some(957_870)
    );
    assert_eq!(
        tip_follow_new_effective_end(957_900, 957_850, 957_900),
        None
    );
    assert_eq!(
        tip_follow_new_effective_end(957_850, 957_850, 957_900),
        None
    );
}

#[serial_test::serial(ibd)]
#[test]
fn emergency_drain_block_rx_admits_gap_height_only() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let (tx, mut rx) = tokio::sync::mpsc::channel(8);
    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    tx.try_send((100u64, Arc::clone(&block), Arc::clone(&w)))
        .unwrap();
    tx.try_send((102u64, Arc::clone(&block), Arc::clone(&w)))
        .unwrap();

    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let mut total = 0u64;
    assert!(!emergency_drain_block_rx_for_gap(
        &mut rx,
        &mut reorder,
        101,
        16,
        64,
        &mut total,
        0,
        256
    ));
    assert_eq!(reorder.len(), 1);
    assert!(reorder.contains_key(&102));

    assert!(emergency_drain_block_rx_for_gap(
        &mut rx,
        &mut reorder,
        102,
        16,
        64,
        &mut total,
        0,
        256
    ));
    assert!(emergency_gap_admission_unblocked(&reorder, 102, 16));
}

#[serial_test::serial(ibd)]
#[test]
fn emergency_gap_admission_requires_present_height() {
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    assert!(!emergency_gap_admission_unblocked(&reorder, 1, 16));
}

#[serial_test::serial(ibd)]
#[test]
fn emergency_gap_admission_requires_buffer_headroom() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    for h in 1..=16u64 {
        reorder.insert(h, (Arc::clone(&block), Arc::clone(&w)));
    }
    assert!(!emergency_may_bulk_recv(&reorder, 16));
    assert!(emergency_has_gap_block(&reorder, 1));
    assert!(!emergency_gap_admission_unblocked(&reorder, 1, 16));
}

#[serial_test::serial(ibd)]
#[test]
fn insert_reorder_gap_aware_drops_far_ahead_when_gap_missing() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 100u64;
    let limit = 64usize;
    let window = 16u64;
    // W29: gap_missing always enforces the window (not only at half-full).
    // Near-gap heights within window are admitted.
    for h in (next_needed + 1)..=(next_needed + window) {
        assert!(insert_reorder_gap_aware(
            &mut reorder,
            h,
            Arc::clone(&block),
            Arc::clone(&w),
            next_needed,
            limit,
            window,
            0, // bridge check disabled
        ));
    }
    assert_eq!(reorder.len(), window as usize);
    // Far ahead beyond window must drop even with small buffer (W29 always-throttle).
    assert!(!insert_reorder_gap_aware(
        &mut reorder,
        next_needed + window + 1,
        Arc::clone(&block),
        Arc::clone(&w),
        next_needed,
        limit,
        window,
        0,
    ));
    // Gap height always admitted.
    assert!(insert_reorder_gap_aware(
        &mut reorder,
        next_needed,
        Arc::clone(&block),
        Arc::clone(&w),
        next_needed,
        limit,
        window,
        0,
    ));
    // Once gap present (and bridge not full), far ahead is admitted again.
    assert!(insert_reorder_gap_aware(
        &mut reorder,
        next_needed + window + 50,
        Arc::clone(&block),
        Arc::clone(&w),
        next_needed,
        limit,
        window,
        0,
    ));
}

/// Phase 0b.2 / rbitcoin request-vs-receive: throttle *new* far-ahead admit; do not
/// clear already-buffered near-gap heights, and tip (`h == next_needed`) still enqueues.
/// See docs/RBITCOIN_VS_BLVM_IBD_ARCHITECTURE.md § Request-vs-receive.
#[serial_test::serial(ibd)]
#[test]
fn admit_throttle_preserves_already_buffered_near_gap() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 100u64;
    let limit = 64usize;
    let window = 16u64;

    // Already-received / buffered near-gap (gap itself still missing → throttle on).
    let buffered: Vec<u64> = ((next_needed + 1)..=(next_needed + 8)).collect();
    for &h in &buffered {
        assert!(insert_reorder_gap_aware(
            &mut reorder,
            h,
            Arc::clone(&block),
            Arc::clone(&w),
            next_needed,
            limit,
            window,
            0,
        ));
    }
    assert_eq!(reorder.len(), buffered.len());

    // New far-ahead assign/admit refused under gap_missing throttle.
    assert!(!insert_reorder_gap_aware(
        &mut reorder,
        next_needed + window + 40,
        Arc::clone(&block),
        Arc::clone(&w),
        next_needed,
        limit,
        window,
        0,
    ));

    // Already-buffered heights must remain (throttle ≠ refuse already-received).
    for &h in &buffered {
        assert!(
            reorder.contains_key(&h),
            "throttle must not clear already-buffered h={h}"
        );
    }
    assert_eq!(reorder.len(), buffered.len());

    // Tip / gap height still enqueues while far-ahead is throttled.
    assert!(insert_reorder_gap_aware(
        &mut reorder,
        next_needed,
        Arc::clone(&block),
        Arc::clone(&w),
        next_needed,
        limit,
        window,
        0,
    ));
    assert!(reorder.contains_key(&next_needed));

    // Dispatch side: tip is never deferred even when WAN tip crawl + gap missing.
    assert!(
        !defer_bridge_ahead_dispatch(
            next_needed,
            next_needed,
            true, // gap_missing
            true, // next_expected_missing
            window,
            true, // wan_tip_crawl
            false,
            false,
        ),
        "tip height must still dispatch while far-ahead is deferred"
    );
    assert!(
        defer_bridge_ahead_dispatch(
            next_needed + 1,
            next_needed,
            true,
            true,
            window,
            true,
            false,
            false,
        ),
        "far-ahead deferred under tip-missing WAN crawl"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn insert_reorder_gap_aware_s2b_drops_when_bridge_full_even_if_gap_present() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 100u64;
    let limit = 64usize;
    let window = 16u64;
    let bridge_max = 512usize;

    // Gap present in reorder.
    reorder.insert(next_needed, (Arc::clone(&block), Arc::clone(&w)));
    // Fill to half capacity with near-gap heights.
    for h in (next_needed + 1)..=(next_needed + 31) {
        assert!(insert_reorder_gap_aware(
            &mut reorder,
            h,
            Arc::clone(&block),
            Arc::clone(&w),
            next_needed,
            limit,
            window,
            bridge_max,
        ));
    }
    assert!(reorder.len() >= limit / 2);

    // Simulate bridge at cap (S2b).
    memory::BRIDGE_PENDING_COUNT.store(bridge_max as u64, Ordering::Relaxed);
    assert!(
        !insert_reorder_gap_aware(
            &mut reorder,
            next_needed + window + 1,
            Arc::clone(&block),
            Arc::clone(&w),
            next_needed,
            limit,
            window,
            bridge_max,
        ),
        "S2b: far-ahead must drop when bridge is full even if gap is present"
    );
    // Gap height still admitted.
    assert!(insert_reorder_gap_aware(
        &mut reorder,
        next_needed,
        Arc::clone(&block),
        Arc::clone(&w),
        next_needed,
        limit,
        window,
        bridge_max,
    ));
    // Near-window still admitted.
    assert!(insert_reorder_gap_aware(
        &mut reorder,
        next_needed + window,
        Arc::clone(&block),
        Arc::clone(&w),
        next_needed,
        limit,
        window,
        bridge_max,
    ));
    memory::BRIDGE_PENDING_COUNT.store(0, Ordering::Relaxed);
}

#[serial_test::serial(ibd)]
#[test]
fn emergency_drain_s2a_uses_coordinator_admit_limit() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 100u64;
    for h in 101..=120u64 {
        reorder.insert(h, (Arc::clone(&block), Arc::clone(&w)));
    }
    assert_eq!(reorder.len(), 20);

    let (tx, mut rx) = tokio::sync::mpsc::channel(4);
    tx.try_send((200u64, Arc::clone(&block), Arc::clone(&w)))
        .unwrap();

    let mut total = 0u64;
    // len=20 < half(32) of coordinator admit_limit=64 — far-ahead must admit.
    emergency_drain_block_rx_for_gap(
        &mut rx,
        &mut reorder,
        next_needed,
        16,
        64,
        &mut total,
        0,
        256,
    );
    assert!(
        reorder.contains_key(&200),
        "S2a: far-ahead should admit when reorder is below half of coordinator limit"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn evict_reorder_gap_pressure_prunes_stale_and_far_ahead() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 100u64;
    let limit = 64usize;
    let window = 16u64;

    reorder.insert(90, (Arc::clone(&block), Arc::clone(&w)));
    for h in (next_needed + 1)..=(next_needed + 32) {
        reorder.insert(h, (Arc::clone(&block), Arc::clone(&w)));
    }
    for h in (next_needed + window + 1)..=(next_needed + 50) {
        reorder.insert(h, (Arc::clone(&block), Arc::clone(&w)));
    }
    assert!(reorder.len() >= limit / 2);
    assert!(reorder.contains_key(&90));
    assert!(!reorder.contains_key(&next_needed));

    let evicted = evict_reorder_gap_pressure(&mut reorder, next_needed, limit, window, 0);
    assert!(evicted > 0);
    assert!(
        !reorder.contains_key(&90),
        "stale heights below next_needed pruned"
    );
    assert!(
        !reorder.contains_key(&(next_needed + 50)),
        "far-ahead beyond window evicted"
    );
    assert!(
        reorder.contains_key(&(next_needed + window)),
        "near-window heights preserved"
    );
    assert!(reorder.len() < limit / 2 + window as usize + 1);
}

#[serial_test::serial(ibd)]
#[test]
fn evict_reorder_s2e_deeper_target_when_bridge_full() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 100u64;
    let limit = 2000usize;
    let window = 256u64;
    // Gap present so W29 gap-missing eviction does not fire — isolate S2e bridge_full path.
    reorder.insert(next_needed, (Arc::clone(&block), Arc::clone(&w)));
    // Fill to the old pressure_target (half-64 = 936) with far-ahead heights.
    for h in (next_needed + window + 1)..(next_needed + window + 1 + 936) {
        reorder.insert(h, (Arc::clone(&block), Arc::clone(&w)));
    }
    assert_eq!(reorder.len(), 937);
    // Without bridge_full: at pressure_target → no eviction (gap present).
    assert_eq!(
        evict_reorder_gap_pressure(&mut reorder, next_needed, limit, window, 0),
        0,
        "at half-64 with bridge empty + gap present: no-op"
    );
    // S2e: simulate bridge at cap → deeper target (half/4 = 500).
    memory::BRIDGE_PENDING_COUNT.store(512, Ordering::Relaxed);
    let evicted = evict_reorder_gap_pressure(&mut reorder, next_needed, limit, window, 512);
    memory::BRIDGE_PENDING_COUNT.store(0, Ordering::Relaxed);
    assert!(
        evicted >= 1,
        "S2e must evict when bridge_full even at old pressure_target (evicted={evicted})"
    );
    assert!(
        reorder.len() < 937,
        "reorder must shrink below 937 under bridge_full"
    );
}

#[serial_test::serial(ibd)]
#[test]
fn w29_evict_reorder_to_window_when_gap_missing() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 100u64;
    let window = 64u64;
    // Tip missing; fill far ahead past window (live W28d signature).
    for h in (next_needed + 1)..=(next_needed + 270) {
        reorder.insert(h, (Arc::clone(&block), Arc::clone(&w)));
    }
    assert_eq!(reorder.len(), 270);
    let mut total = 0usize;
    for _ in 0..16 {
        let n = evict_reorder_gap_pressure(&mut reorder, next_needed, 2000, window, 0);
        if n == 0 {
            break;
        }
        total += n;
    }
    assert!(total > 0, "W29 must evict far-ahead while gap_missing");
    let ceiling = next_needed + window;
    assert!(
        reorder.keys().next_back().copied().unwrap_or(0) <= ceiling
            || reorder.len() <= (window as usize) + 8,
        "reorder must shrink toward window (len={}, max={:?})",
        reorder.len(),
        reorder.keys().next_back()
    );
}

#[serial_test::serial(ibd)]
#[test]
fn evict_reorder_gap_pressure_noop_when_gap_present_and_bridge_empty() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 100u64;
    reorder.insert(next_needed, (Arc::clone(&block), Arc::clone(&w)));
    for h in 150..=200u64 {
        reorder.insert(h, (Arc::clone(&block), Arc::clone(&w)));
    }
    let before = reorder.len();
    let evicted = evict_reorder_gap_pressure(&mut reorder, next_needed, 64, 16, 0);
    assert_eq!(evicted, 0);
    assert_eq!(reorder.len(), before);
}

#[serial_test::serial(ibd)]
#[test]
fn defer_bridge_ahead_dispatch_blocks_far_ahead_when_gap_missing() {
    let next = 100u64;
    let window = 16u64;
    assert!(!defer_bridge_ahead_dispatch(
        next, next, true, false, window, false, false, false
    ));
    assert!(defer_bridge_ahead_dispatch(
        next + window + 1,
        next,
        true,
        false,
        window,
        false,
        false,
        false
    ));
    assert!(!defer_bridge_ahead_dispatch(
        next + window + 1,
        next,
        false,
        false,
        window,
        false,
        false,
        false
    ));
}

#[serial_test::serial(ibd)]
#[test]
fn defer_bridge_ahead_dispatch_tight_band_when_next_expected_missing() {
    let next = 100u64;
    let window = 256u64;
    // Gap height always allowed.
    assert!(!defer_bridge_ahead_dispatch(
        next, next, false, true, window, false, false, false
    ));
    // Inside tight band (≤64) still allowed.
    assert!(!defer_bridge_ahead_dispatch(
        next + 32,
        next,
        false,
        true,
        window,
        false,
        false,
        false
    ));
    // Past tight band deferred even if reorder has the gap.
    assert!(defer_bridge_ahead_dispatch(
        next + 65,
        next,
        false,
        true,
        window,
        false,
        false,
        false
    ));
}

#[serial_test::serial(ibd)]
#[test]
fn defer_bridge_ahead_w17_wan_tip_crawl_defers_all_ahead() {
    let next = 685470u64;
    let window = 256u64;
    // Tip always allowed.
    assert!(!defer_bridge_ahead_dispatch(
        next, next, true, true, window, true, false, false
    ));
    // Tip missing from reorder+bridge → defer all ahead (W17 hole-fill guard).
    assert!(defer_bridge_ahead_dispatch(
        next + 1,
        next,
        true,
        true,
        window,
        true,
        false,
        false
    ));
    assert!(defer_bridge_ahead_dispatch(
        next + 32,
        next,
        true,
        true,
        window,
        true,
        false,
        false
    ));
    // Tip present in reorder → allow contiguous band (W18), defer past band.
    assert!(!defer_bridge_ahead_dispatch(
        next + 32,
        next,
        false,
        false,
        window,
        true,
        false,
        false
    ));
    assert!(defer_bridge_ahead_dispatch(
        next + 65,
        next,
        false,
        false,
        window,
        true,
        false,
        false
    ));
    // Local / non-WAN still allows near-ahead under prior L2 rules.
    assert!(!defer_bridge_ahead_dispatch(
        next + 32,
        next,
        false,
        true,
        window,
        false,
        false,
        false
    ));
}

#[serial_test::serial(ibd)]
#[test]
fn defer_bridge_ahead_w57_never_hole_fill_when_tip_missing() {
    let next = 100u64;
    let window = 256u64;
    // W17/W57: gap + next_expected missing → defer ALL ahead (even feeder-starved).
    assert!(defer_bridge_ahead_dispatch(
        next + 32,
        next,
        true,
        true,
        window,
        true,
        false,
        false
    ));
    assert!(defer_bridge_ahead_dispatch(
        next + 32,
        next,
        true,
        true,
        window,
        true,
        true,
        false
    ));
    // Tip present in reorder (gap_missing=false) — W18 band still allows near-ahead.
    assert!(!defer_bridge_ahead_dispatch(
        next + 32,
        next,
        false,
        true,
        window,
        true,
        true,
        false
    ));
    assert!(defer_bridge_ahead_dispatch(
        next + 65,
        next,
        false,
        true,
        window,
        true,
        true,
        false
    ));
}

#[serial_test::serial(ibd)]
#[test]
fn defer_bridge_ahead_w58_bulk_still_defers_when_tip_missing() {
    let next = 60_000u64;
    let window = 256u64;
    // W58: bulk + tip nowhere → W17 (no hole-fill). Old bulk path allowed tip+32.
    assert!(defer_bridge_ahead_dispatch(
        next + 32,
        next,
        true,
        true,
        window,
        true,
        false,
        true
    ));
    assert!(defer_bridge_ahead_dispatch(
        next + 1,
        next,
        true,
        true,
        window,
        true,
        false,
        true
    ));
    // Tip itself still admitted.
    assert!(!defer_bridge_ahead_dispatch(
        next, next, true, true, window, true, false, true
    ));
    // Bulk + tip present in reorder (gap_missing=false): multi-peer tight band.
    assert!(!defer_bridge_ahead_dispatch(
        next + 32,
        next,
        false,
        true,
        window,
        true,
        false,
        true
    ));
    assert!(defer_bridge_ahead_dispatch(
        next + 65,
        next,
        false,
        true,
        window,
        true,
        false,
        true
    ));
}

#[serial_test::serial(ibd)]
#[test]
fn wan_bulk_catchup_threshold() {
    assert!(!wan_bulk_catchup(0, 60_000));
    assert!(!wan_bulk_catchup(60_100, 60_000)); // only 100 ahead
    assert!(wan_bulk_catchup(70_000, 60_000)); // ≥2048
    assert!(wan_bulk_catchup(900_000, 60_000));
}

#[serial_test::serial(ibd)]
#[test]
fn w76_wan_ahead_policy_feeder_starve_uses_tip_window_even_when_bulk() {
    // Mid-chain: headers at network tip ⇒ bulk=true always; feeder empty must not
    // keep the old 1024 bulk-gap window (live tip never in bridge @ ~350k).
    let (kind, cap) = wan_ahead_policy(true, true, true, 2);
    assert_eq!(kind, "wan_bulk_gap");
    assert_eq!(cap, wan_bulk_tip_gap_ahead_cap());
    assert_eq!(
        cap,
        wan_tip_gap_ahead_cap(),
        "W76 default bulk-gap == tip ahead"
    );
    let (kind2, cap2) = wan_ahead_policy(false, true, true, 2);
    assert_eq!(kind2, "wan_tip");
    assert_eq!(cap2, wan_bulk_tip_gap_ahead_cap());
    let (kind3, cap3) = wan_ahead_policy(true, false, false, 2);
    assert_eq!(kind3, "wan_bulk");
    assert_eq!(cap3, wan_bulk_ahead_cap());
}

#[serial_test::serial(ibd)]
#[test]
fn reorder_has_feeder_prefetch_band_detects_near_blocks() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next = 1000u64;
    assert!(!reorder_has_feeder_prefetch_band(&reorder, next, 16));
    reorder.insert(next + 8, (Arc::clone(&block), Arc::clone(&w)));
    assert!(reorder_has_feeder_prefetch_band(&reorder, next, 16));
    reorder.clear();
    reorder.insert(next + 20, (Arc::clone(&block), Arc::clone(&w)));
    assert!(!reorder_has_feeder_prefetch_band(&reorder, next, 16));
}

#[serial_test::serial(ibd)]
#[test]
fn evict_reorder_gap_pressure_runs_when_one_below_half() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 526_335u64;
    let limit = 2000usize;
    let window = 256u64;
    for h in (next_needed + 1)..=(next_needed + 999) {
        reorder.insert(h, (Arc::clone(&block), Arc::clone(&w)));
    }
    assert_eq!(reorder.len(), 999);

    let evicted = evict_reorder_gap_pressure(&mut reorder, next_needed, limit, window, 512);
    assert!(
        evicted > 0,
        "must evict when reorder=999 and gap_missing under production limits"
    );
    assert!(
        reorder.len() < 999,
        "eviction must shrink below treadmill equilibrium, got {}",
        reorder.len()
    );
}

#[serial_test::serial(ibd)]
#[test]
fn evict_reorder_gap_pressure_batch_caps_at_32_per_tick() {
    use blvm_protocol::{Block, BlockHeader};
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let next_needed = 100u64;
    let limit = 128usize;
    let window = 8u64;
    for h in (next_needed + window + 1)..=(next_needed + 200) {
        reorder.insert(h, (Arc::clone(&block), Arc::clone(&w)));
    }
    let before = reorder.len();
    let evicted = evict_reorder_gap_pressure(&mut reorder, next_needed, limit, window, 0);
    assert_eq!(
        evicted, 32,
        "S2d: batch eviction capped at 32 per coordinator tick"
    );
    assert_eq!(reorder.len(), before - 32);
    assert!(reorder.len() >= limit / 2);
}

#[serial_test::serial(ibd)]
#[test]
fn w54_tip_handoff_ignores_feeder_depth_when_tip_stranded() {
    use blvm_protocol::{Block, BlockHeader};
    use rustc_hash::FxHashSet;
    use std::sync::Arc;

    let block = Arc::new(Block {
        header: BlockHeader::default(),
        transactions: Default::default(),
    });
    let w: SharedWitnesses = Arc::new(vec![]);
    let mut reorder: BTreeMap<u64, (SharedBlock, SharedWitnesses)> = BTreeMap::new();
    let mut dispatched = FxHashSet::default();
    let next_needed = 428_344u64;
    reorder.insert(next_needed, (Arc::clone(&block), Arc::clone(&w)));

    // Pre-W54: feeder_len > 16 returned None and left tip stranded under soft-resume.
    let out = prepare_coordinator_tip_handoff(
        next_needed,
        false,
        383,
        false,
        &mut reorder,
        &mut dispatched,
        None,
        256,
        512,
        true,
        false,
    );
    assert!(
        out.is_some(),
        "W54: stranded tip must hand off with feeder=383"
    );
    assert!(!reorder.contains_key(&next_needed));
    assert!(dispatched.contains(&next_needed));

    reorder.insert(next_needed, (Arc::clone(&block), Arc::clone(&w)));
    let blocked = prepare_coordinator_tip_handoff(
        next_needed,
        false,
        0,
        false,
        &mut reorder,
        &mut dispatched,
        None,
        256,
        512,
        true,
        true, // already in feeder
    );
    assert!(
        blocked.is_none(),
        "must not re-handoff tip already in feeder"
    );
    assert!(reorder.contains_key(&next_needed));
}