zakura 1.0.4

Zakura, an independent, consensus-compatible implementation of a Zcash node
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
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
//! Fixed test vectors for the syncer.

#![allow(clippy::unwrap_in_result)]

use std::{
    collections::{HashMap, HashSet},
    iter,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
    time::Duration,
};

use color_eyre::Report;
use futures::{Future, FutureExt, StreamExt};
use tower::timeout::Timeout;

use zakura_chain::{
    block::{self, Block, Height},
    chain_tip::mock::{MockChainTip, MockChainTipSender},
    serialization::ZcashDeserializeInto,
};
use zakura_consensus::{
    Config as ConsensusConfig, RouterError, VerifyBlockError, VerifyCheckpointError,
};
use zakura_network::{InventoryResponse, PeerSocketAddr};
use zakura_state::Config as StateConfig;
use zakura_test::mock_service::{MockService, PanicAssertion};

use zakura_network as zn;
use zakura_state as zs;

use crate::{
    components::{
        sync::{
            self,
            downloads::{BlockDownloadVerifyError, Downloads},
            legacy_trace::LegacySyncTrace,
            SyncStatus,
        },
        ChainSync,
    },
    config::ZakuradConfig,
};

use InventoryResponse::*;

type TestChainSync = ChainSync<
    MockService<zn::Request, zn::Response, PanicAssertion>,
    MockService<zs::Request, zs::Response, PanicAssertion>,
    MockService<zakura_consensus::Request, block::Hash, PanicAssertion>,
    MockChainTip,
>;

/// Maximum time to wait for a request to any test service.
///
/// The default [`MockService`] value can be too short for some of these tests that take a little
/// longer than expected to actually send the request.
///
/// Increasing this value causes the tests to take longer to complete, so it can't be too large.
const MAX_SERVICE_REQUEST_DELAY: Duration = Duration::from_millis(1000);

/// Maximum time to wait for a request in tests that must outlast [`sync::BLOCK_VERIFY_TIMEOUT`].
///
/// A stalled syncer only recovers by waiting out that timeout and restarting. A mock service that
/// gives up first would panic before the syncer ever gets there, hiding the stall behind an
/// unrelated failure. These tests pause time, so a long delay costs no wall-clock time.
const STALLED_SERVICE_REQUEST_DELAY: Duration = Duration::from_secs(30 * 60);

#[test]
fn oversized_find_blocks_response_is_rejected() {
    let hash = block::Hash([0; 32]);

    // The guard is applied after ObtainTips/ExtendTips strip zcashd's extra
    // trailing hash, so 500 remaining hashes are accepted and 501 are not.
    assert!(sync::has_valid_tips_response_hash_count(&vec![
        hash;
        sync::MAX_TIPS_RESPONSE_HASH_COUNT
    ]));
    assert!(!sync::has_valid_tips_response_hash_count(&vec![
        hash;
        sync::MAX_TIPS_RESPONSE_HASH_COUNT
            + 1
    ]));

    // A zcashd response with 500 chain hashes plus one appended hash must remain
    // usable after the trailing hash is discarded.
    let raw = vec![hash; sync::MAX_TIPS_RESPONSE_HASH_COUNT + 1];
    let stripped = &raw[..raw.len() - 1];
    assert_eq!(stripped.len(), sync::MAX_TIPS_RESPONSE_HASH_COUNT);
    assert!(sync::has_valid_tips_response_hash_count(stripped));
}

/// Test that the syncer downloads genesis, blocks 1-2 using obtain_tips, and blocks 3-4 using extend_tips.
///
/// This test also makes sure that the syncer downloads blocks in order.
#[tokio::test(start_paused = true)]
async fn sync_blocks_ok() -> Result<(), crate::BoxError> {
    // Get services
    let (
        chain_sync_future,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup();

    // Get blocks
    let block0: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

    let block1: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?;
    let block1_hash = block1.hash();

    let block2: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_2_BYTES.zcash_deserialize_into()?;
    let block2_hash = block2.hash();

    let block3: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_3_BYTES.zcash_deserialize_into()?;
    let block3_hash = block3.hash();

    let block4: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_4_BYTES.zcash_deserialize_into()?;
    let block4_hash = block4.hash();

    let block5: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_5_BYTES.zcash_deserialize_into()?;
    let block5_hash = block5.hash();

    // Start the syncer
    let chain_sync_task_handle = tokio::spawn(chain_sync_future);

    // ChainSync::request_genesis

    // State is checked for genesis
    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Block 0 is fetched and committed to the state
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block0_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zakura_consensus::Request::Commit(block0))
        .await
        .respond(block0_hash);

    // Check that nothing unexpected happened.
    // We expect more requests to the state service, because the syncer keeps on running.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    // State is checked for genesis again
    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

    // ChainSync::obtain_tips

    // State is asked for a block locator.
    state_service
        .expect_request(zs::Request::BlockLocator)
        .await
        .respond(zs::Response::BlockLocator(vec![block0_hash]));

    // Network is sent the block locator
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![block0_hash],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            block1_hash, // tip
            block2_hash, // expected_next
            block3_hash, // (discarded - last hash, possibly incorrect)
        ]));

    // State is checked for each candidate hash before it is queued.
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block2_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Clear remaining block locator requests
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![block0_hash],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test obtain tips error")));
    }

    // Check that nothing unexpected happened.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    // State is checked for all non-tip blocks (blocks 1 & 2) in response order
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block2_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Blocks 1 & 2 are fetched in order, then verified concurrently
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block1_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block2_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block2.clone(),
            None,
        ))]));

    // We can't guarantee the verification request order
    let mut remaining_blocks: HashMap<block::Hash, Arc<Block>> =
        [(block1_hash, block1), (block2_hash, block2)]
            .iter()
            .cloned()
            .collect();

    for _ in 1..=2 {
        block_verifier_router
            .expect_request_that(|req| remaining_blocks.remove(&req.block().hash()).is_some())
            .await
            .respond_with(|req| req.block().hash());
    }
    assert_eq!(
        remaining_blocks,
        HashMap::new(),
        "expected all non-tip blocks to be verified by obtain tips"
    );

    // Check that nothing unexpected happened.
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    // ChainSync::extend_tips

    // Network is sent a block locator based on the tip
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![block1_hash],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            block2_hash, // tip (discarded - already fetched)
            block3_hash, // expected_next
            block4_hash,
            block5_hash, // (discarded - last hash, possibly incorrect)
        ]));

    for hash in [block3_hash, block4_hash] {
        state_service
            .expect_request(zs::Request::KnownBlock(hash))
            .await
            .respond(zs::Response::KnownBlock(None));
    }

    // Clear remaining block locator requests
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![block1_hash],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test extend tips error")));
    }

    // Check that nothing unexpected happened.
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    // Blocks 3 & 4 are fetched in order, then verified concurrently
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block3_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block3.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block4_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block4.clone(),
            None,
        ))]));

    // We can't guarantee the verification request order
    let mut remaining_blocks: HashMap<block::Hash, Arc<Block>> =
        [(block3_hash, block3), (block4_hash, block4)]
            .iter()
            .cloned()
            .collect();

    for _ in 3..=4 {
        block_verifier_router
            .expect_request_that(|req| remaining_blocks.remove(&req.block().hash()).is_some())
            .await
            .respond_with(|req| req.block().hash());
    }
    assert_eq!(
        remaining_blocks,
        HashMap::new(),
        "expected all non-tip blocks to be verified by extend tips"
    );

    // Check that nothing unexpected happened.
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    let chain_sync_result = chain_sync_task_handle.now_or_never();
    assert!(
        chain_sync_result.is_none(),
        "unexpected error or panic in chain sync task: {chain_sync_result:?}",
    );

    Ok(())
}

/// An incomplete checkpoint range must not strand the blocks already parked in the verifier.
///
/// This scales the production failure at checkpoints 400 and 800 down to a four-block checkpoint
/// range. Every peer response here is one a real peer would send:
///
/// - the peer's tip is block 3, so `FindBlocks` from genesis answers `[1, 2, 3]`. `obtain_tips`
///   discards the trailing hash for zcashd's quirk of appending an unrelated one, leaving blocks
///   1-2 to download.
/// - extending that tip answers `[2, 3]`, and the same trailing-hash rule discards block 3, so the
///   response extends by nothing and the prospective tip set empties. The peer did extend the tip;
///   the workaround is what drops the block, on the promise that a later fanout re-discovers it.
/// - blocks 1-2 are now parked in the checkpoint verifier, which cannot verify *any* block in a
///   range until the whole range up to checkpoint 4 has arrived. So they stay in flight forever.
///
/// Discovering the rest of the range is the only way out, and only a fresh fanout can do it. The
/// syncer must therefore keep discovering hashes while blocks are parked, rather than waiting for
/// the download queue to drain first — that wait cannot terminate. The chain grows to block 5, a
/// refreshed fanout picks up blocks 3-4, and the range verifies.
///
/// Time is paused, so a syncer that instead waits out [`sync::BLOCK_VERIFY_TIMEOUT`] and restarts
/// fails here in milliseconds of wall-clock time.
#[tokio::test(start_paused = true)]
async fn incomplete_checkpoint_range_refreshes_tips_without_verifier_timeout(
) -> Result<(), crate::BoxError> {
    let (
        chain_sync,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        mock_chain_tip_sender,
    ) = setup_chain_sync_with_options(Height(4), STALLED_SERVICE_REQUEST_DELAY);
    mock_chain_tip_sender.send_best_tip_height(Height(0));

    let blocks: Vec<Arc<Block>> = vec![
        zakura_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?,
        zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?,
        zakura_test::vectors::BLOCK_MAINNET_2_BYTES.zcash_deserialize_into()?,
        zakura_test::vectors::BLOCK_MAINNET_3_BYTES.zcash_deserialize_into()?,
        zakura_test::vectors::BLOCK_MAINNET_4_BYTES.zcash_deserialize_into()?,
        zakura_test::vectors::BLOCK_MAINNET_5_BYTES.zcash_deserialize_into()?,
    ];
    let hashes: Vec<_> = blocks.iter().map(|block| block.hash()).collect();

    let sync_task = tokio::spawn(chain_sync.sync());

    state_service
        .expect_request(zs::Request::KnownBlock(hashes[0]))
        .await
        .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

    // The peer's tip is block 3. The trailing hash is discarded, leaving blocks 1-2 to download,
    // which is only half of the checkpoint range ending at block 4.
    state_service
        .expect_request(zs::Request::BlockLocator)
        .await
        .respond(zs::Response::BlockLocator(vec![hashes[0]]));
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![hashes[0]],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            hashes[1], hashes[2], hashes[3],
        ]));
    state_service
        .expect_request(zs::Request::KnownBlock(hashes[1]))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(hashes[2]))
        .await
        .respond(zs::Response::KnownBlock(None));
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![hashes[0]],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic short-tip peer error")));
    }
    for hash in &hashes[1..=2] {
        state_service
            .expect_request(zs::Request::KnownBlock(*hash))
            .await
            .respond(zs::Response::KnownBlock(None));
    }
    for (hash, block) in hashes[1..=2].iter().zip(&blocks[1..=2]) {
        peer_set
            .expect_request(zn::Request::BlocksByHash(iter::once(*hash).collect()))
            .await
            .respond(zn::Response::Blocks(vec![Available((block.clone(), None))]));
    }

    // Hold blocks 1-2 in the verifier. A checkpoint verifier cannot verify a partial range, so these
    // requests stay pending — and the blocks stay in flight — until blocks 3-4 arrive.
    let mut pending_verifications = Vec::new();
    let mut expected_verifications: HashSet<_> = hashes[1..=2].iter().copied().collect();
    for _ in 0..2 {
        pending_verifications.push(
            block_verifier_router
                .expect_request_that(|request| {
                    expected_verifications.remove(&request.block().hash())
                })
                .await,
        );
    }
    assert!(expected_verifications.is_empty());

    // The peer extends the tip with block 3, but the trailing-hash workaround discards it, so the
    // response extends by nothing and the prospective tip set empties.
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![hashes[1]],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![hashes[2], hashes[3]]));
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![hashes[1]],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from(
                "synthetic empty-extension peer error",
            )));
    }

    // Nothing is left to discover, but blocks 1-2 are parked in the verifier and can only be
    // verified once the rest of the range arrives. The syncer must run a fresh fanout to find it,
    // rather than waiting for its in-flight downloads to drain: that wait cannot terminate.
    let refresh_requested_at = tokio::time::Instant::now();
    let refreshed_locator = tokio::time::timeout(
        sync::BLOCK_VERIFY_TIMEOUT,
        state_service.expect_request(zs::Request::BlockLocator),
    )
    .await
    .expect(
        "syncer must discover the rest of the checkpoint range while its blocks are parked in the \
         verifier: waiting out BLOCK_VERIFY_TIMEOUT and restarting discards the partial range",
    );

    // The chain has grown to block 5, so the refreshed fanout covers the rest of the range. Blocks
    // 1-2 are still in flight, so they are re-dispatched as duplicates and not downloaded again.
    refreshed_locator.respond(zs::Response::BlockLocator(vec![hashes[0]]));
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![hashes[0]],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            hashes[1], hashes[2], hashes[3], hashes[4], hashes[5],
        ]));
    state_service
        .expect_request(zs::Request::KnownBlock(hashes[1]))
        .await
        .respond(zs::Response::KnownBlock(None));
    for hash in &hashes[2..=4] {
        state_service
            .expect_request(zs::Request::KnownBlock(*hash))
            .await
            .respond(zs::Response::KnownBlock(None));
    }
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![hashes[0]],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic refreshed-tip error")));
    }
    for hash in &hashes[1..=4] {
        state_service
            .expect_request(zs::Request::KnownBlock(*hash))
            .await
            .respond(zs::Response::KnownBlock(None));
    }
    for (hash, block) in hashes[3..=4].iter().zip(&blocks[3..=4]) {
        peer_set
            .expect_request(zn::Request::BlocksByHash(iter::once(*hash).collect()))
            .await
            .respond(zn::Response::Blocks(vec![Available((block.clone(), None))]));
    }
    let mut expected_verifications: HashSet<_> = hashes[3..=4].iter().copied().collect();
    for _ in 0..2 {
        pending_verifications.push(
            block_verifier_router
                .expect_request_that(|request| {
                    expected_verifications.remove(&request.block().hash())
                })
                .await,
        );
    }
    assert!(expected_verifications.is_empty());

    // Extending the refreshed tip discards block 5 by the same trailing-hash rule, so this response
    // extends by nothing. The checkpoint range is already complete, so that no longer matters.
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![hashes[3]],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![hashes[4], hashes[5]]));
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![hashes[3]],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic final-tip error")));
    }

    // The whole range is downloaded, so the checkpoint verifier can now verify all four blocks.
    for verification in pending_verifications {
        verification.respond_with(|request| request.block().hash());
    }

    assert!(
        refresh_requested_at.elapsed() < sync::BLOCK_VERIFY_TIMEOUT,
        "the checkpoint range must complete without waiting out BLOCK_VERIFY_TIMEOUT, but it took {:?}",
        refresh_requested_at.elapsed(),
    );

    tokio::task::yield_now().await;
    assert!(
        !sync_task.is_finished(),
        "legacy sync should continue after the checkpoint range completes"
    );
    sync_task.abort();

    Ok(())
}

/// Test that the syncer downloads genesis, blocks 1-2 using obtain_tips, and blocks 3-4 using extend_tips,
/// with unrelated trailing hashes that are discarded.
///
/// This test also makes sure that the syncer downloads blocks in order.
#[tokio::test(start_paused = true)]
async fn sync_blocks_trailing_hashes_ok() -> Result<(), crate::BoxError> {
    // Get services
    let (
        chain_sync_future,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup();

    // Get blocks
    let block0: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

    let block1: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?;
    let block1_hash = block1.hash();

    let block2: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_2_BYTES.zcash_deserialize_into()?;
    let block2_hash = block2.hash();

    let block3: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_3_BYTES.zcash_deserialize_into()?;
    let block3_hash = block3.hash();

    let block4: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_4_BYTES.zcash_deserialize_into()?;
    let block4_hash = block4.hash();

    let block5: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_5_BYTES.zcash_deserialize_into()?;
    let block5_hash = block5.hash();

    // Start the syncer
    let chain_sync_task_handle = tokio::spawn(chain_sync_future);

    // ChainSync::request_genesis

    // State is checked for genesis
    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Block 0 is fetched and committed to the state
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block0_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zakura_consensus::Request::Commit(block0))
        .await
        .respond(block0_hash);

    // Check that nothing unexpected happened.
    // We expect more requests to the state service, because the syncer keeps on running.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    // State is checked for genesis again
    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

    // ChainSync::obtain_tips

    // State is asked for a block locator.
    state_service
        .expect_request(zs::Request::BlockLocator)
        .await
        .respond(zs::Response::BlockLocator(vec![block0_hash]));

    // Network is sent the block locator
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![block0_hash],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            block1_hash, // tip
            block2_hash, // expected_next
            block3_hash, // (discarded - last hash, possibly incorrect)
        ]));

    // State is checked for each candidate hash before it is queued.
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block2_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Clear remaining block locator requests
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![block0_hash],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test obtain tips error")));
    }

    // Check that nothing unexpected happened.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    // State is checked for all non-tip blocks (blocks 1 & 2) in response order
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block2_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Blocks 1 & 2 are fetched in order, then verified concurrently
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block1_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block2_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block2.clone(),
            None,
        ))]));

    // We can't guarantee the verification request order
    let mut remaining_blocks: HashMap<block::Hash, Arc<Block>> =
        [(block1_hash, block1), (block2_hash, block2)]
            .iter()
            .cloned()
            .collect();

    for _ in 1..=2 {
        block_verifier_router
            .expect_request_that(|req| remaining_blocks.remove(&req.block().hash()).is_some())
            .await
            .respond_with(|req| req.block().hash());
    }
    assert_eq!(
        remaining_blocks,
        HashMap::new(),
        "expected all non-tip blocks to be verified by obtain tips"
    );

    // Check that nothing unexpected happened.
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    // ChainSync::extend_tips

    // Network is sent a block locator based on the tip
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![block1_hash],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            block2_hash, // tip (discarded - already fetched)
            block3_hash, // expected_next
            block4_hash,
            block5_hash, // (discarded - last hash, possibly incorrect)
        ]));

    for hash in [block3_hash, block4_hash] {
        state_service
            .expect_request(zs::Request::KnownBlock(hash))
            .await
            .respond(zs::Response::KnownBlock(None));
    }

    // Clear remaining block locator requests
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![block1_hash],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test extend tips error")));
    }

    // Check that nothing unexpected happened.
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    // Blocks 3 & 4 are fetched in order, then verified concurrently
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block3_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block3.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block4_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block4.clone(),
            None,
        ))]));

    // We can't guarantee the verification request order
    let mut remaining_blocks: HashMap<block::Hash, Arc<Block>> =
        [(block3_hash, block3), (block4_hash, block4)]
            .iter()
            .cloned()
            .collect();

    for _ in 3..=4 {
        block_verifier_router
            .expect_request_that(|req| remaining_blocks.remove(&req.block().hash()).is_some())
            .await
            .respond_with(|req| req.block().hash());
    }
    assert_eq!(
        remaining_blocks,
        HashMap::new(),
        "expected all non-tip blocks to be verified by extend tips"
    );

    // Check that nothing unexpected happened.
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    let chain_sync_result = chain_sync_task_handle.now_or_never();
    assert!(
        chain_sync_result.is_none(),
        "unexpected error or panic in chain sync task: {chain_sync_result:?}",
    );

    Ok(())
}

/// Test that zakura-network rejects blocks that are a long way ahead of the state tip.
#[tokio::test]
async fn sync_block_lookahead_drop() -> Result<(), crate::BoxError> {
    // Get services
    let (
        chain_sync_future,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup();

    // Get blocks
    let block0: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

    // Get a block that is a long way away from genesis
    let block982k: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_982681_BYTES.zcash_deserialize_into()?;

    // Start the syncer
    let chain_sync_task_handle = tokio::spawn(chain_sync_future);

    // State is checked for genesis
    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Block 0 is fetched, but the peer returns a much higher block.
    // (Mismatching hashes are usually ignored by the network service,
    // but we use them here to test the syncer lookahead.)
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block0_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block982k.clone(),
            None,
        ))]));

    // Block is dropped because it is too far ahead of the tip.
    // We expect more requests to the state service, because the syncer keeps on running.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    let chain_sync_result = chain_sync_task_handle.now_or_never();
    assert!(
        chain_sync_result.is_none(),
        "unexpected error or panic in chain sync task: {chain_sync_result:?}",
    );

    Ok(())
}

/// Test that the sync downloader rejects blocks that are too high in obtain_tips.
///
/// TODO: also test that it rejects blocks behind the tip limit. (Needs ~100 fake blocks.)
#[tokio::test]
async fn sync_block_too_high_obtain_tips() -> Result<(), crate::BoxError> {
    // Get services
    let (
        chain_sync_future,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup();

    // Get blocks
    let block0: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

    let block1: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?;
    let block1_hash = block1.hash();

    let block2: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_2_BYTES.zcash_deserialize_into()?;
    let block2_hash = block2.hash();

    let block3: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_3_BYTES.zcash_deserialize_into()?;
    let block3_hash = block3.hash();

    // Also get a block that is a long way away from genesis
    let block982k: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_982681_BYTES.zcash_deserialize_into()?;
    let block982k_hash = block982k.hash();

    // Start the syncer
    let chain_sync_task_handle = tokio::spawn(chain_sync_future);

    // ChainSync::request_genesis

    // State is checked for genesis
    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Block 0 is fetched and committed to the state
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block0_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zakura_consensus::Request::Commit(block0))
        .await
        .respond(block0_hash);

    // Check that nothing unexpected happened.
    // We expect more requests to the state service, because the syncer keeps on running.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    // State is checked for genesis again
    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

    // ChainSync::obtain_tips

    // State is asked for a block locator.
    state_service
        .expect_request(zs::Request::BlockLocator)
        .await
        .respond(zs::Response::BlockLocator(vec![block0_hash]));

    // Network is sent the block locator
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![block0_hash],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            block982k_hash,
            block1_hash, // tip
            block2_hash, // expected_next
            block3_hash, // (discarded - last hash, possibly incorrect)
        ]));

    // State is checked for each candidate hash before it is queued.
    state_service
        .expect_request(zs::Request::KnownBlock(block982k_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block2_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Clear remaining block locator requests
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![block0_hash],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test obtain tips error")));
    }

    // Check that nothing unexpected happened.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    // State is checked for all non-tip blocks (blocks 982k, 1, 2) in response order
    state_service
        .expect_request(zs::Request::KnownBlock(block982k_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block2_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Blocks 982k, 1, 2 are fetched in order, then verified concurrently,
    // but block 982k verification is skipped because it is too high.
    peer_set
        .expect_request(zn::Request::BlocksByHash(
            iter::once(block982k_hash).collect(),
        ))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block982k.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block1_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block2_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block2.clone(),
            None,
        ))]));

    // At this point, the following tasks race:
    // - The valid chain verifier requests
    // - The block too high error, which causes a syncer reset and ChainSync::obtain_tips
    // - ChainSync::extend_tips for the next tip

    let chain_sync_result = chain_sync_task_handle.now_or_never();
    assert!(
        chain_sync_result.is_none(),
        "unexpected error or panic in chain sync task: {chain_sync_result:?}",
    );

    Ok(())
}

/// Test that the sync downloader rejects blocks that are too high in extend_tips.
///
/// TODO: also test that it rejects blocks behind the tip limit. (Needs ~100 fake blocks.)
#[tokio::test(start_paused = true)]
async fn sync_block_too_high_extend_tips() -> Result<(), crate::BoxError> {
    // Get services
    let (
        chain_sync_future,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup();

    // Get blocks
    let block0: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

    let block1: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?;
    let block1_hash = block1.hash();

    let block2: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_2_BYTES.zcash_deserialize_into()?;
    let block2_hash = block2.hash();

    let block3: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_3_BYTES.zcash_deserialize_into()?;
    let block3_hash = block3.hash();

    let block4: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_4_BYTES.zcash_deserialize_into()?;
    let block4_hash = block4.hash();

    let block5: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_5_BYTES.zcash_deserialize_into()?;
    let block5_hash = block5.hash();

    // Also get a block that is a long way away from genesis
    let block982k: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_982681_BYTES.zcash_deserialize_into()?;
    let block982k_hash = block982k.hash();

    // Start the syncer
    let chain_sync_task_handle = tokio::spawn(chain_sync_future);

    // ChainSync::request_genesis

    // State is checked for genesis
    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Block 0 is fetched and committed to the state
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block0_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zakura_consensus::Request::Commit(block0))
        .await
        .respond(block0_hash);

    // Check that nothing unexpected happened.
    // We expect more requests to the state service, because the syncer keeps on running.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    // State is checked for genesis again
    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

    // ChainSync::obtain_tips

    // State is asked for a block locator.
    state_service
        .expect_request(zs::Request::BlockLocator)
        .await
        .respond(zs::Response::BlockLocator(vec![block0_hash]));

    // Network is sent the block locator
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![block0_hash],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            block1_hash, // tip
            block2_hash, // expected_next
            block3_hash, // (discarded - last hash, possibly incorrect)
        ]));

    // State is checked for each candidate hash before it is queued.
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block2_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Clear remaining block locator requests
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![block0_hash],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test obtain tips error")));
    }

    // Check that nothing unexpected happened.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    // State is checked for all non-tip blocks (blocks 1 & 2) in response order
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(block2_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    // Blocks 1 & 2 are fetched in order, then verified concurrently
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block1_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block2_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block2.clone(),
            None,
        ))]));

    // We can't guarantee the verification request order
    let mut remaining_blocks: HashMap<block::Hash, Arc<Block>> =
        [(block1_hash, block1), (block2_hash, block2)]
            .iter()
            .cloned()
            .collect();

    for _ in 1..=2 {
        block_verifier_router
            .expect_request_that(|req| remaining_blocks.remove(&req.block().hash()).is_some())
            .await
            .respond_with(|req| req.block().hash());
    }
    assert_eq!(
        remaining_blocks,
        HashMap::new(),
        "expected all non-tip blocks to be verified by obtain tips"
    );

    // Check that nothing unexpected happened.
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    // ChainSync::extend_tips

    // Network is sent a block locator based on the tip
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![block1_hash],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            block2_hash, // tip (discarded - already fetched)
            block3_hash, // expected_next
            block4_hash,
            block982k_hash,
            block5_hash, // (discarded - last hash, possibly incorrect)
        ]));

    for hash in [block3_hash, block4_hash, block982k_hash] {
        state_service
            .expect_request(zs::Request::KnownBlock(hash))
            .await
            .respond(zs::Response::KnownBlock(None));
    }

    // Clear remaining block locator requests
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![block1_hash],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test extend tips error")));
    }

    // Check that nothing unexpected happened.
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    // Blocks 3, 4, 982k are fetched in order, then verified concurrently,
    // but block 982k verification is skipped because it is too high.
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block3_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block3.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block4_hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block4.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlocksByHash(
            iter::once(block982k_hash).collect(),
        ))
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block982k.clone(),
            None,
        ))]));

    // At this point, the following tasks race:
    // - The valid chain verifier requests
    // - The block too high error, which causes a syncer reset and ChainSync::obtain_tips
    // - ChainSync::extend_tips for the next tip

    let chain_sync_result = chain_sync_task_handle.now_or_never();
    assert!(
        chain_sync_result.is_none(),
        "unexpected error or panic in chain sync task: {chain_sync_result:?}",
    );

    Ok(())
}

/// Tests that a `BlockDownloadVerifyError::Invalid` wrapping a
/// `CommitBlockError::Duplicate` error does NOT trigger a sync restart.
#[tokio::test]
async fn should_restart_sync_returns_false() {
    let commit_error = zs::CommitBlockError::Duplicate {
        hash_or_height: None,
        location: zakura_state::KnownBlock::BestChain,
    };

    let verify_block_error = VerifyBlockError::Commit(commit_error);
    let router_error = RouterError::Block {
        source: Box::new(verify_block_error),
    };

    let err = BlockDownloadVerifyError::Invalid {
        error: router_error,
        height: block::Height(42),
        hash: block::Hash::from([0xAA; 32]),
        advertiser_addr: None,
    };

    let restart = ChainSync::<
        MockService<zn::Request, zn::Response, PanicAssertion>,
        MockService<zs::Request, zs::Response, PanicAssertion>,
        MockService<zakura_consensus::Request, block::Hash, PanicAssertion>,
        MockChainTip,
    >::should_restart_sync(&err, false);
    assert!(
        !restart,
        "duplicate commit block errors should NOT trigger sync restart"
    );
}

/// A scratch state can have finalized genesis tip metadata before
/// `KnownBlock(genesis)` can find a block body. In that state, committing the
/// downloaded genesis block returns duplicate/finalized; the genesis bootstrap
/// loop must treat that as success instead of retrying forever.
#[tokio::test]
async fn request_genesis_accepts_duplicate_finalized_genesis() -> Result<(), crate::BoxError> {
    let block0: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

    let state_requests = Arc::new(AtomicUsize::new(0));
    let state_requests_in_service = Arc::clone(&state_requests);
    let state_service = tower::service_fn(move |request| {
        state_requests_in_service.fetch_add(1, Ordering::SeqCst);
        async move {
            assert_eq!(request, zs::Request::KnownBlock(block0_hash));
            Ok::<_, crate::BoxError>(zs::Response::KnownBlock(None))
        }
    });

    let peer_requests = Arc::new(AtomicUsize::new(0));
    let peer_requests_in_service = Arc::clone(&peer_requests);
    let peer_block = block0.clone();
    let peer_set = tower::service_fn(move |request| {
        peer_requests_in_service.fetch_add(1, Ordering::SeqCst);
        let peer_block = peer_block.clone();
        async move {
            assert_eq!(
                request,
                zn::Request::BlocksByHash(iter::once(block0_hash).collect())
            );
            Ok::<_, crate::BoxError>(zn::Response::Blocks(vec![Available((peer_block, None))]))
        }
    });

    let verifier_requests = Arc::new(AtomicUsize::new(0));
    let verifier_requests_in_service = Arc::clone(&verifier_requests);
    let verifier_service = tower::service_fn(move |request| {
        verifier_requests_in_service.fetch_add(1, Ordering::SeqCst);
        async move {
            let zakura_consensus::Request::Commit(block) = request else {
                unreachable!("no other verifier request is allowed")
            };
            assert_eq!(block.hash(), block0_hash);

            let duplicate = zs::CommitBlockError::Duplicate {
                hash_or_height: None,
                location: zs::KnownBlock::Finalized,
            };
            let duplicate = zs::CommitCheckpointVerifiedError::from(duplicate);
            let router_error = RouterError::Checkpoint {
                source: Box::new(VerifyCheckpointError::CommitCheckpointVerified(Box::new(
                    duplicate,
                ))),
            };

            Err::<block::Hash, crate::BoxError>(Box::new(router_error) as crate::BoxError)
        }
    });

    let consensus_config = ConsensusConfig::default();
    let state_config = StateConfig::ephemeral();
    let config = ZakuradConfig {
        consensus: consensus_config,
        state: state_config,
        ..Default::default()
    };
    let (mock_chain_tip, _mock_chain_tip_sender) = MockChainTip::new();
    let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(1);
    let (mut chain_sync, _sync_status) = ChainSync::new(
        &config,
        Height(0),
        peer_set,
        verifier_service,
        state_service,
        mock_chain_tip,
        misbehavior_tx,
    );

    tokio::time::timeout(Duration::from_secs(2), chain_sync.request_genesis())
        .await
        .expect("duplicate finalized genesis should not sleep and retry")
        .expect("duplicate finalized genesis is accepted");

    assert_eq!(state_requests.load(Ordering::SeqCst), 1);
    assert_eq!(peer_requests.load(Ordering::SeqCst), 1);
    assert_eq!(verifier_requests.load(Ordering::SeqCst), 1);

    Ok(())
}

/// In-flight checkpoint downloads can finish after a later contiguous range has
/// already reached finalized state. Those duplicate/finalized responses are
/// stale work, not a reason to restart the whole sync loop.
#[test]
fn duplicate_finalized_checkpoint_block_does_not_restart_sync() -> Result<(), crate::BoxError> {
    let block1: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?;
    let block1_hash = block1.hash();

    let duplicate = zs::CommitBlockError::Duplicate {
        hash_or_height: None,
        location: zs::KnownBlock::Finalized,
    };
    let duplicate = zs::CommitCheckpointVerifiedError::from(duplicate);
    let router_error = RouterError::Checkpoint {
        source: Box::new(VerifyCheckpointError::CommitCheckpointVerified(Box::new(
            duplicate,
        ))),
    };
    let err = BlockDownloadVerifyError::Invalid {
        error: router_error,
        height: Height(1),
        hash: block1_hash,
        advertiser_addr: None,
    };

    let restart = TestChainSync::should_restart_sync(&err, false);

    assert!(
        !restart,
        "duplicate finalized checkpoint blocks are stale in-flight work, not sync restarts"
    );

    Ok(())
}

/// Verifies fix for GHSA-gvjc-3w7c-92jx: `AboveLookaheadHeightLimit` now has
/// an explicit match arm in `should_restart_sync` that returns `false`.
#[tokio::test]
async fn above_lookahead_does_not_restart_sync() {
    let err = BlockDownloadVerifyError::AboveLookaheadHeightLimit {
        height: block::Height(60_000),
        hash: block::Hash::from([0xBB; 32]),
        advertiser_addr: None,
    };

    let restart = ChainSync::<
        MockService<zn::Request, zn::Response, PanicAssertion>,
        MockService<zs::Request, zs::Response, PanicAssertion>,
        MockService<zakura_consensus::Request, block::Hash, PanicAssertion>,
        MockChainTip,
    >::should_restart_sync(&err, false);

    assert!(
        !restart,
        "AboveLookaheadHeightLimit should NOT trigger sync restart (GHSA-gvjc-3w7c-92jx fix)"
    );
}

/// Verifies fix for GHSA-gvjc-3w7c-92jx: `AboveLookaheadHeightLimit` now
/// carries `advertiser_addr` so the offending peer can be scored.
#[tokio::test]
async fn above_lookahead_has_peer_attribution() {
    let addr: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    let err = BlockDownloadVerifyError::AboveLookaheadHeightLimit {
        height: block::Height(60_000),
        hash: block::Hash::from([0xCC; 32]),
        advertiser_addr: Some(addr),
    };

    assert_eq!(
        err.advertiser_addr(),
        Some(addr),
        "AboveLookaheadHeightLimit should carry advertiser_addr for peer scoring \
         (GHSA-gvjc-3w7c-92jx fix)"
    );
}

/// Verifies fix for GHSA-gvjc-3w7c-92jx: both height-limit errors now
/// return `false` from `should_restart_sync` — symmetric handling.
#[tokio::test]
async fn both_height_limits_do_not_restart_sync() {
    let below = BlockDownloadVerifyError::BehindTipHeightLimit {
        height: block::Height(1),
        hash: block::Hash::from([0xDD; 32]),
    };

    let above = BlockDownloadVerifyError::AboveLookaheadHeightLimit {
        height: block::Height(60_000),
        hash: block::Hash::from([0xEE; 32]),
        advertiser_addr: None,
    };

    let restart_below = ChainSync::<
        MockService<zn::Request, zn::Response, PanicAssertion>,
        MockService<zs::Request, zs::Response, PanicAssertion>,
        MockService<zakura_consensus::Request, block::Hash, PanicAssertion>,
        MockChainTip,
    >::should_restart_sync(&below, false);

    let restart_above = ChainSync::<
        MockService<zn::Request, zn::Response, PanicAssertion>,
        MockService<zs::Request, zs::Response, PanicAssertion>,
        MockService<zakura_consensus::Request, block::Hash, PanicAssertion>,
        MockChainTip,
    >::should_restart_sync(&above, false);

    assert!(
        !restart_below,
        "BehindTipHeightLimit should NOT restart sync"
    );
    assert!(
        !restart_above,
        "AboveLookaheadHeightLimit should NOT restart sync (GHSA-gvjc-3w7c-92jx fix)"
    );
}

/// Verifies fix for GHSA-rj6c-83wx-jxf2: `InvalidHeight` does not trigger
/// sync restart and carries `advertiser_addr` for peer scoring.
#[tokio::test]
async fn invalid_height_does_not_restart_sync() {
    let addr: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    let err = BlockDownloadVerifyError::InvalidHeight {
        hash: block::Hash::from([0xFF; 32]),
        advertiser_addr: Some(addr),
    };

    let restart = ChainSync::<
        MockService<zn::Request, zn::Response, PanicAssertion>,
        MockService<zs::Request, zs::Response, PanicAssertion>,
        MockService<zakura_consensus::Request, block::Hash, PanicAssertion>,
        MockChainTip,
    >::should_restart_sync(&err, false);

    assert!(
        !restart,
        "InvalidHeight should NOT trigger sync restart (GHSA-rj6c-83wx-jxf2 fix)"
    );

    assert_eq!(
        err.advertiser_addr(),
        Some(addr),
        "InvalidHeight should carry advertiser_addr for peer scoring"
    );
}

/// Tests that a `notfound` block download failure requeues the missing block
/// before the syncer restarts the whole sync round.
#[tokio::test]
async fn not_found_download_requeues_missing_block() -> Result<(), crate::BoxError> {
    let (
        mut chain_sync,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        _state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let block1: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?;
    let block1_hash = block1.hash();

    let error = BlockDownloadVerifyError::DownloadFailed {
        error: not_found_block_error(block1_hash),
        hash: block1_hash,
    };

    let requeue = tokio::spawn(async move {
        chain_sync
            .handle_block_response_with_missing_retry(Err(error))
            .await
    });

    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(block1_hash).collect()))
        .await
        .respond(Err(not_found_block_error(block1_hash)));

    requeue
        .await
        .expect("missing block retry task should not panic")?;

    block_verifier_router.expect_no_requests().await;

    Ok(())
}

/// Tests that queue-level `notfound` retries are bounded.
#[tokio::test]
async fn not_found_download_restarts_after_queue_retry_limit() {
    let (
        mut chain_sync,
        _sync_status,
        _block_verifier_router,
        mut peer_set,
        _state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let block_hash = block::Hash::from([0xAB; 32]);
    chain_sync
        .missing_block_retry_counts
        .insert(block_hash, sync::MISSING_BLOCK_DOWNLOAD_RETRY_LIMIT);

    let error = BlockDownloadVerifyError::DownloadFailed {
        error: not_found_block_error(block_hash),
        hash: block_hash,
    };

    let result = chain_sync
        .handle_block_response_with_missing_retry(Err(error))
        .await;

    assert!(
        result.is_err(),
        "notfound downloads should restart sync after queue retry limit"
    );

    peer_set.expect_no_requests().await;
}

/// Tests that a `notfound` block download triggers sync restart once the
/// queue-level retry handler has exhausted its retries.
#[tokio::test]
async fn not_found_download_restarts_sync() {
    let block_hash = block::Hash::from([0xCD; 32]);
    let err = BlockDownloadVerifyError::DownloadFailed {
        error: not_found_block_error(block_hash),
        hash: block_hash,
    };

    let restart = TestChainSync::should_restart_sync(&err, false);
    assert!(
        restart,
        "notfound block downloads should restart sync after queue retries"
    );
}

/// Unit test for the refactored [`ChainSync::build_extend`]: it must *discover* the next batch of
/// download hashes from a prospective tip, performing the FindBlocks fan-out and parsing the
/// response, **without** dispatching any block downloads or otherwise touching syncer state.
///
/// This is the core property the continuous-refill `sync_round` `select!` loop relies on: discovery
/// (`build_extend`) runs concurrently as a `self`-free future, while dispatch happens separately via
/// the reserve.
#[tokio::test]
async fn build_extend_discovers_hashes_without_dispatching() -> Result<(), crate::BoxError> {
    let (
        _chain_sync,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let block1: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_1_BYTES.zcash_deserialize_into()?;
    let block1_hash = block1.hash();
    let block2: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_2_BYTES.zcash_deserialize_into()?;
    let block2_hash = block2.hash();
    let block3: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_3_BYTES.zcash_deserialize_into()?;
    let block3_hash = block3.hash();
    let block4: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_4_BYTES.zcash_deserialize_into()?;
    let block4_hash = block4.hash();
    let block5: Arc<Block> =
        zakura_test::vectors::BLOCK_MAINNET_5_BYTES.zcash_deserialize_into()?;
    let block5_hash = block5.hash();

    // A single prospective tip: peers are asked to extend `block1`, expecting `block2` next.
    let tip = sync::CheckedTip {
        tip: block1_hash,
        expected_next: block2_hash,
    };
    let tips: HashSet<_> = iter::once(tip).collect();

    // `build_extend` owns a clone of the tip network so it can run without borrowing `self`.
    let tip_network = Timeout::new(peer_set.clone(), sync::TIPS_RESPONSE_TIMEOUT);
    let extend_handle = tokio::spawn(TestChainSync::build_extend(
        tip_network,
        state_service.clone(),
        tips,
    ));

    // One peer extends the tip. The response starts with the expected hash (the match anchor) and
    // ends with a possibly-incorrect trailing hash that the syncer discards.
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![block1_hash],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            block2_hash, // expected_next (match anchor, not downloaded)
            block3_hash,
            block4_hash,
            block5_hash, // (discarded - last hash, possibly incorrect)
        ]));

    for hash in [block3_hash, block4_hash] {
        state_service
            .expect_request(zs::Request::KnownBlock(hash))
            .await
            .respond(zs::Response::KnownBlock(None));
    }

    // The remaining fan-out requests fail and are ignored.
    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![block1_hash],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test extend tips error")));
    }

    let (download_set, prospective_tips, discovered) = extend_handle
        .await
        .expect("build_extend task should not panic")?;

    // Discovery: blocks 3 & 4 are queued for download, in response order. Block 2 is the match
    // anchor and block 5 is the discarded trailing hash, so neither is downloaded.
    assert_eq!(
        download_set.into_iter().collect::<Vec<_>>(),
        vec![block3_hash, block4_hash],
        "build_extend should discover the inner hashes in response order",
    );
    assert_eq!(
        discovered, 2,
        "discovered count should match the download set length",
    );

    // The new prospective tip extends from block3, expecting block4 next.
    let expected_tip = sync::CheckedTip {
        tip: block3_hash,
        expected_next: block4_hash,
    };
    assert_eq!(
        prospective_tips,
        iter::once(expected_tip).collect(),
        "build_extend should return the next prospective tip",
    );

    // The key property: discovery dispatched no downloads and verified nothing. Only the FindBlocks
    // fan-out was sent — no `BlocksByHash`, no verifier requests.
    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;

    Ok(())
}

#[tokio::test]
async fn obtain_tips_ignores_known_hash_after_first_unknown() -> Result<(), crate::BoxError> {
    let (
        mut chain_sync,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let locator = block::Hash::from([0x01; 32]);
    let unknown = block::Hash::from([0x02; 32]);
    let known_not_in_locator = block::Hash::from([0x03; 32]);
    let trailing = block::Hash::from([0x04; 32]);

    let respond_to_requests = async {
        state_service
            .expect_request(zs::Request::BlockLocator)
            .await
            .respond(zs::Response::BlockLocator(vec![locator]));

        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![locator],
                stop: None,
            })
            .await
            .respond(zn::Response::BlockHashes(vec![
                unknown,
                known_not_in_locator,
                trailing,
            ]));

        state_service
            .expect_request(zs::Request::KnownBlock(unknown))
            .await
            .respond(zs::Response::KnownBlock(None));
        state_service
            .expect_request(zs::Request::KnownBlock(known_not_in_locator))
            .await
            .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

        for _ in 0..(sync::FANOUT - 1) {
            peer_set
                .expect_request(zn::Request::FindBlocks {
                    known_blocks: vec![locator],
                    stop: None,
                })
                .await
                .respond(Err(zn::BoxError::from("synthetic test obtain tips error")));
        }

        Ok::<_, crate::BoxError>(())
    };

    let (extra_hashes, responded) = futures::join!(chain_sync.obtain_tips(), respond_to_requests);
    responded?;
    let extra_hashes = extra_hashes?;
    assert!(extra_hashes.is_empty());

    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    Ok(())
}

#[tokio::test]
async fn build_extend_ignores_malformed_find_blocks_responses() -> Result<(), crate::BoxError> {
    let (
        _chain_sync,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let tip = block::Hash::from([0x10; 32]);
    let expected_next = block::Hash::from([0x11; 32]);
    let unknown = block::Hash::from([0x12; 32]);
    let known_suffix = block::Hash::from([0x13; 32]);
    let trailing = block::Hash::from([0x14; 32]);
    let random = block::Hash::from([0x15; 32]);

    let tips = HashSet::from([sync::CheckedTip { tip, expected_next }]);
    let extend_handle = tokio::spawn(TestChainSync::build_extend(
        Timeout::new(peer_set.clone(), sync::TIPS_RESPONSE_TIMEOUT),
        state_service.clone(),
        tips,
    ));

    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![tip],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            expected_next,
            unknown,
            known_suffix,
            trailing,
        ]));
    state_service
        .expect_request(zs::Request::KnownBlock(unknown))
        .await
        .respond(zs::Response::KnownBlock(None));
    state_service
        .expect_request(zs::Request::KnownBlock(known_suffix))
        .await
        .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![tip],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            expected_next,
            unknown,
            unknown,
            trailing,
        ]));
    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![tip],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![random]));

    let (download_set, prospective_tips, discovered) = extend_handle
        .await
        .expect("build_extend task should not panic")?;
    assert!(download_set.is_empty());
    assert!(prospective_tips.is_empty());
    assert_eq!(discovered, 0);

    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    Ok(())
}

#[tokio::test]
async fn build_extend_rejects_oversized_response_before_state_queries(
) -> Result<(), crate::BoxError> {
    let (
        _chain_sync,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let tip = block::Hash::from([0x20; 32]);
    let expected_next = block::Hash::from([0x21; 32]);
    let trailing = block::Hash::from([0x22; 32]);
    let unknown_hashes = (0..=sync::MAX_TIPS_RESPONSE_HASH_COUNT).map(|index| {
        let index = u64::try_from(index).expect("test hash count fits in u64");
        let mut bytes = [0; 32];
        bytes[..8].copy_from_slice(&index.to_le_bytes());
        block::Hash::from(bytes)
    });
    let response_hashes = std::iter::once(expected_next)
        .chain(unknown_hashes)
        .chain(std::iter::once(trailing))
        .collect();

    let tips = HashSet::from([sync::CheckedTip { tip, expected_next }]);
    let extend_handle = tokio::spawn(TestChainSync::build_extend(
        Timeout::new(peer_set.clone(), sync::TIPS_RESPONSE_TIMEOUT),
        state_service.clone(),
        tips,
    ));

    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![tip],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(response_hashes));

    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![tip],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from(
                "synthetic test oversized response error",
            )));
    }

    let (download_set, prospective_tips, discovered) = extend_handle
        .await
        .expect("build_extend task should not panic")?;
    assert!(download_set.is_empty());
    assert!(prospective_tips.is_empty());
    assert_eq!(discovered, 0);

    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    Ok(())
}

#[tokio::test]
async fn build_extend_rejects_locator_echo_before_state_queries() -> Result<(), crate::BoxError> {
    let (
        _chain_sync,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let tip = block::Hash::from([0x20; 32]);
    let expected_next = block::Hash::from([0x21; 32]);
    let unknown = block::Hash::from([0x22; 32]);
    let trailing = block::Hash::from([0x23; 32]);
    let tips = HashSet::from([sync::CheckedTip { tip, expected_next }]);
    let extend_handle = tokio::spawn(TestChainSync::build_extend(
        Timeout::new(peer_set.clone(), sync::TIPS_RESPONSE_TIMEOUT),
        state_service.clone(),
        tips,
    ));

    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![tip],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            expected_next,
            unknown,
            tip,
            trailing,
        ]));

    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![tip],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test locator echo error")));
    }

    let (download_set, prospective_tips, discovered) = extend_handle
        .await
        .expect("build_extend task should not panic")?;
    assert!(download_set.is_empty());
    assert!(prospective_tips.is_empty());
    assert_eq!(discovered, 0);

    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    Ok(())
}

#[tokio::test]
async fn build_extend_ignores_known_trailing_find_blocks_hash() -> Result<(), crate::BoxError> {
    let (
        _chain_sync,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let tip = block::Hash::from([0x20; 32]);
    let expected_next = block::Hash::from([0x21; 32]);
    let unknown_a = block::Hash::from([0x22; 32]);
    let unknown_b = block::Hash::from([0x23; 32]);

    let tips = HashSet::from([sync::CheckedTip { tip, expected_next }]);
    let extend_handle = tokio::spawn(TestChainSync::build_extend(
        Timeout::new(peer_set.clone(), sync::TIPS_RESPONSE_TIMEOUT),
        state_service.clone(),
        tips,
    ));

    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![tip],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            expected_next,
            unknown_a,
            unknown_b,
            tip, // zcashd can append an unrelated known hash here.
        ]));

    for hash in [unknown_a, unknown_b] {
        state_service
            .expect_request(zs::Request::KnownBlock(hash))
            .await
            .respond(zs::Response::KnownBlock(None));
    }

    for _ in 0..(sync::FANOUT - 1) {
        peer_set
            .expect_request(zn::Request::FindBlocks {
                known_blocks: vec![tip],
                stop: None,
            })
            .await
            .respond(Err(zn::BoxError::from("synthetic test extend tips error")));
    }

    let (download_set, prospective_tips, discovered) = extend_handle
        .await
        .expect("build_extend task should not panic")?;

    assert_eq!(
        download_set.into_iter().collect::<Vec<_>>(),
        vec![unknown_a, unknown_b],
        "build_extend should keep valid inner hashes and discard the trailing known hash",
    );
    assert_eq!(discovered, 2);
    assert_eq!(
        prospective_tips,
        HashSet::from([sync::CheckedTip {
            tip: unknown_a,
            expected_next: unknown_b,
        }]),
    );

    peer_set.expect_no_requests().await;
    block_verifier_router.expect_no_requests().await;
    state_service.expect_no_requests().await;

    Ok(())
}

/// A registry miss (every ready peer marked missing the block) within budget schedules a backoff
/// retry instead of blocking the loop or restarting the round, and does not re-request the block
/// inline — the retry is deferred to the sync loop's timer arm so peers can drain meanwhile.
#[tokio::test]
async fn registry_miss_schedules_backoff_retry() {
    let (
        mut chain_sync,
        _sync_status,
        _block_verifier_router,
        mut peer_set,
        _state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let block_hash = block::Hash::from([0xAB; 32]);
    let error = BlockDownloadVerifyError::DownloadFailed {
        error: not_found_registry_error(block_hash),
        hash: block_hash,
    };

    let result = chain_sync
        .handle_block_response_with_missing_retry(Err(error))
        .await;

    assert!(
        result.is_ok(),
        "a registry miss within budget should keep the round alive, not restart"
    );
    assert!(
        chain_sync.registry_miss_retry.contains_key(&block_hash),
        "the missing block should be scheduled for a backoff retry"
    );
    assert_eq!(
        chain_sync.registry_miss_retry_counts.get(&block_hash),
        Some(&1),
        "the registry-miss retry budget should be consumed once",
    );

    // The retry fires from the sync loop's timer arm, not inline, so no block is re-requested here.
    peer_set.expect_no_requests().await;
}

/// A registry miss past its retry budget restarts the round and clears its retry state.
#[tokio::test]
async fn registry_miss_restarts_after_retry_limit() {
    let (
        mut chain_sync,
        _sync_status,
        _block_verifier_router,
        mut peer_set,
        _state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let block_hash = block::Hash::from([0xCD; 32]);
    chain_sync
        .registry_miss_retry_counts
        .insert(block_hash, sync::MISSING_BLOCK_REGISTRY_RETRY_LIMIT);

    let error = BlockDownloadVerifyError::DownloadFailed {
        error: not_found_registry_error(block_hash),
        hash: block_hash,
    };

    let result = chain_sync
        .handle_block_response_with_missing_retry(Err(error))
        .await;

    assert!(
        result.is_err(),
        "a registry miss should restart sync once the retry budget is exhausted"
    );
    assert!(
        !chain_sync.registry_miss_retry.contains_key(&block_hash),
        "exhausted retry schedule should be cleared"
    );
    assert!(
        !chain_sync
            .registry_miss_retry_counts
            .contains_key(&block_hash),
        "exhausted retry budget should be cleared"
    );

    peer_set.expect_no_requests().await;
}

/// A second block registry-missing while the first is still backing off must not drop the first:
/// both stay scheduled, because the retry state is a per-hash map rather than a single slot.
#[tokio::test]
async fn registry_miss_schedules_multiple_blocks() {
    let (
        mut chain_sync,
        _sync_status,
        _block_verifier_router,
        mut peer_set,
        _state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let first_hash = block::Hash::from([0x11; 32]);
    let second_hash = block::Hash::from([0x22; 32]);

    for hash in [first_hash, second_hash] {
        let error = BlockDownloadVerifyError::DownloadFailed {
            error: not_found_registry_error(hash),
            hash,
        };
        chain_sync
            .handle_block_response_with_missing_retry(Err(error))
            .await
            .expect("a registry miss within budget should not restart");
    }

    assert!(
        chain_sync.registry_miss_retry.contains_key(&first_hash)
            && chain_sync.registry_miss_retry.contains_key(&second_hash),
        "both registry-missed blocks should stay scheduled for retry",
    );

    peer_set.expect_no_requests().await;
}

/// A successful block response clears that block's registry-miss retry schedule and budget, so the
/// head-of-line gate (which pauses speculative dispatch while a retry is pending) lifts and the round
/// resumes once the missing block finally arrives.
#[tokio::test]
async fn registry_miss_retry_clears_on_successful_block() {
    let (
        mut chain_sync,
        _sync_status,
        _block_verifier_router,
        mut peer_set,
        _state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let block_hash = block::Hash::from([0xAB; 32]);

    // A registry miss schedules the block for a backoff retry.
    chain_sync
        .handle_block_response_with_missing_retry(Err(BlockDownloadVerifyError::DownloadFailed {
            error: not_found_registry_error(block_hash),
            hash: block_hash,
        }))
        .await
        .expect("a registry miss within budget should not restart");
    assert!(chain_sync.registry_miss_retry.contains_key(&block_hash));

    // The block then downloads successfully (a peer connected, or the inventory marker expired).
    chain_sync
        .handle_block_response_with_missing_retry(Ok((Height(42), block_hash)))
        .await
        .expect("a successful response should not restart");

    assert!(
        !chain_sync.registry_miss_retry.contains_key(&block_hash),
        "a successful block should clear its scheduled registry-miss retry"
    );
    assert!(
        !chain_sync
            .registry_miss_retry_counts
            .contains_key(&block_hash),
        "a successful block should clear its consumed registry-miss budget"
    );

    peer_set.expect_no_requests().await;
}

/// A successful response clears only the responded block's retry state, leaving other registry-missed
/// blocks scheduled — the retry state is keyed per-hash, so one block arriving must not drop another.
#[tokio::test]
async fn registry_miss_retry_clears_only_the_responded_block() {
    let (
        mut chain_sync,
        _sync_status,
        _block_verifier_router,
        mut peer_set,
        _state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let kept_hash = block::Hash::from([0x11; 32]);
    let arrived_hash = block::Hash::from([0x22; 32]);

    for hash in [kept_hash, arrived_hash] {
        chain_sync
            .handle_block_response_with_missing_retry(Err(
                BlockDownloadVerifyError::DownloadFailed {
                    error: not_found_registry_error(hash),
                    hash,
                },
            ))
            .await
            .expect("a registry miss within budget should not restart");
    }

    // One of the two missing blocks arrives; the other is still missing.
    chain_sync
        .handle_block_response_with_missing_retry(Ok((Height(7), arrived_hash)))
        .await
        .expect("a successful response should not restart");

    assert!(
        !chain_sync.registry_miss_retry.contains_key(&arrived_hash),
        "the arrived block's retry should be cleared"
    );
    assert!(
        chain_sync.registry_miss_retry.contains_key(&kept_hash),
        "a different block's retry must not be cleared by an unrelated success"
    );

    peer_set.expect_no_requests().await;
}

/// The scheduled retry is deferred by the backoff rather than run inline: the recorded deadline is one
/// [`REGISTRY_MISS_RETRY_BACKOFF`] in the future. This is what lets `sync_round` keep draining peers
/// during the wait (the whole point of moving the backoff off the inline blocking `sleep`).
///
/// [`REGISTRY_MISS_RETRY_BACKOFF`]: sync::REGISTRY_MISS_RETRY_BACKOFF
#[tokio::test]
async fn registry_miss_retry_is_deferred_by_the_backoff() {
    let (
        mut chain_sync,
        _sync_status,
        _block_verifier_router,
        mut peer_set,
        _state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let block_hash = block::Hash::from([0xAB; 32]);

    let before = tokio::time::Instant::now();
    chain_sync
        .handle_block_response_with_missing_retry(Err(BlockDownloadVerifyError::DownloadFailed {
            error: not_found_registry_error(block_hash),
            hash: block_hash,
        }))
        .await
        .expect("a registry miss within budget should not restart");
    let after = tokio::time::Instant::now();

    let deadline = chain_sync
        .registry_miss_retry
        .get(&block_hash)
        .copied()
        .expect("the missing block should be scheduled");

    // deadline == insert_time + backoff, and before <= insert_time <= after, so the deadline lands
    // exactly one backoff interval ahead — strictly in the future, never immediate.
    assert!(
        deadline >= before + sync::REGISTRY_MISS_RETRY_BACKOFF
            && deadline <= after + sync::REGISTRY_MISS_RETRY_BACKOFF,
        "the retry deadline should be one backoff interval in the future, not immediate"
    );

    peer_set.expect_no_requests().await;
}

/// Repeated registry misses for the same block accumulate its retry budget and re-arm the backoff
/// deadline each time, so a persistently-missing block keeps head-of-line priority until its budget
/// is exhausted (at which point [`registry_miss_restarts_after_retry_limit`] takes over).
#[tokio::test]
async fn registry_miss_retry_accumulates_budget_for_the_same_block() {
    let (
        mut chain_sync,
        _sync_status,
        _block_verifier_router,
        mut peer_set,
        _state_service,
        _mock_chain_tip_sender,
    ) = setup_chain_sync();

    let block_hash = block::Hash::from([0xAB; 32]);
    let miss = || BlockDownloadVerifyError::DownloadFailed {
        error: not_found_registry_error(block_hash),
        hash: block_hash,
    };

    chain_sync
        .handle_block_response_with_missing_retry(Err(miss()))
        .await
        .expect("a registry miss within budget should not restart");
    let first_deadline = chain_sync
        .registry_miss_retry
        .get(&block_hash)
        .copied()
        .expect("the missing block should be scheduled");

    chain_sync
        .handle_block_response_with_missing_retry(Err(miss()))
        .await
        .expect("a second registry miss within budget should not restart");
    let second_deadline = chain_sync
        .registry_miss_retry
        .get(&block_hash)
        .copied()
        .expect("the missing block should still be scheduled");

    assert_eq!(
        chain_sync.registry_miss_retry_counts.get(&block_hash),
        Some(&2),
        "each registry miss for the same block should consume one more retry from its budget"
    );
    assert!(
        second_deadline >= first_deadline,
        "each miss should re-arm the backoff deadline"
    );

    peer_set.expect_no_requests().await;
}

fn setup() -> (
    // ChainSync
    impl Future<Output = Result<(), Report>> + Send,
    SyncStatus,
    // BlockVerifierRouter
    MockService<zakura_consensus::Request, block::Hash, PanicAssertion>,
    // PeerSet
    MockService<zakura_network::Request, zakura_network::Response, PanicAssertion>,
    // StateService
    MockService<zakura_state::Request, zakura_state::Response, PanicAssertion>,
    MockChainTipSender,
) {
    let (
        chain_sync,
        sync_status,
        block_verifier_router,
        peer_set,
        state_service,
        mock_chain_tip_sender,
    ) = setup_chain_sync();

    let chain_sync_future = chain_sync.sync();

    (
        chain_sync_future,
        sync_status,
        block_verifier_router,
        peer_set,
        state_service,
        mock_chain_tip_sender,
    )
}

fn setup_chain_sync() -> (
    TestChainSync,
    SyncStatus,
    MockService<zakura_consensus::Request, block::Hash, PanicAssertion>,
    MockService<zakura_network::Request, zakura_network::Response, PanicAssertion>,
    MockService<zakura_state::Request, zakura_state::Response, PanicAssertion>,
    MockChainTipSender,
) {
    setup_chain_sync_with_options(Height(0), MAX_SERVICE_REQUEST_DELAY)
}

fn setup_chain_sync_with_options(
    max_checkpoint_height: Height,
    max_service_request_delay: Duration,
) -> (
    TestChainSync,
    SyncStatus,
    MockService<zakura_consensus::Request, block::Hash, PanicAssertion>,
    MockService<zakura_network::Request, zakura_network::Response, PanicAssertion>,
    MockService<zakura_state::Request, zakura_state::Response, PanicAssertion>,
    MockChainTipSender,
) {
    let _init_guard = zakura_test::init();

    let consensus_config = ConsensusConfig::default();
    let state_config = StateConfig::ephemeral();
    let config = ZakuradConfig {
        consensus: consensus_config,
        state: state_config,
        ..Default::default()
    };

    // These tests run multiple tasks in parallel.
    // So machines under heavy load need a longer delay.
    // (For example, CI machines with limited cores.)
    let peer_set = MockService::build()
        .with_max_request_delay(max_service_request_delay)
        .for_unit_tests();

    let block_verifier_router = MockService::build()
        .with_max_request_delay(max_service_request_delay)
        .for_unit_tests();

    let state_service = MockService::build()
        .with_max_request_delay(max_service_request_delay)
        .for_unit_tests();

    let (mock_chain_tip, mock_chain_tip_sender) = MockChainTip::new();

    let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(1);
    let (chain_sync, sync_status) = ChainSync::new(
        &config,
        max_checkpoint_height,
        peer_set.clone(),
        block_verifier_router.clone(),
        state_service.clone(),
        mock_chain_tip,
        misbehavior_tx,
    );

    (
        chain_sync,
        sync_status,
        block_verifier_router,
        peer_set,
        state_service,
        mock_chain_tip_sender,
    )
}

fn not_found_block_error(_hash: block::Hash) -> crate::BoxError {
    zn::SharedPeerError::from(zn::PeerError::NotFoundResponse(Vec::new())).into()
}

/// Builds a download error representing a registry miss: the peer set found
/// every ready peer marked missing the block (a synthetic
/// `NotFoundRegistry`), as opposed to a single peer's `notfound`.
fn not_found_registry_error(_hash: block::Hash) -> crate::BoxError {
    zn::SharedPeerError::from(zn::PeerError::NotFoundRegistry(Vec::new())).into()
}

#[test]
fn debug_skip_regtest_genesis_self_seed_defaults_off_and_is_opt_in() {
    use crate::components::sync::Config;

    // Default is off, so standalone Regtest nodes keep self-seeding genesis.
    assert!(!Config::default().debug_skip_regtest_genesis_self_seed);
    assert_eq!(
        Config::default().debug_blocksync_throughput_target_height,
        None
    );

    // Opt-in still parses despite `deny_unknown_fields`.
    let config: Config = toml::from_str("debug_skip_regtest_genesis_self_seed = true")
        .expect("sync config with the genesis-bootstrap flag parses");
    assert!(config.debug_skip_regtest_genesis_self_seed);
    let config: Config = toml::from_str("debug_blocksync_throughput_target_height = 100")
        .expect("sync config with the block-sync throughput flag parses");
    assert_eq!(config.debug_blocksync_throughput_target_height, Some(100));

    // Skipped on serialize, so `zakurad generate` output (and the stored-config
    // compatibility snapshot) stays stable.
    let serialized = toml::to_string(&Config::default()).expect("sync config serializes");
    assert!(
        !serialized.contains("debug_skip_regtest_genesis_self_seed"),
        "debug bootstrap flag must not appear in generated config output"
    );
    assert!(
        !serialized.contains("debug_blocksync_throughput_target_height"),
        "debug block-sync throughput flag must not appear in generated config output"
    );
}

/// A peer that returns *zero* blocks for a single-hash download request must be
/// treated as a retryable download failure, not crash the whole node.
///
/// Regression for a `downloads.rs` `assert_eq!(blocks.len(), 1)` panic: a
/// gossiped single-hash fetch that raced an empty response took down a Zakura
/// node mid catch-up (`thread 'tokio-rt-worker' panicked ... wrong number of
/// blocks in response to a single hash`, propagated to a fatal syncer panic). A
/// misbehaving or racing peer must not be able to kill the node, so an
/// unexpected block count is surfaced as a `DownloadFailed` the syncer retries.
#[tokio::test]
async fn empty_block_response_is_retryable_download_failure() {
    let _init_guard = zakura_test::init();

    let mut peer_set = MockService::build().for_unit_tests::<zn::Request, zn::Response, _>();
    let verifier =
        MockService::build().for_unit_tests::<zakura_consensus::Request, block::Hash, _>();
    let (chain_tip, _chain_tip_sender) = MockChainTip::new();
    let (past_lookahead_limit_sender, _past_lookahead_limit_receiver) =
        tokio::sync::watch::channel(false);

    let mut downloads = Downloads::new(
        peer_set.clone(),
        verifier,
        chain_tip,
        past_lookahead_limit_sender,
        sync::MIN_CONCURRENCY_LIMIT,
        Height(0),
        LegacySyncTrace::new(None, false),
    );

    let block0: Arc<Block> = zakura_test::vectors::BLOCK_MAINNET_GENESIS_BYTES
        .zcash_deserialize_into()
        .expect("test vector deserializes");
    let hash = block0.hash();

    downloads
        .download_and_verify(hash)
        .await
        .expect("queuing a fresh hash succeeds");

    // The peer responds to the single-hash request with an empty block list.
    peer_set
        .expect_request(zn::Request::BlocksByHash(iter::once(hash).collect()))
        .await
        .respond(zn::Response::Blocks(vec![]));

    let result = downloads
        .next()
        .await
        .expect("the download task produces a result instead of panicking");

    assert!(
        matches!(result, Err(BlockDownloadVerifyError::DownloadFailed { .. })),
        "an empty block response must be a retryable DownloadFailed, got {result:?}",
    );
}