zebrad 7.1.0

The Zcash Foundation's 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
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
//! Fixed test vectors for the syncer.

#![allow(clippy::unwrap_in_result)]

use std::{collections::HashMap, sync::Arc, time::Duration};

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

use zebra_chain::{
    block::{self, Block, Height},
    chain_tip::mock::{MockChainTip, MockChainTipSender},
    parameters::subsidy::SubsidyError,
    serialization::ZcashDeserializeInto,
};
use zebra_consensus::{
    error::TransactionError, BlockError, Config as ConsensusConfig, RouterError, VerifyBlockError,
    VerifyCheckpointError,
};
use zebra_network::{InventoryResponse, PeerSocketAddr};
use zebra_state::Config as StateConfig;
use zebra_test::mock_service::{MockService, PanicAssertion};

use zebra_network as zn;
use zebra_state as zs;

use crate::{
    components::{
        sync::{self, downloads::BlockDownloadVerifyError, RestartReason, SyncStatus},
        ChainSync,
    },
    config::ZebradConfig,
};

use InventoryResponse::*;

/// Maximum time to wait for a request to any test service.
///
/// Mock-only tests pause Tokio time, preserving the full no-request observation window without
/// spending that time idle.
const MAX_SERVICE_REQUEST_DELAY: Duration = Duration::from_millis(1000);

/// 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> =
        zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

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

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

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

    let block4: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_4_BYTES.zcash_deserialize_into()?;
    let block4_hash = block4.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::BlockDownload {
            hash: block0_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zebra_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
        ]));

    // State is checked for the first unknown block (block 1)
    state_service
        .expect_request(zs::Request::KnownBlock(block1_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::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block2_hash,
            advertiser: None,
        })
        .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,
        ]));

    // 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::BlockDownload {
            hash: block3_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block3.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block4_hash,
            advertiser: None,
        })
        .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 the syncer downloads a singleton unknown hash returned by obtain_tips.
#[tokio::test(start_paused = true)]
async fn sync_singleton_obtain_tips_ok() -> Result<(), crate::BoxError> {
    let (
        chain_sync_future,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup();

    let block0: Arc<Block> =
        zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

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

    let chain_sync_task_handle = tokio::spawn(chain_sync_future);

    // ChainSync::request_genesis

    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block0_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

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

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

    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

    // ChainSync::obtain_tips

    state_service
        .expect_request(zs::Request::BlockLocator)
        .await
        .respond(zs::Response::BlockLocator(vec![block0_hash]));

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

    // Find the first unknown hash in this peer response.
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    for _ in 1..sync::FANOUT {
        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")));
    }

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

    // Recheck every hash in the merged download set.
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zebra_consensus::Request::Commit(block1))
        .await
        .respond(block1_hash);

    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 obtain_tips downloads blocks that are queued in the state, waiting for their parent.
///
/// A sync restart cancels in-flight downloads, but blocks that were already queued in the state
/// stay there, so a peer response can contain a missing parent followed by its queued children.
/// If queued blocks were treated as present, obtain_tips would reject every such download set with
/// "queued download of hash behind our chain tip", and the sync would stall forever.
#[tokio::test(start_paused = true)]
async fn sync_obtain_tips_downloads_queued_blocks() -> Result<(), crate::BoxError> {
    let (
        chain_sync_future,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup();

    let block0: Arc<Block> =
        zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

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

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

    let chain_sync_task_handle = tokio::spawn(chain_sync_future);

    // ChainSync::request_genesis

    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

    // ChainSync::obtain_tips

    state_service
        .expect_request(zs::Request::BlockLocator)
        .await
        .respond(zs::Response::BlockLocator(vec![block0_hash]));

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

    // Block 1 is missing, because its download was cancelled by a sync restart.
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    for _ in 1..sync::FANOUT {
        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")));
    }

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

    // Recheck every hash in the merged download set: block 2 is queued, waiting for block 1.
    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(Some(zs::KnownBlock::Queue)));

    // Both blocks are downloaded, so the missing parent reaches the state.
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block2_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block2.clone(),
            None,
        ))]));

    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 the missing parent and its queued child to be verified by obtain tips"
    );

    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 syncer downloads a singleton unknown hash returned by extend_tips.
#[tokio::test(start_paused = true)]
async fn sync_singleton_extend_tips_ok() -> Result<(), crate::BoxError> {
    let (
        chain_sync_future,
        _sync_status,
        mut block_verifier_router,
        mut peer_set,
        mut state_service,
        _mock_chain_tip_sender,
    ) = setup();

    let block0: Arc<Block> =
        zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

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

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

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

    let chain_sync_task_handle = tokio::spawn(chain_sync_future);

    // ChainSync::request_genesis

    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block0_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

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

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

    state_service
        .expect_request(zs::Request::KnownBlock(block0_hash))
        .await
        .respond(zs::Response::KnownBlock(Some(zs::KnownBlock::BestChain)));

    // ChainSync::obtain_tips

    state_service
        .expect_request(zs::Request::BlockLocator)
        .await
        .respond(zs::Response::BlockLocator(vec![block0_hash]));

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

    // Find the first unknown hash in this peer response.
    state_service
        .expect_request(zs::Request::KnownBlock(block1_hash))
        .await
        .respond(zs::Response::KnownBlock(None));

    for _ in 1..sync::FANOUT {
        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")));
    }

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

    // Recheck every hash in the merged download set.
    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));

    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block2_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block2.clone(),
            None,
        ))]));

    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| {
                matches!(req, zebra_consensus::Request::Commit(_))
                    && remaining_blocks.remove(&req.block().hash()).is_some()
            })
            .await
            .respond_with(|req| req.block().hash());
    }
    assert!(
        remaining_blocks.is_empty(),
        "expected obtain tips to verify blocks 1 and 2; remaining blocks: {:?}",
        remaining_blocks.keys().collect::<Vec<_>>(),
    );

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

    // ChainSync::extend_tips

    peer_set
        .expect_request(zn::Request::FindBlocks {
            known_blocks: vec![block1_hash],
            stop: None,
        })
        .await
        .respond(zn::Response::BlockHashes(vec![
            block2_hash, // expected overlap
            block3_hash, // singleton unknown hash
        ]));

    for _ in 1..sync::FANOUT {
        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")));
    }

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

    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block3_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block3.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zebra_consensus::Request::Commit(block3))
        .await
        .respond(block3_hash);

    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 syncer downloads genesis, blocks 1-2 using obtain_tips, and blocks 3-4 using extend_tips,
/// with duplicate block hashes.
///
/// This test also makes sure that the syncer downloads blocks in order.
#[tokio::test(start_paused = true)]
async fn sync_blocks_duplicate_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> =
        zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

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

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

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

    let block4: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_4_BYTES.zcash_deserialize_into()?;
    let block4_hash = block4.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::BlockDownload {
            hash: block0_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zebra_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,
            block1_hash,
            block1_hash, // tip
            block2_hash, // expected_next
        ]));

    // State is checked for the first unknown block (block 1)
    state_service
        .expect_request(zs::Request::KnownBlock(block1_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::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block2_hash,
            advertiser: None,
        })
        .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,
            block3_hash,
            block4_hash,
        ]));

    // 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::BlockDownload {
            hash: block3_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block3.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block4_hash,
            advertiser: None,
        })
        .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 zebra-network rejects blocks that are a long way ahead of the state tip.
#[tokio::test(start_paused = true)]
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> =
        zebra_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> =
        zebra_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::BlockDownload {
            hash: block0_hash,
            advertiser: None,
        })
        .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(start_paused = true)]
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> =
        zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

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

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

    // Also get a block that is a long way away from genesis
    let block982k: Arc<Block> =
        zebra_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::BlockDownload {
            hash: block0_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zebra_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
        ]));

    // State is checked for the first unknown block (block 982k)
    state_service
        .expect_request(zs::Request::KnownBlock(block982k_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::BlockDownload {
            hash: block982k_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block982k.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block2_hash,
            advertiser: None,
        })
        .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> =
        zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES.zcash_deserialize_into()?;
    let block0_hash = block0.hash();

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

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

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

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

    // Also get a block that is a long way away from genesis
    let block982k: Arc<Block> =
        zebra_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::BlockDownload {
            hash: block0_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block0.clone(),
            None,
        ))]));

    block_verifier_router
        .expect_request(zebra_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
        ]));

    // State is checked for the first unknown block (block 1)
    state_service
        .expect_request(zs::Request::KnownBlock(block1_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::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block2_hash,
            advertiser: None,
        })
        .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,
        ]));

    // 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::BlockDownload {
            hash: block3_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block3.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block4_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block4.clone(),
            None,
        ))]));
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block982k_hash,
            advertiser: None,
        })
        .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: zebra_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<zs::ReadRequest, zs::ReadResponse, PanicAssertion>,
        MockService<zebra_consensus::Request, block::Hash, PanicAssertion>,
        MockChainTip,
    >::should_restart_sync(&err);
    assert!(
        !restart,
        "duplicate commit block errors should NOT trigger sync restart"
    );
}

/// 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]),
    };

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

    assert!(
        !restart,
        "AboveLookaheadHeightLimit should NOT trigger sync restart (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]),
        advertiser_addr: None,
    };

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

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

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

    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<zs::ReadRequest, zs::ReadResponse, PanicAssertion>,
        MockService<zebra_consensus::Request, block::Hash, PanicAssertion>,
        MockChainTip,
    >::should_restart_sync(&err);

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

    let has_addr = match &err {
        BlockDownloadVerifyError::InvalidHeight {
            advertiser_addr, ..
        } => advertiser_addr.is_some(),
        _ => false,
    };
    assert!(
        has_addr,
        "InvalidHeight should carry advertiser_addr for peer scoring"
    );
}

/// A concrete `ChainSync` type for calling associated functions in tests.
pub(super) type TestChainSync = ChainSync<
    MockService<zn::Request, zn::Response, PanicAssertion>,
    MockService<zs::Request, zs::Response, PanicAssertion>,
    MockService<zs::ReadRequest, zs::ReadResponse, PanicAssertion>,
    MockService<zebra_consensus::Request, block::Hash, PanicAssertion>,
    MockChainTip,
>;

/// A UTXO lookup timeout and an invalid transaction both leave unrelated downloads running.
#[tokio::test]
async fn transparent_input_not_found_does_not_restart_sync() {
    let make_invalid = |tx_error| BlockDownloadVerifyError::Invalid {
        error: RouterError::Block {
            source: Box::new(VerifyBlockError::Transaction(tx_error)),
        },
        height: block::Height(3_427_629),
        hash: block::Hash::from([0xCC; 32]),
        advertiser_addr: None,
    };

    assert!(
        !TestChainSync::should_restart_sync(&make_invalid(
            TransactionError::TransparentInputNotFound
        )),
        "a transparent input UTXO lookup timeout should NOT trigger sync restart (#11168)"
    );

    assert!(
        !TestChainSync::should_restart_sync(&make_invalid(TransactionError::CoinbasePosition)),
        "an invalid transaction must not cancel unrelated downloads"
    );
}

/// A poisoned `FindBlocks` batch can make every block in a lookahead wave time out on its
/// UTXO lookup with nothing committing in between. The #11168 exemption is bounded so that
/// case still restarts the sync, while a single near-tip race followed by a commit does not.
#[tokio::test]
async fn utxo_lookup_timeouts_without_a_commit_restart_sync() {
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();
    let limit = chain_sync
        .full_verify_concurrency_limit
        .max(sync::MIN_UTXO_RACE_DROPS_BEFORE_RESTART);

    let utxo_timeout = |i: u8| {
        Err(BlockDownloadVerifyError::Invalid {
            error: RouterError::Block {
                source: Box::new(VerifyBlockError::Transaction(
                    TransactionError::TransparentInputNotFound,
                )),
            },
            height: block::Height(3_427_629 + u32::from(i)),
            hash: block::Hash::from([i; 32]),
            advertiser_addr: None,
        })
    };

    for i in 0..(limit - 1) {
        assert!(
            chain_sync
                .handle_block_response(utxo_timeout(i as u8))
                .is_ok(),
            "UTXO lookup timeouts below the lookahead limit should not restart sync (#11168)"
        );
        assert!(
            chain_sync
                .reobtain_hashes
                .contains(&block::Hash::from([i as u8; 32])),
            "a dropped UTXO-race block must be re-requested, not left for a tip walk"
        );
    }

    // A verified block means the race resolved, so the count starts over.
    assert!(chain_sync
        .handle_block_response(Ok((
            block::Height(3_427_628),
            block::Hash::from([0xAA; 32])
        )))
        .is_ok());
    assert!(chain_sync.handle_block_response(utxo_timeout(0)).is_ok());

    for i in 1..(limit - 1) {
        assert!(chain_sync
            .handle_block_response(utxo_timeout(i as u8))
            .is_ok());
    }
    assert!(
        chain_sync
            .handle_block_response(utxo_timeout(0xFF))
            .is_err(),
        "a full lookahead wave of UTXO lookup timeouts with no verified block should restart sync"
    );
}

/// Verifies fix for #11168: the short post-final-checkpoint verify timeout (#5125) does
/// not trigger a sync restart, but the tower-level `BLOCK_VERIFY_TIMEOUT` still does (#5709).
#[tokio::test]
async fn verify_timeout_elapsed_does_not_restart_sync() {
    let tokio_elapsed = tokio::time::timeout(Duration::ZERO, std::future::pending::<()>())
        .await
        .expect_err("timeout on a pending future always elapses");

    let make_error = |error: crate::BoxError| BlockDownloadVerifyError::ValidationRequestError {
        error,
        height: block::Height(3_428_007),
        hash: block::Hash::from([0xCD; 32]),
    };

    assert!(
        !TestChainSync::should_restart_sync(&make_error(tokio_elapsed.into())),
        "the post-final-checkpoint verify timeout should NOT trigger sync restart (#11168)"
    );

    assert!(
        TestChainSync::should_restart_sync(&make_error(
            tower::timeout::error::Elapsed::new().into()
        )),
        "the tower block verify timeout should still trigger sync restart (#5709)"
    );

    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();
    let tokio_elapsed = tokio::time::timeout(Duration::ZERO, std::future::pending::<()>())
        .await
        .expect_err("timeout on a pending future always elapses");
    assert!(chain_sync
        .handle_block_response(Err(make_error(tokio_elapsed.into())))
        .is_ok());
    assert!(
        chain_sync
            .reobtain_hashes
            .contains(&block::Hash::from([0xCD; 32])),
        "a block dropped on the post-checkpoint verify timeout must be re-requested"
    );
}

/// A verifier can drop a valid block because its queue is full of blocks a peer sent, so the
/// syncer requests the block again instead of restarting, which would cancel the downloads that
/// are draining the queue.
#[tokio::test]
async fn queue_full_errors_rerequest_block_without_restart() {
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();

    let errors = [
        RouterError::from(VerifyCheckpointError::QueuedLimit),
        RouterError::from(VerifyBlockError::Commit(
            zs::CommitBlockError::OrphanQueueFull,
        )),
    ];
    for (i, error) in errors.into_iter().enumerate() {
        let hash = block::Hash::from([u8::try_from(i).expect("few errors"); 32]);
        let response = Err(BlockDownloadVerifyError::Invalid {
            error,
            height: block::Height(1),
            hash,
            advertiser_addr: None,
        });

        assert!(chain_sync.handle_block_response(response).is_ok());
        assert!(chain_sync.reobtain_hashes.contains(&hash));
    }
}

/// Regression test for GHSA-g95h-hw6g-pvgv: a behind-tip drop scores the supplying peer and
/// re-queues the hash the syncer still needs.
///
/// Before this fix the drop was free for the peer: it satisfied the download request without
/// delivering a usable block, was never scored, and the hash waited for the next sync round.
#[tokio::test]
async fn behind_tip_height_limit_scores_peer_and_requeues_hash() {
    let (mut chain_sync, mut misbehavior_rx) = new_chain_sync_with_misbehavior();

    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    let hash = block::Hash::from([0xAB; 32]);

    chain_sync
        .handle_block_response(Err(BlockDownloadVerifyError::BehindTipHeightLimit {
            height: block::Height(1),
            hash,
            advertiser_addr: Some(advertiser),
        }))
        .expect("behind-tip drop is non-fatal and must not restart the syncer");

    assert_eq!(
        misbehavior_rx
            .try_recv()
            .ok()
            .map(|report| (report.addr, report.score)),
        Some((advertiser, 100)),
        "BehindTipHeightLimit must score the supplying peer at the ban threshold"
    );
    assert!(
        chain_sync.reobtain_hashes.contains(&hash),
        "BehindTipHeightLimit must re-queue the hash the syncer still needs"
    );
}

/// A behind-tip drop with no peer attribution still re-queues the hash.
///
/// Responses from isolated connections have no transient address, so there is nothing to score, but
/// the hash is still missing.
#[tokio::test]
async fn behind_tip_height_limit_without_advertiser_is_still_requeued() {
    let (mut chain_sync, mut misbehavior_rx) = new_chain_sync_with_misbehavior();

    let hash = block::Hash::from([0xBC; 32]);

    chain_sync
        .handle_block_response(Err(BlockDownloadVerifyError::BehindTipHeightLimit {
            height: block::Height(1),
            hash,
            advertiser_addr: None,
        }))
        .expect("behind-tip drop is non-fatal and must not restart the syncer");

    assert!(
        matches!(
            misbehavior_rx.try_recv(),
            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
        ),
        "an unattributed behind-tip drop must not score any peer"
    );
    assert!(
        chain_sync.reobtain_hashes.contains(&hash),
        "an unattributed behind-tip drop must still re-queue the hash"
    );
}

/// The behind-tip re-request is bounded, so a peer cannot turn it into an unbounded download loop.
#[tokio::test]
async fn behind_tip_height_limit_requeue_is_bounded() {
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();

    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    let hash = block::Hash::from([0xCD; 32]);

    for attempt in 1..=sync::MAX_BLOCK_REOBTAIN_RETRIES + 1 {
        chain_sync
            .handle_block_response(Err(BlockDownloadVerifyError::BehindTipHeightLimit {
                height: block::Height(1),
                hash,
                advertiser_addr: Some(advertiser),
            }))
            .expect("behind-tip drop is non-fatal and must not restart the syncer");

        if attempt <= sync::MAX_BLOCK_REOBTAIN_RETRIES {
            assert!(
                chain_sync.reobtain_hashes.contains(&hash),
                "attempt {attempt} of {} must re-queue the hash",
                sync::MAX_BLOCK_REOBTAIN_RETRIES
            );
        } else {
            assert!(
                chain_sync.reobtain_hashes.is_empty(),
                "the hash must not be re-queued after {} retries",
                sync::MAX_BLOCK_REOBTAIN_RETRIES
            );
            assert!(
                !chain_sync.block_reobtain_retries.contains_key(&hash),
                "exhausted retry bookkeeping must be dropped"
            );
        }

        // Stand in for `reobtain_missing_blocks()`, which drains the set each sync round.
        chain_sync.reobtain_hashes.clear();
    }
}

/// Builds the error the syncer sees when a peer serves a body that doesn't match the
/// authorizing data commitment in the header it was served under.
///
/// The error is wrapped exactly as the production stack wraps it: the state's contextual
/// validation failure, unwrapped by `map_commit_error` into `VerifyBlockError::Commit`,
/// boxed by the router into `RouterError::Block`, and reported by the downloader as
/// `BlockDownloadVerifyError::Invalid`.
fn auth_commitment_mismatch_error(
    hash: block::Hash,
    advertiser_addr: Option<PeerSocketAddr>,
) -> BlockDownloadVerifyError {
    let commit_error = zs::CommitBlockError::ValidateContextError(Box::new(
        zs::ValidateContextError::InvalidBlockCommitment(
            block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment {
                expected: [1; 32],
                actual: [2; 32],
            },
        ),
    ));

    BlockDownloadVerifyError::Invalid {
        error: RouterError::Block {
            source: Box::new(VerifyBlockError::Commit(commit_error)),
        },
        height: block::Height(42),
        hash,
        advertiser_addr,
    }
}

/// A body that fails the authorizing data commitment check must score the serving peer and
/// re-request the hash, without cancelling the sync round.
///
/// The hash is still canonical and still needed — only the served body was forged — so
/// restarting the round would let one forgery idle the syncer for `SYNC_RESTART_DELAY`,
/// and dropping the hash would leave it to a later round to rediscover.
#[tokio::test]
async fn auth_commitment_mismatch_scores_peer_and_requeues_hash_without_restart() {
    let (mut chain_sync, mut misbehavior_rx) = new_chain_sync_with_misbehavior();

    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    let hash = block::Hash::from([0x1A; 32]);

    chain_sync
        .handle_block_response(Err(auth_commitment_mismatch_error(hash, Some(advertiser))))
        .expect("a forged body is non-fatal and must not restart the syncer");

    assert_eq!(
        misbehavior_rx
            .try_recv()
            .ok()
            .map(|report| (report.addr, report.score)),
        Some((advertiser, 100)),
        "the peer that served the forged body must be scored at the ban threshold"
    );
    assert!(
        chain_sync.reobtain_hashes.contains(&hash),
        "the hash is still canonical and still needed, so it must be re-requested"
    );
}

/// The state rejects an honest block queued behind a forged parent along with it. The peer
/// that served the child didn't forge anything, so it must not be scored, but the child's
/// hash is still wanted, so it is re-requested without cancelling the sync round.
///
/// Otherwise one forged body would get every peer that served one of its queued
/// descendants banned too.
#[tokio::test]
async fn descendant_of_auth_commitment_mismatch_is_requeued_without_scoring() {
    let (mut chain_sync, mut misbehavior_rx) = new_chain_sync_with_misbehavior();

    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    let hash = block::Hash::from([0x6F; 32]);

    let commit_error = zs::CommitBlockError::ValidateContextError(Box::new(
        zs::ValidateContextError::InvalidBlockCommitment(
            block::CommitmentError::InvalidChainHistoryBlockTxAuthCommitment {
                expected: [1; 32],
                actual: [2; 32],
            },
        )
        .for_descendant(block::Hash::from([0x1A; 32])),
    ));
    let error = BlockDownloadVerifyError::Invalid {
        error: RouterError::Block {
            source: Box::new(VerifyBlockError::Commit(commit_error)),
        },
        height: block::Height(43),
        hash,
        advertiser_addr: Some(advertiser),
    };

    chain_sync
        .handle_block_response(Err(error))
        .expect("a child of a forged body is non-fatal and must not restart the syncer");

    assert!(
        matches!(
            misbehavior_rx.try_recv(),
            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
        ),
        "the peer that served an honest child of a forged body must not be scored"
    );
    assert!(
        chain_sync.reobtain_hashes.contains(&hash),
        "the child's hash is still wanted, so it must be re-requested"
    );
}

/// A block body that doesn't match its header must score the serving peer and re-request the
/// hash, without cancelling the sync round, whichever component found the mismatch.
///
/// A peer can serve a requested hash with the requested header and a rewritten coinbase height
/// (GHSA-g9rc-89v4-hhvf). Before the block verifiers and the downloader checked that the header
/// commits to that height, the claimed height could get the block dropped as a duplicate, as
/// `Finished`, or as too far ahead or behind, unscored and not re-requested, so its checkpoint
/// range never verified. The errors are wrapped as the router and the downloader wrap them.
#[tokio::test]
async fn body_header_mismatch_scores_peer_and_requeues_hash_without_restart() {
    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    let hash = block::Hash::from([0x9C; 32]);

    for source in [
        // A rewritten coinbase height in a V5 or later coinbase.
        BlockError::Transaction(TransactionError::CoinbaseExpiryBlockHeight {
            expiry_height: Some(Height(43)),
            block_height: Height(42),
            transaction_hash: [3; 32].into(),
        }),
        // Any rewritten transaction ID, including a coinbase height before V5.
        BlockError::BadMerkleRoot {
            actual: block::merkle::Root([1; 32]),
            expected: block::merkle::Root([2; 32]),
        },
        BlockError::DuplicateTransaction,
    ] {
        let invalid = |error| BlockDownloadVerifyError::Invalid {
            error,
            height: Height(42),
            hash,
            advertiser_addr: Some(advertiser),
        };
        let errors = [
            // The checkpoint verifier.
            invalid(RouterError::from(VerifyCheckpointError::from(
                source.clone(),
            ))),
            // The semantic verifier, for a claimed height above the final checkpoint.
            invalid(RouterError::from(VerifyBlockError::from(source.clone()))),
            // The downloader, for a claimed height that would get the block dropped.
            BlockDownloadVerifyError::BodyHeaderMismatch {
                error: source.clone(),
                hash,
                advertiser_addr: Some(advertiser),
            },
        ];

        for error in errors {
            let (mut chain_sync, mut misbehavior_rx) = new_chain_sync_with_misbehavior();
            let description = format!("{error:?}");

            chain_sync
                .handle_block_response(Err(error))
                .expect("a forged body is non-fatal and must not restart the syncer");

            assert_eq!(
                misbehavior_rx
                    .try_recv()
                    .ok()
                    .map(|report| (report.addr, report.score)),
                Some((advertiser, 100)),
                "the peer that served the forged body must be scored at the ban threshold: \
                 {description}"
            );
            assert!(
                chain_sync.reobtain_hashes.contains(&hash),
                "the hash is still wanted, so it must be re-requested: {description}"
            );
        }
    }
}

/// The forged-body re-request is bounded, so a peer cannot turn it into an unbounded
/// download loop.
///
/// The ban for the serving peer is sent to the address book right away, but the first
/// re-request can still reach the same peer before the ban does. This bound is what makes
/// that acceptable.
#[tokio::test]
async fn auth_commitment_mismatch_requeue_is_bounded() {
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();

    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    let hash = block::Hash::from([0x2B; 32]);

    for attempt in 1..=sync::MAX_BLOCK_REOBTAIN_RETRIES + 1 {
        chain_sync
            .handle_block_response(Err(auth_commitment_mismatch_error(hash, Some(advertiser))))
            .expect("a forged body is non-fatal and must not restart the syncer");

        if attempt <= sync::MAX_BLOCK_REOBTAIN_RETRIES {
            assert!(
                chain_sync.reobtain_hashes.contains(&hash),
                "attempt {attempt} of {} must re-queue the hash",
                sync::MAX_BLOCK_REOBTAIN_RETRIES
            );
        } else {
            assert!(
                chain_sync.reobtain_hashes.is_empty(),
                "the hash must not be re-queued after {} retries",
                sync::MAX_BLOCK_REOBTAIN_RETRIES
            );
        }

        // Stand in for `reobtain_missing_blocks()`, which drains the set each sync round.
        chain_sync.reobtain_hashes.clear();
    }
}

/// A forged body served over an isolated connection has no address to score, but the hash
/// is still missing, so it is still re-requested.
#[tokio::test]
async fn auth_commitment_mismatch_without_advertiser_is_still_requeued() {
    let (mut chain_sync, mut misbehavior_rx) = new_chain_sync_with_misbehavior();

    let hash = block::Hash::from([0x3C; 32]);

    chain_sync
        .handle_block_response(Err(auth_commitment_mismatch_error(hash, None)))
        .expect("a forged body is non-fatal and must not restart the syncer");

    assert!(
        matches!(
            misbehavior_rx.try_recv(),
            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
        ),
        "an unattributed forged body must not score any peer"
    );
    assert!(
        chain_sync.reobtain_hashes.contains(&hash),
        "an unattributed forged body must still re-queue the hash"
    );
}

/// Invalid headers and a finished checkpoint verifier do not need a different body.
///
/// A full checkpoint queue is different: the block might be valid, so it is re-requested a
/// bounded number of times (see `queue_pressure`).
#[tokio::test]
async fn other_invalid_errors_are_dropped_without_restart_or_requeue() {
    use zebra_consensus::VerifyCheckpointError;

    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();

    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    let hash = block::Hash::from([0x4D; 32]);

    let errors = [
        RouterError::Block {
            source: Box::new(VerifyBlockError::Block {
                source: zebra_consensus::BlockError::InvalidDifficulty(Height(42), hash),
            }),
        },
        RouterError::Checkpoint {
            source: Box::new(VerifyCheckpointError::Finished),
        },
    ];

    for error in errors {
        let err = BlockDownloadVerifyError::Invalid {
            error,
            height: block::Height(42),
            hash,
            advertiser_addr: Some(advertiser),
        };

        assert!(
            chain_sync.handle_block_response(Err(err)).is_ok(),
            "a block-specific failure must not cancel unrelated downloads"
        );
        assert!(
            !chain_sync.reobtain_hashes.contains(&hash),
            "a block the verifier rejected must not be re-requested"
        );
    }
}

/// Body validation errors share the bounded retry path in both verifier routes.
#[tokio::test]
async fn body_validation_failures_have_bounded_retries() {
    use zebra_consensus::{BlockError, VerifyCheckpointError};

    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();
    let hash = block::Hash::from([0x5D; 32]);
    let errors = [
        BlockError::NoTransactions,
        BlockError::BadMerkleRoot {
            actual: block::merkle::Root([0; 32]),
            expected: block::merkle::Root([1; 32]),
        },
        BlockError::DuplicateTransaction,
        BlockError::WrongTransactionConsensusBranchId,
        BlockError::MissingHeight(hash),
        BlockError::MaxHeight(Height::MAX, hash, Height(1)),
        BlockError::Transaction(TransactionError::Subsidy(SubsidyError::NoCoinbase)),
        BlockError::Transaction(TransactionError::Groth16("invalid proof".into())),
        BlockError::Transaction(TransactionError::MalformedGroth16(
            "invalid encoding".into(),
        )),
        BlockError::Transaction(TransactionError::SaplingVerificationFailed),
        BlockError::Transaction(TransactionError::Halo2VerificationFailed),
        BlockError::Transaction(TransactionError::OrchardProofSize),
        BlockError::Transaction(TransactionError::IronwoodProofSize),
        BlockError::Transaction(TransactionError::Other(
            "transaction has Orchard actions (temporarily disabled)".into(),
        )),
    ];
    for checkpoint in [false, true] {
        for source in &errors {
            for attempt in 1..=sync::MAX_BLOCK_REOBTAIN_RETRIES + 1 {
                let error = VerifyBlockError::from(source.clone());
                let error = if checkpoint {
                    RouterError::Checkpoint {
                        source: Box::new(VerifyCheckpointError::VerifyBlock(error)),
                    }
                } else {
                    RouterError::Block {
                        source: Box::new(error),
                    }
                };
                chain_sync
                    .handle_block_response(Err(BlockDownloadVerifyError::Invalid {
                        error,
                        height: Height(42),
                        hash,
                        advertiser_addr: None,
                    }))
                    .unwrap();
                assert_eq!(
                    chain_sync.reobtain_hashes.shift_remove(&hash),
                    attempt <= sync::MAX_BLOCK_REOBTAIN_RETRIES,
                    "retry {attempt} for {source:?} with checkpoint={checkpoint}"
                );
            }
        }
    }
}

/// Canonical headers do not make a peer's transaction body trustworthy.
#[tokio::test(start_paused = true)]
async fn checkpoint_modified_body_is_retried() {
    canonical_header_modified_body_is_retried(true).await;
}

/// Full verification must recover the same hash after a body-only failure.
#[tokio::test(start_paused = true)]
async fn semantic_modified_body_is_retried() {
    canonical_header_modified_body_is_retried(false).await;
}

async fn canonical_header_modified_body_is_retried(checkpoint_sync: bool) {
    use tower::ServiceExt;
    use zebra_chain::parameters::Network;
    use zebra_consensus::{BlockError, VerifyCheckpointError};

    let _init_guard = zebra_test::init();
    let honest: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1687108_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let hash = honest.hash();
    let height = honest.coinbase_height().unwrap();
    let parent_hash = honest.header.previous_block_hash;
    let parent_height = (height - 1).unwrap();
    let mut forged = honest.as_ref().clone();
    assert!(forged.transactions.len() > 1);
    forged.transactions.pop();
    let forged = Arc::new(forged);
    assert_eq!(
        forged.hash(),
        hash,
        "the peer preserves the canonical header"
    );
    assert_ne!(
        forged
            .transactions
            .iter()
            .map(|tx| tx.hash())
            .collect::<block::merkle::Root>(),
        honest.header.merkle_root
    );

    let state = tower::service_fn(move |request| {
        futures::future::ok::<_, crate::BoxError>(match request {
            zs::Request::Tip => zs::Response::Tip(Some((parent_height, parent_hash))),
            zs::Request::BestChainBlockHash(_) => zs::Response::BlockHash(None),
            zs::Request::KnownBlock(_) => zs::Response::KnownBlock(None),
            _ => unreachable!("a forged body must fail before transaction or state verification"),
        })
    });
    let (router, _mempool, tasks, max_checkpoint_height) = zebra_consensus::router::init_test(
        ConsensusConfig { checkpoint_sync },
        &Network::Mainnet,
        state,
    )
    .await;
    assert_eq!(height <= max_checkpoint_height, checkpoint_sync);
    let mut network = MockService::build().for_unit_tests();
    let (tip, tip_sender) = MockChainTip::new();
    tip_sender.send_best_tip_height(parent_height);
    let (misbehavior_tx, mut misbehavior_rx) = tokio::sync::mpsc::channel(1);
    let (mut chain_sync, _status) = ChainSync::new(
        &ZebradConfig::default(),
        max_checkpoint_height,
        network.clone(),
        router.map_err(crate::BoxError::from),
        state,
        MockService::build().for_unit_tests(),
        tip,
        misbehavior_tx,
    );
    chain_sync
        .downloads
        .download_and_verify(hash)
        .await
        .unwrap();
    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();
    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            forged,
            Some(advertiser),
        ))]));
    let error = chain_sync.downloads.next().await.unwrap().unwrap_err();
    let BlockDownloadVerifyError::Invalid {
        error: ref router_error,
        ..
    } = error
    else {
        panic!("expected a body validation failure, got {error:?}");
    };
    let block_error = match router_error {
        RouterError::Block { source } => source.as_ref(),
        RouterError::Checkpoint { source } => match source.as_ref() {
            VerifyCheckpointError::VerifyBlock(error) => error,
            other => panic!("unexpected checkpoint error: {other:?}"),
        },
    };
    assert!(matches!(
        block_error,
        VerifyBlockError::Block {
            source: BlockError::BadMerkleRoot { .. }
        }
    ));
    chain_sync.handle_block_response(Err(error)).unwrap();
    assert!(
        chain_sync.reobtain_hashes.contains(&hash),
        "a bad body must not discard its still-needed canonical block hash"
    );
    assert_eq!(misbehavior_rx.try_recv().unwrap().score, 100);
    chain_sync.reobtain_missing_blocks().await;
    network
        .expect_request(zn::Request::BlockDownload {
            hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((honest, None))]));
    chain_sync.downloads.cancel_all();
    tasks.state_checkpoint_verify_handle.abort();
}

/// An honest body whose authorizing data matches its header must not be classified as a
/// forgery, whatever else went wrong with it.
///
/// This is the guard against over-banning and over-re-requesting: the errors a
/// behind-tip or far-ahead honest body produces, and the other contextual validation
/// failures, must all stay outside the new arm.
#[tokio::test]
async fn honest_bodies_are_not_classified_as_forgeries() {
    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();

    // A duplicate commit is the benign case the syncer already tolerated.
    let duplicate = zs::CommitBlockError::Duplicate {
        hash_or_height: None,
        location: zs::KnownBlock::BestChain,
    };
    assert!(
        !duplicate.is_auth_commitment_mismatch(),
        "a duplicate block is not a forged body"
    );

    // A sibling commitment failure, which doesn't prove the *serving* peer forged
    // anything: the chain history root is the node's own view of the chain, so a
    // mismatch there can be a local disagreement rather than a forged body.
    let other_context = zs::CommitBlockError::ValidateContextError(Box::new(
        zs::ValidateContextError::InvalidBlockCommitment(
            block::CommitmentError::InvalidChainHistoryRoot {
                expected: [1; 32],
                actual: [2; 32],
            },
        ),
    ));
    assert!(
        !other_context.is_auth_commitment_mismatch(),
        "an unrelated commitment failure is not a forged body"
    );
    assert_eq!(
        other_context.misbehavior_score(),
        0,
        "an unrelated contextual failure must not score the serving peer"
    );

    // The height-limit errors an honest behind-tip or far-ahead body produces are not
    // `Invalid`, so they never reach the new arm.
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();
    let above_hash = block::Hash::from([0x5E; 32]);
    chain_sync
        .handle_block_response(Err(BlockDownloadVerifyError::AboveLookaheadHeightLimit {
            height: block::Height(60_000),
            hash: above_hash,
        }))
        .expect("a far-ahead block is non-fatal and must not restart the syncer");
    assert!(
        chain_sync.reobtain_hashes.is_empty(),
        "a far-ahead honest body must not be re-requested as a forgery"
    );

    let behind_hash = block::Hash::from([0x6F; 32]);
    chain_sync
        .handle_block_response(Err(BlockDownloadVerifyError::BehindTipHeightLimit {
            height: block::Height(1),
            hash: behind_hash,
            advertiser_addr: Some(advertiser),
        }))
        .expect("a behind-tip block is non-fatal and must not restart the syncer");
    assert!(
        chain_sync.reobtain_hashes.contains(&behind_hash),
        "the behind-tip re-request is unchanged by the forged-body arm"
    );
}

/// Every failed block download is re-requested without restarting the sync (#5709).
///
/// Both cases share one bounded re-queue with the behind-tip fix.
#[tokio::test]
async fn download_failures_are_requeued_without_restart() {
    let (mut chain_sync, mut misbehavior_rx) = new_chain_sync_with_misbehavior();

    let missing_hash = block::Hash::from([0xDE; 32]);
    chain_sync
        .handle_block_response(Err(BlockDownloadVerifyError::DownloadFailed {
            error: std::io::Error::new(std::io::ErrorKind::NotFound, "NotFoundResponse").into(),
            hash: missing_hash,
        }))
        .expect("a missing block is non-fatal and must not restart the syncer");

    assert!(
        chain_sync.reobtain_hashes.contains(&missing_hash),
        "a block no peer delivered must be re-queued (#5709)"
    );

    // Other download failures do not restart the sync, so they need the same retry.
    let failed_hash = block::Hash::from([0xEF; 32]);
    let restart = chain_sync
        .handle_block_response(Err(BlockDownloadVerifyError::DownloadFailed {
            error: std::io::Error::new(std::io::ErrorKind::ConnectionReset, "connection reset")
                .into(),
            hash: failed_hash,
        }))
        .is_err();
    assert!(
        !restart,
        "a failed download must not cancel unrelated downloads"
    );

    assert!(
        chain_sync.reobtain_hashes.contains(&failed_hash),
        "a download that failed for another reason must be re-queued"
    );

    // Neither case attributes misbehavior: the download never produced a block to judge.
    assert!(
        matches!(
            misbehavior_rx.try_recv(),
            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
        ),
        "a failed download must not score any peer"
    );
}

/// A download round that expires is re-requested like a missing block, instead of restarting sync.
///
/// When one hedged request fails with `NotFound`, it waits for its sibling, so the round deadline
/// can drop that `NotFound`.
#[tokio::test]
async fn download_round_timeout_is_requeued_without_restart() {
    let (mut chain_sync, mut misbehavior_rx) = new_chain_sync_with_misbehavior();

    let timed_out_hash = block::Hash::from([0xA5; 32]);
    chain_sync
        .handle_block_response(Err(BlockDownloadVerifyError::DownloadTimedOut {
            hash: timed_out_hash,
        }))
        .expect("a download round timeout is non-fatal and must not restart the syncer");

    assert!(
        chain_sync.reobtain_hashes.contains(&timed_out_hash),
        "a block no peer delivered within the download round must be re-queued"
    );

    assert!(
        matches!(
            misbehavior_rx.try_recv(),
            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
        ),
        "a timed out download must not score any peer"
    );
}

/// A block that arrives while its hash is queued for re-download is not re-requested.
#[tokio::test]
async fn verified_block_is_removed_from_reobtain_queue() {
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();

    let hash = block::Hash::from([0xC3; 32]);
    chain_sync.reobtain_hashes.insert(hash);
    chain_sync.block_reobtain_retries.insert(hash, 1);

    chain_sync
        .handle_block_response(Ok((Height(1), hash)))
        .expect("a verified block is not an error");

    assert!(
        !chain_sync.reobtain_hashes.contains(&hash),
        "a verified block must not be re-requested"
    );
    assert!(!chain_sync.block_reobtain_retries.contains_key(&hash));
}

/// Records counters, so tests can check what the syncer counts.
#[derive(Default)]
struct CounterRecorder(std::sync::Mutex<HashMap<metrics::Key, Arc<std::sync::atomic::AtomicU64>>>);

impl CounterRecorder {
    /// Returns the count of the counter with `name` and `labels`, in the order they're recorded.
    fn count(&self, name: &'static str, labels: &[(&'static str, &'static str)]) -> u64 {
        let labels: Vec<_> = labels
            .iter()
            .map(|&(key, value)| metrics::Label::new(key, value))
            .collect();

        self.0
            .lock()
            .expect("test recorder mutex is unpoisoned")
            .get(&metrics::Key::from_parts(name, labels))
            .map_or(0, |count| count.load(std::sync::atomic::Ordering::Relaxed))
    }
}

impl metrics::Recorder for CounterRecorder {
    fn describe_counter(
        &self,
        _: metrics::KeyName,
        _: Option<metrics::Unit>,
        _: metrics::SharedString,
    ) {
    }

    fn describe_gauge(
        &self,
        _: metrics::KeyName,
        _: Option<metrics::Unit>,
        _: metrics::SharedString,
    ) {
    }

    fn describe_histogram(
        &self,
        _: metrics::KeyName,
        _: Option<metrics::Unit>,
        _: metrics::SharedString,
    ) {
    }

    fn register_counter(&self, key: &metrics::Key, _: &metrics::Metadata<'_>) -> metrics::Counter {
        metrics::Counter::from_arc(
            self.0
                .lock()
                .expect("test recorder mutex is unpoisoned")
                .entry(key.clone())
                .or_default()
                .clone(),
        )
    }

    fn register_gauge(&self, _: &metrics::Key, _: &metrics::Metadata<'_>) -> metrics::Gauge {
        metrics::Gauge::noop()
    }

    fn register_histogram(
        &self,
        _: &metrics::Key,
        _: &metrics::Metadata<'_>,
    ) -> metrics::Histogram {
        metrics::Histogram::noop()
    }
}

/// Block errors are counted by bounded kind, and restarts track whether the state tip advanced.
#[tokio::test]
async fn sync_diagnostics_count_block_errors_and_restarts() {
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();
    let diagnostics = chain_sync.diagnostics.subscribe();
    let hash = block::Hash::from([0xC1; 32]);
    let recorder = CounterRecorder::default();

    metrics::with_local_recorder(&recorder, || {
        for error in [
            BlockDownloadVerifyError::DownloadTimedOut { hash },
            BlockDownloadVerifyError::DownloadTimedOut { hash },
            BlockDownloadVerifyError::CancelledDuringDownload { hash },
        ] {
            let _ = chain_sync.handle_block_response(Err(error));
        }

        chain_sync.record_restart(RestartReason::BlockError, false);
        chain_sync.record_restart(RestartReason::ExhaustedTips, false);
        assert_eq!(diagnostics.borrow().restarts_without_progress, 2);

        chain_sync.record_restart(RestartReason::ExhaustedTips, true);
    });

    let error_count = |kind| recorder.count("sync.block.error.count", &[("kind", kind)]);
    assert_eq!(error_count("download_timed_out"), 2);
    assert_eq!(error_count("cancelled"), 1);

    let restart_count = |reason, made_progress| {
        recorder.count(
            "sync.restart.count",
            &[("reason", reason), ("made_progress", made_progress)],
        )
    };
    assert_eq!(restart_count("block_error", "false"), 1);
    assert_eq!(restart_count("exhausted_tips", "false"), 1);
    assert_eq!(restart_count("exhausted_tips", "true"), 1);

    let diagnostics = diagnostics.borrow();
    assert_eq!(diagnostics.last_restart, Some(RestartReason::ExhaustedTips));
    assert_eq!(diagnostics.restarts_without_progress, 0);
}

/// Re-downloads retain the queue if dispatch is cancelled or network readiness times out.
#[tokio::test(start_paused = true)]
async fn reobtain_keeps_blocks_when_cancelled_or_network_readiness_times_out() {
    use tower::limit::ConcurrencyLimit;

    let _init_guard = zebra_test::init();

    let config = ZebradConfig {
        consensus: ConsensusConfig::default(),
        state: StateConfig::ephemeral(),
        ..Default::default()
    };
    let (mock_chain_tip, _mock_chain_tip_sender) = MockChainTip::new();
    let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(4);
    // A peer set with no ready peers: a zero-permit limit never becomes ready.
    let never_ready_network = ConcurrencyLimit::new(MockService::build().for_unit_tests(), 0);
    let (mut chain_sync, _sync_status) = ChainSync::new(
        &config,
        Height(0),
        never_ready_network,
        MockService::build().for_unit_tests(),
        MockService::build().for_unit_tests(),
        MockService::build().for_unit_tests(),
        mock_chain_tip,
        misbehavior_tx,
    );

    let missing = [block::Hash::from([0xB1; 32]), block::Hash::from([0xB2; 32])];
    chain_sync.reobtain_hashes.extend(missing);

    assert!(
        tokio::time::timeout(
            sync::BLOCK_DOWNLOAD_ROUND_TIMEOUT / 2,
            chain_sync.reobtain_missing_blocks(),
        )
        .await
        .is_err(),
        "the dispatch must still be waiting for network capacity"
    );
    assert_eq!(
        chain_sync
            .reobtain_hashes
            .iter()
            .copied()
            .collect::<Vec<_>>(),
        missing,
        "cancelling dispatch must preserve all queued retries"
    );

    let recorder = CounterRecorder::default();
    let metrics_guard = metrics::set_default_local_recorder(&recorder);
    let started = tokio::time::Instant::now();
    chain_sync.reobtain_missing_blocks().await;
    drop(metrics_guard);

    assert_eq!(
        chain_sync
            .reobtain_hashes
            .iter()
            .copied()
            .collect::<Vec<_>>(),
        missing,
        "blocks that couldn't be re-requested must stay queued for the next sync round"
    );
    assert_eq!(
        tokio::time::Instant::now() - started,
        sync::BLOCK_DOWNLOAD_ROUND_TIMEOUT,
        "only the first block waits out its download deadline"
    );
    assert_eq!(
        recorder.count(
            "sync.block.error.count",
            &[("kind", "network_ready_timeout")]
        ),
        1,
        "a block that never got network capacity is counted once"
    );
}

/// Blocks that fail to queue while obtaining or extending tips restart the sync as block errors,
/// while other tip failures keep their stage.
#[test]
fn tip_block_submission_failures_restart_as_block_errors() {
    let block = TestChainSync::tips_restart_error(
        RestartReason::ExtendTipsError,
        BlockDownloadVerifyError::Timeout.into(),
    );
    assert_eq!(block.reason, RestartReason::BlockError);
    assert_eq!(block.kind, Some("network_ready_timeout"));

    let other = TestChainSync::tips_restart_error(
        RestartReason::ObtainTipsError,
        color_eyre::eyre::eyre!("queued download of hash behind our chain tip"),
    );
    assert_eq!(other.reason, RestartReason::ObtainTipsError);
    assert_eq!(other.kind, None);
}

/// A genesis block that can't get network capacity is counted as a block error.
#[tokio::test(start_paused = true)]
async fn genesis_submission_failures_are_counted() {
    let _init_guard = zebra_test::init();

    // A peer set with no ready peers: a zero-permit limit never becomes ready.
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with(
        peer_set_with_permits(0),
        MockService::build().for_unit_tests(),
    );

    let recorder = CounterRecorder::default();
    let metrics_guard = metrics::set_default_local_recorder(&recorder);
    assert!(chain_sync.request_genesis_once().await.is_err());
    drop(metrics_guard);

    assert_eq!(
        recorder.count(
            "sync.block.error.count",
            &[("kind", "network_ready_timeout")]
        ),
        1,
    );
}

/// A genesis retry that finds the block still queued from a timed-out attempt doesn't count a
/// block error, because the syncer ignores it and keeps waiting for that download.
#[tokio::test(start_paused = true)]
async fn genesis_retries_while_the_block_is_queued_are_not_counted() {
    let _init_guard = zebra_test::init();

    // The genesis download gets the only permit, and the mock peer set never answers it.
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with(
        peer_set_with_permits(1),
        MockService::build().for_unit_tests(),
    );

    let recorder = CounterRecorder::default();
    let metrics_guard = metrics::set_default_local_recorder(&recorder);

    for attempt in ["first", "retry"] {
        let genesis =
            tokio::time::timeout(Duration::from_secs(1), chain_sync.request_genesis_once());
        assert!(
            genesis.await.is_err(),
            "the {attempt} attempt never downloads"
        );
    }
    drop(metrics_guard);

    assert_eq!(
        recorder.count("sync.block.error.count", &[("kind", "duplicate_queued")]),
        0,
    );
}

/// A wait for network capacity that the obtain tips or genesis timeout cancels, because both are
/// shorter than the readiness deadline, is counted once as a network readiness timeout.
#[tokio::test(start_paused = true)]
async fn network_capacity_waits_cancelled_by_a_timeout_are_counted_once() {
    use indexmap::IndexSet;

    let _init_guard = zebra_test::init();

    // A peer set with no ready peers: a zero-permit limit never becomes ready.
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with(
        peer_set_with_permits(0),
        MockService::build().for_unit_tests(),
    );

    let recorder = CounterRecorder::default();
    let metrics_guard = metrics::set_default_local_recorder(&recorder);

    let batch = IndexSet::from([block::Hash::from([0xE1; 32])]);
    let tips = tokio::time::timeout(Duration::from_secs(1), chain_sync.request_blocks(batch));
    assert!(tips.await.is_err(), "the block waits for network capacity");
    assert!(chain_sync.count_cancelled_network_wait());

    let genesis = tokio::time::timeout(Duration::from_secs(1), chain_sync.request_genesis_once());
    assert!(
        genesis.await.is_err(),
        "the genesis block waits for network capacity"
    );
    assert!(chain_sync.count_cancelled_network_wait());

    assert!(!chain_sync.count_cancelled_network_wait());
    drop(metrics_guard);

    assert_eq!(
        recorder.count(
            "sync.block.error.count",
            &[("kind", "network_ready_timeout")]
        ),
        2,
    );
}

/// A download that failed before a restart is counted when the restart drops the downloads the
/// syncer hasn't read yet.
#[tokio::test(start_paused = true)]
async fn finished_block_errors_are_counted_before_a_restart_drops_them() {
    use indexmap::IndexSet;

    let _init_guard = zebra_test::init();

    let mut peer_set = MockService::build().for_unit_tests();
    let mut block_verifier_router = MockService::build().for_unit_tests();
    let (mut chain_sync, _misbehavior_rx) =
        new_chain_sync_with(peer_set.clone(), block_verifier_router.clone());

    let block1: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .expect("test vector is a valid block");
    let block1_hash = block1.hash();

    chain_sync
        .request_blocks(IndexSet::from([block1_hash]))
        .await
        .expect("the peer set has capacity");
    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    block_verifier_router
        .expect_request(zebra_consensus::Request::Commit(block1))
        .await
        .respond(Err(zebra_consensus::BoxError::from(
            "synthetic test verifier error",
        )));
    tokio::time::sleep(Duration::from_secs(1)).await;

    let recorder = CounterRecorder::default();
    let metrics_guard = metrics::set_default_local_recorder(&recorder);
    chain_sync.count_finished_block_errors();
    drop(metrics_guard);

    assert_eq!(
        recorder.count("sync.block.error.count", &[("kind", "validation_request")]),
        1,
    );
    assert_eq!(chain_sync.downloads.in_flight(), 0);
}

/// A timeout that cancels a queued block after it got network capacity isn't counted as a wait for
/// network capacity, even when it fires before the queue call returns.
#[tokio::test(start_paused = true)]
async fn timeouts_after_network_capacity_arrives_are_not_counted_as_network_waits() {
    let _init_guard = zebra_test::init();

    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with(
        MockService::build().for_unit_tests(),
        MockService::build().for_unit_tests(),
    );

    // The peer set is ready at once, so this poll sends the download and then yields.
    let mut queueing = Box::pin(chain_sync.queue_block(block::Hash::from([0xE3; 32])));
    assert!(futures::poll!(&mut queueing).is_pending());
    drop(queueing);

    assert!(!chain_sync.count_cancelled_network_wait());
}

/// An obtain tips or sync step timeout that cancels a block's wait for network capacity restarts
/// the sync as that block's network readiness timeout, and counts it. Otherwise the timeout keeps
/// its own restart reason.
#[tokio::test(start_paused = true)]
async fn stage_timeouts_that_cancel_a_network_wait_restart_as_block_errors() {
    use indexmap::IndexSet;

    let _init_guard = zebra_test::init();

    // A peer set with no ready peers: a zero-permit limit never becomes ready.
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with(
        peer_set_with_permits(0),
        MockService::build().for_unit_tests(),
    );

    let recorder = CounterRecorder::default();
    let metrics_guard = metrics::set_default_local_recorder(&recorder);

    let batch = IndexSet::from([block::Hash::from([0xE2; 32])]);
    let elapsed = tokio::time::timeout(Duration::from_secs(1), chain_sync.request_blocks(batch))
        .await
        .expect_err("the block waits for network capacity");
    let waiting = chain_sync.stage_timeout_error(RestartReason::SyncStepTimeout, elapsed);
    assert_eq!(waiting.reason, RestartReason::BlockError);
    assert_eq!(waiting.kind, Some("network_ready_timeout"));

    let elapsed = tokio::time::timeout(Duration::from_secs(1), std::future::pending::<()>())
        .await
        .expect_err("the future never finishes");
    let idle = chain_sync.stage_timeout_error(RestartReason::SyncStepTimeout, elapsed);
    assert_eq!(idle.reason, RestartReason::SyncStepTimeout);
    assert_eq!(idle.kind, None);
    drop(metrics_guard);

    assert_eq!(
        recorder.count(
            "sync.block.error.count",
            &[("kind", "network_ready_timeout")]
        ),
        1,
    );
}

/// A genesis attempt that times out while its queued block downloads is a genesis timeout, which
/// isn't counted, and one that times out waiting for network capacity is a network readiness
/// timeout.
#[tokio::test(start_paused = true)]
async fn genesis_timeouts_are_told_apart_from_network_readiness_timeouts() {
    let _init_guard = zebra_test::init();

    let recorder = CounterRecorder::default();
    let metrics_guard = metrics::set_default_local_recorder(&recorder);

    // The genesis download gets the only permit, and the mock peer set never answers it.
    let (mut downloading, _misbehavior_rx) = new_chain_sync_with(
        peer_set_with_permits(1),
        MockService::build().for_unit_tests(),
    );
    let genesis = tokio::time::timeout(Duration::from_secs(1), downloading.request_genesis_once());
    assert!(genesis.await.is_err(), "the genesis block never downloads");
    assert!(matches!(
        downloading.genesis_timeout(),
        BlockDownloadVerifyError::GenesisTimeout
    ));

    // A peer set with no ready peers: a zero-permit limit never becomes ready.
    let (mut waiting, _misbehavior_rx) = new_chain_sync_with(
        peer_set_with_permits(0),
        MockService::build().for_unit_tests(),
    );
    let genesis = tokio::time::timeout(Duration::from_secs(1), waiting.request_genesis_once());
    assert!(
        genesis.await.is_err(),
        "the genesis block waits for network capacity"
    );
    assert!(matches!(
        waiting.genesis_timeout(),
        BlockDownloadVerifyError::Timeout
    ));
    drop(metrics_guard);

    assert_eq!(
        recorder.count("sync.block.error.count", &[("kind", "genesis_timeout")]),
        0,
    );
    assert_eq!(
        recorder.count(
            "sync.block.error.count",
            &[("kind", "network_ready_timeout")]
        ),
        1,
    );
}

/// While a batch waits for network capacity, the published download state includes the blocks
/// queued earlier in that batch.
#[tokio::test(start_paused = true)]
async fn diagnostics_include_blocks_queued_before_a_readiness_wait() {
    use indexmap::IndexSet;

    let _init_guard = zebra_test::init();

    // The first download holds the only permit, so the second waits for network capacity.
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with(
        peer_set_with_permits(1),
        MockService::build().for_unit_tests(),
    );
    let diagnostics = chain_sync.diagnostics.subscribe();

    let batch = IndexSet::from([block::Hash::from([0xD1; 32]), block::Hash::from([0xD2; 32])]);
    let waiting = tokio::time::timeout(Duration::from_secs(1), chain_sync.request_blocks(batch));
    assert!(
        waiting.await.is_err(),
        "the second block waits for network capacity"
    );

    let diagnostics = diagnostics.borrow();
    assert_eq!(diagnostics.in_flight, 1);
    assert!(diagnostics
        .oldest_in_flight_age(std::time::Instant::now())
        .is_some());
}

/// A genesis block download that never finishes is published as in flight, so the progress task
/// reports its age before the node has a chain tip.
#[tokio::test(start_paused = true)]
async fn diagnostics_include_a_genesis_block_that_never_downloads() {
    let _init_guard = zebra_test::init();

    // The genesis download gets the only permit, and the mock peer set never answers it.
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with(
        peer_set_with_permits(1),
        MockService::build().for_unit_tests(),
    );
    let diagnostics = chain_sync.diagnostics.subscribe();

    let waiting = tokio::time::timeout(Duration::from_secs(1), chain_sync.request_genesis_once());
    assert!(waiting.await.is_err(), "the genesis block never downloads");

    let diagnostics = diagnostics.borrow();
    assert_eq!(diagnostics.in_flight, 1);
    assert!(diagnostics
        .oldest_in_flight_age(std::time::Instant::now())
        .is_some());
}

/// A download that finished isn't reported as in flight while the syncer hasn't read its result,
/// which a node at the tip can leave unread for several sync rounds after queueing the one block
/// it was missing.
#[tokio::test(start_paused = true)]
async fn diagnostics_leave_out_finished_downloads_the_syncer_has_not_read() {
    use indexmap::IndexSet;

    let _init_guard = zebra_test::init();

    let mut peer_set = MockService::build().for_unit_tests();
    let mut block_verifier_router = MockService::build().for_unit_tests();
    let (mut chain_sync, _misbehavior_rx) =
        new_chain_sync_with(peer_set.clone(), block_verifier_router.clone());
    let diagnostics = chain_sync.diagnostics.subscribe();

    let block1: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .expect("test vector is a valid block");
    let block1_hash = block1.hash();

    chain_sync
        .request_blocks(IndexSet::from([block1_hash]))
        .await
        .expect("the peer set has capacity");
    assert!(diagnostics
        .borrow()
        .oldest_in_flight_age(std::time::Instant::now())
        .is_some());

    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    block_verifier_router
        .expect_request(zebra_consensus::Request::Commit(block1))
        .await
        .respond(block1_hash);
    tokio::time::sleep(Duration::from_secs(1)).await;

    assert!(diagnostics
        .borrow()
        .oldest_in_flight_age(std::time::Instant::now())
        .is_none());
}

/// When the oldest download finishes before the syncer reads its result, the age is that of the
/// next download that is still running, even though the syncer hasn't republished since.
#[tokio::test(start_paused = true)]
async fn diagnostics_report_the_next_running_download_when_the_oldest_finishes() {
    use indexmap::IndexSet;

    let _init_guard = zebra_test::init();

    let mut peer_set = MockService::build().for_unit_tests();
    let mut block_verifier_router = MockService::build().for_unit_tests();
    let (mut chain_sync, _misbehavior_rx) =
        new_chain_sync_with(peer_set.clone(), block_verifier_router.clone());
    let diagnostics = chain_sync.diagnostics.subscribe();

    let block1: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .expect("test vector is a valid block");
    let block1_hash = block1.hash();
    // The mock peer set never answers this download.
    let stuck_hash = block::Hash::from([0xD4; 32]);

    chain_sync
        .request_blocks(IndexSet::from([block1_hash]))
        .await
        .expect("the peer set has capacity");
    let stuck_queued_after = std::time::Instant::now();
    chain_sync
        .request_blocks(IndexSet::from([stuck_hash]))
        .await
        .expect("the peer set has capacity");

    peer_set
        .expect_request(zn::Request::BlockDownload {
            hash: block1_hash,
            advertiser: None,
        })
        .await
        .respond(zn::Response::Blocks(vec![Available((
            block1.clone(),
            None,
        ))]));
    block_verifier_router
        .expect_request(zebra_consensus::Request::Commit(block1))
        .await
        .respond(block1_hash);
    tokio::time::sleep(Duration::from_secs(1)).await;

    let now = std::time::Instant::now();
    let age = diagnostics
        .borrow()
        .oldest_in_flight_age(now)
        .expect("the stuck download is still running");
    assert!(
        age <= now.saturating_duration_since(stuck_queued_after),
        "the age is measured from the stuck download, not the finished one"
    );
}

/// Verifies fix for GHSA-qhr3-cvch-5fh2: a block that lands above the lookahead
/// height limit must NOT score the peer that served it, while consensus-invalid
/// blocks still must.
///
/// Far-ahead hashes from a malicious `FindBlocks` response carry no peer attribution,
/// so the follow-up `BlockDownload` request is routed to an independently chosen,
/// honest peer. That serving peer did not choose the height, so scoring this path bans
/// honest peers at the attacker's direction.
#[tokio::test]
async fn far_ahead_block_does_not_produce_misbehavior_score() {
    let (mut chain_sync, mut misbehavior_rx) = new_chain_sync_with_misbehavior();

    let peer: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();

    // Positive control, and proof the channel plumbing works: a consensus-invalid
    // block with a non-zero score must still be reported.
    let router_error = RouterError::Block {
        source: Box::new(VerifyBlockError::Subsidy(SubsidyError::NoCoinbase)),
    };
    let expected_score = router_error.misbehavior_score();
    assert_ne!(
        expected_score, 0,
        "this control needs an error with a non-zero misbehavior score"
    );

    let _ = chain_sync.handle_block_response(Err(BlockDownloadVerifyError::Invalid {
        error: router_error,
        height: block::Height(60_000),
        hash: block::Hash::from([0xAB; 32]),
        advertiser_addr: Some(peer),
    }));
    let report = misbehavior_rx
        .try_recv()
        .expect("consensus-invalid blocks must still score the serving peer");
    assert_eq!(
        (report.addr, report.score),
        (peer, expected_score),
        "consensus-invalid blocks must still score the serving peer"
    );
    assert!(
        report
            .reason
            .starts_with("block failed consensus validation: ")
            && report.reason.contains("NoCoinbase"),
        "the report must explain why the peer was scored, got: {:?}",
        report.reason,
    );

    // The fix: an above-lookahead block must not produce any misbehavior score.
    let _ = chain_sync.handle_block_response(Err(
        BlockDownloadVerifyError::AboveLookaheadHeightLimit {
            height: block::Height(60_000),
            hash: block::Hash::from([0xBB; 32]),
        },
    ));
    assert_eq!(
        misbehavior_rx.try_recv(),
        Err(tokio::sync::mpsc::error::TryRecvError::Empty),
        "GHSA-qhr3-cvch-5fh2: an above-lookahead block must not score the serving peer"
    );
}

/// Build a [`ChainSync`] wired to mock services, returning the receiver end of the misbehavior
/// channel so a test can assert whether a peer was scored.
///
/// Unlike [`setup`], this returns the `ChainSync` value itself rather than its `sync` future, so a
/// test can call response-handling methods directly.
#[allow(clippy::type_complexity)]
pub(in crate::components::sync) fn new_chain_sync_with_misbehavior() -> (
    ChainSync<
        MockService<zn::Request, zn::Response, PanicAssertion>,
        MockService<zs::Request, zs::Response, PanicAssertion>,
        MockService<zs::ReadRequest, zs::ReadResponse, PanicAssertion>,
        MockService<zebra_consensus::Request, block::Hash, PanicAssertion>,
        MockChainTip,
    >,
    tokio::sync::mpsc::Receiver<zn::MisbehaviorReport>,
) {
    let _init_guard = zebra_test::init();

    new_chain_sync_with(
        MockService::build().for_unit_tests(),
        MockService::build().for_unit_tests(),
    )
}

/// Builds a [`ChainSync`] like [`new_chain_sync_with_misbehavior`], downloading from `peer_set`
/// and verifying with `block_verifier_router`.
#[allow(clippy::type_complexity)]
pub(super) fn new_chain_sync_with<ZN>(
    peer_set: ZN,
    block_verifier_router: MockService<zebra_consensus::Request, block::Hash, PanicAssertion>,
) -> (
    ChainSync<
        ZN,
        MockService<zs::Request, zs::Response, PanicAssertion>,
        MockService<zs::ReadRequest, zs::ReadResponse, PanicAssertion>,
        MockService<zebra_consensus::Request, block::Hash, PanicAssertion>,
        MockChainTip,
    >,
    tokio::sync::mpsc::Receiver<zn::MisbehaviorReport>,
)
where
    ZN: tower::Service<zn::Request, Response = zn::Response, Error = crate::BoxError>
        + Send
        + Sync
        + Clone
        + 'static,
    ZN::Future: Send + 'static,
{
    let config = ZebradConfig {
        consensus: ConsensusConfig::default(),
        state: StateConfig::ephemeral(),
        ..Default::default()
    };

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

    let (misbehavior_tx, misbehavior_rx) = tokio::sync::mpsc::channel(4);
    let (chain_sync, _sync_status) = ChainSync::new(
        &config,
        Height(0),
        peer_set,
        block_verifier_router,
        MockService::build().for_unit_tests(),
        MockService::build().for_unit_tests(),
        mock_chain_tip,
        misbehavior_tx,
    );

    (chain_sync, misbehavior_rx)
}

/// A mock peer set that never answers, and serves at most `permits` requests at a time.
///
/// With no permits, it never becomes ready.
fn peer_set_with_permits(
    permits: usize,
) -> tower::limit::ConcurrencyLimit<MockService<zn::Request, zn::Response, PanicAssertion>> {
    tower::limit::ConcurrencyLimit::new(MockService::build().for_unit_tests(), permits)
}

fn setup() -> (
    // ChainSync
    impl Future<Output = Result<(), Report>> + Send,
    SyncStatus,
    // BlockVerifierRouter
    MockService<zebra_consensus::Request, block::Hash, PanicAssertion>,
    // PeerSet
    MockService<zebra_network::Request, zebra_network::Response, PanicAssertion>,
    // StateService
    MockService<zebra_state::Request, zebra_state::Response, PanicAssertion>,
    MockChainTipSender,
) {
    let _init_guard = zebra_test::init();

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

    // All services are in-process mocks, so paused Tokio time cannot race real I/O.
    // Keep the full observation windows for absence assertions.
    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 read_state_service: MockService<zs::ReadRequest, zs::ReadResponse, PanicAssertion> =
        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,
        Height(0),
        peer_set.clone(),
        block_verifier_router.clone(),
        state_service.clone(),
        read_state_service,
        mock_chain_tip,
        misbehavior_tx,
    );

    let chain_sync_future = chain_sync.sync();

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

/// A hash advertised once must exhaust its retry budget across empty and singleton tip rounds.
#[tokio::test(start_paused = true)]
async fn singleton_tip_rounds_reap_completed_downloads() {
    use std::sync::atomic::{AtomicBool, Ordering};

    let _init_guard = zebra_test::init();
    let hash = block::Hash::from([0xF1; 32]);
    let known_hash = block::Hash::from([0xF2; 32]);
    for singleton in [false, true] {
        for download_timeout in [false, true] {
            let advertised = Arc::new(AtomicBool::new(false));
            let network_advertised = advertised.clone();
            let network = tower::service_fn(move |request| {
                let response = match request {
                    zn::Request::FindBlocks { .. } => {
                        let hashes = if !network_advertised.load(Ordering::SeqCst) {
                            vec![hash]
                        } else if singleton {
                            vec![known_hash]
                        } else {
                            Vec::new()
                        };
                        Some(Ok(zn::Response::BlockHashes(hashes)))
                    }
                    zn::Request::BlockDownload {
                        hash: requested, ..
                    } => {
                        assert_eq!(requested, hash);
                        if download_timeout {
                            None
                        } else {
                            Some(Err(crate::BoxError::from("NotFoundResponse")))
                        }
                    }
                    _ => unreachable!("the syncer only requests tips and blocks"),
                };
                async move {
                    match response {
                        Some(response) => response,
                        None => futures::future::pending().await,
                    }
                }
            });
            let state = tower::service_fn(move |request| {
                futures::future::ok::<_, crate::BoxError>(match request {
                    zs::Request::BlockLocator => zs::Response::BlockLocator(vec![known_hash]),
                    zs::Request::KnownBlock(requested) => zs::Response::KnownBlock(
                        (requested == known_hash).then_some(zs::KnownBlock::BestChain),
                    ),
                    _ => unreachable!("the syncer only checks known blocks and the locator"),
                })
            });
            let (tip, _tip_sender) = MockChainTip::new();
            let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(4);
            let (mut chain_sync, _status) = ChainSync::new(
                &ZebradConfig::default(),
                Height(0),
                network,
                MockService::build().for_unit_tests(),
                state,
                MockService::build().for_unit_tests(),
                tip,
                misbehavior_tx,
            );
            chain_sync.full_verify_concurrency_limit = 2;
            chain_sync.try_to_sync().await.unwrap();
            assert_eq!(chain_sync.downloads.in_flight(), 1);
            advertised.store(true, Ordering::SeqCst);

            for attempt in 1..=sync::MAX_BLOCK_REOBTAIN_RETRIES + 1 {
                tokio::time::sleep(sync::BLOCK_DOWNLOAD_ROUND_TIMEOUT + sync::SYNC_RESTART_DELAY)
                    .await;
                tokio::time::timeout(sync::SYNC_RESTART_DELAY, chain_sync.try_to_sync())
                    .await
                    .expect("an empty or singleton tip round must finish")
                    .unwrap();
                assert!(chain_sync.prospective_tips.is_empty());
                let retrying = attempt <= sync::MAX_BLOCK_REOBTAIN_RETRIES;
                assert_eq!(
                    chain_sync.downloads.in_flight(),
                    usize::from(retrying),
                    "the hash must be dropped after its retry budget is exhausted"
                );
                assert_eq!(
                    chain_sync.block_reobtain_retries.get(&hash).copied(),
                    retrying.then_some(attempt),
                    "retry counts must survive the inter-round sleep"
                );
            }
            assert!(chain_sync.reobtain_hashes.is_empty());
            chain_sync.try_to_sync().await.unwrap();
            assert!(chain_sync.downloads.is_empty());
            chain_sync
                .downloads
                .download_and_verify(hash)
                .await
                .expect("reaping the exhausted download must remove its cancellation handle");
            chain_sync.downloads.cancel_all();
        }
    }
}

/// A terminal header rejection must not leave its previous retry budget behind.
#[tokio::test(start_paused = true)]
async fn terminal_header_failure_reaps_retry_counter_next_round() {
    let _init_guard = zebra_test::init();
    let hash = block::Hash::from([0xE1; 32]);
    let network = tower::service_fn(|request| {
        assert!(matches!(request, zn::Request::FindBlocks { .. }));
        futures::future::ok::<_, crate::BoxError>(zn::Response::BlockHashes(Vec::new()))
    });
    let state = tower::service_fn(move |request| {
        assert!(matches!(request, zs::Request::BlockLocator));
        futures::future::ok::<_, crate::BoxError>(zs::Response::BlockLocator(vec![hash]))
    });
    let (tip, _tip_sender) = MockChainTip::new();
    let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(4);
    let (mut chain_sync, _status) = ChainSync::new(
        &ZebradConfig::default(),
        Height(0),
        network,
        MockService::build().for_unit_tests(),
        state,
        MockService::build().for_unit_tests(),
        tip,
        misbehavior_tx,
    );

    chain_sync
        .handle_block_response(Err(BlockDownloadVerifyError::DownloadTimedOut { hash }))
        .unwrap();
    assert!(chain_sync.reobtain_hashes.shift_remove(&hash));
    chain_sync
        .handle_block_response(Err(BlockDownloadVerifyError::Invalid {
            error: RouterError::Block {
                source: Box::new(VerifyBlockError::Block {
                    source: zebra_consensus::BlockError::InvalidDifficulty(Height(1), hash),
                }),
            },
            height: Height(1),
            hash,
            advertiser_addr: None,
        }))
        .unwrap();
    assert!(chain_sync.block_reobtain_retries.contains_key(&hash));
    chain_sync.try_to_sync().await.unwrap();
    assert!(
        !chain_sync.block_reobtain_retries.contains_key(&hash),
        "terminal failures must release retry bookkeeping before the next tip round"
    );
}

/// A failed ancestor is retried after the inter-round sleep, even without fresh tip hashes.
#[tokio::test(start_paused = true)]
async fn inter_round_ancestor_failure_is_retried() {
    use std::sync::atomic::{AtomicBool, Ordering};

    let _init_guard = zebra_test::init();
    let parent: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let child: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_2_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let parent_hash = parent.hash();
    let child_hash = child.hash();
    for singleton in [false, true] {
        let recovered = Arc::new(AtomicBool::new(false));
        let network_recovered = recovered.clone();
        let parent = parent.clone();
        let network_child = child.clone();
        let network = tower::service_fn(move |request| {
            let response = match request {
                zn::Request::FindBlocks { .. } => {
                    let hashes = if !network_recovered.load(Ordering::SeqCst) {
                        vec![parent_hash]
                    } else if singleton {
                        vec![child_hash]
                    } else {
                        Vec::new()
                    };
                    Ok(zn::Response::BlockHashes(hashes))
                }
                zn::Request::BlockDownload { hash, .. } if hash == child_hash => Ok(
                    zn::Response::Blocks(vec![Available((network_child.clone(), None))]),
                ),
                zn::Request::BlockDownload { hash, .. } if hash == parent_hash => {
                    if network_recovered.load(Ordering::SeqCst) {
                        Ok(zn::Response::Blocks(vec![Available((
                            parent.clone(),
                            None,
                        ))]))
                    } else {
                        Err(crate::BoxError::from("NotFoundResponse"))
                    }
                }
                _ => unreachable!("only the parent, child, and tips are requested"),
            };
            futures::future::ready(response)
        });
        let state = tower::service_fn(move |request| {
            futures::future::ok::<_, crate::BoxError>(match request {
                zs::Request::BlockLocator => zs::Response::BlockLocator(vec![parent_hash]),
                zs::Request::KnownBlock(_) => zs::Response::KnownBlock(None),
                _ => unreachable!("only known blocks and the locator are queried"),
            })
        });
        let mut verifier = MockService::build().for_unit_tests();
        let (tip, _tip_sender) = MockChainTip::new();
        let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(1);
        let (mut chain_sync, _status) = ChainSync::new(
            &ZebradConfig::default(),
            Height(0),
            network,
            verifier.clone(),
            state,
            MockService::build().for_unit_tests(),
            tip,
            misbehavior_tx,
        );
        chain_sync
            .downloads
            .download_and_verify(child_hash)
            .await
            .unwrap();
        let pending_child = verifier
            .expect_request(zebra_consensus::Request::Commit(child.clone()))
            .await;
        chain_sync.try_to_sync().await.unwrap();
        tokio::time::sleep(sync::SYNC_RESTART_DELAY).await;
        recovered.store(true, Ordering::SeqCst);
        chain_sync.try_to_sync().await.unwrap();
        verifier
            .expect_request_that(|request: &zebra_consensus::Request| {
                request.block().hash() == parent_hash
            })
            .await
            .respond(parent_hash);
        pending_child.respond(child_hash);
        let results = tokio::time::timeout(Duration::from_secs(1), async {
            let mut hashes = Vec::new();
            while let Some(response) = chain_sync.downloads.next().await {
                hashes.push(response.unwrap().1);
            }
            hashes
        })
        .await
        .expect("the recovered parent and retained child must both finish");
        assert!(results.contains(&parent_hash) && results.contains(&child_hash));
    }
}

/// A first responder must not fill the batch before another peer's next block is admitted.
#[tokio::test(start_paused = true)]
async fn sync_tip_responses_share_batch_capacity() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    let _init_guard = zebra_test::init();
    let [honest, adversary_first, adversary_second, overlap] =
        [1, 98, 99, 97].map(|byte| block::Hash::from([byte; 32]));

    for extend in [false, true] {
        for duplicate in [false, true] {
            let response_index = Arc::new(AtomicUsize::new(0));
            let network = tower::service_fn(move |request| {
                let response = match request {
                    zn::Request::FindBlocks { .. } => {
                        let mut hashes = match response_index.fetch_add(1, Ordering::SeqCst) {
                            0 => {
                                let mut hashes = vec![adversary_first, adversary_second];
                                if duplicate {
                                    hashes.push(honest);
                                }
                                hashes
                            }
                            1 => vec![honest],
                            _ => Vec::new(),
                        };
                        if extend {
                            hashes.insert(0, overlap);
                        }
                        Some(zn::Response::BlockHashes(hashes))
                    }
                    zn::Request::BlockDownload { .. } => None,
                    _ => unreachable!("the syncer only requests tips and blocks"),
                };
                // Each tip response completes before the fanout yields to dispatch the next.
                async move {
                    match response {
                        Some(response) => Ok::<_, crate::BoxError>(response),
                        None => futures::future::pending().await,
                    }
                }
            });
            let state = tower::service_fn(|request| {
                let response = match request {
                    zs::Request::BlockLocator => {
                        zs::Response::BlockLocator(vec![block::Hash::from([0; 32])])
                    }
                    zs::Request::KnownBlock(_) => zs::Response::KnownBlock(None),
                    _ => unreachable!("the syncer only checks known blocks and the locator"),
                };
                futures::future::ok::<_, crate::BoxError>(response)
            });
            let (tip, tip_sender) = MockChainTip::new();
            tip_sender.send_best_tip_height(Height(0));
            let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(1);
            let (mut chain_sync, _status) = ChainSync::new(
                &ZebradConfig::default(),
                Height(0),
                network,
                MockService::build().for_unit_tests(),
                state,
                MockService::build().for_unit_tests(),
                tip,
                misbehavior_tx,
            );
            chain_sync.full_verify_concurrency_limit = 2;
            if extend {
                chain_sync.prospective_tips.insert(sync::CheckedTip {
                    tip: block::Hash::from([0; 32]),
                    expected_next: overlap,
                });
            }

            let extra = tokio::time::timeout(MAX_SERVICE_REQUEST_DELAY, async {
                if extend {
                    chain_sync.extend_tips().await
                } else {
                    chain_sync.obtain_tips().await
                }
            })
            .await
            .expect("a tip round must finish without waiting for pending block downloads")
            .unwrap();

            assert_eq!(
                extra.into_iter().collect::<Vec<_>>(),
                vec![adversary_second],
                "the honest successor must be admitted in this round"
            );
            assert_eq!(chain_sync.downloads.in_flight(), 2);
            assert!(matches!(
                chain_sync.downloads.download_and_verify(honest).await,
                Err(BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { .. })
            ));
            chain_sync.downloads.cancel_all();
        }
    }
}

/// New batches use only the remaining lookahead capacity and preserve the unqueued suffix.
#[tokio::test(start_paused = true)]
async fn request_blocks_respects_remaining_capacity() {
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();
    chain_sync.full_verify_concurrency_limit = 2;
    let hashes = [1, 2, 3].map(|byte| block::Hash::from([byte; 32]));

    assert!(chain_sync
        .request_blocks([hashes[0]].into_iter().collect())
        .await
        .unwrap()
        .is_empty());
    let extra = chain_sync
        .request_blocks(hashes[1..].iter().copied().collect())
        .await
        .unwrap();
    assert_eq!(extra.iter().copied().collect::<Vec<_>>(), vec![hashes[2]]);
    assert_eq!(chain_sync.downloads.in_flight(), 2);

    let extra = chain_sync.request_blocks(extra).await.unwrap();
    assert_eq!(extra.into_iter().collect::<Vec<_>>(), vec![hashes[2]]);
    assert_eq!(chain_sync.downloads.in_flight(), 2);
    chain_sync.downloads.cancel_all();
}

/// Delayed retries retain capacity so a fresh batch cannot overfill the queue when they resume.
#[tokio::test(start_paused = true)]
async fn request_blocks_reserves_capacity_for_retries() {
    let (mut chain_sync, _misbehavior_rx) = new_chain_sync_with_misbehavior();
    chain_sync.full_verify_concurrency_limit = 2;
    let hashes = [1, 2, 3].map(|byte| block::Hash::from([byte; 32]));
    chain_sync.reobtain_hashes.insert(hashes[0]);

    let extra = chain_sync
        .request_blocks(hashes[1..].iter().copied().collect())
        .await
        .unwrap();
    assert_eq!(extra.into_iter().collect::<Vec<_>>(), vec![hashes[2]]);
    assert_eq!(chain_sync.downloads.in_flight(), 1);

    chain_sync.reobtain_missing_blocks().await;
    assert_eq!(chain_sync.downloads.in_flight(), 2);
    assert!(chain_sync.reobtain_hashes.is_empty());
    chain_sync.downloads.cancel_all();
}

/// A partially queued final checkpoint must leave room for its missing blocks.
#[tokio::test(start_paused = true)]
async fn partial_final_checkpoint_keeps_admission_capacity() {
    let _init_guard = zebra_test::init();
    let blocks: Vec<Arc<Block>> = zebra_test::vectors::CONTINUOUS_MAINNET_BLOCKS
        .range(1..=9)
        .map(|(_, bytes)| bytes.zcash_deserialize_into().unwrap())
        .collect();
    let hashes: Vec<_> = blocks.iter().map(|block| block.hash()).collect();
    let network = tower::service_fn(move |request| {
        let zn::Request::BlockDownload { hash, .. } = request else {
            panic!("only block downloads are expected");
        };
        let block = blocks.iter().find(|block| block.hash() == hash).unwrap();
        futures::future::ok::<_, crate::BoxError>(zn::Response::Blocks(vec![Available((
            block.clone(),
            None,
        ))]))
    });
    let mut verifier = MockService::build().for_unit_tests();
    let (tip, tip_sender) = MockChainTip::new();
    tip_sender.send_best_tip_height(Height(0));
    let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(1);
    let mut config = ZebradConfig::default();
    config.sync.full_verify_concurrency_limit = 1;
    let (mut chain_sync, _status) = ChainSync::new(
        &config,
        Height(5),
        network,
        verifier.clone(),
        MockService::build().for_unit_tests(),
        MockService::build().for_unit_tests(),
        tip,
        misbehavior_tx,
    );

    assert!(chain_sync
        .request_blocks(hashes[..3].iter().copied().collect())
        .await
        .unwrap()
        .is_empty());
    let mut pending_checkpoint = Vec::new();
    for _ in 0..3 {
        pending_checkpoint.push(verifier.expect_request_that(|_| true).await);
    }
    let extra = chain_sync
        .request_blocks(hashes[3..].iter().copied().collect())
        .await
        .unwrap();
    assert_eq!(chain_sync.downloads.in_flight(), 6);
    assert_eq!(extra.iter().copied().collect::<Vec<_>>(), hashes[6..]);
    for _ in 0..3 {
        pending_checkpoint.push(verifier.expect_request_that(|_| true).await);
    }
    assert!(pending_checkpoint
        .iter()
        .any(|request| request.request().block().coinbase_height() == Some(Height(5))));

    // The final checkpoint and first fully verified block can now finish.
    for request in pending_checkpoint {
        request.respond_with(|request| request.block().hash());
    }
    tip_sender.send_best_tip_height(Height(6));
    let extra = tokio::time::timeout(
        MAX_SERVICE_REQUEST_DELAY,
        chain_sync.try_to_sync_once(extra),
    )
    .await
    .expect("a completed final checkpoint must not block the full-verification pipeline")
    .unwrap();
    assert_eq!(chain_sync.downloads.in_flight(), 1);
    assert_eq!(extra.into_iter().collect::<Vec<_>>(), hashes[7..]);
    chain_sync.downloads.cancel_all();
}

/// A stale height-pause flag must not make a single-slot queue wait for a nonexistent task.
#[tokio::test(start_paused = true)]
async fn high_invalid_block_does_not_pause_an_empty_queue() {
    let _init_guard = zebra_test::init();
    let block: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_347499_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let hash = block.hash();
    let next_hash = block::Hash::from([0xA7; 32]);
    let network = tower::service_fn(move |request| {
        let block = block.clone();
        async move {
            match request {
                zn::Request::BlockDownload {
                    hash: requested, ..
                } if requested == hash => Ok(zn::Response::Blocks(vec![Available((block, None))])),
                zn::Request::BlockDownload { hash, .. } if hash == next_hash => {
                    futures::future::pending::<Result<zn::Response, crate::BoxError>>().await
                }
                _ => unreachable!("only the advertised blocks are requested"),
            }
        }
    });
    let verifier = tower::service_fn(move |_| {
        futures::future::err::<block::Hash, crate::BoxError>(
            RouterError::Block {
                source: Box::new(VerifyBlockError::Block {
                    source: zebra_consensus::BlockError::InvalidDifficulty(Height(347_499), hash),
                }),
            }
            .into(),
        )
    });
    let (tip, tip_sender) = MockChainTip::new();
    tip_sender.send_best_tip_height(Height(300_000));
    let (misbehavior_tx, _misbehavior_rx) = tokio::sync::mpsc::channel(1);
    let mut config = ZebradConfig::default();
    config.sync.full_verify_concurrency_limit = 1;
    let (mut chain_sync, _status) = ChainSync::new(
        &config,
        Height(0),
        network,
        verifier,
        MockService::build().for_unit_tests(),
        MockService::build().for_unit_tests(),
        tip,
        misbehavior_tx,
    );
    chain_sync
        .request_blocks([hash].into_iter().collect())
        .await
        .unwrap();
    let extra = tokio::time::timeout(
        MAX_SERVICE_REQUEST_DELAY,
        chain_sync.try_to_sync_once([next_hash].into_iter().collect()),
    )
    .await
    .expect("a failed block must release the only download slot")
    .unwrap();
    assert!(chain_sync.past_lookahead_limit_receiver.cloned_watch_data());
    assert!(extra.is_empty());
    assert_eq!(chain_sync.downloads.in_flight(), 1);
    chain_sync.downloads.cancel_all();
}

/// One invalid block or exhausted download must not cancel an honest pending verification.
#[tokio::test(start_paused = true)]
async fn failed_block_preserves_honest_pending_verification() {
    let _init_guard = zebra_test::init();
    let honest: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let invalid: Arc<Block> = zebra_test::vectors::BLOCK_MAINNET_2_BYTES
        .zcash_deserialize_into()
        .unwrap();
    let honest_hash = honest.hash();
    let invalid_hash = invalid.hash();
    let advertiser: PeerSocketAddr = "127.0.0.1:8233".parse().unwrap();

    for download_failure in [false, true] {
        let blocks = [honest.clone(), invalid.clone()];
        let network = tower::service_fn(move |request| {
            let zn::Request::BlockDownload { hash, .. } = request else {
                panic!("no tip requests are needed without prospective tips");
            };
            let response = if download_failure && hash == invalid_hash {
                Err(crate::BoxError::from("connection reset"))
            } else {
                let block = blocks.iter().find(|block| block.hash() == hash).unwrap();
                Ok(zn::Response::Blocks(vec![Available((
                    block.clone(),
                    Some(advertiser),
                ))]))
            };
            futures::future::ready(response)
        });
        let mut verifier = MockService::build().for_unit_tests();
        let (tip, _tip_sender) = MockChainTip::new();
        let (misbehavior_tx, mut misbehavior_rx) = tokio::sync::mpsc::channel(4);
        let (mut chain_sync, _status) = ChainSync::new(
            &ZebradConfig::default(),
            Height(0),
            network,
            verifier.clone(),
            MockService::build().for_unit_tests(),
            MockService::build().for_unit_tests(),
            tip,
            misbehavior_tx,
        );
        chain_sync.full_verify_concurrency_limit = 2;

        chain_sync
            .request_blocks([invalid_hash].into_iter().collect())
            .await
            .unwrap();
        let invalid_request = if download_failure {
            None
        } else {
            Some(
                verifier
                    .expect_request(zebra_consensus::Request::Commit(invalid.clone()))
                    .await,
            )
        };
        chain_sync
            .request_blocks([honest_hash].into_iter().collect())
            .await
            .unwrap();
        let honest_request = verifier
            .expect_request(zebra_consensus::Request::Commit(honest.clone()))
            .await;

        let error = RouterError::Block {
            source: Box::new(VerifyBlockError::Block {
                source: zebra_consensus::BlockError::InvalidDifficulty(Height(2), invalid_hash),
            }),
        };
        let expected_score = error.misbehavior_score();
        if let Some(request) = invalid_request {
            request.respond_error(error.into());
        }
        tokio::time::timeout(
            sync::BLOCK_DOWNLOAD_TIMEOUT,
            chain_sync.try_to_sync_once(Default::default()),
        )
        .await
        .expect("handling a failed block must not wait for the honest verification")
        .expect("a failed block must not restart the sync round");

        // A failed download is re-requested while the honest block waits, until its bounded
        // retries are exhausted. An invalid header is not re-requested.
        assert_eq!(chain_sync.downloads.in_flight(), 1);
        assert!(chain_sync.reobtain_hashes.is_empty());
        assert!(chain_sync.block_reobtain_retries.is_empty());
        if download_failure {
            assert!(misbehavior_rx.try_recv().is_err());
        } else {
            let report = misbehavior_rx.try_recv().unwrap();
            assert_ne!(expected_score, 0);
            assert_eq!((report.addr, report.score), (advertiser, expected_score));
        }

        honest_request.respond(honest_hash);
        let committed =
            tokio::time::timeout(MAX_SERVICE_REQUEST_DELAY, chain_sync.downloads.next())
                .await
                .expect("the honest verification must still complete")
                .expect("the honest download must still be tracked")
                .expect("the honest download must not be cancelled");
        assert_eq!(committed, (Height(1), honest_hash));
        assert!(chain_sync.downloads.is_empty());
    }
}

/// Wrapped service, state, and shutdown errors still require a sync restart.
#[test]
fn infrastructure_verification_errors_restart_sync() {
    use zebra_consensus::{BlockError, VerifyCheckpointError};

    let hash = block::Hash::from([0xD1; 32]);
    let block_errors = [
        VerifyBlockError::Depth {
            source: "state depth failed".into(),
            hash,
        },
        VerifyBlockError::StateService {
            source: "state failed".into(),
            hash,
        },
        VerifyBlockError::Commit(zs::CommitBlockError::new_write_task_exited()),
        VerifyBlockError::Block {
            source: BlockError::Other("internal failure".into()),
        },
        VerifyBlockError::Transaction(TransactionError::InternalDowncastError(
            "unknown verifier failure".into(),
        )),
    ];
    let mut errors: Vec<_> = block_errors
        .into_iter()
        .map(|error| RouterError::Block {
            source: Box::new(error),
        })
        .collect();
    errors.extend(
        [
            VerifyCheckpointError::VerifyBlock(VerifyBlockError::Depth {
                source: "state depth failed".into(),
                hash,
            }),
            VerifyCheckpointError::CommitCheckpointVerified(
                zs::CommitCheckpointVerifiedError::from(
                    zs::CommitBlockError::new_write_task_exited(),
                )
                .into(),
            ),
            VerifyCheckpointError::CommitCheckpointVerified("state commit failed".into()),
            VerifyCheckpointError::Tip("state tip failed".into()),
            VerifyCheckpointError::CheckpointList("checkpoint list failed".into()),
            VerifyCheckpointError::Dropped,
            VerifyCheckpointError::ShuttingDown,
        ]
        .into_iter()
        .map(|error| RouterError::Checkpoint {
            source: Box::new(error),
        }),
    );

    for error in errors {
        let error = BlockDownloadVerifyError::Invalid {
            error,
            height: Height(1),
            hash,
            advertiser_addr: None,
        };
        assert!(TestChainSync::should_restart_sync(&error), "{error:?}");
    }
}