zakura-consensus 5.0.0

Implementation of Zcash consensus checks for the Zakura node. Internal crate, published to support cargo install zakura
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
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
//! Tests for Zcash transaction consensus checks.

#![allow(clippy::unwrap_in_result)]

//
// TODO: split fixed test vectors into a `vectors` module?

use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};

use chrono::{DateTime, TimeZone, Utc};
use color_eyre::eyre::Report;
use futures::{FutureExt, TryFutureExt};
use halo2::pasta::{group::ff::PrimeField, pallas};
use tokio::time::timeout;
use tower::{buffer::Buffer, service_fn, Service, ServiceExt};
use tower_batch_control::{Batch, BatchControl};
use tower_fallback::Fallback;

use zakura_chain::{
    amount::{Amount, NegativeAllowed, NonNegative},
    block::{self, Block, Height},
    orchard::{Action, AuthorizedAction, Flags},
    parameters::{
        testnet::{ConfiguredActivationHeights, Parameters},
        Network, NetworkUpgrade,
    },
    primitives::{ed25519, x25519, Groth16Proof},
    sapling,
    serialization::{
        AtLeastOne, DateTime32, ZcashDeserialize, ZcashDeserializeInto, ZcashSerialize,
    },
    sprout,
    transaction::{
        arbitrary::{
            insert_fake_orchard_shielded_data, test_transactions, transactions_from_blocks,
            v5_transactions,
        },
        zip317, Hash, HashType, JoinSplitData, LockTime, Transaction,
    },
    transparent::{self, CoinbaseSpendRestriction},
};
use zakura_chain::{ironwood, orchard};

use zakura_node_services::mempool;
use zakura_state::ValidateContextError;
use zakura_test::mock_service::MockService;

use crate::{error::TransactionError, transaction::POLL_MEMPOOL_DELAY};

use super::{check, Request, Verifier};

#[cfg(test)]
mod prop;

/// Returns the timeout duration for tests, extended when running under coverage
/// instrumentation to account for the performance overhead.
fn test_timeout() -> std::time::Duration {
    // Check if we're running under cargo-llvm-cov by looking for its environment variables
    if std::env::var("LLVM_COV_FLAGS").is_ok() || std::env::var("CARGO_LLVM_COV").is_ok() {
        // Use a 5x longer timeout when running with coverage (150 seconds)
        std::time::Duration::from_secs(150)
    } else {
        std::time::Duration::from_secs(30)
    }
}

#[test]
fn v5_transactions_basic_check() -> Result<(), Report> {
    let _init_guard = zakura_test::init();

    for network in Network::iter() {
        for transaction in v5_transactions(network.block_iter()) {
            match check::has_inputs_and_outputs(&transaction) {
                Ok(()) => (),
                Err(TransactionError::NoInputs) | Err(TransactionError::NoOutputs) => (),
                Err(_) => panic!("error must be NoInputs or NoOutputs"),
            };

            // make sure there are no joinsplits nor spends in coinbase
            check::coinbase_tx_no_prevout_joinsplit_spend(&transaction)?;
        }
    }

    Ok(())
}

/// Orchard and Ironwood nullifiers are separate namespaces: a V6 transaction
/// whose Orchard and Ironwood bundles happen to contain bit-identical
/// nullifiers must not be rejected as a double-spend, because each pool tracks
/// its own nullifier set. `spend_conflicts` must only reject duplicates
/// *within* a pool.
#[test]
fn matching_orchard_and_ironwood_nullifiers_are_not_conflicts() {
    let _init_guard = zakura_test::init();

    let shielded_data = Network::iter()
        .flat_map(|network| v5_transactions(network.block_iter()))
        .find_map(|transaction| transaction.orchard_shielded_data().cloned())
        .expect("test vectors include an Orchard transaction");
    let transaction = Transaction::V6 {
        network_upgrade: NetworkUpgrade::Nu6_3,
        lock_time: LockTime::unlocked(),
        expiry_height: Height(1),
        inputs: Vec::new(),
        outputs: Vec::new(),
        sapling_shielded_data: None,
        orchard_shielded_data: Some(shielded_data.clone()),
        ironwood_shielded_data: Some(shielded_data),
    };

    assert_eq!(
        transaction.orchard_nullifiers().collect::<Vec<_>>(),
        transaction.ironwood_nullifiers().collect::<Vec<_>>()
    );
    check::spend_conflicts(&transaction)
        .expect("matching bit patterns in separate nullifier sets are not duplicates");
}

#[test]
fn v5_transaction_with_orchard_actions_has_inputs_and_outputs() {
    for net in Network::iter() {
        let mut tx = v5_transactions(net.block_iter())
            .find(|transaction| {
                transaction.inputs().is_empty()
                    && transaction.outputs().is_empty()
                    && transaction.sapling_spends_per_anchor().next().is_none()
                    && transaction.sapling_outputs().next().is_none()
                    && transaction.joinsplit_count() == 0
            })
            .expect("V5 tx with only Orchard shielded data");

        tx.orchard_shielded_data_mut().unwrap().flags = Flags::empty();

        // The check will fail if the transaction has no flags
        assert_eq!(
            check::has_inputs_and_outputs(&tx),
            Err(TransactionError::NoInputs)
        );

        // If we add ENABLE_SPENDS flag it will pass the inputs check but fails with the outputs
        tx.orchard_shielded_data_mut().unwrap().flags = Flags::ENABLE_SPENDS;

        assert_eq!(
            check::has_inputs_and_outputs(&tx),
            Err(TransactionError::NoOutputs)
        );

        // If we add ENABLE_OUTPUTS flag it will pass the outputs check but fails with the inputs
        tx.orchard_shielded_data_mut().unwrap().flags = Flags::ENABLE_OUTPUTS;

        assert_eq!(
            check::has_inputs_and_outputs(&tx),
            Err(TransactionError::NoInputs)
        );

        // Finally make it valid by adding both required flags
        tx.orchard_shielded_data_mut().unwrap().flags =
            Flags::ENABLE_SPENDS | Flags::ENABLE_OUTPUTS;

        assert!(check::has_inputs_and_outputs(&tx).is_ok());
    }
}

fn nu6_3_test_network_and_height() -> (Network, Height) {
    let network = Parameters::build()
        .with_activation_heights(ConfiguredActivationHeights {
            nu6_3: Some(1),
            ..Default::default()
        })
        .expect("failed to set NU6.3 activation height")
        .clear_funding_streams()
        .to_network()
        .expect("failed to build configured network");

    (network, Height(1))
}

fn orchard_fixture() -> orchard::ShieldedData {
    let default_testnet = Network::new_default_testnet();

    v5_transactions(default_testnet.block_iter())
        .find_map(|transaction| transaction.orchard_shielded_data().cloned())
        .expect("test vectors include a transaction with Orchard shielded data")
}

fn orchard_shielded_data(value_balance: i64, flags: Flags) -> orchard::ShieldedData {
    let mut shielded_data = orchard_fixture();
    shielded_data.value_balance =
        Amount::<NegativeAllowed>::try_from(value_balance).expect("valid test amount");
    shielded_data.flags = flags;

    shielded_data
}

fn ironwood_shielded_data(value_balance: i64, flags: ironwood::Flags) -> ironwood::ShieldedData {
    let mut shielded_data = orchard_fixture();
    shielded_data.value_balance =
        Amount::<NegativeAllowed>::try_from(value_balance).expect("valid test amount");
    shielded_data.flags = flags;

    shielded_data
}

fn v6_pool_flow_transaction(
    orchard_shielded_data: Option<orchard::ShieldedData>,
    ironwood_shielded_data: Option<ironwood::ShieldedData>,
    transparent_outputs: Vec<transparent::Output>,
) -> Transaction {
    Transaction::V6 {
        network_upgrade: NetworkUpgrade::Nu6_3,
        lock_time: LockTime::Height(block::Height(0)),
        expiry_height: Height(1),
        inputs: vec![],
        outputs: transparent_outputs,
        sapling_shielded_data: None,
        orchard_shielded_data,
        ironwood_shielded_data,
    }
}

fn transparent_output(value: u64) -> transparent::Output {
    transparent::Output {
        value: Amount::<NonNegative>::try_from(value).expect("valid test amount"),
        lock_script: transparent::Script::new(&[1, 1]),
    }
}

fn empty_utxos() -> HashMap<transparent::OutPoint, transparent::Utxo> {
    HashMap::new()
}

#[test]
fn orchard_rejects_net_deposits_after_nu6_3() {
    let (network, height) = nu6_3_test_network_and_height();

    let orchard_withdraw = v6_pool_flow_transaction(
        Some(orchard_shielded_data(10, Flags::ENABLE_SPENDS)),
        None,
        vec![transparent_output(10)],
    );

    assert_eq!(
        check::disabled_add_to_orchard_pool(&orchard_withdraw, height, &network),
        Ok(())
    );
    assert_eq!(check::has_inputs_and_outputs(&orchard_withdraw), Ok(()));
    assert_eq!(
        orchard_withdraw
            .value_balance(&empty_utxos())
            .expect("valid value balance")
            .remaining_transaction_value(),
        Ok(Amount::<NonNegative>::zero())
    );

    let orchard_no_flow = v6_pool_flow_transaction(
        Some(orchard_shielded_data(
            0,
            Flags::ENABLE_SPENDS | Flags::ENABLE_OUTPUTS,
        )),
        None,
        vec![],
    );

    // Zero value balance leaves the Orchard chain pool unchanged, so Orchard
    // spends and outputs in the same transaction remain valid after NU6.3.
    assert_eq!(
        check::disabled_add_to_orchard_pool(&orchard_no_flow, height, &network),
        Ok(())
    );

    let orchard_deposit = v6_pool_flow_transaction(
        Some(orchard_shielded_data(-10, Flags::ENABLE_OUTPUTS)),
        None,
        vec![],
    );

    assert_eq!(
        check::disabled_add_to_orchard_pool(&orchard_deposit, height, &network),
        Err(TransactionError::DisabledAddToOrchardPool)
    );
}

#[test]
fn coinbase_rejects_orchard_shielded_data_after_nu6_3() {
    let (network, height) = nu6_3_test_network_and_height();

    let coinbase_input = || transparent::Input::Coinbase {
        height,
        data: vec![],
        sequence: u32::MAX,
    };

    // A V6 coinbase carrying an Orchard bundle is rejected after NU6.3. The bundle has a
    // zero value balance, so `disabled_add_to_orchard_pool` does NOT catch it — this
    // structural rule is what rejects it (the two rules are not redundant).
    let coinbase_with_orchard = Transaction::V6 {
        network_upgrade: NetworkUpgrade::Nu6_3,
        lock_time: LockTime::Height(Height(0)),
        expiry_height: height,
        inputs: vec![coinbase_input()],
        outputs: vec![],
        sapling_shielded_data: None,
        orchard_shielded_data: Some(orchard_shielded_data(0, Flags::ENABLE_OUTPUTS)),
        ironwood_shielded_data: None,
    };
    assert!(coinbase_with_orchard.is_coinbase());
    assert_eq!(
        check::coinbase_has_no_orchard_shielded_data(&coinbase_with_orchard, height, &network),
        Err(TransactionError::CoinbaseHasOrchardShieldedData)
    );
    assert_eq!(
        check::disabled_add_to_orchard_pool(&coinbase_with_orchard, height, &network),
        Ok(())
    );

    // A V6 coinbase paying shielded output through Ironwood (no Orchard bundle) is allowed.
    let coinbase_with_ironwood = Transaction::V6 {
        network_upgrade: NetworkUpgrade::Nu6_3,
        lock_time: LockTime::Height(Height(0)),
        expiry_height: height,
        inputs: vec![coinbase_input()],
        outputs: vec![],
        sapling_shielded_data: None,
        orchard_shielded_data: None,
        ironwood_shielded_data: Some(ironwood_shielded_data(0, ironwood::Flags::ENABLE_OUTPUTS)),
    };
    assert_eq!(
        check::coinbase_has_no_orchard_shielded_data(&coinbase_with_ironwood, height, &network),
        Ok(())
    );

    // Before NU6.3 the rule is a no-op: the same Orchard-bearing coinbase is allowed below
    // the NU6.3 activation height.
    assert_eq!(
        check::coinbase_has_no_orchard_shielded_data(&coinbase_with_orchard, Height(0), &network),
        Ok(())
    );
}

#[test]
fn orchard_cross_address_flag_is_disabled_after_nu6_3() {
    let orchard_cross_address = v6_pool_flow_transaction(
        Some(orchard_shielded_data(
            0,
            Flags::ENABLE_SPENDS | Flags::ENABLE_OUTPUTS | Flags::ENABLE_CROSS_ADDRESS,
        )),
        None,
        vec![],
    );

    assert_eq!(
        check::orchard_cross_address_disabled(&orchard_cross_address),
        Err(TransactionError::OrchardHasEnableCrossAddress)
    );

    let ironwood_cross_address = v6_pool_flow_transaction(
        None,
        Some(ironwood_shielded_data(
            0,
            ironwood::Flags::ENABLE_SPENDS
                | ironwood::Flags::ENABLE_OUTPUTS
                | ironwood::Flags::ENABLE_CROSS_ADDRESS,
        )),
        vec![],
    );

    assert_eq!(
        check::orchard_cross_address_disabled(&ironwood_cross_address),
        Ok(())
    );
}

#[test]
fn ironwood_cross_address_flag_is_optional_after_nu6_3() {
    // After NU6.3 the cross-address bit is OPTIONAL for Ironwood shielded data: a bundle
    // is accepted whether or not it sets ENABLE_CROSS_ADDRESS. (Orchard bundles still MUST
    // NOT set it — that rule is unrelated and lives in `orchard_cross_address_disabled`.)
    let ironwood_without_cross_address = v6_pool_flow_transaction(
        None,
        Some(ironwood_shielded_data(
            0,
            ironwood::Flags::ENABLE_SPENDS | ironwood::Flags::ENABLE_OUTPUTS,
        )),
        vec![],
    );

    // `has_enough_ironwood_flags` is the only consensus check that inspects Ironwood flags,
    // and it ignores the cross-address bit, so a bundle without it is accepted.
    assert_eq!(
        check::has_enough_ironwood_flags(&ironwood_without_cross_address),
        Ok(())
    );
    // The Orchard cross-address rule must stay a no-op on an Ironwood-only bundle.
    assert_eq!(
        check::orchard_cross_address_disabled(&ironwood_without_cross_address),
        Ok(())
    );

    let ironwood_with_cross_address = v6_pool_flow_transaction(
        None,
        Some(ironwood_shielded_data(
            0,
            ironwood::Flags::ENABLE_SPENDS
                | ironwood::Flags::ENABLE_OUTPUTS
                | ironwood::Flags::ENABLE_CROSS_ADDRESS,
        )),
        vec![],
    );

    assert_eq!(
        check::has_enough_ironwood_flags(&ironwood_with_cross_address),
        Ok(())
    );
    assert_eq!(
        check::orchard_cross_address_disabled(&ironwood_with_cross_address),
        Ok(())
    );
}

#[test]
fn ironwood_cross_address_only_is_not_a_spend_or_output_flag() {
    let tx = v6_pool_flow_transaction(
        None,
        Some(ironwood_shielded_data(
            0,
            ironwood::Flags::ENABLE_CROSS_ADDRESS,
        )),
        vec![],
    );

    assert!(!tx.has_shielded_inputs());
    assert!(!tx.has_shielded_outputs());
    assert_eq!(
        check::has_inputs_and_outputs(&tx),
        Err(TransactionError::NoInputs)
    );
    assert_eq!(
        check::has_enough_ironwood_flags(&tx),
        Err(TransactionError::NotEnoughIronwoodFlags)
    );
}

#[test]
fn orchard_to_ironwood_migration_balances() {
    let (network, height) = nu6_3_test_network_and_height();
    let tx = v6_pool_flow_transaction(
        Some(orchard_shielded_data(10, Flags::ENABLE_SPENDS)),
        Some(ironwood_shielded_data(-10, ironwood::Flags::ENABLE_OUTPUTS)),
        vec![],
    );

    assert_eq!(
        check::disabled_add_to_orchard_pool(&tx, height, &network),
        Ok(())
    );
    assert_eq!(check::has_inputs_and_outputs(&tx), Ok(()));

    let value_balance = tx
        .value_balance(&empty_utxos())
        .expect("valid value balance");

    assert_eq!(
        value_balance.orchard_amount(),
        Amount::<NegativeAllowed>::try_from(10).expect("valid test amount")
    );
    assert_eq!(
        value_balance.ironwood_amount(),
        Amount::<NegativeAllowed>::try_from(-10).expect("valid test amount")
    );
    assert_eq!(
        value_balance.remaining_transaction_value(),
        Ok(Amount::<NonNegative>::zero())
    );
}

#[test]
fn ironwood_withdraw_balances() {
    let tx = v6_pool_flow_transaction(
        None,
        Some(ironwood_shielded_data(10, ironwood::Flags::ENABLE_SPENDS)),
        vec![transparent_output(10)],
    );

    assert_eq!(check::has_inputs_and_outputs(&tx), Ok(()));

    let value_balance = tx
        .value_balance(&empty_utxos())
        .expect("valid value balance");

    assert_eq!(
        value_balance.transparent_amount(),
        Amount::<NegativeAllowed>::try_from(-10).expect("valid test amount")
    );
    assert_eq!(
        value_balance.ironwood_amount(),
        Amount::<NegativeAllowed>::try_from(10).expect("valid test amount")
    );
    assert_eq!(
        value_balance.remaining_transaction_value(),
        Ok(Amount::<NonNegative>::zero())
    );
}

#[test]
fn v5_transaction_with_orchard_actions_has_flags() {
    for net in Network::iter() {
        let mut tx = v5_transactions(net.block_iter())
            .find(|transaction| {
                transaction.inputs().is_empty()
                    && transaction.outputs().is_empty()
                    && transaction.sapling_spends_per_anchor().next().is_none()
                    && transaction.sapling_outputs().next().is_none()
                    && transaction.joinsplit_count() == 0
            })
            .expect("V5 tx with only Orchard actions");

        tx.orchard_shielded_data_mut().unwrap().flags = Flags::empty();

        // The check will fail if the transaction has no flags
        assert_eq!(
            check::has_enough_orchard_flags(&tx),
            Err(TransactionError::NotEnoughFlags)
        );

        // If we add ENABLE_SPENDS flag it will pass.
        tx.orchard_shielded_data_mut().unwrap().flags = Flags::ENABLE_SPENDS;
        assert!(check::has_enough_orchard_flags(&tx).is_ok());

        tx.orchard_shielded_data_mut().unwrap().flags = Flags::empty();

        // If we add ENABLE_OUTPUTS flag instead, it will pass.
        tx.orchard_shielded_data_mut().unwrap().flags = Flags::ENABLE_OUTPUTS;
        assert!(check::has_enough_orchard_flags(&tx).is_ok());

        tx.orchard_shielded_data_mut().unwrap().flags = Flags::empty();

        // If we add BOTH ENABLE_SPENDS and ENABLE_OUTPUTS flags it will pass.
        tx.orchard_shielded_data_mut().unwrap().flags =
            Flags::ENABLE_SPENDS | Flags::ENABLE_OUTPUTS;
        assert!(check::has_enough_orchard_flags(&tx).is_ok());
    }
}

#[test]
fn v5_transaction_with_no_inputs_fails_verification() {
    let (_, output, _) = mock_transparent_transfer(
        Height(1),
        true,
        0,
        Amount::try_from(1).expect("valid value"),
    );

    for net in Network::iter() {
        let transaction = Transaction::V5 {
            inputs: vec![],
            outputs: vec![output.clone()],
            lock_time: LockTime::Height(block::Height(0)),
            expiry_height: NetworkUpgrade::Nu5.activation_height(&net).expect("height"),
            sapling_shielded_data: None,
            orchard_shielded_data: None,
            network_upgrade: NetworkUpgrade::Nu5,
        };

        assert_eq!(
            check::has_inputs_and_outputs(&transaction),
            Err(TransactionError::NoInputs)
        );
    }
}

#[test]
fn v5_transaction_with_no_outputs_fails_verification() {
    let (input, _, _) = mock_transparent_transfer(
        Height(1),
        true,
        0,
        Amount::try_from(1).expect("valid value"),
    );

    for net in Network::iter() {
        let transaction = Transaction::V5 {
            inputs: vec![input.clone()],
            outputs: vec![],
            lock_time: LockTime::Height(block::Height(0)),
            expiry_height: NetworkUpgrade::Nu5.activation_height(&net).expect("height"),
            sapling_shielded_data: None,
            orchard_shielded_data: None,
            network_upgrade: NetworkUpgrade::Nu5,
        };

        assert_eq!(
            check::has_inputs_and_outputs(&transaction),
            Err(TransactionError::NoOutputs)
        );
    }
}

#[tokio::test]
async fn mempool_request_with_missing_input_is_rejected() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_unit_tests();

    for net in Network::iter() {
        let verifier = Verifier::new_for_tests(&net, state.clone());

        let (height, tx) = transactions_from_blocks(net.block_iter())
            .find(|(_, tx)| !(tx.is_coinbase() || tx.inputs().is_empty()))
            .expect(
                "At least one non-coinbase transaction with transparent inputs in test vectors",
            );

        let input_outpoint = match tx.inputs()[0] {
            transparent::Input::PrevOut { outpoint, .. } => outpoint,
            transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
        };

        // The first non-coinbase transaction with transparent inputs in our test vectors
        // does not use a lock time, so we don't see Request::BestChainNextMedianTimePast here

        let state_req = state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .map(|responder| responder.respond(zakura_state::Response::UnspentBestChainUtxo(None)));

        let verifier_req = verifier.oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        });

        let (rsp, _) = futures::join!(verifier_req, state_req);

        assert_eq!(rsp, Err(TransactionError::TransparentInputNotFound));
    }
}

#[tokio::test]
async fn mempool_request_with_present_input_is_accepted() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let tx = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height: height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    assert!(
        verifier_response.is_ok(),
        "expected successful verification, got: {verifier_response:?}"
    );
}

#[tokio::test]
async fn mempool_request_with_invalid_lock_time_is_rejected() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let tx = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::max_lock_time_timestamp(),
        expiry_height: height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::BestChainNextMedianTimePast)
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::BestChainNextMedianTimePast(
                DateTime32::from(
                    u32::try_from(LockTime::MIN_TIMESTAMP).expect("min time is valid"),
                ),
            ));

        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    assert_eq!(
        verifier_response,
        Err(TransactionError::LockedUntilAfterBlockTime(
            Utc.timestamp_opt(u32::MAX.into(), 0).unwrap()
        ))
    );
}

#[tokio::test]
async fn mempool_request_with_unlocked_lock_time_is_accepted() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let tx = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height: height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    assert!(
        verifier_response.is_ok(),
        "expected successful verification, got: {verifier_response:?}"
    );
}

#[tokio::test]
async fn mempool_request_with_lock_time_max_sequence_number_is_accepted() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (mut input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    // Ignore the lock time.
    input.set_sequence(u32::MAX);

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let tx = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::max_lock_time_timestamp(),
        expiry_height: height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    assert!(
        verifier_response.is_ok(),
        "expected successful verification, got: {verifier_response:?}"
    );
}

#[tokio::test]
async fn mempool_request_with_past_lock_time_is_accepted() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let tx = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::min_lock_time_timestamp(),
        expiry_height: height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::BestChainNextMedianTimePast)
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::BestChainNextMedianTimePast(
                DateTime32::MAX,
            ));

        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    assert!(
        verifier_response.is_ok(),
        "expected successful verification, got: {verifier_response:?}"
    );
}

#[tokio::test]
async fn mempool_request_with_unmined_output_spends_is_accepted() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let mempool: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let (mempool_setup_tx, mempool_setup_rx) = tokio::sync::oneshot::channel();
    let verifier = Verifier::new(&Network::Mainnet, state.clone(), mempool_setup_rx);
    mempool_setup_tx
        .send(mempool.clone())
        .ok()
        .expect("send should succeed");

    let height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let tx = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::min_lock_time_timestamp(),
        expiry_height: height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::BestChainNextMedianTimePast)
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::BestChainNextMedianTimePast(
                DateTime32::MAX,
            ));

        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(None));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let mut mempool_clone = mempool.clone();
    tokio::spawn(async move {
        mempool_clone
            .expect_request(mempool::Request::AwaitOutput(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(mempool::Response::UnspentOutput(
                known_utxos
                    .get(&input_outpoint)
                    .expect("input outpoint should exist in known_utxos")
                    .utxo
                    .output
                    .clone(),
            ));
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    assert!(
        verifier_response.is_ok(),
        "expected successful verification, got: {verifier_response:?}"
    );

    let crate::transaction::Response::Mempool {
        transaction: _,
        spent_mempool_outpoints,
    } = verifier_response.expect("already checked that response is ok")
    else {
        panic!("unexpected response variant from transaction verifier for Mempool request")
    };

    assert_eq!(
        spent_mempool_outpoints,
        vec![input_outpoint],
        "spent_mempool_outpoints in tx verifier response should match input_outpoint"
    );

    tokio::time::sleep(POLL_MEMPOOL_DELAY * 2).await;
    // polled before AwaitOutput request and after a mempool transaction with transparent outputs
    // is successfully verified
    assert_eq!(
        mempool.poll_count(),
        2,
        "the mempool service should have been polled twice"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn dont_skip_verification_of_block_transactions_in_mempool() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let mempool: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let (mempool_setup_tx, mempool_setup_rx) = tokio::sync::oneshot::channel();
    let verifier = Verifier::new(&Network::Mainnet, state.clone(), mempool_setup_rx);
    let verifier = Buffer::new(verifier, 1);

    mempool_setup_tx
        .send(mempool.clone())
        .ok()
        .expect("send should succeed");

    let height = NetworkUpgrade::Nu6
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu6,
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::min_lock_time_timestamp(),
        expiry_height: height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let tx_hash = tx.hash();
    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    let mut state_clone = state.clone();
    tokio::spawn(async move {
        state_clone
            .expect_request(zakura_state::Request::BestChainNextMedianTimePast)
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::BestChainNextMedianTimePast(
                DateTime32::MAX,
            ));

        state_clone
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(None));

        state_clone
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let utxo = known_utxos
        .get(&input_outpoint)
        .expect("input outpoint should exist in known_utxos")
        .utxo
        .clone();

    let mut mempool_clone = mempool.clone();
    let output = utxo.output.clone();
    tokio::spawn(async move {
        mempool_clone
            .expect_request(mempool::Request::AwaitOutput(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(mempool::Response::UnspentOutput(output));
    });

    // Briefly yield and sleep so the spawned task can first expect an await output request.
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;

    let verifier_response = verifier
        .clone()
        .oneshot(Request::Mempool {
            transaction: tx.clone().into(),
            height,
        })
        .await;

    assert!(
        verifier_response.is_ok(),
        "expected successful verification, got: {verifier_response:?}"
    );

    let crate::transaction::Response::Mempool {
        transaction: _,
        spent_mempool_outpoints,
    } = verifier_response.expect("already checked that response is ok")
    else {
        panic!("unexpected response variant from transaction verifier for Mempool request")
    };

    assert_eq!(
        spent_mempool_outpoints,
        vec![input_outpoint],
        "spent_mempool_outpoints in tx verifier response should match input_outpoint"
    );

    let make_request = |known_outpoint_hashes| Request::Block {
        transaction_hash: tx_hash,
        transaction: Arc::new(tx),
        known_outpoint_hashes,
        known_utxos: Arc::new(HashMap::new()),
        height,
        time: Utc::now(),
    };

    // Both block requests go through full verification (no mempool bypass), so each
    // calls AwaitUtxo on the state service.
    let utxo_clone = utxo.clone();
    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::AwaitUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::Utxo(utxo_clone));

        state
            .expect_request(zakura_state::Request::AwaitUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::Utxo(utxo));
    });

    // Briefly yield and sleep so the spawned task can first expect the requests.
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;

    let crate::transaction::Response::Block { .. } = verifier
        .clone()
        .oneshot(make_request.clone()(Arc::new([input_outpoint.hash].into())))
        .await
        .expect("should succeed after calling state service")
    else {
        panic!("unexpected response variant from transaction verifier for Block request")
    };

    let crate::transaction::Response::Block { .. } = verifier
        .clone()
        .oneshot(make_request.clone()(Arc::new(HashSet::new())))
        .await
        .expect("should succeed after calling state service")
    else {
        panic!("unexpected response variant from transaction verifier for Block request")
    };

    tokio::time::sleep(POLL_MEMPOOL_DELAY * 2).await;
    // polled before AwaitOutput request and after a mempool transaction with transparent outputs
    // is successfully verified.
    assert_eq!(
        mempool.poll_count(),
        2,
        "the mempool service should have been polled twice"
    );
}

/// Tests that calls to the transaction verifier with a mempool request that spends
/// immature coinbase outputs will return an error.
#[tokio::test]
async fn mempool_request_with_immature_spend_is_rejected() {
    let _init_guard = zakura_test::init();

    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let tx = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::min_lock_time_timestamp(),
        expiry_height: height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    let spend_restriction = tx.coinbase_spend_restriction(&Network::Mainnet, height);

    let coinbase_spend_height = Height(5);

    let utxo = known_utxos
        .get(&input_outpoint)
        .map(|utxo| {
            let mut utxo = utxo.utxo.clone();
            utxo.height = coinbase_spend_height;
            utxo.from_coinbase = true;
            utxo
        })
        .expect("known_utxos should contain the outpoint");

    let expected_error =
        zakura_state::check::transparent_coinbase_spend(input_outpoint, spend_restriction, &utxo)
            .map_err(Box::new)
            .map_err(TransactionError::ValidateContextError)
            .expect_err("check should fail");

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::BestChainNextMedianTimePast)
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::BestChainNextMedianTimePast(
                DateTime32::MAX,
            ));

        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos.get(&input_outpoint).map(|utxo| {
                    let mut utxo = utxo.utxo.clone();
                    utxo.height = coinbase_spend_height;
                    utxo.from_coinbase = true;
                    utxo
                }),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await
        .expect_err("verification of transaction with immature spend should fail");

    assert_eq!(
        verifier_response, expected_error,
        "expected to fail verification, got: {verifier_response:?}"
    );
}

/// Tests that calls to the transaction verifier with a mempool request that spends
/// mature coinbase outputs to transparent outputs will return Ok() on Regtest.
#[tokio::test]
async fn mempool_request_with_transparent_coinbase_spend_is_accepted_on_regtest() {
    let _init_guard = zakura_test::init();

    let network = Network::new_regtest(
        ConfiguredActivationHeights {
            canopy: Some(1),
            nu5: Some(100),
            nu6: Some(1_000),
            ..Default::default()
        }
        .into(),
    );
    let mut state: MockService<_, _, _, _> = MockService::build().for_unit_tests();
    let verifier = Verifier::new_for_tests(&network, state.clone());

    let height = NetworkUpgrade::Nu6
        .activation_height(&network)
        .expect("NU6 activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    // Create a non-coinbase V5 tx with the last valid expiry height.
    let tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu6,
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::min_lock_time_timestamp(),
        expiry_height: height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    let spend_restriction = tx.coinbase_spend_restriction(&network, height);

    assert_eq!(
        spend_restriction,
        CoinbaseSpendRestriction::CheckCoinbaseMaturity {
            spend_height: height
        }
    );

    let coinbase_spend_height = Height(5);

    let utxo = known_utxos
        .get(&input_outpoint)
        .map(|utxo| {
            let mut utxo = utxo.utxo.clone();
            utxo.height = coinbase_spend_height;
            utxo.from_coinbase = true;
            utxo
        })
        .expect("known_utxos should contain the outpoint");

    zakura_state::check::transparent_coinbase_spend(input_outpoint, spend_restriction, &utxo)
        .expect("check should pass");

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::BestChainNextMedianTimePast)
            .await
            .respond(zakura_state::Response::BestChainNextMedianTimePast(
                DateTime32::MAX,
            ));

        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .respond(zakura_state::Response::UnspentBestChainUtxo(Some(utxo)));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await
        .expect("verification of transaction with mature spend to transparent outputs should pass");
}

/// Tests that errors from the read state service are correctly converted into
/// transaction verifier errors.
#[tokio::test]
async fn state_error_converted_correctly() {
    use zakura_state::DuplicateNullifierError;

    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let tx = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height: height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    let make_validate_context_error =
        || sprout::Nullifier([0; 32].into()).duplicate_nullifier_error(true);

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(Err::<zakura_state::Response, zakura_state::BoxError>(
                make_validate_context_error().into(),
            ));
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    let transaction_error =
        verifier_response.expect_err("expected failed verification, got: {verifier_response:?}");

    assert_eq!(
        TransactionError::from(make_validate_context_error()),
        transaction_error,
        "expected matching state and transaction errors"
    );

    let state_error = zakura_state::BoxError::from(make_validate_context_error())
        .downcast::<ValidateContextError>()
        .map(|boxed| TransactionError::from(*boxed))
        .expect("downcast should succeed");

    assert_eq!(
        state_error, transaction_error,
        "expected matching state and transaction errors"
    );

    let TransactionError::ValidateContextError(propagated_validate_context_error) =
        transaction_error
    else {
        panic!("should be a ValidateContextError variant");
    };

    assert_eq!(
        *propagated_validate_context_error,
        make_validate_context_error(),
        "expected matching state and transaction errors"
    );
}

#[test]
fn v5_coinbase_transaction_without_enable_spends_flag_passes_validation() {
    for net in Network::iter() {
        let mut tx = v5_transactions(net.block_iter())
            .find(|transaction| transaction.is_coinbase())
            .expect("V5 coinbase tx");

        let shielded_data = insert_fake_orchard_shielded_data(&mut tx);

        assert!(!shielded_data.flags.contains(Flags::ENABLE_SPENDS));

        assert!(check::coinbase_tx_no_prevout_joinsplit_spend(&tx).is_ok());
    }
}

#[test]
fn v5_coinbase_transaction_with_enable_spends_flag_fails_validation() {
    for net in Network::iter() {
        let mut tx = v5_transactions(net.block_iter())
            .find(|transaction| transaction.is_coinbase())
            .expect("V5 coinbase tx");

        let shielded_data = insert_fake_orchard_shielded_data(&mut tx);

        assert!(!shielded_data.flags.contains(Flags::ENABLE_SPENDS));

        shielded_data.flags = Flags::ENABLE_SPENDS;

        assert_eq!(
            check::coinbase_tx_no_prevout_joinsplit_spend(&tx),
            Err(TransactionError::CoinbaseHasEnableSpendsOrchard)
        );
    }
}

#[tokio::test]
async fn v5_transaction_is_rejected_before_nu5_activation() {
    let sapling = NetworkUpgrade::Sapling;

    for net in Network::iter() {
        let verifier = Verifier::new_for_tests(
            &net,
            service_fn(|_| async { unreachable!("Service should not be called") }),
        );

        let tx = v5_transactions(net.block_iter()).next().expect("V5 tx");

        assert_eq!(
            verifier
                .oneshot(Request::Block {
                    transaction_hash: tx.hash(),
                    transaction: Arc::new(tx),
                    known_utxos: Arc::new(HashMap::new()),
                    known_outpoint_hashes: Arc::new(HashSet::new()),
                    height: sapling.activation_height(&net).expect("height"),
                    time: DateTime::<Utc>::MAX_UTC,
                })
                .await,
            Err(TransactionError::UnsupportedByNetworkUpgrade(5, sapling))
        );
    }
}

#[tokio::test]
async fn v5_transaction_is_accepted_after_nu5_activation() {
    let _init_guard = zakura_test::init();

    for net in Network::iter() {
        let state = service_fn(|_| async { unreachable!("Service should not be called") });
        let tx = v5_transactions(net.block_iter()).next().expect("V5 tx");
        let tx_height = tx.expiry_height().expect("V5 must have expiry_height");
        let expected = tx.unmined_id();

        assert!(tx_height >= NetworkUpgrade::Nu5.activation_height(&net).expect("height"));

        let verif_res = Verifier::new_for_tests(&net, state)
            .oneshot(Request::Block {
                transaction_hash: tx.hash(),
                transaction: Arc::new(tx),
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height: tx_height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await;

        assert_eq!(verif_res.expect("success").tx_id(), expected);
    }
}

/// Test if V4 transaction with transparent funds is accepted.
#[tokio::test]
async fn v4_transaction_with_transparent_transfer_is_accepted() {
    let network = Network::Mainnet;

    let canopy_activation_height = NetworkUpgrade::Canopy
        .activation_height(&network)
        .expect("Canopy activation height is specified");

    let transaction_block_height =
        (canopy_activation_height + 10).expect("transaction block height is too large");

    let fake_source_fund_height =
        (transaction_block_height - 1).expect("fake source fund block height is too small");

    // Create a fake transparent transfer that should succeed
    let (input, output, known_utxos) = mock_transparent_transfer(
        fake_source_fund_height,
        true,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // Create a V4 transaction
    let transaction = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::Height(block::Height(0)),
        expiry_height: (transaction_block_height + 1).expect("expiry height is too large"),
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let transaction_hash = transaction.unmined_id();

    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: transaction_block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result.expect("unexpected error response").tx_id(),
        transaction_hash
    );
}

/// Tests if a non-coinbase V4 transaction with the last valid expiry height is
/// accepted.
#[tokio::test]
async fn v4_transaction_with_last_valid_expiry_height() {
    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state_service);

    let block_height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");
    let fund_height = (block_height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // Create a non-coinbase V4 tx with the last valid expiry height.
    let transaction = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height: block_height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction.clone()),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result.expect("unexpected error response").tx_id(),
        transaction.unmined_id()
    );
}

/// Tests if a coinbase V4 transaction with an expiry height lower than the
/// block height is accepted.
///
/// Note that an expiry height lower than the block height is considered
/// *expired* for *non-coinbase* transactions.
#[tokio::test]
async fn v4_coinbase_transaction_with_low_expiry_height() {
    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state_service);

    let block_height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");

    let (input, output) = mock_coinbase_transparent_output(block_height);

    // This is a correct expiry height for coinbase V4 transactions.
    let expiry_height = (block_height - 1).expect("original block height is too small");

    // Create a coinbase V4 tx.
    let transaction = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction.clone()),
            known_utxos: Arc::new(HashMap::new()),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result.expect("unexpected error response").tx_id(),
        transaction.unmined_id()
    );
}

/// Tests if an expired non-coinbase V4 transaction is rejected.
#[tokio::test]
async fn v4_transaction_with_too_low_expiry_height() {
    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state_service);

    let block_height = NetworkUpgrade::Canopy
        .activation_height(&Network::Mainnet)
        .expect("Canopy activation height is specified");

    let fund_height = (block_height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // This expiry height is too low so that the tx should seem expired to the verifier.
    let expiry_height = (block_height - 1).expect("original block height is too small");

    // Create a non-coinbase V4 tx.
    let transaction = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction.clone()),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result,
        Err(TransactionError::ExpiredTransaction {
            expiry_height,
            block_height,
            transaction_hash: transaction.hash(),
        })
    );
}

/// Tests if a non-coinbase V4 transaction with an expiry height exceeding the
/// maximum is rejected.
#[tokio::test]
async fn v4_transaction_with_exceeding_expiry_height() {
    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state_service);

    let block_height = block::Height::MAX;

    let fund_height = (block_height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // This expiry height exceeds the maximum defined by the specification.
    let expiry_height = block::Height(500_000_000);

    // Create a non-coinbase V4 tx.
    let transaction = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction.clone()),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result,
        Err(TransactionError::MaximumExpiryHeight {
            expiry_height,
            is_coinbase: false,
            block_height,
            transaction_hash: transaction.hash(),
        })
    );
}

/// Tests if a coinbase V4 transaction with an expiry height exceeding the
/// maximum is rejected.
#[tokio::test]
async fn v4_coinbase_transaction_with_exceeding_expiry_height() {
    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state_service);

    // Use an arbitrary pre-NU5 block height.
    // It can't be NU5-onward because the expiry height limit is not enforced
    // for coinbase transactions (it needs to match the block height instead),
    // which is what is used in this test.
    let block_height = (NetworkUpgrade::Nu5
        .activation_height(&Network::Mainnet)
        .expect("NU5 height must be set")
        - 1)
    .expect("will not underflow");

    let (input, output) = mock_coinbase_transparent_output(block_height);

    // This expiry height exceeds the maximum defined by the specification.
    let expiry_height = block::Height(500_000_000);

    // Create a coinbase V4 tx.
    let transaction = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction.clone()),
            known_utxos: Arc::new(HashMap::new()),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result,
        Err(TransactionError::MaximumExpiryHeight {
            expiry_height,
            is_coinbase: true,
            block_height,
            transaction_hash: transaction.hash(),
        })
    );
}

/// Test if V4 coinbase transaction is accepted.
#[tokio::test]
async fn v4_coinbase_transaction_is_accepted() {
    let network = Network::Mainnet;

    let canopy_activation_height = NetworkUpgrade::Canopy
        .activation_height(&network)
        .expect("Canopy activation height is specified");

    let transaction_block_height =
        (canopy_activation_height + 10).expect("transaction block height is too large");

    // Create a fake transparent coinbase that should succeed
    let (input, output) = mock_coinbase_transparent_output(transaction_block_height);

    // Create a V4 coinbase transaction
    let transaction = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::Height(block::Height(0)),
        expiry_height: transaction_block_height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let transaction_hash = transaction.unmined_id();

    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction),
            known_utxos: Arc::new(HashMap::new()),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: transaction_block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result.expect("unexpected error response").tx_id(),
        transaction_hash
    );
}

/// Test if V4 transaction with transparent funds is rejected if the source script prevents it.
///
/// This test simulates the case where the script verifier rejects the transaction because the
/// script prevents spending the source UTXO.
#[tokio::test]
async fn v4_transaction_with_transparent_transfer_is_rejected_by_the_script() {
    let network = Network::Mainnet;

    let canopy_activation_height = NetworkUpgrade::Canopy
        .activation_height(&network)
        .expect("Canopy activation height is specified");

    let transaction_block_height =
        (canopy_activation_height + 10).expect("transaction block height is too large");

    let fake_source_fund_height =
        (transaction_block_height - 1).expect("fake source fund block height is too small");

    // Create a fake transparent transfer that should not succeed
    let (input, output, known_utxos) = mock_transparent_transfer(
        fake_source_fund_height,
        false,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // Create a V4 transaction
    let transaction = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::Height(block::Height(0)),
        expiry_height: (transaction_block_height + 1).expect("expiry height is too large"),
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: transaction_block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result,
        Err(TransactionError::Script(
            zakura_script::Error::ScriptInvalid
        ))
    );
}

/// Test if V4 transaction with an internal double spend of transparent funds is rejected.
#[tokio::test]
async fn v4_transaction_with_conflicting_transparent_spend_is_rejected() {
    let network = Network::Mainnet;

    let canopy_activation_height = NetworkUpgrade::Canopy
        .activation_height(&network)
        .expect("Canopy activation height is specified");

    let transaction_block_height =
        (canopy_activation_height + 10).expect("transaction block height is too large");

    let fake_source_fund_height =
        (transaction_block_height - 1).expect("fake source fund block height is too small");

    // Create a fake transparent transfer that should succeed
    let (input, output, known_utxos) = mock_transparent_transfer(
        fake_source_fund_height,
        true,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // Create a V4 transaction
    let transaction = Transaction::V4 {
        inputs: vec![input.clone(), input.clone()],
        outputs: vec![output],
        lock_time: LockTime::Height(block::Height(0)),
        expiry_height: (transaction_block_height + 1).expect("expiry height is too large"),
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: transaction_block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    let expected_outpoint = input.outpoint().expect("Input should have an outpoint");

    assert_eq!(
        result,
        Err(TransactionError::DuplicateTransparentSpend(
            expected_outpoint
        ))
    );
}

/// Test if V4 transaction with a joinsplit that has duplicate nullifiers is rejected.
#[test]
fn v4_transaction_with_conflicting_sprout_nullifier_inside_joinsplit_is_rejected() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;
        let nu = NetworkUpgrade::Canopy;

        let canopy_activation_height = NetworkUpgrade::Canopy
            .activation_height(&network)
            .expect("Canopy activation height is specified");

        let transaction_block_height =
            (canopy_activation_height + 10).expect("transaction block height is too large");

        // Create a fake Sprout join split
        let (mut joinsplit_data, signing_key) = mock_sprout_join_split_data();

        // Make both nullifiers the same inside the joinsplit transaction
        let duplicate_nullifier = joinsplit_data.first.nullifiers[0];
        joinsplit_data.first.nullifiers[1] = duplicate_nullifier;

        // Create a V4 transaction
        let mut transaction = Transaction::V4 {
            inputs: vec![],
            outputs: vec![],
            lock_time: LockTime::Height(block::Height(0)),
            expiry_height: (transaction_block_height + 1).expect("expiry height is too large"),
            joinsplit_data: Some(joinsplit_data),
            sapling_shielded_data: None,
        };

        // Sign the transaction
        let sighash = transaction
            .sighash(nu, HashType::ALL, Arc::new(Vec::new()), None)
            .expect("network upgrade should be valid for tx");

        match &mut transaction {
            Transaction::V4 {
                joinsplit_data: Some(joinsplit_data),
                ..
            } => joinsplit_data.sig = signing_key.sign(sighash.as_ref()),
            _ => unreachable!("Mock transaction was created incorrectly"),
        }

        let state_service =
            service_fn(|_| async { unreachable!("State service should not be called") });
        let verifier = Verifier::new_for_tests(&network, state_service);

        let result = verifier
            .oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction: Arc::new(transaction),
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height: transaction_block_height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await;

        assert_eq!(
            result,
            Err(TransactionError::DuplicateSproutNullifier(
                duplicate_nullifier
            ))
        );
    });
}

/// Test if V4 transaction with duplicate nullifiers across joinsplits is rejected.
#[test]
fn v4_transaction_with_conflicting_sprout_nullifier_across_joinsplits_is_rejected() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;
        let nu = NetworkUpgrade::Canopy;

        let canopy_activation_height = NetworkUpgrade::Canopy
            .activation_height(&network)
            .expect("Canopy activation height is specified");

        let transaction_block_height =
            (canopy_activation_height + 10).expect("transaction block height is too large");

        // Create a fake Sprout join split
        let (mut joinsplit_data, signing_key) = mock_sprout_join_split_data();

        // Duplicate a nullifier from the created joinsplit
        let duplicate_nullifier = joinsplit_data.first.nullifiers[1];

        // Add a new joinsplit with the duplicate nullifier
        let mut new_joinsplit = joinsplit_data.first.clone();
        new_joinsplit.nullifiers[0] = duplicate_nullifier;
        new_joinsplit.nullifiers[1] = sprout::note::Nullifier([2u8; 32].into());

        joinsplit_data.rest.push(new_joinsplit);

        // Create a V4 transaction
        let mut transaction = Transaction::V4 {
            inputs: vec![],
            outputs: vec![],
            lock_time: LockTime::Height(block::Height(0)),
            expiry_height: (transaction_block_height + 1).expect("expiry height is too large"),
            joinsplit_data: Some(joinsplit_data),
            sapling_shielded_data: None,
        };

        // Sign the transaction
        let sighash = transaction
            .sighash(nu, HashType::ALL, Arc::new(Vec::new()), None)
            .expect("network upgrade should be valid for tx");

        match &mut transaction {
            Transaction::V4 {
                joinsplit_data: Some(joinsplit_data),
                ..
            } => joinsplit_data.sig = signing_key.sign(sighash.as_ref()),
            _ => unreachable!("Mock transaction was created incorrectly"),
        }

        let state_service =
            service_fn(|_| async { unreachable!("State service should not be called") });
        let verifier = Verifier::new_for_tests(&network, state_service);

        let result = verifier
            .oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction: Arc::new(transaction),
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height: transaction_block_height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await;

        assert_eq!(
            result,
            Err(TransactionError::DuplicateSproutNullifier(
                duplicate_nullifier
            ))
        );
    });
}

/// Test if V5 transaction with transparent funds is accepted.
#[tokio::test]
async fn v5_transaction_with_transparent_transfer_is_accepted() {
    let network = Network::new_default_testnet();
    let network_upgrade = NetworkUpgrade::Nu5;

    let nu5_activation_height = network_upgrade
        .activation_height(&network)
        .expect("NU5 activation height is specified");

    let transaction_block_height =
        (nu5_activation_height + 10).expect("transaction block height is too large");

    let fake_source_fund_height =
        (transaction_block_height - 1).expect("fake source fund block height is too small");

    // Create a fake transparent transfer that should succeed
    let (input, output, known_utxos) = mock_transparent_transfer(
        fake_source_fund_height,
        true,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // Create a V5 transaction
    let transaction = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::Height(block::Height(0)),
        expiry_height: (transaction_block_height + 1).expect("expiry height is too large"),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
        network_upgrade,
    };

    let transaction_hash = transaction.unmined_id();

    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: transaction_block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result.expect("unexpected error response").tx_id(),
        transaction_hash
    );
}

/// Tests if a non-coinbase V5 transaction with the last valid expiry height is
/// accepted.
#[tokio::test]
async fn v5_transaction_with_last_valid_expiry_height() {
    let network = Network::new_default_testnet();
    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);

    let block_height = NetworkUpgrade::Nu5
        .activation_height(&network)
        .expect("Nu5 activation height for testnet is specified");
    let fund_height = (block_height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // Create a non-coinbase V5 tx with the last valid expiry height.
    let transaction = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height: block_height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
        network_upgrade: NetworkUpgrade::Nu5,
    };

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction.clone()),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result.expect("unexpected error response").tx_id(),
        transaction.unmined_id()
    );
}

/// Tests that a coinbase V5 transaction is accepted only if its expiry height
/// is equal to the height of the block the transaction belongs to.
#[tokio::test]
async fn v5_coinbase_transaction_expiry_height() {
    let network = Network::new_default_testnet();
    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);
    let verifier = Buffer::new(verifier, 10);

    let block_height = NetworkUpgrade::Nu5
        .activation_height(&network)
        .expect("Nu5 activation height for testnet is specified");

    let (input, output) = mock_coinbase_transparent_output(block_height);

    // Create a coinbase V5 tx with an expiry height that matches the height of
    // the block. Note that this is the only valid expiry height for a V5
    // coinbase tx.
    let transaction = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height: block_height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
        network_upgrade: NetworkUpgrade::Nu5,
    };

    let result = verifier
        .clone()
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction.clone()),
            known_utxos: Arc::new(HashMap::new()),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result.expect("unexpected error response").tx_id(),
        transaction.unmined_id()
    );

    // Increment the expiry height so that it becomes invalid.
    let new_expiry_height = (block_height + 1).expect("transaction block height is too large");
    let mut new_transaction = transaction.clone();

    *new_transaction.expiry_height_mut() = new_expiry_height;

    let result = verifier
        .clone()
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(new_transaction.clone()),
            known_utxos: Arc::new(HashMap::new()),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await
        .map_err(|err| {
            *err.downcast()
                .expect("error type should be TransactionError")
        });

    assert_eq!(
        result,
        Err(TransactionError::CoinbaseExpiryBlockHeight {
            expiry_height: Some(new_expiry_height),
            block_height,
            transaction_hash: new_transaction.hash(),
        })
    );

    // Decrement the expiry height so that it becomes invalid.
    let new_expiry_height = (block_height - 1).expect("transaction block height is too low");
    let mut new_transaction = transaction.clone();

    *new_transaction.expiry_height_mut() = new_expiry_height;

    let result = verifier
        .clone()
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(new_transaction.clone()),
            known_utxos: Arc::new(HashMap::new()),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await
        .map_err(|err| {
            *err.downcast()
                .expect("error type should be TransactionError")
        });

    assert_eq!(
        result,
        Err(TransactionError::CoinbaseExpiryBlockHeight {
            expiry_height: Some(new_expiry_height),
            block_height,
            transaction_hash: new_transaction.hash(),
        })
    );

    // Test with matching heights again, but using a very high value
    // that is greater than the limit for non-coinbase transactions,
    // to ensure the limit is not being enforced for coinbase transactions.
    let new_expiry_height = Height::MAX;
    let mut new_transaction = transaction.clone();

    *new_transaction.expiry_height_mut() = new_expiry_height;

    // Setting the new expiry height as the block height will activate NU6, so we need to set NU6
    // for the tx as well.
    let height = new_expiry_height;
    new_transaction
        .update_network_upgrade(NetworkUpgrade::current(&network, height))
        .expect("updating the network upgrade for a V5 tx should succeed");

    let verification_result = verifier
        .clone()
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(new_transaction.clone()),
            known_utxos: Arc::new(HashMap::new()),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        verification_result
            .expect("successful verification")
            .tx_id(),
        new_transaction.unmined_id()
    );
}

/// Tests if an expired non-coinbase V5 transaction is rejected.
#[tokio::test]
async fn v5_transaction_with_too_low_expiry_height() {
    let network = Network::new_default_testnet();

    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);

    let block_height = NetworkUpgrade::Nu5
        .activation_height(&network)
        .expect("Nu5 activation height for testnet is specified");
    let fund_height = (block_height - 1).expect("fake source fund block height is too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // This expiry height is too low so that the tx should seem expired to the verifier.
    let expiry_height = (block_height - 1).expect("original block height is too small");

    // Create a non-coinbase V5 tx.
    let transaction = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
        network_upgrade: NetworkUpgrade::Nu5,
    };

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction.clone()),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result,
        Err(TransactionError::ExpiredTransaction {
            expiry_height,
            block_height,
            transaction_hash: transaction.hash(),
        })
    );
}

/// Tests if a non-coinbase V5 transaction with an expiry height exceeding the maximum is rejected.
#[tokio::test]
async fn v5_transaction_with_exceeding_expiry_height() {
    let state = service_fn(|_| async { unreachable!("State service should not be called") });

    let height_max = block::Height::MAX;

    let (input, output, known_utxos) = mock_transparent_transfer(
        height_max.previous().expect("valid height"),
        true,
        0,
        Amount::try_from(1).expect("valid amount"),
    );

    // This expiry height exceeds the maximum defined by the specification.
    let expiry_height = block::Height(500_000_000);

    // Create a non-coinbase V5 tx.
    let transaction = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
        network_upgrade: NetworkUpgrade::Nu6_3,
    };

    let transaction_hash = transaction.hash();

    let verification_result = Verifier::new_for_tests(&Network::Mainnet, state)
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction.clone()),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: height_max,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        verification_result,
        Err(TransactionError::MaximumExpiryHeight {
            expiry_height,
            is_coinbase: false,
            block_height: height_max,
            transaction_hash,
        })
    );
}

/// Test if V5 coinbase transaction is accepted.
#[tokio::test]
async fn v5_coinbase_transaction_is_accepted() {
    let network = Network::new_default_testnet();
    let network_upgrade = NetworkUpgrade::Nu5;

    let nu5_activation_height = network_upgrade
        .activation_height(&network)
        .expect("NU5 activation height is specified");

    let transaction_block_height =
        (nu5_activation_height + 10).expect("transaction block height is too large");

    // Create a fake transparent coinbase that should succeed
    let (input, output) = mock_coinbase_transparent_output(transaction_block_height);
    let known_utxos = HashMap::new();

    // Create a V5 coinbase transaction
    let transaction = Transaction::V5 {
        network_upgrade,
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::Height(block::Height(0)),
        expiry_height: transaction_block_height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let transaction_hash = transaction.unmined_id();

    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: transaction_block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result.expect("unexpected error response").tx_id(),
        transaction_hash
    );
}

/// Test if V5 transaction with transparent funds is rejected if the source script prevents it.
///
/// This test simulates the case where the script verifier rejects the transaction because the
/// script prevents spending the source UTXO.
#[tokio::test]
async fn v5_transaction_with_transparent_transfer_is_rejected_by_the_script() {
    let network = Network::new_default_testnet();
    let network_upgrade = NetworkUpgrade::Nu5;

    let nu5_activation_height = network_upgrade
        .activation_height(&network)
        .expect("NU5 activation height is specified");

    let transaction_block_height =
        (nu5_activation_height + 10).expect("transaction block height is too large");

    let fake_source_fund_height =
        (transaction_block_height - 1).expect("fake source fund block height is too small");

    // Create a fake transparent transfer that should not succeed
    let (input, output, known_utxos) = mock_transparent_transfer(
        fake_source_fund_height,
        false,
        0,
        Amount::try_from(1).expect("invalid value"),
    );

    // Create a V5 transaction
    let transaction = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::Height(block::Height(0)),
        expiry_height: (transaction_block_height + 1).expect("expiry height is too large"),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
        network_upgrade,
    };

    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called") });
    let verifier = Verifier::new_for_tests(&network, state_service);

    let result = verifier
        .oneshot(Request::Block {
            transaction_hash: transaction.hash(),
            transaction: Arc::new(transaction),
            known_utxos: Arc::new(known_utxos),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height: transaction_block_height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert_eq!(
        result,
        Err(TransactionError::Script(
            zakura_script::Error::ScriptInvalid
        ))
    );
}

/// Test if V5 transaction with an internal double spend of transparent funds is rejected.
#[tokio::test]
async fn v5_transaction_with_conflicting_transparent_spend_is_rejected() {
    for network in Network::iter() {
        let canopy_activation_height = NetworkUpgrade::Canopy
            .activation_height(&network)
            .expect("Canopy activation height is specified");

        let height = (canopy_activation_height + 10).expect("valid height");

        // Create a fake transparent transfer that should succeed
        let (input, output, known_utxos) = mock_transparent_transfer(
            height.previous().expect("valid height"),
            true,
            0,
            Amount::try_from(1).expect("valid amount"),
        );

        let transaction = Transaction::V5 {
            inputs: vec![input.clone(), input.clone()],
            outputs: vec![output],
            lock_time: LockTime::Height(block::Height(0)),
            expiry_height: height.next().expect("valid height"),
            sapling_shielded_data: None,
            orchard_shielded_data: None,
            network_upgrade: NetworkUpgrade::Canopy,
        };

        let state = service_fn(|_| async { unreachable!("State service should not be called") });

        let verification_result = Verifier::new_for_tests(&network, state)
            .oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction: Arc::new(transaction),
                known_utxos: Arc::new(known_utxos),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await;

        assert_eq!(
            verification_result,
            Err(TransactionError::DuplicateTransparentSpend(
                input.outpoint().expect("Input should have an outpoint")
            ))
        );
    }
}

/// Test if signed V4 transaction with a dummy [`sprout::JoinSplit`] is accepted.
///
/// This test verifies if the transaction verifier correctly accepts a signed transaction.
#[test]
fn v4_with_signed_sprout_transfer_is_accepted() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;

        let (height, transaction) = test_transactions(&network)
            .rev()
            .filter(|(_, transaction)| {
                !transaction.is_coinbase() && transaction.inputs().is_empty()
            })
            .find(|(_, transaction)| transaction.sprout_groth16_joinsplits().next().is_some())
            .expect("No transaction found with Groth16 JoinSplits");

        let expected_hash = transaction.unmined_id();

        // Initialize the verifier
        let state_service =
            service_fn(|_| async { unreachable!("State service should not be called") });
        let verifier = Verifier::new_for_tests(&network, state_service);

        // Test the transaction verifier
        let result = verifier
            .oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction,
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await;

        assert_eq!(
            result.expect("unexpected error response").tx_id(),
            expected_hash
        );
    })
}

/// Test if an V4 transaction with a modified [`sprout::JoinSplit`] is rejected.
///
/// This test verifies if the transaction verifier correctly rejects the transaction because of the
/// invalid JoinSplit.
#[test]
fn v4_with_modified_joinsplit_is_rejected() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        v4_with_joinsplit_is_rejected_for_modification(
            JoinSplitModification::CorruptSignature,
            TransactionError::Ed25519(ed25519::Error::InvalidSignature),
        )
        .await;

        v4_with_joinsplit_is_rejected_for_modification(
            JoinSplitModification::CorruptProof,
            TransactionError::Groth16("proof verification failed".to_string()),
        )
        .await;

        v4_with_joinsplit_is_rejected_for_modification(
            JoinSplitModification::ZeroProof,
            TransactionError::MalformedGroth16("invalid G1".to_string()),
        )
        .await;
    })
}

async fn v4_with_joinsplit_is_rejected_for_modification(
    modification: JoinSplitModification,
    expected_error: TransactionError,
) {
    let network = Network::Mainnet;

    let (height, mut transaction) = test_transactions(&network)
        .rev()
        .filter(|(_, tx)| {
            !tx.is_coinbase() && tx.inputs().is_empty() && !tx.has_sapling_shielded_data()
        })
        .find(|(_, tx)| tx.sprout_groth16_joinsplits().next().is_some())
        .expect("There should be a tx with Groth16 JoinSplits.");

    let expected_error = Err(expected_error);

    // Modify a JoinSplit in the transaction following the given modification type.
    let tx = Arc::get_mut(&mut transaction).expect("The tx should have only one active reference.");
    match tx {
        Transaction::V4 {
            joinsplit_data: Some(ref mut joinsplit_data),
            ..
        } => modify_joinsplit_data(joinsplit_data, modification),
        _ => unreachable!("Transaction should have some JoinSplit shielded data."),
    }

    // Initialize the verifier
    let state_service =
        service_fn(|_| async { unreachable!("State service should not be called.") });
    let verifier = Verifier::new_for_tests(&network, state_service);
    let verifier = Buffer::new(verifier, 10);

    // Test the transaction verifier.
    //
    // Note that modifying the JoinSplit data invalidates the tx signatures. The signatures are
    // checked concurrently with the ZK proofs, and when a signature check finishes before the proof
    // check, the verifier reports an invalid signature instead of invalid proof. This race
    // condition happens only occasionally, so we run the verifier in a loop with a small iteration
    // threshold until it returns the correct error.
    let mut i = 1;
    let result = loop {
        let result = verifier
            .clone()
            .oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction: transaction.clone(),
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await
            .map_err(|err| {
                *err.downcast()
                    .expect("error type should be TransactionError")
            });

        if result == expected_error || i >= 100 {
            break result;
        }

        i += 1;
    };

    assert_eq!(result, expected_error);
}

/// Test if V4 and V5 transactions with Sapling spends are accepted by the verifier.
///
/// Keeping both versions in one test amortizes Sapling verifying-key
/// initialization under nextest's process-per-test execution model.
#[test]
fn v4_and_v5_with_sapling_spends() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;

        let (height, transaction) = test_transactions(&network)
            .rev()
            .filter(|(_, transaction)| {
                !transaction.is_coinbase() && transaction.inputs().is_empty()
            })
            .find(|(_, transaction)| transaction.sapling_spends_per_anchor().next().is_some())
            .expect("No transaction found with Sapling spends");

        let expected_hash = transaction.unmined_id();

        // Initialize the verifier
        let state_service =
            service_fn(|_| async { unreachable!("State service should not be called") });
        let verifier = Verifier::new_for_tests(&network, state_service);

        // Test the transaction verifier
        let result = timeout(
            test_timeout(),
            verifier.oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction,
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height,
                time: DateTime::<Utc>::MAX_UTC,
            }),
        )
        .await
        .expect("timeout expired");

        assert_eq!(
            result.expect("unexpected error response").tx_id(),
            expected_hash
        );

        for net in Network::iter() {
            let nu5_activation = NetworkUpgrade::Nu5.activation_height(&net);

            let tx = v5_transactions(net.block_iter())
                .filter(|tx| {
                    !tx.is_coinbase()
                        && tx.inputs().is_empty()
                        && tx.expiry_height() >= nu5_activation
                })
                .find(|tx| tx.sapling_spends_per_anchor().next().is_some())
                .expect("V5 tx with Sapling spends");

            let expected_hash = tx.unmined_id();
            let height = tx.expiry_height().expect("expiry height");

            let verifier = Verifier::new_for_tests(
                &net,
                service_fn(|_| async { unreachable!("State service should not be called") }),
            );

            assert_eq!(
                timeout(
                    test_timeout(),
                    verifier.oneshot(Request::Block {
                        transaction_hash: tx.hash(),
                        transaction: Arc::new(tx),
                        known_utxos: Arc::new(HashMap::new()),
                        known_outpoint_hashes: Arc::new(HashSet::new()),
                        height,
                        time: DateTime::<Utc>::MAX_UTC,
                    })
                )
                .await
                .expect("timeout expired")
                .expect("unexpected error response")
                .tx_id(),
                expected_hash
            );
        }
    });
}

/// An invalid Sapling proof is reported as a typed verification error by both
/// the batch verifier and its single-verification fallback.
#[test]
fn v4_with_invalid_sapling_proof_returns_typed_error() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;

        let (height, mut transaction) = test_transactions(&network)
            .rev()
            .find(|(_, transaction)| {
                !transaction.is_coinbase()
                    && transaction.inputs().is_empty()
                    && transaction.sapling_spends_per_anchor().next().is_some()
            })
            .expect("test vectors include a V4 transaction with Sapling spends");

        let (valid_bundle_one, valid_bundle_two, valid_sighash) = {
            let sighasher = transaction
                .sighasher(
                    NetworkUpgrade::current(&network, height),
                    Arc::new(Vec::new()),
                )
                .expect("test fixture has no transparent inputs");
            let valid_bundle_one = sighasher
                .sapling_bundle()
                .expect("test fixture has Sapling shielded data");
            let valid_bundle_two = sighasher
                .sapling_bundle()
                .expect("test fixture has Sapling shielded data");
            let valid_sighash = sighasher.sighash(HashType::ALL, None);

            (valid_bundle_one, valid_bundle_two, valid_sighash)
        };

        modify_first_sapling_spend_proof(
            Arc::get_mut(&mut transaction).expect("transaction only has one active reference"),
            SaplingProofModification::Corrupt,
        );

        let sighasher = transaction
            .sighasher(
                NetworkUpgrade::current(&network, height),
                Arc::new(Vec::new()),
            )
            .expect("test fixture has no transparent inputs");
        let batch_bundle = sighasher
            .sapling_bundle()
            .expect("test fixture has Sapling shielded data");
        let single_bundle = sighasher
            .sapling_bundle()
            .expect("test fixture has Sapling shielded data");
        let fallback_bundle = sighasher
            .sapling_bundle()
            .expect("test fixture has Sapling shielded data");
        let synchronous_check_bundle = sighasher
            .sapling_bundle()
            .expect("test fixture has Sapling shielded data");
        let sighash = sighasher.sighash(HashType::ALL, None);
        drop(sighasher);

        let mut verifier = sapling_crypto::BatchValidator::default();
        assert!(
            verifier.check_bundle(synchronous_check_bundle, sighash.into()),
            "the corrupted proof must pass synchronous checks and fail batch validation"
        );

        let mut batch_verifier = crate::primitives::sapling::Verifier::default();
        let batch_result = batch_verifier.call(BatchControl::Item(
            crate::primitives::sapling::Item::new(batch_bundle, sighash),
        ));
        let flush_result = batch_verifier.call(BatchControl::Flush);
        let (batch_result, flush_result) = futures::join!(batch_result, flush_result);
        flush_result.expect("batch flush must complete");

        assert_sapling_verification_error(
            batch_result.expect_err("corrupted Sapling proof must be rejected"),
        );

        let single_result = crate::primitives::sapling::verify_single(
            crate::primitives::sapling::Item::new(single_bundle, sighash),
        )
        .await;
        assert_sapling_verification_error(
            single_result.expect_err("corrupted Sapling proof must be rejected"),
        );

        let invalid_item = crate::primitives::sapling::Item::new(fallback_bundle, sighash);
        let items = vec![
            crate::primitives::sapling::Item::new(valid_bundle_one, valid_sighash),
            invalid_item.clone(),
            crate::primitives::sapling::Item::new(valid_bundle_two, valid_sighash),
        ];
        let expected_results: Vec<_> = futures::future::join_all(
            items
                .iter()
                .cloned()
                .map(crate::primitives::sapling::verify_single),
        )
        .await
        .into_iter()
        .map(|result| result.is_ok())
        .collect();
        assert_eq!(
            expected_results,
            [true, false, true],
            "the fixture must contain valid neighbors around one invalid proof"
        );

        let mut verifier = Fallback::new(
            Batch::new(
                crate::primitives::sapling::Verifier::default(),
                100,
                1,
                std::time::Duration::from_secs(1000),
            ),
            service_fn(crate::primitives::sapling::verify_single),
        );
        verifier
            .ready()
            .await
            .expect("test verifier must become ready");
        let invalid_singleton = verifier.call(invalid_item);
        let mut primary = verifier.primary().clone();
        assert!(
            primary
                .try_flush()
                .expect("explicit Sapling singleton flush must not fail"),
            "explicit Sapling singleton flush must be queued"
        );
        assert!(
            timeout(test_timeout(), invalid_singleton)
                .await
                .expect("explicitly flushed Sapling singleton must complete")
                .is_err(),
            "an explicitly flushed invalid Sapling singleton must be rejected"
        );

        let mut batch_results = Vec::new();
        for item in items {
            verifier
                .ready()
                .await
                .expect("test verifier must become ready");
            batch_results.push(verifier.call(item));
        }

        assert!(
            primary
                .try_flush()
                .expect("explicit Sapling test flush must not fail"),
            "explicit Sapling test flush must be queued"
        );

        let actual_results: Vec<_> =
            timeout(test_timeout(), futures::future::join_all(batch_results))
                .await
                .expect("explicitly flushed Sapling verification must complete")
                .into_iter()
                .map(|result| result.is_ok())
                .collect();
        assert_eq!(
            actual_results, expected_results,
            "explicit Sapling batch flush plus fallback must match single verification"
        );

        let known_outpoint_hashes = Arc::new(HashSet::new());
        let _block_batch_flush =
            crate::primitives::register_block_verifier_batch_flush(&known_outpoint_hashes, 1);
        let transaction_hash = transaction.hash();
        let transaction_verifier = Verifier::new_for_tests(
            &network,
            service_fn(|_| async { unreachable!("fixture has no transparent inputs") }),
        );
        let block_transaction_result = timeout(
            test_timeout(),
            transaction_verifier.oneshot(Request::Block {
                transaction_hash,
                transaction,
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes,
                height,
                time: DateTime::<Utc>::MAX_UTC,
            }),
        )
        .await
        .expect("block-boundary-flushed transaction verification must complete");
        assert_eq!(
            block_transaction_result,
            Err(TransactionError::SaplingVerificationFailed),
            "the block-boundary flush path must reject an invalid Sapling proof"
        );
    });
}

/// A malformed Sapling proof is reported as a typed verification error before
/// it is queued for batch validation.
#[test]
fn v4_with_malformed_sapling_proof_returns_typed_error() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;

        let (height, mut transaction) = test_transactions(&network)
            .rev()
            .find(|(_, transaction)| {
                !transaction.is_coinbase()
                    && transaction.inputs().is_empty()
                    && transaction.sapling_spends_per_anchor().next().is_some()
            })
            .expect("test vectors include a V4 transaction with Sapling spends");

        modify_first_sapling_spend_proof(
            Arc::get_mut(&mut transaction).expect("transaction only has one active reference"),
            SaplingProofModification::Zero,
        );

        let sighasher = transaction
            .sighasher(
                NetworkUpgrade::current(&network, height),
                Arc::new(Vec::new()),
            )
            .expect("test fixture has no transparent inputs");
        let check_bundle = sighasher
            .sapling_bundle()
            .expect("test fixture has Sapling shielded data");
        let bundle = sighasher
            .sapling_bundle()
            .expect("test fixture has Sapling shielded data");
        let sighash = sighasher.sighash(HashType::ALL, None);

        let mut verifier = sapling_crypto::BatchValidator::default();
        assert!(
            !verifier.check_bundle(check_bundle, sighash.into()),
            "the malformed proof must fail synchronous bundle checks"
        );

        let result = crate::primitives::sapling::verify_single(
            crate::primitives::sapling::Item::new(bundle, sighash),
        )
        .await;
        assert_sapling_verification_error(
            result.expect_err("malformed Sapling proof must be rejected"),
        );
    });
}

fn assert_sapling_verification_error(error: crate::BoxError) {
    let error = error
        .downcast::<TransactionError>()
        .expect("Sapling verification failure must be a TransactionError");

    assert_eq!(*error, TransactionError::SaplingVerificationFailed);
}

/// Test if a V4 transaction with a duplicate Sapling spend is rejected by the verifier.
#[test]
fn v4_with_duplicate_sapling_spends() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;

        let (height, mut transaction) = test_transactions(&network)
            .rev()
            .filter(|(_, transaction)| {
                !transaction.is_coinbase() && transaction.inputs().is_empty()
            })
            .find(|(_, transaction)| transaction.sapling_spends_per_anchor().next().is_some())
            .expect("No transaction found with Sapling spends");

        // Duplicate one of the spends
        let duplicate_nullifier = duplicate_sapling_spend(
            Arc::get_mut(&mut transaction).expect("Transaction only has one active reference"),
        );

        // Initialize the verifier
        let state_service =
            service_fn(|_| async { unreachable!("State service should not be called") });
        let verifier = Verifier::new_for_tests(&network, state_service);

        // Test the transaction verifier
        let result = verifier
            .oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction,
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await;

        assert_eq!(
            result,
            Err(TransactionError::DuplicateSaplingNullifier(
                duplicate_nullifier
            ))
        );
    });
}

/// Test if a V4 transaction with Sapling outputs but no spends is accepted by the verifier.
#[test]
fn v4_with_sapling_outputs_and_no_spends() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;

        let (height, transaction) = test_transactions(&network)
            .rev()
            .filter(|(_, transaction)| {
                !transaction.is_coinbase() && transaction.inputs().is_empty()
            })
            .find(|(_, transaction)| {
                transaction.sapling_spends_per_anchor().next().is_none()
                    && transaction.sapling_outputs().next().is_some()
            })
            .expect("No transaction found with Sapling outputs and no Sapling spends");

        let expected_hash = transaction.unmined_id();

        // Initialize the verifier
        let state_service =
            service_fn(|_| async { unreachable!("State service should not be called") });
        let verifier = Verifier::new_for_tests(&network, state_service);

        // Test the transaction verifier
        let result = verifier
            .oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction,
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await;

        assert_eq!(
            result.expect("unexpected error response").tx_id(),
            expected_hash
        );
    })
}

/// A transaction whose Sapling output has an invalid (off-curve) ephemeral key
/// is rejected by the verifier with `SmallOrder`.
///
/// The Sapling `cv`/`epk` not-small-order check is deferred from deserialization
/// and re-enforced in the verifier's early quick checks via
/// `Transaction::sapling_point_encodings_are_valid`. This drives the full verifier
/// end-to-end: the state service is `unreachable!` because the check fires before
/// any state lookup. It mirrors `v4_with_sapling_outputs_and_no_spends` (which
/// accepts this shape) with only the ephemeral key corrupted.
#[test]
fn sapling_output_with_invalid_ephemeral_key_is_rejected() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;

        let (height, mut transaction) = test_transactions(&network)
            .rev()
            .filter(|(_, transaction)| {
                !transaction.is_coinbase() && transaction.inputs().is_empty()
            })
            .find(|(_, transaction)| {
                transaction.sapling_spends_per_anchor().next().is_none()
                    && transaction.sapling_outputs().next().is_some()
            })
            .expect("a transaction with Sapling outputs and no Sapling spends");

        // Corrupt the first Sapling output's ephemeral key to an off-curve point.
        corrupt_first_sapling_output_ephemeral_key(
            Arc::get_mut(&mut transaction).expect("transaction only has one active reference"),
        );

        // The state service must not be reached: the check fires before any
        // state lookup.
        let state_service =
            service_fn(|_| async { unreachable!("State service should not be called") });
        let verifier = Verifier::new_for_tests(&network, state_service);

        let result = verifier
            .oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction,
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await;

        assert_eq!(
            result,
            Err(TransactionError::SmallOrder),
            "a Sapling output with an off-curve ephemeral key must be rejected with SmallOrder",
        );
    });
}

/// A transaction whose Sapling output has an invalid (off-curve) value
/// commitment is rejected by the verifier with `SmallOrder`.
///
/// Unlike the ephemeral-key regression above, this also round-trips the
/// corrupted V4 transaction through serialization. That pins the lazy V4
/// output path: the parser preserves the raw `cv` bytes, and the early
/// semantic check rejects them before any state lookup.
#[test]
fn sapling_v4_output_with_invalid_value_commitment_is_rejected_after_roundtrip() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;

        let (height, mut transaction) = test_transactions(&network)
            .rev()
            .filter(|(_, transaction)| {
                !transaction.is_coinbase() && transaction.inputs().is_empty()
            })
            .find(|(_, transaction)| {
                transaction.sapling_spends_per_anchor().next().is_none()
                    && transaction.sapling_outputs().next().is_some()
            })
            .expect("a V4 transaction with Sapling outputs and no Sapling spends");

        assert!(
            matches!(transaction.as_ref(), Transaction::V4 { .. }),
            "test vector must exercise the V4 output encoding"
        );

        corrupt_first_sapling_output_value_commitment(
            Arc::get_mut(&mut transaction).expect("transaction only has one active reference"),
        );

        let serialized = transaction
            .zcash_serialize_to_vec()
            .expect("corrupted V4 transaction must serialize raw Sapling cv bytes");
        let transaction = Arc::new(
            serialized
                .zcash_deserialize_into::<Transaction>()
                .expect("lazy V4 output deserialization must preserve invalid cv bytes"),
        );

        assert!(
            !transaction.sapling_point_encodings_are_valid(),
            "the deferred Sapling point check must reject the round-tripped invalid cv"
        );

        let state_service =
            service_fn(|_| async { unreachable!("State service should not be called") });
        let verifier = Verifier::new_for_tests(&network, state_service);

        let result = verifier
            .oneshot(Request::Block {
                transaction_hash: transaction.hash(),
                transaction,
                known_utxos: Arc::new(HashMap::new()),
                known_outpoint_hashes: Arc::new(HashSet::new()),
                height,
                time: DateTime::<Utc>::MAX_UTC,
            })
            .await;

        assert_eq!(
            result,
            Err(TransactionError::SmallOrder),
            "a V4 Sapling output with an off-curve cv must be rejected with SmallOrder",
        );
    });
}

/// Transactions whose Sapling spend has an invalid (off-curve) value
/// commitment are rejected by the verifier with `SmallOrder`.
///
/// This pins both spend encodings affected by lazy Sapling `cv` parsing:
/// V4 stores the full `Spend<PerSpendAnchor>` inline, while V5 stores the
/// `SpendPrefixInTransactionV5` fields separately. In both cases the parser
/// preserves the raw bytes and the early semantic check rejects them before
/// any state lookup.
#[test]
fn sapling_spends_with_invalid_value_commitments_are_rejected_after_roundtrip() {
    let _init_guard = zakura_test::init();
    zakura_test::MULTI_THREADED_RUNTIME.block_on(async {
        let network = Network::Mainnet;

        let v4 = test_transactions(&network)
            .rev()
            .filter(|(_, transaction)| {
                !transaction.is_coinbase() && transaction.inputs().is_empty()
            })
            .find(|(_, transaction)| {
                matches!(transaction.as_ref(), Transaction::V4 { .. })
                    && transaction.sapling_spends_per_anchor().next().is_some()
            })
            .expect("a V4 transaction with Sapling spends");

        let v5 = transactions_from_blocks(network.block_iter())
            .rev()
            .filter(|(_, transaction)| {
                !transaction.is_coinbase() && transaction.inputs().is_empty()
            })
            .find(|(_, transaction)| {
                matches!(transaction.as_ref(), Transaction::V5 { .. })
                    && transaction.sapling_spends_per_anchor().next().is_some()
            })
            .expect("a V5 transaction with Sapling spends");

        for (version, height, mut transaction) in [("V4", v4.0, v4.1), ("V5", v5.0, v5.1)] {
            corrupt_first_sapling_spend_value_commitment(
                Arc::get_mut(&mut transaction).expect("transaction only has one active reference"),
            );

            let serialized = transaction
                .zcash_serialize_to_vec()
                .expect("corrupted transaction must serialize raw Sapling cv bytes");
            let transaction = Arc::new(
                serialized
                    .zcash_deserialize_into::<Transaction>()
                    .expect("lazy spend deserialization must preserve invalid cv bytes"),
            );
            assert_eq!(
                serialized,
                transaction
                    .zcash_serialize_to_vec()
                    .expect("round-tripped transaction must reserialize"),
                "lazy {version} spend cv bytes must round-trip exactly",
            );

            assert!(
                !transaction.sapling_point_encodings_are_valid(),
                "the deferred Sapling point check must reject the round-tripped {version} spend cv"
            );

            let state_service =
                service_fn(|_| async { unreachable!("State service should not be called") });
            let verifier = Verifier::new_for_tests(&network, state_service);

            let result = verifier
                .oneshot(Request::Block {
                    transaction_hash: transaction.hash(),
                    transaction,
                    known_utxos: Arc::new(HashMap::new()),
                    known_outpoint_hashes: Arc::new(HashSet::new()),
                    height,
                    time: DateTime::<Utc>::MAX_UTC,
                })
                .await;

            assert_eq!(
                result,
                Err(TransactionError::SmallOrder),
                "a {version} Sapling spend with an off-curve cv must be rejected with SmallOrder",
            );
        }
    });
}

/// Replaces the first Sapling output's ephemeral key with an off-curve point,
/// for `sapling_output_with_invalid_ephemeral_key_is_rejected`.
fn corrupt_first_sapling_output_ephemeral_key(transaction: &mut Transaction) {
    let bad_epk = sapling::keys::EphemeralPublicKey::try_from([0xffu8; 32])
        .expect("deserialization defers point validation, so try_from stores the bytes");

    match transaction {
        Transaction::V4 {
            sapling_shielded_data: Some(shielded_data),
            ..
        } => set_first_sapling_output_ephemeral_key(&mut shielded_data.transfers, bad_epk),
        Transaction::V5 {
            sapling_shielded_data: Some(shielded_data),
            ..
        } => set_first_sapling_output_ephemeral_key(&mut shielded_data.transfers, bad_epk),
        _ => panic!("expected a V4 or V5 transaction with Sapling data"),
    }
}

/// Replaces the first Sapling output's value commitment with off-curve bytes,
/// for `sapling_v4_output_with_invalid_value_commitment_is_rejected_after_roundtrip`.
fn corrupt_first_sapling_output_value_commitment(transaction: &mut Transaction) {
    let bad_cv = [0xffu8; 32][..]
        .zcash_deserialize_into::<sapling::ValueCommitment>()
        .expect("deserialization defers point validation, so it stores the bytes");

    match transaction {
        Transaction::V4 {
            sapling_shielded_data: Some(shielded_data),
            ..
        } => set_first_sapling_output_value_commitment(&mut shielded_data.transfers, bad_cv),
        _ => panic!("expected a V4 transaction with Sapling data"),
    }
}

/// Replaces the first Sapling spend's value commitment with off-curve bytes,
/// for `sapling_spends_with_invalid_value_commitments_are_rejected_after_roundtrip`.
fn corrupt_first_sapling_spend_value_commitment(transaction: &mut Transaction) {
    let bad_cv = [0xffu8; 32][..]
        .zcash_deserialize_into::<sapling::ValueCommitment>()
        .expect("deserialization defers point validation, so it stores the bytes");

    match transaction {
        Transaction::V4 {
            sapling_shielded_data: Some(shielded_data),
            ..
        } => set_first_sapling_spend_value_commitment(&mut shielded_data.transfers, bad_cv),
        Transaction::V5 {
            sapling_shielded_data: Some(shielded_data),
            ..
        } => set_first_sapling_spend_value_commitment(&mut shielded_data.transfers, bad_cv),
        Transaction::V6 {
            sapling_shielded_data: Some(shielded_data),
            ..
        } => set_first_sapling_spend_value_commitment(&mut shielded_data.transfers, bad_cv),
        _ => panic!("expected a V4, V5, or V6 transaction with Sapling data"),
    }
}

fn set_first_sapling_output_ephemeral_key<A: sapling::AnchorVariant + Clone>(
    transfers: &mut sapling::TransferData<A>,
    ephemeral_key: sapling::keys::EphemeralPublicKey,
) {
    match transfers {
        sapling::TransferData::JustOutputs { outputs } => {
            let mut outputs_vec = outputs.as_slice().to_vec();
            outputs_vec[0].ephemeral_key = ephemeral_key;
            *outputs = AtLeastOne::from_vec(outputs_vec)
                .expect("replacing a field keeps at least one output");
        }
        sapling::TransferData::SpendsAndMaybeOutputs { maybe_outputs, .. } => {
            maybe_outputs[0].ephemeral_key = ephemeral_key;
        }
    }
}

fn set_first_sapling_output_value_commitment<A: sapling::AnchorVariant + Clone>(
    transfers: &mut sapling::TransferData<A>,
    value_commitment: sapling::ValueCommitment,
) {
    match transfers {
        sapling::TransferData::JustOutputs { outputs } => {
            let mut outputs_vec = outputs.as_slice().to_vec();
            outputs_vec[0].cv = value_commitment;
            *outputs = AtLeastOne::from_vec(outputs_vec)
                .expect("replacing a field keeps at least one output");
        }
        sapling::TransferData::SpendsAndMaybeOutputs { maybe_outputs, .. } => {
            maybe_outputs[0].cv = value_commitment;
        }
    }
}

fn set_first_sapling_spend_value_commitment<A: sapling::AnchorVariant + Clone>(
    transfers: &mut sapling::TransferData<A>,
    value_commitment: sapling::ValueCommitment,
) {
    match transfers {
        sapling::TransferData::SpendsAndMaybeOutputs { spends, .. } => {
            let mut spends_vec = spends.as_slice().to_vec();
            spends_vec[0].cv = value_commitment;
            *spends = AtLeastOne::from_vec(spends_vec)
                .expect("replacing a field keeps at least one spend");
        }
        sapling::TransferData::JustOutputs { .. } => {
            panic!("expected Sapling shielded data with spends")
        }
    }
}

#[derive(Clone, Copy)]
enum SaplingProofModification {
    /// Keep the proof well-formed while making it invalid.
    Corrupt,
    /// Make the proof malformed.
    Zero,
}

/// Modifies the first Sapling spend proof without changing the transaction's
/// structure.
fn modify_first_sapling_spend_proof(
    transaction: &mut Transaction,
    modification: SaplingProofModification,
) {
    match transaction {
        Transaction::V4 {
            sapling_shielded_data: Some(shielded_data),
            ..
        } => modify_first_sapling_spend_proof_in_transfers(
            &mut shielded_data.transfers,
            modification,
        ),
        Transaction::V5 {
            sapling_shielded_data: Some(shielded_data),
            ..
        }
        | Transaction::V6 {
            sapling_shielded_data: Some(shielded_data),
            ..
        } => modify_first_sapling_spend_proof_in_transfers(
            &mut shielded_data.transfers,
            modification,
        ),
        _ => panic!("expected a transaction with Sapling spends"),
    }
}

fn modify_first_sapling_spend_proof_in_transfers<A: sapling::AnchorVariant + Clone>(
    transfers: &mut sapling::TransferData<A>,
    modification: SaplingProofModification,
) {
    match transfers {
        sapling::TransferData::SpendsAndMaybeOutputs { spends, .. } => {
            let mut spends_vec = spends.as_slice().to_vec();
            match modification {
                SaplingProofModification::Corrupt => {
                    // A Groth16 proof has two 48-byte compressed G1 elements around a
                    // 96-byte compressed G2 element. Swapping the G1 elements keeps the
                    // proof well-formed but invalid.
                    let (first, rest) = spends_vec[0].zkproof.0.split_at_mut(48);
                    first.swap_with_slice(&mut rest[96..144]);
                }
                SaplingProofModification::Zero => spends_vec[0].zkproof.0 = [0; 192],
            }
            *spends = AtLeastOne::from_vec(spends_vec)
                .expect("replacing a proof keeps at least one spend");
        }
        sapling::TransferData::JustOutputs { .. } => {
            panic!("expected Sapling shielded data with spends")
        }
    }
}

/// Test if a V5 transaction with a duplicate Sapling spend is rejected by the verifier.
#[tokio::test]
async fn v5_with_duplicate_sapling_spends() {
    let _init_guard = zakura_test::init();

    for net in Network::iter() {
        let mut tx = v5_transactions(net.block_iter())
            .filter(|tx| !tx.is_coinbase() && tx.inputs().is_empty())
            .find(|tx| tx.sapling_spends_per_anchor().next().is_some())
            .expect("V5 tx with Sapling spends");

        let height = tx.expiry_height().expect("expiry height");

        // Duplicate one of the spends
        let duplicate_nullifier = duplicate_sapling_spend(&mut tx);

        let verifier = Verifier::new_for_tests(
            &net,
            service_fn(|_| async { unreachable!("State service should not be called") }),
        );

        assert_eq!(
            verifier
                .oneshot(Request::Block {
                    transaction_hash: tx.hash(),
                    transaction: Arc::new(tx),
                    known_utxos: Arc::new(HashMap::new()),
                    known_outpoint_hashes: Arc::new(HashSet::new()),
                    height,
                    time: DateTime::<Utc>::MAX_UTC,
                })
                .await,
            Err(TransactionError::DuplicateSaplingNullifier(
                duplicate_nullifier
            ))
        );
    }
}

/// Test if a V5 transaction with a duplicate Orchard action is rejected by the verifier.
#[tokio::test]
async fn v5_with_duplicate_orchard_action() {
    let _init_guard = zakura_test::init();

    for net in Network::iter() {
        let mut tx = v5_transactions(net.block_iter())
            .rev()
            .find(|transaction| {
                transaction.inputs().is_empty()
                    && transaction.outputs().is_empty()
                    && transaction.sapling_spends_per_anchor().next().is_none()
                    && transaction.sapling_outputs().next().is_none()
                    && transaction.joinsplit_count() == 0
            })
            .expect("V5 tx with only Orchard actions");

        let height = tx.expiry_height().expect("expiry height");

        let orchard_shielded_data = tx
            .orchard_shielded_data_mut()
            .expect("tx without transparent, Sprout, or Sapling outputs must have Orchard actions");

        // Enable spends
        orchard_shielded_data.flags = Flags::ENABLE_SPENDS | Flags::ENABLE_OUTPUTS;

        let duplicate_action = orchard_shielded_data.actions.first().clone();
        let duplicate_nullifier = duplicate_action.action.nullifier;

        // Duplicate the first action
        let mut actions_vec = orchard_shielded_data.actions.as_slice().to_vec();
        actions_vec.push(duplicate_action.clone());
        orchard_shielded_data.actions = AtLeastOne::from_vec(actions_vec)
            .expect("pushing one element never breaks at least one constraints");

        let verifier = Verifier::new_for_tests(
            &net,
            service_fn(|_| async { unreachable!("State service should not be called") }),
        );

        assert_eq!(
            verifier
                .oneshot(Request::Block {
                    transaction_hash: tx.hash(),
                    transaction: Arc::new(tx),
                    known_utxos: Arc::new(HashMap::new()),
                    known_outpoint_hashes: Arc::new(HashSet::new()),
                    height,
                    time: DateTime::<Utc>::MAX_UTC,
                })
                .await,
            Err(TransactionError::DuplicateOrchardNullifier(
                duplicate_nullifier
            ))
        );
    }
}

/// Checks the activation boundary of the temporary Orchard-disabling soft fork:
/// it is inactive below the configured height and active at and above it, can be
/// disabled entirely, and Mainnet uses its fixed activation height.
#[test]
fn orchard_disabling_soft_fork_activation_boundary() {
    let _init_guard = zakura_test::init();

    let soft_fork_height = Height(2_000_000);

    // A Testnet with the soft fork configured to activate at `soft_fork_height`.
    let network = Parameters::build()
        .with_temporary_orchard_disabling_soft_fork_height(soft_fork_height)
        .to_network()
        .expect("failed to build configured network");

    assert!(
        !network.temporary_orchard_disabling_soft_fork_active(Height(1_999_999)),
        "soft fork must be inactive below the configured height",
    );
    assert!(
        network.temporary_orchard_disabling_soft_fork_active(soft_fork_height),
        "soft fork must be active at the configured height",
    );
    assert!(
        network.temporary_orchard_disabling_soft_fork_active(Height(2_000_001)),
        "soft fork must be active above the configured height",
    );

    // A Testnet with the soft fork disabled is never active.
    let disabled = Parameters::build()
        .disable_temporary_orchard_disabling_soft_fork()
        .to_network()
        .expect("failed to build configured network");

    assert!(
        !disabled.temporary_orchard_disabling_soft_fork_active(Height(4_042_000)),
        "a disabled soft fork must never be active",
    );

    // Mainnet uses a fixed activation height (3_363_426).
    assert!(
        !Network::Mainnet.temporary_orchard_disabling_soft_fork_active(Height(3_363_425)),
        "Mainnet soft fork must be inactive below its fixed height",
    );
    assert!(
        Network::Mainnet.temporary_orchard_disabling_soft_fork_active(Height(3_363_426)),
        "Mainnet soft fork must be active at its fixed height",
    );
}

/// The temporary Orchard-disabling soft fork must reject transactions that
/// contain Orchard actions once it is active, in both block and mempool
/// verification contexts.
#[tokio::test]
async fn orchard_disabling_soft_fork_rejects_orchard_actions_in_blocks_and_mempool() {
    let _init_guard = zakura_test::init();

    // Find a V5 transaction whose only shielded data is Orchard, so it both
    // contains Orchard actions and can pass `has_inputs_and_outputs` once the
    // Orchard flags are set below.
    let default_testnet = Network::new_default_testnet();
    let mut tx = v5_transactions(default_testnet.block_iter())
        .rev()
        .find(|transaction| {
            transaction.inputs().is_empty()
                && transaction.outputs().is_empty()
                && transaction.sapling_spends_per_anchor().next().is_none()
                && transaction.sapling_outputs().next().is_none()
                && transaction.joinsplit_count() == 0
        })
        .expect("V5 tx with only Orchard actions");

    // Enable spends and outputs so the transaction passes `has_inputs_and_outputs`
    // and `has_enough_orchard_flags`, reaching the soft-fork check.
    tx.orchard_shielded_data_mut()
        .expect("tx without transparent, Sprout, or Sapling data must have Orchard actions")
        .flags = Flags::ENABLE_SPENDS | Flags::ENABLE_OUTPUTS;

    // Verify at the transaction's own expiry height, where its NU5 consensus
    // branch id is valid on the default Testnet activation schedule.
    let height = tx.expiry_height().expect("V5 tx has an expiry height");

    // Configure a Testnet identical to the default public Testnet except that the
    // Orchard-disabling soft fork activates at `height`, so it is active for this
    // transaction.
    let network = Parameters::build()
        .with_temporary_orchard_disabling_soft_fork_height(height)
        .to_network()
        .expect("failed to build configured network");

    assert!(
        network.temporary_orchard_disabling_soft_fork_active(height),
        "soft fork must be active at the transaction's height",
    );

    let expected = Err(TransactionError::Other(
        "transaction has Orchard actions (temporarily disabled)".into(),
    ));

    // The soft-fork check runs before any state-service query, so the state
    // service must never be called.
    let block_response = Verifier::new_for_tests(
        &network,
        service_fn(|_| async { unreachable!("state service should not be called") }),
    )
    .oneshot(Request::Block {
        transaction_hash: tx.hash(),
        transaction: Arc::new(tx.clone()),
        known_utxos: Arc::new(HashMap::new()),
        known_outpoint_hashes: Arc::new(HashSet::new()),
        height,
        time: DateTime::<Utc>::MAX_UTC,
    })
    .await;

    assert_eq!(
        block_response, expected,
        "block verification must reject a transaction with Orchard actions after the soft fork",
    );

    let mempool_response = Verifier::new_for_tests(
        &network,
        service_fn(|_| async { unreachable!("state service should not be called") }),
    )
    .oneshot(Request::Mempool {
        transaction: tx.into(),
        height,
    })
    .await;

    assert_eq!(
        mempool_response, expected,
        "mempool verification must reject a transaction with Orchard actions after the soft fork",
    );
}

/// Negative control mirroring the zcashd test: a transaction without Orchard
/// actions is unaffected by the soft fork and is still accepted while it is
/// active.
#[tokio::test]
async fn orchard_disabling_soft_fork_accepts_non_orchard_transactions() {
    let _init_guard = zakura_test::init();

    // A Testnet with the Orchard-disabling soft fork active from height 1.
    let network = Parameters::build()
        .with_temporary_orchard_disabling_soft_fork_height(Height(1))
        .to_network()
        .expect("failed to build configured network");

    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();

    let canopy_activation_height = NetworkUpgrade::Canopy
        .activation_height(&network)
        .expect("Canopy activation height is specified");

    let transaction_block_height =
        (canopy_activation_height + 10).expect("transaction block height is too large");
    let fake_source_fund_height =
        (transaction_block_height - 1).expect("fake source fund block height is too small");

    assert!(
        network.temporary_orchard_disabling_soft_fork_active(transaction_block_height),
        "soft fork must be active at the transaction's height",
    );

    // A transparent transfer has no Orchard actions, so the soft fork must not
    // affect it. The input must exceed the output by enough to pay the ZIP-317
    // conventional fee, so the transaction is otherwise valid.
    let (input, output, known_utxos) = mock_transparent_transfer(
        fake_source_fund_height,
        true,
        0,
        Amount::try_from(10001).expect("valid amount"),
    );

    let transaction = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::Height(block::Height(0)),
        expiry_height: (transaction_block_height + 1).expect("expiry height is too large"),
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let input_outpoint = match transaction.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    let verifier = Verifier::new_for_tests(&network, state.clone());

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let response = verifier
        .oneshot(Request::Mempool {
            transaction: transaction.into(),
            height: transaction_block_height,
        })
        .await;

    assert!(
        response.is_ok(),
        "non-Orchard transaction must be accepted while the soft fork is active, got: {response:?}",
    );
}

/// Mirrors the zcashd boundary test: the soft fork must accept an Orchard
/// transaction one block below its activation height but reject the same
/// transaction at the activation height.
#[tokio::test]
async fn orchard_disabling_soft_fork_accepts_orchard_actions_below_activation_height() {
    let _init_guard = zakura_test::init();

    // Use an unmodified Orchard-only V5 transaction from the test vectors so its
    // proofs remain valid for the acceptance path.
    let default_testnet = Network::new_default_testnet();
    let tx = v5_transactions(default_testnet.block_iter())
        .rev()
        .find(|transaction| {
            transaction.inputs().is_empty()
                && transaction.outputs().is_empty()
                && transaction.sapling_spends_per_anchor().next().is_none()
                && transaction.sapling_outputs().next().is_none()
                && transaction.joinsplit_count() == 0
        })
        .expect("V5 tx with only Orchard actions");

    assert!(
        tx.orchard_shielded_data().is_some(),
        "test transaction must contain Orchard actions",
    );

    let height = tx.expiry_height().expect("V5 tx has an expiry height");

    // The soft fork activates one block above the transaction's height, so it is
    // inactive for this transaction and verification proceeds normally.
    let accepting_network = Parameters::build()
        .with_temporary_orchard_disabling_soft_fork_height(
            (height + 1).expect("height is too large"),
        )
        .to_network()
        .expect("failed to build configured network");

    assert!(
        !accepting_network.temporary_orchard_disabling_soft_fork_active(height),
        "soft fork must be inactive below its activation height",
    );

    // The only state request for an Orchard-only transaction verified as part of
    // a block is the nullifier and anchor check.
    let mut state: MockService<zakura_state::Request, zakura_state::Response, _, _> =
        MockService::build().for_prop_tests();
    let accept_verifier = Verifier::new_for_tests(&accepting_network, state.clone());

    tokio::spawn(async move {
        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let accept_response = accept_verifier
        .oneshot(Request::Block {
            transaction_hash: tx.hash(),
            transaction: Arc::new(tx.clone()),
            known_utxos: Arc::new(HashMap::new()),
            known_outpoint_hashes: Arc::new(HashSet::new()),
            height,
            time: DateTime::<Utc>::MAX_UTC,
        })
        .await;

    assert!(
        accept_response.is_ok(),
        "Orchard transaction must be accepted below the soft fork height, got: {accept_response:?}",
    );

    // At the activation height the same transaction is rejected. The soft-fork
    // check runs before any state query, so the state service is never called.
    let rejecting_network = Parameters::build()
        .with_temporary_orchard_disabling_soft_fork_height(height)
        .to_network()
        .expect("failed to build configured network");

    let reject_response = Verifier::new_for_tests(
        &rejecting_network,
        service_fn(|_| async { unreachable!("state service should not be called") }),
    )
    .oneshot(Request::Block {
        transaction_hash: tx.hash(),
        transaction: Arc::new(tx),
        known_utxos: Arc::new(HashMap::new()),
        known_outpoint_hashes: Arc::new(HashSet::new()),
        height,
        time: DateTime::<Utc>::MAX_UTC,
    })
    .await;

    assert_eq!(
        reject_response,
        Err(TransactionError::Other(
            "transaction has Orchard actions (temporarily disabled)".into()
        )),
        "Orchard transaction must be rejected at the soft fork height",
    );
}

/// Checks that public-network branch-ID admission switches exactly at NU6.3 activation.
#[test]
fn public_nu6_3_consensus_branch_id_boundary() {
    let mut tx = Transaction::V5 {
        inputs: Vec::new(),
        outputs: Vec::new(),
        lock_time: LockTime::unlocked(),
        expiry_height: Height::MAX_EXPIRY_HEIGHT,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
        network_upgrade: NetworkUpgrade::Nu6_2,
    };

    for network in Network::iter() {
        let activation_height = NetworkUpgrade::Nu6_3
            .activation_height(&network)
            .expect("NU6.3 is scheduled on both public networks");
        let previous_height = (activation_height - 1).expect("NU6.3 is not genesis");

        assert_eq!(
            check::consensus_branch_id(&tx, previous_height, &network),
            Ok(()),
        );
        assert_eq!(
            check::consensus_branch_id(&tx, activation_height, &network),
            Err(TransactionError::WrongConsensusBranchId),
        );
        assert!(super::is_nu6_3_branch_id_misbehavior_grace_period(
            &tx,
            (activation_height + 39).expect("NU6.3 grace period should fit in a height"),
            &network,
        ));
        assert!(!super::is_nu6_3_branch_id_misbehavior_grace_period(
            &tx,
            (activation_height + 40).expect("NU6.3 grace period should fit in a height"),
            &network,
        ));
        assert_eq!(
            TransactionError::WrongConsensusBranchIdNu6_3GracePeriod.mempool_misbehavior_score(),
            0,
        );

        tx.update_network_upgrade(NetworkUpgrade::Nu6_1)
            .expect("V5 transactions support the NU6.1 branch ID");
        assert_eq!(
            check::consensus_branch_id(&tx, activation_height, &network),
            Err(TransactionError::WrongConsensusBranchId),
        );
        assert_eq!(
            TransactionError::WrongConsensusBranchId.mempool_misbehavior_score(),
            100,
        );

        tx.update_network_upgrade(NetworkUpgrade::Nu6_3)
            .expect("V5 transactions support the NU6.3 branch ID");

        assert_eq!(
            check::consensus_branch_id(&tx, previous_height, &network),
            Err(TransactionError::WrongConsensusBranchId),
        );
        assert_eq!(
            check::consensus_branch_id(&tx, activation_height, &network),
            Ok(()),
        );

        tx.update_network_upgrade(NetworkUpgrade::Nu6_2)
            .expect("V5 transactions support the NU6.2 branch ID");
    }
}

/// Checks that the tx verifier handles consensus branch ids in V5 txs correctly.
#[tokio::test]
async fn v5_consensus_branch_ids() {
    let mut state = MockService::build().for_unit_tests();

    let (input, output, known_utxos) = mock_transparent_transfer(
        Height(1),
        true,
        0,
        Amount::try_from(10001).expect("valid amount"),
    );

    let known_utxos = Arc::new(known_utxos);

    // NU5 is the first network upgrade that supports V5 txs.
    let mut network_upgrade = NetworkUpgrade::Nu5;

    let mut tx = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height: Height::MAX_EXPIRY_HEIGHT,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
        network_upgrade,
    };

    let outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    for network in Network::iter() {
        let verifier = Buffer::new(Verifier::new_for_tests(&network, state.clone()), 10);

        while let Some(next_nu) = network_upgrade.next_upgrade() {
            // Check an outdated network upgrade.
            let Some(height) = next_nu.activation_height(&network) else {
                tracing::warn!(?next_nu, "missing activation height",);
                // Shift the network upgrade for the next loop iteration.
                network_upgrade = next_nu;
                continue;
            };

            let block_req = verifier
                .clone()
                .oneshot(Request::Block {
                    transaction_hash: tx.hash(),
                    transaction: Arc::new(tx.clone()),
                    known_utxos: known_utxos.clone(),
                    known_outpoint_hashes: Arc::new(HashSet::new()),
                    // The consensus branch ID of the tx is outdated for this height.
                    height,
                    time: DateTime::<Utc>::MAX_UTC,
                })
                .map_err(|err| *err.downcast().expect("`TransactionError` type"));

            let mempool_req = verifier
                .clone()
                .oneshot(Request::Mempool {
                    transaction: tx.clone().into(),
                    // The consensus branch ID of the tx is outdated for this height.
                    height,
                })
                .map_err(|err| *err.downcast().expect("`TransactionError` type"));

            let (block_rsp, mempool_rsp) = futures::join!(block_req, mempool_req);

            assert_eq!(block_rsp, Err(TransactionError::WrongConsensusBranchId));
            let mempool_expected_error =
                if network_upgrade == NetworkUpgrade::Nu6_2 && next_nu == NetworkUpgrade::Nu6_3 {
                    TransactionError::WrongConsensusBranchIdNu6_3GracePeriod
                } else {
                    TransactionError::WrongConsensusBranchId
                };
            assert_eq!(mempool_rsp, Err(mempool_expected_error));

            if network_upgrade == NetworkUpgrade::Nu6_2 && next_nu == NetworkUpgrade::Nu6_3 {
                let grace_period_last_height =
                    (height + 39).expect("NU6.3 grace period should fit in a height");
                let grace_period_response = verifier
                    .clone()
                    .oneshot(Request::Mempool {
                        transaction: tx.clone().into(),
                        height: grace_period_last_height,
                    })
                    .map_err(|err| *err.downcast().expect("`TransactionError` type"))
                    .await;
                assert_eq!(
                    grace_period_response,
                    Err(TransactionError::WrongConsensusBranchIdNu6_3GracePeriod),
                );

                let grace_period_end_height =
                    (height + 40).expect("NU6.3 grace period should fit in a height");
                let grace_period_end_response = verifier
                    .clone()
                    .oneshot(Request::Mempool {
                        transaction: tx.clone().into(),
                        height: grace_period_end_height,
                    })
                    .map_err(|err| *err.downcast().expect("`TransactionError` type"))
                    .await;
                assert_eq!(
                    grace_period_end_response,
                    Err(TransactionError::WrongConsensusBranchId),
                );
            }

            // Check the currently supported network upgrade.
            let height = network_upgrade.activation_height(&network).expect("height");

            let block_req = verifier
                .clone()
                .oneshot(Request::Block {
                    transaction_hash: tx.hash(),
                    transaction: Arc::new(tx.clone()),
                    known_utxos: known_utxos.clone(),
                    known_outpoint_hashes: Arc::new(HashSet::new()),
                    // The consensus branch ID of the tx is supported by this height.
                    height,
                    time: DateTime::<Utc>::MAX_UTC,
                })
                .map_ok(|rsp| rsp.tx_id())
                .map_err(|e| format!("{e}"));

            let mempool_req = verifier
                .clone()
                .oneshot(Request::Mempool {
                    transaction: tx.clone().into(),
                    // The consensus branch ID of the tx is supported by this height.
                    height,
                })
                .map_ok(|rsp| rsp.tx_id())
                .map_err(|e| format!("{e}"));

            let state_req = async {
                state
                    .expect_request(zakura_state::Request::UnspentBestChainUtxo(outpoint))
                    .map(|r| {
                        r.respond(zakura_state::Response::UnspentBestChainUtxo(
                            known_utxos.get(&outpoint).map(|utxo| utxo.utxo.clone()),
                        ))
                    })
                    .await;

                state
                    .expect_request_that(|req| {
                        matches!(
                            req,
                            zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                        )
                    })
                    .map(|r| {
                        r.respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors)
                    })
                    .await;
            };

            let (block_rsp, mempool_rsp, _) = futures::join!(block_req, mempool_req, state_req);
            let txid = tx.unmined_id();

            assert_eq!(block_rsp, Ok(txid));
            assert_eq!(mempool_rsp, Ok(txid));

            // Check a network upgrade that Zebra doesn't support yet.
            tx.update_network_upgrade(next_nu)
                .expect("V5 txs support updating NUs");

            let height = network_upgrade.activation_height(&network).expect("height");

            let block_req = verifier
                .clone()
                .oneshot(Request::Block {
                    transaction_hash: tx.hash(),
                    transaction: Arc::new(tx.clone()),
                    known_utxos: known_utxos.clone(),
                    known_outpoint_hashes: Arc::new(HashSet::new()),
                    // The consensus branch ID of the tx is not supported by this height.
                    height,
                    time: DateTime::<Utc>::MAX_UTC,
                })
                .map_err(|err| *err.downcast().expect("`TransactionError` type"));

            let mempool_req = verifier
                .clone()
                .oneshot(Request::Mempool {
                    transaction: tx.clone().into(),
                    // The consensus branch ID of the tx is not supported by this height.
                    height,
                })
                .map_err(|err| *err.downcast().expect("`TransactionError` type"));

            let (block_rsp, mempool_rsp) = futures::join!(block_req, mempool_req);

            assert_eq!(block_rsp, Err(TransactionError::WrongConsensusBranchId));
            assert_eq!(mempool_rsp, Err(TransactionError::WrongConsensusBranchId));

            // Shift the network upgrade for the next loop iteration.
            network_upgrade = next_nu;
        }
    }
}

// Utility functions

/// Create a mock transparent transfer to be included in a transaction.
///
/// First, this creates a fake unspent transaction output from a fake transaction included in the
/// specified `previous_utxo_height` block height. This fake [`Utxo`] also contains a simple script
/// that can either accept or reject any spend attempt, depending on if `script_should_succeed` is
/// `true` or `false`. Since the `tx_index_in_block` is irrelevant for blocks that have already
/// been verified, it is set to `1`.
///
/// Then, a [`transparent::Input::PrevOut`] is created that attempts to spend the previously created fake
/// UTXO to a new [`transparent::Output`].
///
/// Finally, the initial fake UTXO is placed in a `known_utxos` [`HashMap`] so that it can be
/// retrieved during verification.
///
/// The function then returns the generated transparent input and output, as well as the
/// `known_utxos` map.
///
/// Note: `known_utxos` is only intended to be used for UTXOs within the same block,
/// so future verification changes might break this mocking function.
fn mock_transparent_transfer(
    previous_utxo_height: block::Height,
    script_should_succeed: bool,
    outpoint_index: u32,
    previous_output_value: Amount<NonNegative>,
) -> (
    transparent::Input,
    transparent::Output,
    HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
) {
    // Standard, signature-free P2SH inputs that either pass or fail in the script interpreter.
    // Both variants pass the mempool `AreInputsStandard` gate.
    const OP_FALSE: u8 = 0x00;
    const OP_TRUE: u8 = 0x51;
    let accepting_unlock_script = transparent::Script::new(&[0x01, OP_TRUE]);
    let rejecting_unlock_script = transparent::Script::new(&[0x01, OP_FALSE]);

    // `scriptPubKey`: OP_HASH160 <HASH160(redeem script)> OP_EQUAL.
    let mut p2sh_lock_bytes = vec![0xa9, 0x14];
    p2sh_lock_bytes.extend_from_slice(&[
        0xda, 0x17, 0x45, 0xe9, 0xb5, 0x49, 0xbd, 0x0b, 0xfa, 0x1a, 0x56, 0x99, 0x71, 0xc7, 0x7e,
        0xba, 0x30, 0xcd, 0x5a, 0x4b,
    ]);
    p2sh_lock_bytes.push(0x87);
    let accepting_lock_script = transparent::Script::new(&p2sh_lock_bytes);

    let mut p2sh_lock_bytes = vec![0xa9, 0x14];
    p2sh_lock_bytes.extend_from_slice(&[
        0x9f, 0x7f, 0xd0, 0x96, 0xd3, 0x7e, 0xd2, 0xc0, 0xe3, 0xf7, 0xf0, 0xcf, 0xc9, 0x24, 0xbe,
        0xef, 0x4f, 0xfc, 0xeb, 0x68,
    ]);
    p2sh_lock_bytes.push(0x87);
    let rejecting_lock_script = transparent::Script::new(&p2sh_lock_bytes);

    // Mock an unspent transaction output
    let previous_outpoint = transparent::OutPoint {
        hash: Hash([1u8; 32]),
        index: outpoint_index,
    };

    let (lock_script, unlock_script) = if script_should_succeed {
        (accepting_lock_script, accepting_unlock_script)
    } else {
        (rejecting_lock_script, rejecting_unlock_script)
    };

    let previous_output = transparent::Output {
        value: previous_output_value,
        lock_script,
    };

    let previous_utxo = transparent::OrderedUtxo::new(previous_output, previous_utxo_height, 1);

    // Use the `previous_outpoint` as input
    let input = transparent::Input::PrevOut {
        outpoint: previous_outpoint,
        unlock_script,
        sequence: 0,
    };

    // The output resulting from the transfer
    // Using the rejecting script pretends the amount is burned because it can't be spent again
    let output = transparent::Output {
        value: Amount::try_from(1).expect("1 is an invalid amount"),
        lock_script: transparent::Script::new(&[OP_FALSE]),
    };

    // Cache the source of the fund so that it can be used during verification
    let mut known_utxos = HashMap::new();
    known_utxos.insert(previous_outpoint, previous_utxo);

    (input, output, known_utxos)
}

/// Create a mock coinbase input with a transparent output.
///
/// Create a [`transparent::Input::Coinbase`] at `coinbase_height`.
/// Then create UTXO with a [`transparent::Output`] spending some coinbase funds.
///
/// Returns the generated coinbase input and transparent output.
fn mock_coinbase_transparent_output(
    coinbase_height: block::Height,
) -> (transparent::Input, transparent::Output) {
    // A script with a single opcode that rejects the transaction (OP_FALSE)
    let rejecting_script = transparent::Script::new(&[0]);

    let input = transparent::Input::Coinbase {
        height: coinbase_height,
        data: vec![],
        sequence: u32::MAX,
    };

    // The output resulting from the transfer
    // Using the rejecting script pretends the amount is burned because it can't be spent again
    let output = transparent::Output {
        value: Amount::try_from(1).expect("1 is an invalid amount"),
        lock_script: rejecting_script,
    };

    (input, output)
}

/// Create a mock [`sprout::JoinSplit`] and include it in a [`transaction::JoinSplitData`].
///
/// This creates a dummy join split. By itself it is invalid, but it is useful for including in a
/// transaction to check the signatures.
///
/// The [`transaction::JoinSplitData`] with the dummy [`sprout::JoinSplit`] is returned together
/// with the [`ed25519::SigningKey`] that can be used to create a signature to later add to the
/// returned join split data.
fn mock_sprout_join_split_data() -> (JoinSplitData<Groth16Proof>, ed25519::SigningKey) {
    // Prepare dummy inputs for the join split
    let zero_amount = 0_i32
        .try_into()
        .expect("Invalid JoinSplit transparent input");
    let anchor = sprout::tree::Root::default();
    let first_nullifier = sprout::note::Nullifier([0u8; 32].into());
    let second_nullifier = sprout::note::Nullifier([1u8; 32].into());
    let commitment = sprout::commitment::NoteCommitment::from([0u8; 32]);
    let ephemeral_key =
        x25519::PublicKey::from(&x25519::EphemeralSecret::random_from_rng(rand::thread_rng()));
    let random_seed = sprout::RandomSeed::from([0u8; 32]);
    let mac = sprout::note::Mac::zcash_deserialize(&[0u8; 32][..])
        .expect("Failure to deserialize dummy MAC");
    let zkproof = Groth16Proof([0u8; 192]);
    let encrypted_note = sprout::note::EncryptedNote([0u8; 601]);

    // Create an dummy join split
    let joinsplit = sprout::JoinSplit {
        vpub_old: zero_amount,
        vpub_new: zero_amount,
        anchor,
        nullifiers: [first_nullifier, second_nullifier],
        commitments: [commitment; 2],
        ephemeral_key,
        random_seed,
        vmacs: [mac.clone(), mac],
        zkproof,
        enc_ciphertexts: [encrypted_note; 2],
    };

    // Create a usable signing key
    let signing_key = ed25519::SigningKey::new(rand::thread_rng());
    let verification_key = ed25519::VerificationKey::from(&signing_key);

    // Populate join split data with the dummy join split.
    let joinsplit_data = JoinSplitData {
        first: joinsplit,
        rest: vec![],
        pub_key: verification_key.into(),
        sig: [0u8; 64].into(),
    };

    (joinsplit_data, signing_key)
}

/// A type of JoinSplit modification to test.
#[derive(Clone, Copy)]
enum JoinSplitModification {
    // Corrupt a signature, making it invalid.
    CorruptSignature,
    // Corrupt a proof, making it invalid, but still well-formed.
    CorruptProof,
    // Make a proof all-zeroes, making it malformed.
    ZeroProof,
}

/// Modify a [`JoinSplitData`] following the given modification type.
fn modify_joinsplit_data(
    joinsplit_data: &mut JoinSplitData<Groth16Proof>,
    modification: JoinSplitModification,
) {
    match modification {
        JoinSplitModification::CorruptSignature => {
            let mut sig_bytes: [u8; 64] = joinsplit_data.sig.into();
            // Flip a bit from an arbitrary byte of the signature.
            sig_bytes[10] ^= 0x01;
            joinsplit_data.sig = sig_bytes.into();
        }
        JoinSplitModification::CorruptProof => {
            let joinsplit = joinsplit_data
                .joinsplits_mut()
                .next()
                .expect("must have a JoinSplit");
            {
                // A proof is composed of three field elements, the first and last having 48 bytes.
                // (The middle one has 96 bytes.) To corrupt the proof without making it malformed,
                // simply swap those first and last elements.
                let (first, rest) = joinsplit.zkproof.0.split_at_mut(48);
                first.swap_with_slice(&mut rest[96..144]);
            }
        }
        JoinSplitModification::ZeroProof => {
            let joinsplit = joinsplit_data
                .joinsplits_mut()
                .next()
                .expect("must have a JoinSplit");
            joinsplit.zkproof.0 = [0; 192];
        }
    }
}

/// Duplicate a Sapling spend inside a `transaction`.
///
/// Returns the nullifier of the duplicate spend.
///
/// # Panics
///
/// Will panic if the `transaction` does not have Sapling spends.
fn duplicate_sapling_spend(transaction: &mut Transaction) -> sapling::Nullifier {
    match transaction {
        Transaction::V4 {
            sapling_shielded_data: Some(ref mut shielded_data),
            ..
        } => duplicate_sapling_spend_in_shielded_data(shielded_data),
        Transaction::V5 {
            sapling_shielded_data: Some(ref mut shielded_data),
            ..
        } => duplicate_sapling_spend_in_shielded_data(shielded_data),
        _ => unreachable!("Transaction has no Sapling shielded data"),
    }
}

/// Duplicates the first spend of the `shielded_data`.
///
/// Returns the nullifier of the duplicate spend.
///
/// # Panics
///
/// Will panic if `shielded_data` has no spends.
fn duplicate_sapling_spend_in_shielded_data<A: sapling::AnchorVariant + Clone>(
    shielded_data: &mut sapling::ShieldedData<A>,
) -> sapling::Nullifier {
    match shielded_data.transfers {
        sapling::TransferData::SpendsAndMaybeOutputs { ref mut spends, .. } => {
            let duplicate_spend = spends.first().clone();
            let duplicate_nullifier = duplicate_spend.nullifier;

            let mut spends_vec = spends.as_slice().to_vec();
            spends_vec.push(duplicate_spend);
            *spends = AtLeastOne::from_vec(spends_vec)
                .expect("pushing one element never breaks at least one constraints");

            duplicate_nullifier
        }
        sapling::TransferData::JustOutputs { .. } => {
            unreachable!("Sapling shielded data has no spends")
        }
    }
}

#[test]
fn add_to_sprout_pool_after_nu() {
    let _init_guard = zakura_test::init();

    // get a block that we know it haves a transaction with `vpub_old` field greater than 0.
    let block: Arc<_> = zakura_chain::block::Block::zcash_deserialize(
        &zakura_test::vectors::BLOCK_MAINNET_419199_BYTES[..],
    )
    .unwrap()
    .into();

    // create a block height at canopy activation.
    let network = Network::Mainnet;
    let block_height = NetworkUpgrade::Canopy.activation_height(&network).unwrap();

    // create a zero amount.
    let zero = Amount::<NonNegative>::try_from(0).expect("an amount of 0 is always valid");

    // the coinbase transaction should pass the check.
    assert_eq!(
        check::disabled_add_to_sprout_pool(&block.transactions[0], block_height, &network),
        Ok(())
    );

    // the 2nd transaction has no joinsplits, should pass the check.
    assert_eq!(block.transactions[1].joinsplit_count(), 0);
    assert_eq!(
        check::disabled_add_to_sprout_pool(&block.transactions[1], block_height, &network),
        Ok(())
    );

    // the 5th transaction has joinsplits and the `vpub_old` cumulative is greater than 0,
    // should fail the check.
    assert!(block.transactions[4].joinsplit_count() > 0);
    let vpub_old: Amount<NonNegative> = block.transactions[4]
        .output_values_to_sprout()
        .fold(zero, |acc, &x| (acc + x).unwrap());
    assert!(vpub_old > zero);

    assert_eq!(
        check::disabled_add_to_sprout_pool(&block.transactions[3], block_height, &network),
        Err(TransactionError::DisabledAddToSproutPool)
    );

    // the 8th transaction has joinsplits and the `vpub_old` cumulative is 0,
    // should pass the check.
    assert!(block.transactions[7].joinsplit_count() > 0);
    let vpub_old: Amount<NonNegative> = block.transactions[7]
        .output_values_to_sprout()
        .fold(zero, |acc, &x| (acc + x).unwrap());
    assert_eq!(vpub_old, zero);

    assert_eq!(
        check::disabled_add_to_sprout_pool(&block.transactions[7], block_height, &network),
        Ok(())
    );
}

#[test]
fn add_to_orchard_pool_after_nu6_3() {
    let _init_guard = zakura_test::init();

    const ADD_TO_ORCHARD_POOL: i64 = -1;
    const ORCHARD_POOL_UNCHANGED: i64 = 0;
    const REMOVE_FROM_ORCHARD_POOL: i64 = 1;

    let nu6_3_height = Height(10);
    let network = Parameters::build()
        .with_activation_heights(ConfiguredActivationHeights {
            nu6_3: Some(nu6_3_height.0),
            ..Default::default()
        })
        .expect("failed to set NU6.3 activation height")
        .clear_funding_streams()
        .to_network()
        .expect("failed to build configured network");

    let mut tx = v5_transactions(Network::new_default_testnet().block_iter())
        .find(|tx| tx.orchard_shielded_data().is_some())
        .expect("test vectors include a transaction with Orchard shielded data");

    let orchard_amount =
        |amount| Amount::<NegativeAllowed>::try_from(amount).expect("valid test amount");

    *tx.orchard_value_balance_mut()
        .expect("transaction has Orchard shielded data") = orchard_amount(ADD_TO_ORCHARD_POOL);

    assert_eq!(
        check::disabled_add_to_orchard_pool(
            &tx,
            (nu6_3_height - 1).expect("NU6.3 is not genesis"),
            &network,
        ),
        Ok(()),
        "transparent -> Orchard is allowed before NU6.3"
    );

    assert_eq!(
        check::disabled_add_to_orchard_pool(&tx, nu6_3_height, &Network::Mainnet),
        Ok(()),
        "transparent -> Orchard is allowed if NU6.3 is unscheduled"
    );

    assert_eq!(
        check::disabled_add_to_orchard_pool(&tx, nu6_3_height, &network),
        Err(TransactionError::DisabledAddToOrchardPool),
        "transparent -> Orchard is rejected after NU6.3"
    );

    *tx.orchard_value_balance_mut()
        .expect("transaction has Orchard shielded data") = orchard_amount(REMOVE_FROM_ORCHARD_POOL);

    assert_eq!(
        check::disabled_add_to_orchard_pool(&tx, nu6_3_height, &network),
        Ok(()),
        "Orchard -> transparent is still allowed after NU6.3"
    );

    *tx.orchard_value_balance_mut()
        .expect("transaction has Orchard shielded data") = orchard_amount(ORCHARD_POOL_UNCHANGED);

    assert_eq!(
        check::disabled_add_to_orchard_pool(&tx, nu6_3_height, &network),
        Ok(()),
        "zero-balance Orchard spends and outputs are still allowed after NU6.3"
    );
}

#[test]
fn coinbase_orchard_bundle_after_nu6_3() {
    let _init_guard = zakura_test::init();

    let nu6_3_height = Height(10);
    let network = Parameters::build()
        .with_activation_heights(ConfiguredActivationHeights {
            nu6_3: Some(nu6_3_height.0),
            ..Default::default()
        })
        .expect("failed to set NU6.3 activation height")
        .clear_funding_streams()
        .to_network()
        .expect("failed to build configured network");

    let mut tx = v5_transactions(Network::new_default_testnet().block_iter())
        .find(|tx| tx.orchard_shielded_data().is_some())
        .expect("test vectors include a transaction with Orchard shielded data");

    *tx.inputs_mut() = vec![transparent::Input::Coinbase {
        height: nu6_3_height,
        data: vec![],
        sequence: u32::MAX,
    }];

    *tx.orchard_value_balance_mut()
        .expect("transaction has Orchard shielded data") = Amount::<NegativeAllowed>::zero();

    assert!(tx.is_coinbase());
    assert_eq!(
        check::coinbase_has_no_orchard_shielded_data(&tx, nu6_3_height, &network),
        Err(TransactionError::CoinbaseHasOrchardShieldedData),
        "coinbase Orchard bundles are rejected after NU6.3"
    );
    assert_eq!(
        check::disabled_add_to_orchard_pool(&tx, nu6_3_height, &network),
        Ok(()),
        "zero-balance coinbase Orchard bundles need the structural check"
    );
    assert_eq!(
        check::coinbase_has_no_orchard_shielded_data(
            &tx,
            (nu6_3_height - 1).expect("NU6.3 is not genesis"),
            &network,
        ),
        Ok(()),
        "coinbase Orchard bundles are still allowed before NU6.3"
    );
    assert_eq!(
        check::coinbase_has_no_orchard_shielded_data(&tx, nu6_3_height, &Network::Mainnet),
        Ok(()),
        "the rule is inactive when NU6.3 is unscheduled"
    );
}

/// Checks that Heartwood onward, all Sapling and Orchard outputs in coinbase txs decrypt to a note
/// plaintext, i.e. the procedure in § 4.20.3 ‘Decryption using a Full Viewing Key (Sapling and
/// Orchard )’ does not return ⊥, using a sequence of 32 zero bytes as the outgoing viewing key. We
/// will refer to such a sequence as the _zero key_.
#[test]
fn coinbase_outputs_are_decryptable() -> Result<(), Report> {
    let _init_guard = zakura_test::init();

    for net in Network::iter() {
        let mut tested_post_heartwood_shielded_coinbase_tx = false;
        let mut tested_pre_heartwood_shielded_coinbase_tx = false;

        let mut tested_post_heartwood_unshielded_coinbase_tx = false;
        let mut tested_pre_heartwood_unshielded_coinbase_tx = false;

        let mut tested_post_heartwood_shielded_non_coinbase_tx = false;
        let mut tested_pre_heartwood_shielded_non_coinbase_tx = false;

        let mut tested_post_heartwood_unshielded_non_coinbase_tx = false;
        let mut tested_pre_heartwood_unshielded_non_coinbase_tx = false;

        for (height, block) in net.block_iter() {
            let block = block.zcash_deserialize_into::<Block>().expect("block");
            let height = Height(*height);
            let is_heartwood = height >= NetworkUpgrade::Heartwood.activation_height(&net).unwrap();
            let coinbase = block.transactions.first().expect("coinbase transaction");

            if coinbase.has_shielded_outputs() && is_heartwood {
                tested_post_heartwood_shielded_coinbase_tx = true;
                check::coinbase_outputs_are_decryptable(coinbase, &net, height).expect(
                    "post-Heartwood shielded coinbase outputs must be decryptable with the zero key",
                );
            }

            if coinbase.has_shielded_outputs() && !is_heartwood {
                tested_pre_heartwood_shielded_coinbase_tx = true;
                check::coinbase_outputs_are_decryptable(coinbase, &net, height)
                    .expect("the consensus rule does not apply to pre-Heartwood txs");
            }

            if !coinbase.has_shielded_outputs() && is_heartwood {
                tested_post_heartwood_unshielded_coinbase_tx = true;
                check::coinbase_outputs_are_decryptable(coinbase, &net, height)
                    .expect("the consensus rule does not apply to txs with no shielded outputs");
            }

            if !coinbase.has_shielded_outputs() && !is_heartwood {
                tested_pre_heartwood_unshielded_coinbase_tx = true;
                check::coinbase_outputs_are_decryptable(coinbase, &net, height)
                    .expect("the consensus rule does not apply to pre-Heartwood txs");
            }

            // For non-coinbase txs, check if existing outputs are NOT decryptable with an all-zero
            // key, if applicable.
            for non_coinbase in block.transactions.iter().skip(1) {
                if non_coinbase.has_shielded_outputs() && is_heartwood {
                    tested_post_heartwood_shielded_non_coinbase_tx = true;
                    assert_eq!(
                        check::coinbase_outputs_are_decryptable(non_coinbase, &net, height),
                        Err(TransactionError::NotCoinbase)
                    )
                }

                if non_coinbase.has_shielded_outputs() && !is_heartwood {
                    tested_pre_heartwood_shielded_non_coinbase_tx = true;
                    check::coinbase_outputs_are_decryptable(non_coinbase, &net, height)
                        .expect("the consensus rule does not apply to pre-Heartwood txs");
                }

                if !non_coinbase.has_shielded_outputs() && is_heartwood {
                    tested_post_heartwood_unshielded_non_coinbase_tx = true;
                    check::coinbase_outputs_are_decryptable(non_coinbase, &net, height).expect(
                        "the consensus rule does not apply to txs with no shielded outputs",
                    );
                }

                if !non_coinbase.has_shielded_outputs() && !is_heartwood {
                    tested_pre_heartwood_unshielded_non_coinbase_tx = true;
                    check::coinbase_outputs_are_decryptable(non_coinbase, &net, height)
                        .expect("the consensus rule does not apply to pre-Heartwood txs");
                }
            }
        }

        assert!(tested_post_heartwood_shielded_coinbase_tx);
        // We have no pre-Heartwood shielded coinbase txs.
        assert!(!tested_pre_heartwood_shielded_coinbase_tx);
        assert!(tested_post_heartwood_unshielded_coinbase_tx);
        assert!(tested_pre_heartwood_unshielded_coinbase_tx);
        assert!(tested_post_heartwood_shielded_non_coinbase_tx);
        assert!(tested_pre_heartwood_shielded_non_coinbase_tx);
        assert!(tested_post_heartwood_unshielded_non_coinbase_tx);
        assert!(tested_pre_heartwood_unshielded_non_coinbase_tx);
    }

    Ok(())
}

/// Given an Orchard action as a base, fill fields related to note encryption
/// from the given test vector and returned the modified action.
fn fill_action_with_note_encryption_test_vector(
    action: &Action,
    v: &zakura_test::vectors::TestVector,
) -> Action {
    let mut action = action.clone();
    action.cv = v.cv_net.try_into().expect("test vector must be valid");
    action.cm_x = pallas::Base::from_repr(v.cmx).unwrap();
    action.nullifier = v.rho.try_into().expect("test vector must be valid");
    action.ephemeral_key = v
        .ephemeral_key
        .try_into()
        .expect("test vector must be valid");
    action.out_ciphertext = v.c_out.into();
    action.enc_ciphertext = v.c_enc.into();
    action
}

/// Test if shielded coinbase outputs are decryptable with an all-zero outgoing viewing key.
#[test]
fn coinbase_outputs_are_decryptable_for_fake_v5_blocks() {
    for v in zakura_test::vectors::ORCHARD_NOTE_ENCRYPTION_ZERO_VECTOR.iter() {
        for net in Network::iter() {
            let mut transaction = v5_transactions(net.block_iter())
                .find(|tx| tx.is_coinbase())
                .expect("coinbase V5 tx");

            let shielded_data = insert_fake_orchard_shielded_data(&mut transaction);
            shielded_data.flags = Flags::ENABLE_OUTPUTS;

            let action = fill_action_with_note_encryption_test_vector(
                &shielded_data.actions.first().action,
                v,
            );
            let sig = shielded_data.actions.first().spend_auth_sig;
            shielded_data.actions = vec![AuthorizedAction::from_parts(action, sig)]
                .try_into()
                .unwrap();

            assert_eq!(
                check::coinbase_outputs_are_decryptable(
                    &transaction,
                    &net,
                    NetworkUpgrade::Nu5.activation_height(&net).unwrap(),
                ),
                Ok(())
            );
        }
    }
}

/// Test if random shielded outputs are NOT decryptable with an all-zero outgoing viewing key.
#[test]
fn shielded_outputs_are_not_decryptable_for_fake_v5_blocks() {
    for v in zakura_test::vectors::ORCHARD_NOTE_ENCRYPTION_VECTOR.iter() {
        for net in Network::iter() {
            let mut tx = v5_transactions(net.block_iter())
                .find(|tx| tx.is_coinbase())
                .expect("V5 coinbase tx");

            let shielded_data = insert_fake_orchard_shielded_data(&mut tx);
            shielded_data.flags = Flags::ENABLE_OUTPUTS;

            let action = fill_action_with_note_encryption_test_vector(
                &shielded_data.actions.first().action,
                v,
            );
            let sig = shielded_data.actions.first().spend_auth_sig;
            shielded_data.actions = vec![AuthorizedAction::from_parts(action, sig)]
                .try_into()
                .unwrap();

            assert_eq!(
                check::coinbase_outputs_are_decryptable(
                    &tx,
                    &net,
                    NetworkUpgrade::Nu5.activation_height(&net).unwrap(),
                ),
                Err(TransactionError::CoinbaseOutputsNotDecryptable)
            );
        }
    }
}

#[tokio::test]
async fn mempool_zip317_error() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Nu5
        .activation_height(&Network::Mainnet)
        .expect("Nu5 activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");

    // This transaction has both an insufficient fee and a standard P2SH input whose redeem
    // script fails. ZIP-317 must reject it before the script interpreter is invoked.
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        false,
        0,
        Amount::try_from(10).expect("valid amount"),
    );

    // Create a non-coinbase V5 tx.
    let tx = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        network_upgrade: NetworkUpgrade::Nu5,
        expiry_height: height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    // Mempool refuses to add this transaction into storage.
    assert!(verifier_response.is_err());
    assert_eq!(
        verifier_response.err(),
        Some(TransactionError::Zip317(zip317::Error::UnpaidActions))
    );
}

#[tokio::test]
async fn mempool_zip317_ok() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Nu5
        .activation_height(&Network::Mainnet)
        .expect("Nu5 activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");

    // Will produce a big enough miner fee to pass the check.
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10_001).expect("valid amount"),
    );

    // Create a non-coinbase V5 tx.
    let tx = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        network_upgrade: NetworkUpgrade::Nu5,
        expiry_height: height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    assert!(
        verifier_response.is_ok(),
        "expected successful verification, got: {verifier_response:?}"
    );
}

#[tokio::test]
async fn mempool_transaction_with_sufficient_fee_is_rejected_by_script() {
    let mut state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let verifier = Verifier::new_for_tests(&Network::Mainnet, state.clone());

    let height = NetworkUpgrade::Nu5
        .activation_height(&Network::Mainnet)
        .expect("Nu5 activation height is specified");
    let fund_height = (height - 1).expect("fake source fund block height is too small");

    // The fee passes ZIP-317, but the standard P2SH input's redeem script fails.
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        false,
        0,
        Amount::try_from(10_001).expect("valid amount"),
    );

    let tx = Transaction::V5 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        network_upgrade: NetworkUpgrade::Nu5,
        expiry_height: height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    tokio::spawn(async move {
        state
            .expect_request(zakura_state::Request::UnspentBestChainUtxo(input_outpoint))
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::UnspentBestChainUtxo(
                known_utxos
                    .get(&input_outpoint)
                    .map(|utxo| utxo.utxo.clone()),
            ));

        state
            .expect_request_that(|req| {
                matches!(
                    req,
                    zakura_state::Request::CheckBestChainTipNullifiersAndAnchors(_)
                )
            })
            .await
            .expect("verifier should call mock state service with correct request")
            .respond(zakura_state::Response::ValidBestChainTipNullifiersAndAnchors);
    });

    let verifier_response = verifier
        .oneshot(Request::Mempool {
            transaction: tx.into(),
            height,
        })
        .await;

    assert_eq!(
        verifier_response,
        Err(TransactionError::Script(
            zakura_script::Error::ScriptInvalid
        ))
    );
}

/// Test for CVE-2026-34377 https://github.com/ZcashFoundation/zebra/security/advisories/GHSA-3vmh-33xr-9cqh
///
/// Ensure a block with a transaction with garbage Orchard proofs is rejected, even if the mempool has a valid version of the same transaction.
#[tokio::test(flavor = "multi_thread")]
async fn block_with_garbage_orchard_proofs_is_rejected() {
    use zakura_chain::{primitives::Halo2Proof, transaction::VerifiedUnminedTx};

    let _init_guard = zakura_test::init();

    let mempool: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let state: MockService<_, _, _, _> = MockService::build().for_prop_tests();
    let (mempool_setup_tx, mempool_setup_rx) = tokio::sync::oneshot::channel();
    let verifier = Verifier::new(&Network::Mainnet, state.clone(), mempool_setup_rx);
    let verifier = Buffer::new(verifier, 1);

    mempool_setup_tx
        .send(mempool.clone())
        .ok()
        .expect("send should succeed");

    let height = NetworkUpgrade::Nu6
        .activation_height(&Network::Mainnet)
        .expect("Nu6 activation height is specified");
    let fund_height = (height - 1).expect("too small");
    let (input, output, known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("invalid value"),
    );

    let mut tx = Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu6,
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::min_lock_time_timestamp(),
        expiry_height: height,
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };
    insert_fake_orchard_shielded_data(&mut tx);

    let tx_hash = tx.hash();
    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("not coinbase"),
    };

    // corrupt only auth data, txid stays the same (ZIP-244)
    let mut garbage_tx = tx.clone();
    let od = garbage_tx.orchard_shielded_data_mut().unwrap();
    od.proof = Halo2Proof(vec![0xDE, 0xAD, 0xBE, 0xEF]);
    od.binding_sig = [0xFF; 64].into();
    for action in od.actions.iter_mut() {
        action.spend_auth_sig = [0xFF; 64].into();
    }
    assert_eq!(tx.hash(), garbage_tx.hash());

    // simulate valid version in mempool
    let spent_output = known_utxos
        .get(&input_outpoint)
        .unwrap()
        .utxo
        .output
        .clone();
    let verified_tx = VerifiedUnminedTx::new(
        tx.clone().into(),
        Amount::try_from(10000).unwrap(),
        0,
        0,
        Arc::new(vec![spent_output]),
    )
    .unwrap();

    let mut mc = mempool.clone();
    tokio::spawn(async move {
        mc.expect_request(mempool::Request::TransactionWithDepsByMinedId(tx_hash))
            .await
            .unwrap()
            .respond(mempool::Response::TransactionWithDeps {
                transaction: verified_tx,
                dependencies: [input_outpoint.hash].into(),
            });
    });
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;

    // submit garbage version as block tx, must be rejected
    let resp = verifier
        .clone()
        .oneshot(Request::Block {
            transaction_hash: tx_hash,
            transaction: Arc::new(garbage_tx),
            known_outpoint_hashes: Arc::new([input_outpoint.hash].into()),
            known_utxos: Arc::new(HashMap::new()),
            height,
            time: Utc::now(),
        })
        .await;

    assert!(resp.is_err(), "garbage proof must be rejected");
}

/// Regression test for the mempool-cache expiry bypass vulnerability.
///
/// A non-coinbase transaction with `nExpiryHeight = H+1` that was cached in the
/// mempool as valid at height `H+1` can be presented inside a block at height
/// `H+2`.  The block transaction verifier must re-run the expiry check even
/// when it hits the mempool cache fast path in `find_verified_unmined_tx`;
/// skipping that check lets Zebra accept a block that honest nodes reject,
/// causing a consensus split.
///
/// # Attack window
///
/// The attack is possible because:
/// * The mempool is active while Zebra is "close to tip" (not only at exact tip).
/// * The download/verification pipeline accepts blocks up to
///   `tip + full_verify_concurrency_limit` ahead of the current tip.
/// * `find_verified_unmined_tx` returns the cached result before the normal
///   expiry validation.
///
/// Concretely: while Zebra's best tip is still `H`, the mempool can already
/// hold a `VerifiedUnminedTx` for a transaction with `nExpiryHeight = H+1`.
/// If the verifier is simultaneously asked to semantically verify a candidate
/// block at `H+2` that contains the same transaction, the cache hit fires and
/// the block passes semantic verification with an expired transaction inside.
#[tokio::test(flavor = "multi_thread")]
async fn mempool_cached_result_bypasses_expiry_check_for_block_at_next_height() {
    let _init_guard = zakura_test::init();

    let network = Network::Mainnet;

    // Heights used in the scenario:
    //   H   = canopy_height    (local best tip while the attack occurs)
    //   H+1 = mempool_height   (nExpiryHeight; tx is valid for mempool admission here)
    //   H+2 = expired_block_height (block height at which the tx has expired)
    let canopy_height = NetworkUpgrade::Canopy
        .activation_height(&network)
        .expect("Canopy activation height is specified");
    let mempool_height = (canopy_height + 1).expect("mempool height should be valid");
    let expired_block_height = (canopy_height + 2).expect("expired block height should be valid");
    let fund_height = (canopy_height - 1).expect("fund height should be valid");

    let (input, output, _known_utxos) = mock_transparent_transfer(
        fund_height,
        true,
        0,
        Amount::try_from(10001).expect("valid value"),
    );

    // V4 transaction with nExpiryHeight = mempool_height (H+1).
    // Valid in block H+1 (block_height == expiry_height) but expired in H+2
    // (block_height > expiry_height).  LockTime::unlocked() avoids a
    // BestChainNextMedianTimePast state query, keeping the test simpler.
    let tx = Transaction::V4 {
        inputs: vec![input],
        outputs: vec![output],
        lock_time: LockTime::unlocked(),
        expiry_height: mempool_height,
        joinsplit_data: None,
        sapling_shielded_data: None,
    };

    let tx_hash = tx.hash();
    let input_outpoint = match tx.inputs()[0] {
        transparent::Input::PrevOut { outpoint, .. } => outpoint,
        transparent::Input::Coinbase { .. } => panic!("requires a non-coinbase transaction"),
    };

    let mempool: MockService<_, _, _, _> = MockService::build().for_unit_tests();
    let state: MockService<_, _, _, _> = MockService::build().for_unit_tests();
    let (mempool_setup_tx, mempool_setup_rx) = tokio::sync::oneshot::channel();
    let verifier = Verifier::new(&network, state.clone(), mempool_setup_rx);
    let verifier = Buffer::new(verifier, 1);

    mempool_setup_tx
        .send(mempool.clone())
        .ok()
        .expect("send should succeed");

    // Submit the same transaction as a Block request at expired_block_height
    // (H+2).  The known_outpoint_hashes set satisfies the dependency check
    // inside find_verified_unmined_tx so the cache hit fires immediately.
    //
    // The verifier must return Err(TransactionError::ExpiredTransaction)
    // because H+2 > nExpiryHeight.
    let result = timeout(
        test_timeout(),
        verifier.clone().oneshot(Request::Block {
            transaction_hash: tx_hash,
            transaction: Arc::new(tx.clone()),
            known_outpoint_hashes: Arc::new([input_outpoint.hash].into()),
            known_utxos: Arc::new(HashMap::new()),
            height: expired_block_height,
            time: Utc::now(),
        }),
    )
    .await
    .expect("block request should not time out");

    // Buffer boxes the service error, so downcast to check the specific variant.
    let err = result.expect_err(
        "expected block verification to fail for a transaction with \
         expired nExpiryHeight mined via the mempool cache path",
    );
    let tx_err = err
        .downcast::<TransactionError>()
        .expect("error should downcast to TransactionError");
    assert!(
        matches!(*tx_err, TransactionError::ExpiredTransaction { .. }),
        "expected ExpiredTransaction error for block at height {expired_block_height:?} \
         with nExpiryHeight {mempool_height:?} via mempool cache; \
         got: {tx_err:?}"
    );
}

/// Test the mempool standardness gate that runs before script verification:
/// a P2SH input whose redeem script exceeds `MAX_P2SH_SIGOPS` (15) must be rejected,
/// while a redeem script at the limit is accepted.
#[test]
fn mempool_standard_input_scripts_limits_p2sh_redeem_sigops() {
    let _init_guard = zakura_test::init();

    const OP_CHECKSIG: u8 = 0xac;

    // scriptPubKey: OP_HASH160 <20 bytes> OP_EQUAL
    let mut p2sh_lock_bytes = vec![0xa9, 0x14];
    p2sh_lock_bytes.extend_from_slice(&[0u8; 20]);
    p2sh_lock_bytes.push(0x87);

    let spent_output = transparent::Output {
        value: Amount::try_from(1_000_000).expect("valid amount"),
        lock_script: transparent::Script::new(&p2sh_lock_bytes),
    };

    // A scriptSig with a single direct push of `sigops` OP_CHECKSIGs: for a P2SH spend, the pushed
    // data is the (non-standard) redeem script, and each OP_CHECKSIG counts as one accurate sigop.
    let unlock_bytes_with_sigops = |sigops: usize| {
        let mut unlock_bytes = vec![u8::try_from(sigops).expect("small test count")];
        unlock_bytes.extend_from_slice(&vec![OP_CHECKSIG; sigops]);
        unlock_bytes
    };

    let tx_spending = |unlock_bytes: &[u8]| Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(unlock_bytes),
            sequence: u32::MAX,
        }],
        outputs: vec![spent_output.clone()],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    // A non-standard redeem script at the standardness limit is accepted.
    let tx = tx_spending(&unlock_bytes_with_sigops(15));
    assert_eq!(
        check::mempool_standard_input_scripts(&tx, std::slice::from_ref(&spent_output)),
        Ok(()),
        "P2SH redeem script with MAX_P2SH_SIGOPS sigops should be standard"
    );

    // One sigop above the limit is rejected before script verification.
    let tx = tx_spending(&unlock_bytes_with_sigops(16));
    assert_eq!(
        check::mempool_standard_input_scripts(&tx, std::slice::from_ref(&spent_output)),
        Err(TransactionError::NonStandardInputs),
        "P2SH redeem script above MAX_P2SH_SIGOPS should be rejected"
    );
}

/// Test the mempool standardness gate that runs before script verification:
/// spending a non-standard (high-sigop) scriptPubKey must be rejected via `AreInputsStandard`,
/// so the interpreter is never asked to run its signature operations; a genuinely standard
/// P2PKH input is accepted.
#[test]
fn mempool_standard_input_scripts_rejects_nonstandard_spent_output() {
    let _init_guard = zakura_test::init();

    let tx_spending = |unlock_bytes: &[u8], spent_output: &transparent::Output| Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(unlock_bytes),
            sequence: u32::MAX,
        }],
        outputs: vec![spent_output.clone()],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    // A non-standard spent scriptPubKey (50 x OP_CHECKSIG) is not a recognized standard type, so
    // the input is rejected before verification would run its 50 signature checks. This is the
    // non-P2SH counterpart of the P2SH redeem-script limit: without classifying the spent output,
    // a peer could plant such a UTXO and drive expensive verification with a cheap spend.
    let nonstandard_output = transparent::Output {
        value: Amount::try_from(1_000_000).expect("valid amount"),
        lock_script: transparent::Script::new(&[0xac; 50]),
    };
    let tx = tx_spending(&[0x01, 0xaa], &nonstandard_output);
    assert_eq!(
        check::mempool_standard_input_scripts(&tx, std::slice::from_ref(&nonstandard_output)),
        Err(TransactionError::NonStandardInputs),
        "spending a non-standard scriptPubKey should be rejected before script verification"
    );

    // A genuinely standard P2PKH input (2 scriptSig pushes: sig + pubkey) is accepted.
    let mut p2pkh_lock_bytes = vec![0x76, 0xa9, 0x14];
    p2pkh_lock_bytes.extend_from_slice(&[0u8; 20]);
    p2pkh_lock_bytes.extend_from_slice(&[0x88, 0xac]);
    let p2pkh_output = transparent::Output {
        value: Amount::try_from(1_000_000).expect("valid amount"),
        lock_script: transparent::Script::new(&p2pkh_lock_bytes),
    };
    let tx = tx_spending(&[0x01, 0xaa, 0x01, 0xbb], &p2pkh_output);
    assert_eq!(
        check::mempool_standard_input_scripts(&tx, std::slice::from_ref(&p2pkh_output)),
        Ok(()),
        "a standard P2PKH input with the correct stack depth should be accepted"
    );
}

/// Test the mempool standardness gate that runs before script verification:
/// non-push-only and oversized scriptSigs must be rejected, so signature operations
/// can't be hidden in a scriptSig that the interpreter would execute.
#[test]
fn mempool_standard_input_scripts_rejects_nonstandard_script_sigs() {
    let _init_guard = zakura_test::init();

    // scriptPubKey: OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG
    let mut p2pkh_lock_bytes = vec![0x76, 0xa9, 0x14];
    p2pkh_lock_bytes.extend_from_slice(&[0u8; 20]);
    p2pkh_lock_bytes.extend_from_slice(&[0x88, 0xac]);

    let spent_output = transparent::Output {
        value: Amount::try_from(1_000_000).expect("valid amount"),
        lock_script: transparent::Script::new(&p2pkh_lock_bytes),
    };

    let tx_spending = |unlock_bytes: &[u8]| Transaction::V5 {
        network_upgrade: NetworkUpgrade::Nu5,
        inputs: vec![transparent::Input::PrevOut {
            outpoint: transparent::OutPoint {
                hash: Hash([0u8; 32]),
                index: 0,
            },
            unlock_script: transparent::Script::new(unlock_bytes),
            sequence: u32::MAX,
        }],
        outputs: vec![spent_output.clone()],
        lock_time: LockTime::unlocked(),
        expiry_height: Height(0),
        sapling_shielded_data: None,
        orchard_shielded_data: None,
    };

    // A scriptSig containing an operation (OP_CHECKSIG) instead of only pushes is rejected.
    let tx = tx_spending(&[0xac]);
    assert_eq!(
        check::mempool_standard_input_scripts(&tx, std::slice::from_ref(&spent_output)),
        Err(TransactionError::NonStandardScriptSigNotPushOnly { input_index: 0 }),
        "non-push-only scriptSig should be rejected"
    );

    // A push-only scriptSig above MAX_STANDARD_SCRIPTSIG_SIZE (1650) bytes is rejected:
    // OP_PUSHDATA2 <1648 little-endian> <1648 bytes> is 1651 bytes in total.
    let mut oversized_unlock_bytes = vec![0x4d, 0x70, 0x06];
    oversized_unlock_bytes.extend_from_slice(&[0u8; 1648]);
    let tx = tx_spending(&oversized_unlock_bytes);
    assert_eq!(
        check::mempool_standard_input_scripts(&tx, std::slice::from_ref(&spent_output)),
        Err(TransactionError::NonStandardScriptSigSize {
            input_index: 0,
            size: 1651,
        }),
        "oversized scriptSig should be rejected"
    );
}

// Unit tests for the private scriptSig-analysis helpers used by `check::are_inputs_standard`.

#[test]
fn count_script_push_ops_counts_pushes() {
    let _init_guard = zakura_test::init();
    // OP_0 <push 1 byte> <push 1 byte>
    assert_eq!(
        check::count_script_push_ops(&[0x00, 0x01, 0xaa, 0x01, 0xbb]),
        3
    );
}

#[test]
fn count_script_push_ops_empty_script() {
    let _init_guard = zakura_test::init();
    assert_eq!(check::count_script_push_ops(&[]), 0);
}

#[test]
fn count_script_push_ops_pushdata_variants() {
    let _init_guard = zakura_test::init();
    // OP_PUSHDATA1 <len=3> <3 bytes>
    assert_eq!(
        check::count_script_push_ops(&[0x4c, 0x03, 0xaa, 0xbb, 0xcc]),
        1
    );
    // OP_PUSHDATA2 <len=3 LE> <3 bytes>
    assert_eq!(
        check::count_script_push_ops(&[0x4d, 0x03, 0x00, 0xaa, 0xbb, 0xcc]),
        1
    );
    // OP_PUSHDATA4 <len=2 LE> <2 bytes>
    assert_eq!(
        check::count_script_push_ops(&[0x4e, 0x02, 0x00, 0x00, 0x00, 0xaa, 0xbb]),
        1
    );
}

#[test]
fn count_script_push_ops_truncated_script() {
    let _init_guard = zakura_test::init();
    // OP_PUSHBYTES_10 with only 3 bytes: the incomplete push errors and is filtered out.
    assert_eq!(check::count_script_push_ops(&[0x0a, 0xaa, 0xbb, 0xcc]), 0);
}

#[test]
fn extract_p2sh_redeemed_script_extracts_last_push() {
    let _init_guard = zakura_test::init();
    // <push "abc"> <push "de">: the redeemed script is the last push.
    let unlock_script = transparent::Script::new(&[0x03, 0x61, 0x62, 0x63, 0x02, 0x64, 0x65]);
    assert_eq!(
        check::extract_p2sh_redeemed_script(&unlock_script),
        Some(vec![0x64, 0x65])
    );
}

#[test]
fn extract_p2sh_redeemed_script_empty_script() {
    let _init_guard = zakura_test::init();
    assert!(check::extract_p2sh_redeemed_script(&transparent::Script::new(&[])).is_none());
}

#[test]
fn script_sig_args_expected_values() {
    use zcash_script::solver::ScriptKind;

    let _init_guard = zakura_test::init();

    // Build a P2PK lock script: <compressed_pubkey> OP_CHECKSIG
    fn p2pk_lock_script(pubkey: &[u8; 33]) -> transparent::Script {
        let mut s = Vec::with_capacity(1 + 33 + 1);
        s.push(0x21); // OP_PUSHBYTES_33
        s.extend_from_slice(pubkey);
        s.push(0xac); // OP_CHECKSIG
        transparent::Script::new(&s)
    }

    // Build a bare multisig lock script: OP_<required> <pubkeys...> OP_<total> OP_CHECKMULTISIG
    fn multisig_lock_script(required: u8, pubkeys: &[&[u8; 33]]) -> transparent::Script {
        let mut s = Vec::new();
        s.push(0x50 + required); // OP_1..=OP_16
        for pk in pubkeys {
            s.push(0x21); // OP_PUSHBYTES_33
            s.extend_from_slice(*pk);
        }
        s.push(0x50 + pubkeys.len() as u8); // OP_N total
        s.push(0xae); // OP_CHECKMULTISIG
        transparent::Script::new(&s)
    }

    // P2PKH: sig + pubkey.
    assert_eq!(
        check::script_sig_args_expected(&ScriptKind::PubKeyHash { hash: [0xaa; 20] }),
        Some(2)
    );
    // P2SH: the redeemed script push.
    assert_eq!(
        check::script_sig_args_expected(&ScriptKind::ScriptHash { hash: [0xbb; 20] }),
        Some(1)
    );
    // OP_RETURN: non-standard to spend.
    assert_eq!(
        check::script_sig_args_expected(&ScriptKind::NullData { data: vec![] }),
        None
    );

    // P2PK: sig only (classified via the solver).
    let p2pk_kind = check::standard_script_kind(&p2pk_lock_script(&[0x02; 33]))
        .expect("P2PK should be a standard script kind");
    assert_eq!(check::script_sig_args_expected(&p2pk_kind), Some(1));

    // 1-of-1 multisig: OP_0 + 1 sig.
    let ms_kind = multisig_lock_script(1, &[&[0x02; 33]]);
    let ms_kind = check::standard_script_kind(&ms_kind)
        .expect("1-of-1 multisig should be a standard script kind");
    assert_eq!(check::script_sig_args_expected(&ms_kind), Some(2));
}