zakura-client-backend 0.1.0-rc2

APIs for creating shielded Zcash light clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
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
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
use std::{
    cmp::Eq,
    collections::HashSet,
    convert::Infallible,
    hash::Hash,
    num::{NonZeroU8, NonZeroU32, NonZeroU64, NonZeroUsize},
};

use assert_matches::assert_matches;
use incrementalmerkletree::{Hashable, Level, Position, frontier::Frontier};
use rand_08::{Rng, RngCore};
use secrecy::Secret;
use shardtree::error::ShardTreeError;

use transparent::address::TransparentAddress;
use zcash_keys::{address::Address, keys::UnifiedSpendingKey};
use zcash_primitives::{
    block::BlockHash,
    transaction::{
        Transaction,
        fees::zip317::{FeeRule as Zip317FeeRule, MARGINAL_FEE, MINIMUM_FEE},
    },
};
use zcash_protocol::{
    ShieldedPool,
    consensus::{self, BlockHeight, NetworkUpgrade, Parameters},
    local_consensus::LocalNetwork,
    memo::{Memo, MemoBytes},
    value::Zatoshis,
};
use zip32::Scope;
use zip321::{Payment, TransactionRequest};

use crate::{
    data_api::{
        self, Account as _, AccountBirthday, BoundedU8, DecryptedTransaction, InputSource,
        MaxSpendMode, NoteFilter, Ratio, TargetValue, WalletCommitmentTrees, WalletRead,
        WalletSummary, WalletTest, WalletWrite,
        anchor_retention::AnchorRetentionInterval,
        chain::{self, ChainState, CommitmentTreeRoot, ScanSummary},
        error::Error,
        testing::{
            AddressType, CacheInsertionResult, FakeCompactOutput, InitialChainState, TestBuilder,
            single_output_change_strategy,
        },
        wallet::{
            ConfirmationsPolicy, TargetHeight, TransferErrT, decrypt_and_store_transaction,
            input_selection::{GreedyInputSelector, LockFilter, NoteSelection, SpendPolicy},
        },
    },
    decrypt_transaction,
    fees::{
        self, DustOutputPolicy, SplitPolicy, StandardFeeRule,
        standard::{self, SingleOutputChangeStrategy},
    },
    scanning::ScanError,
    wallet::{Note, NoteId, OvkPolicy, ReceivedNote},
};

use super::{
    DataStoreFactory, Reset, TestCache, TestFvk, TestRng, TestState,
    random_frontier_with_prior_subtree_roots,
};

fn random_sapling_frontier<const DEPTH: u8>(
    rng: &mut TestRng,
    tree_size: u64,
    subtree_depth: NonZeroU8,
) -> (Vec<::sapling::Node>, Frontier<::sapling::Node, DEPTH>) {
    random_frontier_with_prior_subtree_roots(rng, tree_size, subtree_depth, |rng| {
        ::sapling::Node::random(rng)
    })
}

#[cfg(feature = "orchard")]
fn random_orchard_frontier<const DEPTH: u8>(
    rng: &mut TestRng,
    tree_size: u64,
    subtree_depth: NonZeroU8,
) -> (
    Vec<::orchard::tree::MerkleHashOrchard>,
    Frontier<::orchard::tree::MerkleHashOrchard, DEPTH>,
) {
    random_frontier_with_prior_subtree_roots(rng, tree_size, subtree_depth, |rng| {
        ::orchard::tree::MerkleHashOrchard::random(rng)
    })
}

use crate::data_api::ll::wallet::PRUNING_DEPTH;
use crate::data_api::wallet::input_selection::GreedyInputSelectorError;
use crate::{
    data_api::BlockMetadata,
    scanning::{
        Nullifiers, ScanningKeys,
        full::{decrypt_block, scan_block},
    },
};
use incrementalmerkletree::Retention;
use nonempty::NonEmpty;
use shardtree::{ShardTree, store::ShardStore};
use std::collections::BTreeSet;
use zcash_primitives::block::{Block, BlockHeaderData};
use zcash_protocol::PoolType;

#[cfg(feature = "orchard")]
use {
    super::orchard::OrchardPoolTester,
    crate::data_api::wallet::propose_transfer,
    std::collections::BTreeMap,
    zcash_primitives::transaction::{TxVersion, builder::BundlePadding},
    zcash_protocol::zip318::{AnchorBucketInterval, MAX_RESIDUAL_VALUE},
};

#[cfg(not(feature = "orchard"))]
use zcash_address::{
    ZcashAddress,
    unified::{self, Encoding as _, Receiver},
};

// `ProposalError` also reaches this module through the `transparent-inputs` group below,
// so this arm covers only the configuration in which that group is absent.
#[cfg(all(feature = "orchard", not(feature = "transparent-inputs")))]
use crate::proposal::ProposalError;

#[cfg(feature = "transparent-inputs")]
use {
    crate::{
        data_api::{CoinbaseFilter, OutputOfSentTx, TransactionDataRequest, TransactionStatus},
        fees::ChangeValue,
        proposal::{Proposal, ProposalError, StepOutput, StepOutputIndex},
        wallet::{Exposure, TransparentAddressSource, WalletTransparentOutput},
    },
    secrecy::ExposeSecret,
    std::str::FromStr,
    transparent::{
        bundle::{OutPoint, TxOut},
        keys::{NonHardenedChildIndex, TransparentKeyScope},
    },
    zcash_keys::keys::{UnifiedAddressRequest, transparent::gap_limits::GapLimits},
    zcash_primitives::transaction::{
        builder::DEFAULT_TX_EXPIRY_DELTA,
        fees::{FeeRule, transparent::InputSize, zip317},
    },
    zcash_protocol::{
        TxId,
        value::{BalanceError, MAX_MONEY, ZatBalance},
    },
};

#[cfg(feature = "pczt")]
use {
    crate::data_api::wallet::{SignerView, redact_pczt_for_batch_signer, redact_pczt_for_signer},
    pczt::roles::{combiner::Combiner, prover::Prover, signer::Signer},
    rand::{rand_core::UnwrapErr, rngs::SysRng},
    transparent::builder::TransparentSigningSet,
    zcash_primitives::transaction::builder::{BuildConfig, Builder},
    zcash_proofs::prover::LocalTxProver,
    zcash_protocol::consensus::ZIP212_GRACE_PERIOD,
    zcash_script::opcode::PushValue,
};

#[cfg(feature = "pczt")]
#[allow(non_upper_case_globals)]
const OsRng: UnwrapErr<SysRng> = UnwrapErr(SysRng);

#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
use {
    crate::data_api::wallet::input_selection::LockedInputPolicy,
    zcash_protocol::consensus::COINBASE_MATURITY_BLOCKS,
};

pub mod dsl;
use dsl::{TestDsl, TestNoteConfig, TestScenario};

pub mod locking;
pub use locking::*;

/// Trait that exposes the pool-specific types and operations necessary to run the
/// single-shielded-pool tests on a given pool.
///
/// You should not need to implement this yourself; instead use [`SaplingPoolTester`] or
/// [`OrchardPoolTester`] as appropriate.
///
/// [`SaplingPoolTester`]: super::sapling::SaplingPoolTester
#[cfg_attr(
    feature = "orchard",
    doc = "[`OrchardPoolTester`]: super::orchard::OrchardPoolTester"
)]
#[cfg_attr(
    not(feature = "orchard"),
    doc = "[`OrchardPoolTester`]: https://github.com/zcash/librustzcash/blob/0777cbc2def6ba6b99f96333eaf96c314c1f3a37/zcash_client_backend/src/data_api/testing/orchard.rs#L33"
)]
pub trait ShieldedPoolTester {
    const SHIELDED_PROTOCOL: ShieldedPool;

    type Sk;
    type Fvk: TestFvk;
    type MerkleTreeHash;
    type Note;

    fn test_account_fvk<Cache, DbT: WalletTest, P: consensus::Parameters>(
        st: &TestState<Cache, DbT, P>,
    ) -> Self::Fvk;
    fn usk_to_sk(usk: &UnifiedSpendingKey) -> &Self::Sk;
    fn sk(seed: &[u8]) -> Self::Sk;
    fn sk_to_fvk(sk: &Self::Sk) -> Self::Fvk;
    fn sk_default_address(sk: &Self::Sk) -> Address;
    fn fvk_default_address(fvk: &Self::Fvk) -> Address;
    fn fvks_equal(a: &Self::Fvk, b: &Self::Fvk) -> bool;

    fn random_fvk(mut rng: impl RngCore) -> Self::Fvk {
        let sk = {
            let mut sk_bytes = vec![0; 32];
            rng.fill_bytes(&mut sk_bytes);
            Self::sk(&sk_bytes)
        };

        Self::sk_to_fvk(&sk)
    }
    fn random_address(rng: impl RngCore) -> Address {
        Self::fvk_default_address(&Self::random_fvk(rng))
    }

    fn empty_tree_leaf() -> Self::MerkleTreeHash;
    fn empty_tree_root(level: Level) -> Self::MerkleTreeHash;

    fn put_subtree_roots<Cache, DbT: WalletTest + WalletCommitmentTrees, P>(
        st: &mut TestState<Cache, DbT, P>,
        start_index: u64,
        roots: &[CommitmentTreeRoot<Self::MerkleTreeHash>],
    ) -> Result<(), ShardTreeError<<DbT as WalletCommitmentTrees>::Error>>;

    /// Computes the actual root of the `shard_index`-th shard from the wallet's local
    /// shardtree state, reading whatever leaves and cached annotations are currently
    /// stored. Used by tests that need to call [`Self::put_subtree_roots`] with a root
    /// that matches the shard's actual computed root — for example, when declaring a
    /// shard complete after filling its last position via `scan_cached_blocks`.
    fn shard_root<Cache, DbT: WalletTest + WalletCommitmentTrees, P>(
        st: &mut TestState<Cache, DbT, P>,
        shard_index: u64,
    ) -> Result<Self::MerkleTreeHash, ShardTreeError<<DbT as WalletCommitmentTrees>::Error>>;

    fn next_subtree_index<A: Hash + Eq>(s: &WalletSummary<A>) -> u64;

    fn note_value(note: &Self::Note) -> Zatoshis;

    #[allow(clippy::type_complexity)]
    fn select_spendable_notes<Cache, DbT: InputSource + WalletTest, P>(
        st: &TestState<Cache, DbT, P>,
        account: <DbT as InputSource>::AccountId,
        target_value: TargetValue,
        target_height: TargetHeight,
        confirmations_policy: ConfirmationsPolicy,
        exclude: &[DbT::NoteRef],
    ) -> Result<Vec<ReceivedNote<DbT::NoteRef, Self::Note>>, <DbT as InputSource>::Error>;

    #[allow(clippy::type_complexity)]
    fn select_unspent_notes<Cache, DbT: InputSource + WalletTest, P>(
        st: &TestState<Cache, DbT, P>,
        account: <DbT as InputSource>::AccountId,
        target_height: TargetHeight,
        exclude: &[DbT::NoteRef],
    ) -> Result<Vec<ReceivedNote<DbT::NoteRef, Self::Note>>, <DbT as InputSource>::Error>;

    fn decrypted_pool_outputs_count<A>(d_tx: &DecryptedTransaction<Transaction, A>) -> usize;

    fn with_decrypted_pool_memos<A>(
        d_tx: &DecryptedTransaction<Transaction, A>,
        f: impl FnMut(&MemoBytes),
    );

    fn try_output_recovery<P: consensus::Parameters>(
        params: &P,
        height: BlockHeight,
        tx: &Transaction,
        fvk: &Self::Fvk,
    ) -> Option<(Note, Address, MemoBytes)>;

    fn received_note_count(summary: &ScanSummary) -> usize;

    #[cfg(feature = "pczt")]
    fn add_proof_generation_keys(
        pczt: pczt::Pczt,
        usk: &UnifiedSpendingKey,
    ) -> Result<pczt::Pczt, pczt::roles::updater::SaplingError>;

    #[cfg(feature = "pczt")]
    fn apply_signatures_to_pczt(
        signer: &mut Signer,
        usk: &UnifiedSpendingKey,
    ) -> Result<(), pczt::roles::signer::Error>;
}

fn selected_notes_for_transfer<T, Cache, Dsf>(
    st: &mut TestDsl<TestScenario<T, Cache, Dsf>>,
    amount: Zatoshis,
    note_selection: NoteSelection,
) -> Vec<Zatoshis>
where
    T: ShieldedPoolTester,
    Cache: TestCache,
    Dsf: DataStoreFactory,
{
    let account_id = st.test_account().unwrap().id();
    let recipient_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
    let recipient = T::fvk_default_address(&recipient_fvk).to_zcash_address(st.network());
    let request = TransactionRequest::new(vec![Payment::without_memo(recipient, amount)]).unwrap();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
    let spend_policy =
        SpendPolicy::shielded_pools([T::SHIELDED_PROTOCOL]).with_note_selection(note_selection);
    let proposal = st
        .propose_transfer_with_policy(
            account_id,
            &GreedyInputSelector::new(),
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
            &spend_policy,
        )
        .expect("the selected notes cover the payment and fee");

    proposal
        .steps()
        .first()
        .shielded_inputs()
        .expect("the proposal spends shielded notes")
        .notes()
        .iter()
        .map(|note| note.note().value())
        .collect()
}

/// Tests sending funds within the given shielded pool in a single transaction.
///
/// The test:
/// - Adds funds to the wallet in a single note.
/// - Checks that the wallet balances are correct.
/// - Constructs a request to spend part of that balance to an external address in the
///   same pool.
/// - Builds the transaction.
/// - Checks that the transaction was stored, and that the outputs are decryptable and
///   have the expected details.
pub fn send_single_step_proposed_transfer<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note
    let (h, _, _) = st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));

    let to_extsk = T::sk(&[0xf5; 32]);
    let to: Address = T::sk_default_address(&to_extsk);
    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        Zatoshis::const_from_u64(10000),
    )])
    .unwrap();

    let fee_rule = StandardFeeRule::Zip317;

    let change_memo = "Test change memo".parse::<Memo>().unwrap();
    let change_strategy = standard::SingleOutputChangeStrategy::new(
        fee_rule,
        Some(change_memo.clone().into()),
        T::SHIELDED_PROTOCOL,
        DustOutputPolicy::default(),
    );
    let input_selector = GreedyInputSelector::new();

    let account = st.get_account();
    let proposal = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];

    // Verify that the sent transaction was stored and that we can decrypt the memos
    let tx = st
        .wallet()
        .get_transaction(sent_tx_id)
        .unwrap()
        .expect("Created transaction was stored.");
    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
        .into_iter()
        .collect();
    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 2);

    let mut found_tx_change_memo = false;
    let mut found_tx_empty_memo = false;
    T::with_decrypted_pool_memos(&d_tx, |memo| {
        if Memo::try_from(memo).unwrap() == change_memo {
            found_tx_change_memo = true
        }
        if Memo::try_from(memo).unwrap() == Memo::Empty {
            found_tx_empty_memo = true
        }
    });
    assert!(found_tx_change_memo);
    assert!(found_tx_empty_memo);

    // Verify that the stored sent notes match what we're expecting
    let sent_note_ids = st
        .wallet()
        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(sent_note_ids.len(), 2);

    // The sent memo should be the empty memo for the sent output, and the
    // change output's memo should be as specified.
    let mut found_sent_change_memo = false;
    let mut found_sent_empty_memo = false;
    for sent_note_id in sent_note_ids {
        match st
            .wallet()
            .get_memo(sent_note_id)
            .expect("Note id is valid")
            .as_ref()
        {
            Some(m) if m == &change_memo => {
                found_sent_change_memo = true;
            }
            Some(m) if m == &Memo::Empty => {
                found_sent_empty_memo = true;
            }
            Some(other) => panic!("Unexpected memo value: {other:?}"),
            None => panic!("Memo should not be stored as NULL"),
        }
    }
    assert!(found_sent_change_memo);
    assert!(found_sent_empty_memo);

    // Check that querying for a nonexistent sent note returns None
    assert_matches!(
        st.wallet()
            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
        Ok(None)
    );

    let tx_history = st.wallet().get_tx_history().unwrap();
    assert_eq!(tx_history.len(), 2);
    {
        let tx_0 = &tx_history[0];
        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
    }

    {
        let tx_1 = &tx_history[1];
        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(40000));
    }

    let network = *st.network();
    assert_matches!(
        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
        Ok(_)
    );
}

/// Builds a real transaction via the proposal/creation path, assembles it into a full
/// block, and verifies that [`decrypt_block`] followed by [`scan_block`] detects the
/// wallet output (the change note) that it contains.
///
/// [`decrypt_block`]: crate::scanning::full::decrypt_block
/// [`scan_block`]: crate::scanning::full::scan_block
pub fn scan_full_block_detects_outputs<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note.
    let (h, _, _) = st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));

    // Propose and create a transfer to an external recipient. The resulting transaction
    // has two shielded outputs: the payment, and the change returned to the wallet.
    let to_extsk = T::sk(&[0xf5; 32]);
    let to: Address = T::sk_default_address(&to_extsk);
    let request = TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        Zatoshis::const_from_u64(10000),
    )])
    .unwrap();

    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
    let input_selector = GreedyInputSelector::new();

    let account = st.get_account();
    let proposal = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let txids = st
        .create_proposed_transactions::<Infallible, _, Infallible, _>(
            account.usk(),
            OvkPolicy::Sender,
            &proposal,
        )
        .unwrap();
    assert_eq!(txids.len(), 1);

    let tx = st
        .wallet()
        .get_transaction(*txids.first())
        .unwrap()
        .expect("the created transaction was stored");

    // Build a `ScanningKeys` set for the wallet account. The account identifier used for
    // scanning is independent of the wallet database's account identifier.
    let ufvk = account.usk().to_unified_full_viewing_key();
    let scanning_keys = ScanningKeys::from_account_ufvks([(zip32::AccountId::ZERO, ufvk)]);

    // Assemble a single-transaction block containing the created transaction. The block
    // is scanned in isolation, so we treat the note commitment trees as empty as of the
    // immediately preceding block.
    let network = *st.network();
    let header = BlockHeaderData {
        version: 4,
        prev_block: BlockHash([0; 32]),
        merkle_root: [0; 32],
        final_sapling_root: [0; 32],
        time: 0,
        bits: 0,
        nonce: [0; 32],
        solution: vec![],
    }
    .freeze()
    .unwrap();
    let block = Block::from_parts(header, NonEmpty::singleton(tx), h);

    let prior_block_metadata = BlockMetadata::from_parts(
        h - 1,
        BlockHash([0; 32]),
        Some(0),
        #[cfg(feature = "orchard")]
        Some(0),
        #[cfg(feature = "orchard")]
        Some(0),
    );

    // Phase 1: decrypt the block's shielded outputs.
    let (header, vtx) = decrypt_block(&network, block, &scanning_keys);

    // Phase 2: scan the decrypted block.
    #[cfg(feature = "transparent-inputs")]
    let scanned = scan_block(
        &network,
        h,
        &header,
        vtx,
        &scanning_keys,
        &Nullifiers::empty(),
        Some(&prior_block_metadata),
        |_addr| Ok::<_, Infallible>(None),
    )
    .expect("scanning the block succeeds");
    #[cfg(not(feature = "transparent-inputs"))]
    let scanned = scan_block::<_, _, _, Infallible>(
        &network,
        h,
        &header,
        vtx,
        &scanning_keys,
        &Nullifiers::empty(),
        Some(&prior_block_metadata),
    )
    .expect("scanning the block succeeds");

    // The wallet should have detected exactly the change output returned to its internal
    // address; the payment output was sent to a recipient outside the wallet.
    assert_eq!(scanned.transactions().len(), 1);
    let received_outputs: usize = scanned
        .transactions()
        .iter()
        .map(|wtx| {
            let n = wtx.sapling_outputs().len();
            #[cfg(feature = "orchard")]
            let n = n + wtx.orchard_outputs().len();
            n
        })
        .sum();
    assert_eq!(received_outputs, 1);

    // The note commitment tree should have grown by exactly the two shielded outputs in
    // the block's single transaction (the payment and the change), starting from the
    // empty prior tree. The outputs all belong to the pool under test; the other pool (if
    // compiled in) sees no outputs.
    let total_commitments = scanned.sapling().commitments().len();
    #[cfg(feature = "orchard")]
    let total_commitments = total_commitments + scanned.orchard().commitments().len();
    assert_eq!(total_commitments, 2);

    let total_final_tree_size = scanned.sapling().final_tree_size();
    #[cfg(feature = "orchard")]
    let total_final_tree_size = total_final_tree_size + scanned.orchard().final_tree_size();
    assert_eq!(total_final_tree_size, 2);

    // The final note added in the block must be marked as a checkpoint at this block
    // height; this is what lets the wallet anchor witnesses to the block. Getting the
    // "last outputs in the block" boundary wrong is the most error-prone part of position
    // tracking, so we assert it explicitly.
    let last_retention = scanned.sapling().commitments().last().map(|(_, r)| *r);
    #[cfg(feature = "orchard")]
    let last_retention = scanned
        .orchard()
        .commitments()
        .last()
        .map(|(_, r)| *r)
        .or(last_retention);
    assert!(
        matches!(last_retention, Some(Retention::Checkpoint { id, .. }) if id == h),
        "final note commitment should be a checkpoint at height {h:?}, got {last_retention:?}",
    );
}

#[derive(Clone, Copy, Debug, PartialEq)]
struct ConfirmationStep {
    i: u32,
    confirmation_requirement: u32,
    number_of_confirmations: u32,
    pending_balance: Zatoshis,
    spendable_balance: Zatoshis,
    total_balance: Zatoshis,
}

/// An enumeration of mechanisms for generating transaction inputs for confirmations policy
/// testing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InputTrust {
    /// Generate a wallet-internal output.
    Internal,
    /// Generate an output as if it was sent to the wallet by an untrusted counterparty.
    ExternalUntrusted,
    /// Generate an output as if it was sent to the wallet by a trusted counterparty.
    ExternalTrusted,
}

/// Tests that inputs from a source can be spent according to the default
/// `ConfirmationsPolicy`.
///
/// The test:
/// - Adds funds to the wallet in a single note from an certain source.
/// - Checks that the wallet balances are correct after N confirmations, according to
///   the policy.
pub fn zip_315_confirmations_test_steps<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
    input_trust: InputTrust,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
    let account = st.test_account().cloned().unwrap();
    let starting_balance = Zatoshis::const_from_u64(60_000);

    // Add funds to the wallet in a single note, owned by the internal spending key,
    // which will have one confirmation.
    let confirmations_policy = ConfirmationsPolicy::default();
    let (address_type, min_confirmations) = match input_trust {
        InputTrust::Internal => (AddressType::Internal, confirmations_policy.trusted()),
        InputTrust::ExternalUntrusted => (
            AddressType::DefaultExternal,
            confirmations_policy.untrusted(),
        ),
        InputTrust::ExternalTrusted => {
            (AddressType::DefaultExternal, confirmations_policy.trusted())
        }
    };
    let min_confirmations = u32::from(min_confirmations);

    let (_, r, _) = st.add_a_single_note_checking_balance(
        TestNoteConfig::from(starting_balance).with_address_type(address_type),
    );
    let txid = r.txids()[0];

    // Mark the external input as explicitly trusted, if so requested
    let trusted = input_trust == InputTrust::ExternalTrusted;
    if trusted {
        st.wallet_mut().set_tx_trust(txid, true).unwrap();
    }

    let add_confirmation = |i: u32| {
        let (h, _) = st.generate_empty_block();
        st.scan_cached_blocks(h, 1);
        let outputs = st
            .wallet()
            .get_received_outputs(txid, TargetHeight::from(h + 1), confirmations_policy)
            .unwrap();
        assert_eq!(outputs.len(), 1);
        assert_eq!(
            outputs[0].confirmations_until_spendable(),
            u32::from(if trusted {
                confirmations_policy.trusted()
            } else {
                confirmations_policy.untrusted()
            })
            .saturating_sub(i + 1)
        );
        ConfirmationStep {
            i,
            confirmation_requirement: min_confirmations,
            number_of_confirmations: 1 + i,
            pending_balance: st.get_pending_shielded_balance(account.id(), confirmations_policy),
            spendable_balance: st.get_spendable_balance(account.id(), confirmations_policy),
            total_balance: st.get_total_balance(account.id()),
        }
    };

    // Generate N confirmations by mining blocks
    let steps = (1u32..min_confirmations)
        .map(add_confirmation)
        .collect::<Vec<_>>();

    assert!(
        steps
            .iter()
            .filter(|step| step.number_of_confirmations < min_confirmations)
            .all(|step| step.spendable_balance == Zatoshis::ZERO),
        "spendable balance is equal to starting balance until we have sufficient confirmations"
    );

    let to = T::random_address(st.rng_mut());
    // Now that the funds are spendable, propose a transaction
    let proposed = st.propose_standard_transfer::<Infallible>(
        account.id(),
        StandardFeeRule::Zip317,
        confirmations_policy,
        &to,
        Zatoshis::const_from_u64(10_000),
        None,
        None,
        T::SHIELDED_PROTOCOL,
    );
    assert!(
        proposed.is_ok(),
        "Could not spend funds by confirmation policy ({input_trust:?}): {proposed:#?}\n\
        steps: {steps:#?}",
    );
}

/// Tests max spendable funds within the given shielded pool in a
/// single transaction.
///
/// The test:
/// - Adds funds to the wallet in two notes with different confirmation heights
/// - Checks that the wallet balances are correct.
/// - Constructs a request to spend the whole balance to an external address in the
///   same pool.
/// - Builds the transaction.
/// - Checks that the transaction was stored, and that the outputs are decryptable and
///   have the expected details.
pub fn spend_max_spendable_single_step_proposed_transfer<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in two notes over 5 blocks
    let value = Zatoshis::const_from_u64(60000);
    let h = st
        .add_notes_checking_balance([Some(value), None, None, None, Some(value)])
        .block_height()
        .unwrap();

    // Spendable balance matches total balance
    let account = st.test_account().cloned().unwrap();
    let confirmation_policy = ConfirmationsPolicy::new_symmetrical(
        NonZeroU32::new(2).expect("2 is not zero"),
        #[cfg(feature = "transparent-inputs")]
        false,
    );
    assert_eq!(
        st.get_spendable_balance(account.id(), confirmation_policy),
        value
    );

    let to_extsk = T::sk(&[0xf5; 32]);
    let to: Address = T::sk_default_address(&to_extsk);

    let fee_rule = StandardFeeRule::Zip317;

    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();

    let addy = to.to_zcash_address(st.network());
    let proposal = st
        .propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            Some(MemoBytes::from(send_max_memo.clone())),
            MaxSpendMode::MaxSpendable,
            confirmation_policy,
        )
        .unwrap();

    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];

    // Verify that the sent transaction was stored and that we can decrypt the memos
    let tx = st
        .wallet()
        .get_transaction(sent_tx_id)
        .unwrap()
        .expect("Created transaction was stored.");
    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
        .into_iter()
        .collect();
    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 1);

    let mut found_send_max_memo = false;
    let mut found_tx_empty_memo = false;
    T::with_decrypted_pool_memos(&d_tx, |memo| {
        if Memo::try_from(memo).unwrap() == send_max_memo {
            found_send_max_memo = true
        }
        if Memo::try_from(memo).unwrap() == Memo::Empty {
            found_tx_empty_memo = true
        }
    });
    assert!(found_send_max_memo);
    assert!(!found_tx_empty_memo); // there's no empty memo in this case

    // Verify that the stored sent notes match what we're expecting
    let sent_note_ids = st
        .wallet()
        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(sent_note_ids.len(), 1);

    // The sent memo should the specified memo for the sent output
    let mut found_sent_empty_memo = false;
    let mut found_sent_max_memo = false;
    for sent_note_id in sent_note_ids {
        match st
            .wallet()
            .get_memo(sent_note_id)
            .expect("Memo retrieval should succeed")
            .as_ref()
        {
            Some(m) if m == &Memo::Empty => {
                found_sent_empty_memo = true;
            }
            Some(m) if m == &send_max_memo => {
                found_sent_max_memo = true;
            }
            Some(other) => panic!("Unexpected memo value: {other:?}"),
            None => panic!("Memo should not be stored as NULL"),
        }
    }

    assert!(found_sent_max_memo);
    assert!(!found_sent_empty_memo);

    // Check that querying for a nonexistent sent note returns None
    assert_matches!(
        st.wallet()
            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
        Ok(None)
    );

    let tx_history = st.wallet().get_tx_history().unwrap();
    assert_eq!(tx_history.len(), 3);
    {
        let tx_0 = &tx_history[0];
        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
    }
    {
        let tx_1 = &tx_history[1];
        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(0));
        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(60000));
    }
    {
        let tx_2 = &tx_history[2];
        assert_eq!(tx_2.total_spent(), Zatoshis::const_from_u64(60000));
        assert_eq!(tx_2.total_received(), Zatoshis::const_from_u64(0));
    }

    let network = *st.network();
    assert_matches!(
        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
        Ok(_)
    );
}

/// Tests sending every piece of spendable funds within the given shielded pool in a
/// single transaction.
///
/// The test:
/// - Adds funds to the wallet in a single note.
/// - Checks that the wallet balances are correct.
/// - Constructs a request to spend the whole balance to an external address in the
///   same pool.
/// - Builds the transaction.
/// - Checks that the transaction was stored, and that the outputs are decryptable and
///   have the expected details.
pub fn spend_everything_single_step_proposed_transfer<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();

    // Add funds to the wallet in a single note
    let (h, _, _) = st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));

    let to_extsk = T::sk(&[0xf5; 32]);
    let to: Address = T::sk_default_address(&to_extsk);

    let fee_rule = StandardFeeRule::Zip317;

    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();

    let addy = to.to_zcash_address(st.network());
    let proposal = st
        .propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            Some(MemoBytes::from(send_max_memo.clone())),
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];

    // Verify that the sent transaction was stored and that we can decrypt the memos
    let tx = st
        .wallet()
        .get_transaction(sent_tx_id)
        .unwrap()
        .expect("Created transaction was stored.");
    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
        .into_iter()
        .collect();
    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 1);

    let mut found_send_max_memo = false;
    let mut found_tx_empty_memo = false;
    T::with_decrypted_pool_memos(&d_tx, |memo| {
        if Memo::try_from(memo).unwrap() == send_max_memo {
            found_send_max_memo = true
        }
        if Memo::try_from(memo).unwrap() == Memo::Empty {
            found_tx_empty_memo = true
        }
    });
    assert!(found_send_max_memo);
    assert!(!found_tx_empty_memo); // there's no empty memo in this case

    // Verify that the stored sent notes match what we're expecting
    let sent_note_ids = st
        .wallet()
        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(sent_note_ids.len(), 1);

    // The sent memo should the specified memo for the sent output
    let mut found_sent_empty_memo = false;
    let mut found_sent_max_memo = false;
    for sent_note_id in sent_note_ids {
        match st
            .wallet()
            .get_memo(sent_note_id)
            .expect("Memo retrieval should succeed")
            .as_ref()
        {
            Some(m) if m == &Memo::Empty => {
                found_sent_empty_memo = true;
            }
            Some(m) if m == &send_max_memo => {
                found_sent_max_memo = true;
            }
            Some(other) => panic!("Unexpected memo value: {other:?}"),
            None => panic!("Memo should not be stored as NULL"),
        }
    }

    assert!(found_sent_max_memo);
    assert!(!found_sent_empty_memo);

    // Check that querying for a nonexistent sent note returns None
    assert_matches!(
        st.wallet()
            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
        Ok(None)
    );

    let tx_history = st.wallet().get_tx_history().unwrap();
    assert_eq!(tx_history.len(), 2);
    {
        let tx_0 = &tx_history[0];
        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
    }

    {
        let tx_1 = &tx_history[1];
        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(0));
    }

    let network = *st.network();
    assert_matches!(
        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
        Ok(_)
    );
}

/// Tests that sending all the spendable funds within the given shielded pool in a
/// single transaction to a transparent address with a memo fails.
///
/// The test:
/// - Adds funds to the wallet in a single note.
/// - Checks that the wallet balances are correct.
/// - Tries to propose a send max transaction to a T-address with a memo
/// - Fails gracefully with Zip321Error.
#[cfg(feature = "transparent-inputs")]
pub fn fails_to_send_max_spendable_to_transparent_with_memo<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note
    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));

    let account = st.test_account().cloned().unwrap();
    let (default_addr, _) = account.usk().default_transparent_address();

    let to: Address = Address::Transparent(default_addr);

    let fee_rule = StandardFeeRule::Zip317;

    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();

    let addy = to.to_zcash_address(st.network());
    assert_matches!(
        st.propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            Some(MemoBytes::from(send_max_memo.clone())),
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN
        ),
        Err(data_api::error::Error::Payment(
            zip321::PaymentError::TransparentMemo
        ))
    );
}

/// Tests that sending all the spendable funds within the given shielded pool to a
/// transparent (non-TEX) recipient succeeds.
///
/// The test:
/// - Adds funds to the wallet in a single note.
/// - Proposes a send-max transaction to a transparent address, without a memo.
/// - Verifies that the proposal consists of a single step paying the whole balance,
///   less the fee, to the transparent recipient.
/// - Builds the transaction.
#[cfg(feature = "transparent-inputs")]
pub fn send_max_spendable_to_transparent<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note
    let value = Zatoshis::const_from_u64(60000);
    st.add_a_single_note_checking_balance(value);

    let account = st.test_account().cloned().unwrap();
    let to: Address = Address::Transparent(TransparentAddress::PublicKeyHash([0x7f; 20]));

    let fee_rule = StandardFeeRule::Zip317;

    // The proposed transaction carries one shielded spend (padded to two shielded
    // outputs) and one transparent output.
    let expected_fee = (zip317::MARGINAL_FEE * 3u64).unwrap();
    let expected_payment = (value - expected_fee).unwrap();

    let addy = to.to_zcash_address(st.network());
    let proposal = st
        .propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
    assert_eq!(steps.len(), 1);
    assert_eq!(steps[0].balance().fee_required(), expected_fee);
    assert_eq!(steps[0].balance().proposed_change(), []);
    assert_eq!(
        steps[0].payment_pools(),
        &std::collections::BTreeMap::from([(0, PoolType::TRANSPARENT)])
    );
    assert_matches!(
        steps[0].transaction_request().payments().get(&0),
        Some(payment) if payment.amount() == Some(expected_payment)
    );

    st.create_proposed_expecting(&proposal, 1);
}

/// Tests that a send-max proposal whose total required fee overflows the maximum
/// monetary amount fails with a balance error rather than panicking.
#[cfg(feature = "transparent-inputs")]
pub fn send_max_fee_overflow_is_an_error<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    /// A fee rule that requires the maximum monetary amount for every transaction.
    #[derive(Clone, Debug)]
    struct MaxMoneyFeeRule;

    impl FeeRule for MaxMoneyFeeRule {
        type Error = Infallible;

        fn fee_required<P: consensus::Parameters>(
            &self,
            _params: &P,
            _target_height: BlockHeight,
            _transparent_input_sizes: impl IntoIterator<Item = InputSize>,
            _transparent_output_sizes: impl IntoIterator<Item = usize>,
            _sapling_input_count: usize,
            _sapling_output_count: usize,
            _orchard_action_count: usize,
            _ironwood_action_count: usize,
        ) -> Result<Zatoshis, Self::Error> {
            Ok(Zatoshis::const_from_u64(MAX_MONEY))
        }
    }

    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note
    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));

    let account = st.test_account().cloned().unwrap();

    // A TEX recipient requires a second transaction, so the total required fee is the
    // sum of two per-transaction fees, which overflows the maximum monetary amount.
    let tex_addr = Address::Tex([0x4; 20]);
    let addy = tex_addr.to_zcash_address(st.network());

    assert_matches!(
        st.propose_send_max_transfer(
            account.id(),
            &MaxMoneyFeeRule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        ),
        Err(data_api::error::Error::NoteSelection(
            GreedyInputSelectorError::Balance(BalanceError::Overflow)
        ))
    );
}

/// Tests that a send-max proposal spends notes from multiple shielded pools in a single
/// transaction when the wallet's funds are split across pools.
///
/// The test:
/// - Adds one note in each of the `P0` and `P1` pools.
/// - Proposes a send-max transaction to an external `P1` recipient, so that the value of
///   the `P0` note crosses pools.
/// - Verifies that the proposal consists of a single step spending both notes and paying
///   the whole balance, less the fee, to the recipient.
/// - Builds the transaction, mines it, and verifies that the wallet is left empty.
#[cfg(feature = "orchard")]
pub fn send_max_spends_inputs_across_pools<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
    let account = st.test_account().cloned().unwrap();

    // Add one note in each of the P0 and P1 pools.
    let p0_fvk = P0::test_account_fvk(&st);
    let p1_fvk = P1::test_account_fvk(&st);
    let note_value = Zatoshis::const_from_u64(350000);
    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
    st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
    st.scan_cached_blocks(account.birthday().height(), 2);

    let total = (note_value * 2u64).unwrap();
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        total
    );

    let to: Address = P1::sk_default_address(&P1::sk(&[0xf5; 32]));
    let fee_rule = StandardFeeRule::Zip317;

    // The proposed transaction spends one note in each pool and pays a single shielded
    // output; under ZIP 317, each of the two shielded bundles is padded to two logical
    // actions.
    let expected_fee = (MARGINAL_FEE * 4u64).unwrap();
    let expected_payment = (total - expected_fee).unwrap();

    let addy = to.to_zcash_address(st.network());
    let proposal = st
        .propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
    assert_eq!(steps.len(), 1);
    assert_eq!(steps[0].balance().fee_required(), expected_fee);
    assert_eq!(steps[0].balance().proposed_change(), []);
    assert_eq!(
        steps[0].payment_pools(),
        &BTreeMap::from([(0, PoolType::Shielded(P1::SHIELDED_PROTOCOL))])
    );
    assert_matches!(
        steps[0].transaction_request().payments().get(&0),
        Some(payment) if payment.amount() == Some(expected_payment)
    );

    // The proposal spends both notes, one from each pool.
    let input_notes = steps[0]
        .shielded_inputs()
        .expect("the proposal has shielded inputs")
        .notes();
    assert_eq!(input_notes.len(), 2);
    let input_pools = input_notes
        .iter()
        .map(|n| match n.note() {
            Note::Sapling(_) => ShieldedPool::Sapling,
            Note::Orchard { pool, .. } => match pool {
                ::orchard::ValuePool::Orchard => ShieldedPool::Orchard,
                ::orchard::ValuePool::Ironwood => ShieldedPool::Ironwood,
            },
        })
        .collect::<BTreeSet<_>>();
    assert_eq!(
        input_pools,
        BTreeSet::from([P0::SHIELDED_PROTOCOL, P1::SHIELDED_PROTOCOL])
    );

    let txids = st.create_proposed_expecting(&proposal, 1);

    // Mine the transaction and verify that the entire balance has been spent.
    let (h, _) = st.generate_next_block_including(txids[0]);
    st.scan_cached_blocks(h, 1);
    assert_eq!(st.get_total_balance(account.id()), Zatoshis::ZERO);
}

/// Tests that proposing a send-max transfer to a TEX recipient fails with a meaningful
/// error when the `transparent-inputs` feature is not enabled.
#[cfg(not(feature = "transparent-inputs"))]
pub fn send_max_to_tex_fails_without_transparent_inputs<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note
    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));

    let account = st.test_account().cloned().unwrap();
    let tex_addr = Address::Tex([0x4; 20]);
    let fee_rule = StandardFeeRule::Zip317;

    let addy = tex_addr.to_zcash_address(st.network());
    assert_matches!(
        st.propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        ),
        Err(data_api::error::Error::NoteSelection(
            GreedyInputSelectorError::UnsupportedTexAddress
        ))
    );
}

/// Tests that a send-max proposal to a unified address having both Sapling and Orchard
/// receivers is delivered via the Sapling receiver when the `orchard` feature is not
/// enabled, rather than failing.
#[cfg(not(feature = "orchard"))]
pub fn send_max_delivers_via_sapling_when_orchard_is_unavailable<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note
    let value = Zatoshis::const_from_u64(60000);
    st.add_a_single_note_checking_balance(value);

    let account = st.test_account().cloned().unwrap();

    // Construct a unified address carrying both a Sapling receiver and an Orchard
    // receiver. Without the `orchard` feature, the Orchard receiver's contents are
    // not parsed, so arbitrary receiver bytes suffice.
    let sapling_receiver = match T::sk_default_address(&T::sk(&[0xf5; 32])) {
        Address::Sapling(addr) => addr.to_bytes(),
        _ => panic!("expected a Sapling address"),
    };
    let ua = unified::Address::try_from_items(vec![
        Receiver::Sapling(sapling_receiver),
        Receiver::Orchard([0xab; 43]),
    ])
    .unwrap();
    let addy = ZcashAddress::try_from_encoded(&ua.encode(&st.network().network_type())).unwrap();

    let fee_rule = StandardFeeRule::Zip317;

    // The proposed transaction carries one Sapling spend and one requested Sapling
    // output (padded to two logical actions under ZIP 317).
    let expected_fee = MINIMUM_FEE;
    let expected_payment = (value - expected_fee).unwrap();

    let proposal = st
        .propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
    assert_eq!(steps.len(), 1);
    assert_eq!(steps[0].balance().fee_required(), expected_fee);
    assert_eq!(
        steps[0].payment_pools(),
        &std::collections::BTreeMap::from([(0, PoolType::SAPLING)])
    );
    assert_matches!(
        steps[0].transaction_request().payments().get(&0),
        Some(payment) if payment.amount() == Some(expected_payment)
    );

    st.create_proposed_expecting(&proposal, 1);
}

/// Tests that a send-max proposal to a unified address whose only receiver cannot be
/// paid by this build (an Orchard-only address, without the `orchard` feature) fails
/// with `GreedyInputSelectorError::UnsupportedAddress`.
#[cfg(not(feature = "orchard"))]
pub fn send_max_to_orchard_only_ua_fails_without_orchard<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note
    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));

    let account = st.test_account().cloned().unwrap();

    // Without the `orchard` feature, the Orchard receiver's contents are not parsed,
    // so arbitrary receiver bytes suffice.
    let ua = unified::Address::try_from_items(vec![Receiver::Orchard([0xab; 43])]).unwrap();
    let addy = ZcashAddress::try_from_encoded(&ua.encode(&st.network().network_type())).unwrap();

    let fee_rule = StandardFeeRule::Zip317;

    assert_matches!(
        st.propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        ),
        Err(data_api::error::Error::NoteSelection(
            GreedyInputSelectorError::UnsupportedAddress(_)
        ))
    );
}

/// Tests that a send-max proposal fails with `InsufficientFunds` when the entire wallet
/// balance would be consumed by fees, rather than proposing a transaction that delivers
/// nothing to the recipient.
pub fn send_max_fails_when_balance_is_consumed_by_fees<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds equal to the exact fee of a send-max transaction spending a single note
    // to a same-pool recipient (two logical actions under ZIP 317).
    let value = MINIMUM_FEE;
    st.add_a_single_note_checking_balance(value);

    let account = st.test_account().cloned().unwrap();
    let to: Address = T::sk_default_address(&T::sk(&[0xf5; 32]));
    let fee_rule = StandardFeeRule::Zip317;

    let addy = to.to_zcash_address(st.network());
    assert_matches!(
        st.propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        ),
        Err(data_api::error::Error::InsufficientFunds { available, required })
            if available == value && required > value
    );
}

/// Tests that attempting to send all the spendable funds within the given shielded pool in a
/// single transaction fail if there are funds that are not yet confirmed.
///
/// The test:
/// - Adds funds to the wallet in a single note.
/// - Checks that the wallet balances are correct.
/// - Mine empty blocks
/// - Add more funds
/// - Attempts to construct a request to spend the whole balance to an external address in the
///   same pool.
/// - catches failure
/// - verifies the failure is the one expected
pub fn spend_everything_proposal_fails_when_unconfirmed_funds_present<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
    st.add_notes_checking_balance([
        Some(Zatoshis::const_from_u64(60000)),
        None,
        None,
        Some(Zatoshis::const_from_u64(123456)),
    ]);

    // Spendable balance doesn't match total balance
    let account = st.test_account().cloned().unwrap();
    let total_balance = st.get_total_balance(account.id());
    let spendable_balance = st.get_spendable_balance(
        account.id(),
        ConfirmationsPolicy::new_symmetrical_unchecked(
            2,
            #[cfg(feature = "transparent-inputs")]
            true,
        ),
    );
    assert_ne!(total_balance, spendable_balance);

    let to_extsk = T::sk(&[0xf5; 32]);
    let to: Address = T::sk_default_address(&to_extsk);

    let fee_rule = StandardFeeRule::Zip317;

    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();

    let addy = to.to_zcash_address(st.network());
    assert_matches!(
        st.propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            Some(MemoBytes::from(send_max_memo.clone())),
            MaxSpendMode::Everything,
            ConfirmationsPolicy::new_symmetrical_unchecked(
                2,
                #[cfg(feature = "transparent-inputs")]
                true
            )
        ),
        Err(data_api::error::Error::DataSource(_))
    );
}

/// Tests that attempting to send `MaxSpendable` funds within the given shielded pool in a
/// single transaction succeeds if there are funds that are not yet confirmed.
///
/// The test:
/// - Adds funds to the wallet in a single note.
/// - Checks that the wallet balances are correct.
/// - Mine empty blocks
/// - Add more funds
/// - Attempts to construct a request to spend the whole balance to an external address in the
///   same pool.
/// - succeeds at doing so
pub fn send_max_spendable_proposal_succeeds_when_unconfirmed_funds_present<
    T: ShieldedPoolTester,
>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
    let h = st
        .add_notes_checking_balance([
            Some(Zatoshis::const_from_u64(60000)),
            None,
            None,
            Some(Zatoshis::const_from_u64(123456)),
        ])
        .block_height()
        .unwrap();

    // Spendable balance doesn't match total balance
    let account = st.test_account().cloned().unwrap();
    let total_balance = st.get_total_balance(account.id());
    let spendable_balance = st.get_spendable_balance(
        account.id(),
        ConfirmationsPolicy::new_symmetrical_unchecked(
            2,
            #[cfg(feature = "transparent-inputs")]
            true,
        ),
    );
    assert_ne!(total_balance, spendable_balance);

    let to_extsk = T::sk(&[0xf5; 32]);
    let to: Address = T::sk_default_address(&to_extsk);

    let fee_rule = StandardFeeRule::Zip317;

    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();

    let addy = to.to_zcash_address(st.network());
    let proposal = st
        .propose_send_max_transfer(
            account.id(),
            &fee_rule,
            addy,
            Some(MemoBytes::from(send_max_memo.clone())),
            MaxSpendMode::MaxSpendable,
            ConfirmationsPolicy::new_symmetrical_unchecked(
                2,
                #[cfg(feature = "transparent-inputs")]
                true,
            ),
        )
        .unwrap();

    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];

    // Verify that the sent transaction was stored and that we can decrypt the memos
    let tx = st
        .wallet()
        .get_transaction(sent_tx_id)
        .unwrap()
        .expect("Created transaction was stored.");
    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
        .into_iter()
        .collect();
    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 1);

    let mut found_send_max_memo = false;
    let mut found_tx_empty_memo = false;
    T::with_decrypted_pool_memos(&d_tx, |memo| {
        if Memo::try_from(memo).unwrap() == send_max_memo {
            found_send_max_memo = true
        }
        if Memo::try_from(memo).unwrap() == Memo::Empty {
            found_tx_empty_memo = true
        }
    });
    assert!(found_send_max_memo);
    assert!(!found_tx_empty_memo); // there's no empty memo in this case

    // Verify that the stored sent notes match what we're expecting
    let sent_note_ids = st
        .wallet()
        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(sent_note_ids.len(), 1);

    // The sent memo should the specified memo for the sent output
    let mut found_sent_empty_memo = false;
    let mut found_sent_max_memo = false;
    for sent_note_id in sent_note_ids {
        match st
            .wallet()
            .get_memo(sent_note_id)
            .expect("Memo retrieval should succeed")
            .as_ref()
        {
            Some(m) if m == &Memo::Empty => {
                found_sent_empty_memo = true;
            }
            Some(m) if m == &send_max_memo => {
                found_sent_max_memo = true;
            }
            Some(other) => panic!("Unexpected memo value: {other:?}"),
            None => panic!("Memo should not be stored as NULL"),
        }
    }

    assert!(found_sent_max_memo);
    assert!(!found_sent_empty_memo);

    // Check that querying for a nonexistent sent note returns None
    assert_matches!(
        st.wallet()
            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
        Ok(None)
    );

    let tx_history = st.wallet().get_tx_history().unwrap();
    assert_eq!(tx_history.len(), 2);
    {
        let tx_0 = &tx_history[0];
        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
    }

    {
        let tx_1 = &tx_history[1];
        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(0));
    }

    let network = *st.network();
    assert_matches!(
        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
        Ok(_)
    );
}

/// This test attempts to send the max spendable funds to a TEX address recipient
/// checks that the transactions were stored and that the amounts involved are correct
#[cfg(feature = "transparent-inputs")]
pub fn spend_everything_multi_step_single_note_proposed_transfer<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
        .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
        .build::<T>();

    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();

    let value = Zatoshis::const_from_u64(100000);

    // Add funds to the wallet.
    st.add_a_single_note_checking_balance(value);
    let initial_balance = value;
    assert_eq!(
        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
        initial_balance
    );

    let expected_step0_fee = (zip317::MARGINAL_FEE * 3u64).unwrap();
    let expected_step1_fee = zip317::MINIMUM_FEE;
    let expected_ephemeral_spend = (value - expected_step0_fee - expected_step1_fee).unwrap();
    let expected_ephemeral_balance = (value - expected_step0_fee).unwrap();
    let expected_step0_change = (value - expected_step0_fee).unwrap();

    let total_sent = (expected_step0_fee + expected_step1_fee + expected_ephemeral_spend).unwrap();

    // check that the napkin math is Ok. Total value send should be the whole
    // value of the wallet
    assert_eq!(total_sent, value);

    // Generate a ZIP 320 proposal, sending to an external TEX address.
    let tex_addr = Address::Tex([0x4; 20]);

    // TODO: Do we want to allow shielded change memos in ephemeral transfers?
    //let change_memo = Memo::from_str("change").expect("valid memo").encode();
    let fee_rule = StandardFeeRule::Zip317;

    // We use `st.propose_standard_transfer` here in order to also test round-trip
    // serialization of the proposal.
    let addy = tex_addr.to_zcash_address(st.network());
    let proposal = st
        .propose_send_max_transfer(
            account_id,
            &fee_rule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
    assert_eq!(steps.len(), 2);

    assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
    assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
    assert_eq!(
        steps[0].balance().proposed_change(),
        [
            // TODO: Do we want to allow shielded change memos in ephemeral transfers?
            //ChangeValue::shielded(
            //    T::SHIELDED_PROTOCOL,
            //    expected_step0_change,
            //    Some(change_memo)
            //),
            ChangeValue::ephemeral_transparent(
                (total_sent - expected_step0_fee).expect("value is non-zero")
            ),
        ]
    );
    assert_eq!(steps[1].balance().proposed_change(), []);

    let txids = st.create_proposed_expecting(&proposal, 2);

    // Mine the created transactions.
    for txid in txids.iter() {
        let (h, _) = st.generate_next_block_including(*txid);
        st.scan_cached_blocks(h, 1);
    }

    // Check that there are sent outputs with the correct values.
    let confirmed_sent: Vec<Vec<_>> = txids
        .iter()
        .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
        .collect();

    // Verify that a status request has been generated for the second transaction of
    // the ZIP 320 pair.
    let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
    assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));

    assert!(expected_step0_change > expected_ephemeral_spend);
    assert_eq!(confirmed_sent.len(), 2);
    assert_eq!(confirmed_sent[0].len(), 1);
    assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
    let OutputOfSentTx {
        value: ephemeral_v, ..
    } = confirmed_sent[0][0].clone();
    assert_eq!(ephemeral_v, expected_ephemeral_balance);

    assert_eq!(confirmed_sent[1].len(), 1);
    assert_matches!(
            &confirmed_sent[1][0],
            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
            if sent_v == &expected_ephemeral_spend && sent_to_addr == &Some(tex_addr));

    // Check that the transaction history matches what we expect.
    let tx_history = st.wallet().get_tx_history().unwrap();

    let tx_0 = tx_history
        .iter()
        .find(|tx| tx.txid() == *txids.first())
        .unwrap();
    let tx_1 = tx_history
        .iter()
        .find(|tx| tx.txid() == *txids.last())
        .unwrap();

    assert_eq!(tx_0.account_id(), &account_id);
    assert!(!tx_0.expired_unmined());
    assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
    assert!(!tx_0.is_shielding());
    assert_eq!(
        tx_0.account_value_delta(),
        -ZatBalance::from(expected_step0_fee),
    );

    assert_eq!(tx_1.account_id(), &account_id);
    assert!(!tx_1.expired_unmined());
    assert!(!tx_1.has_change());
    assert!(!tx_0.is_shielding());
    assert_eq!(
        tx_1.account_value_delta(),
        -ZatBalance::from(expected_ephemeral_balance),
    );

    let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
    assert_eq!(initial_balance - total_sent, ending_balance.into());
}

/// This test attempts to send the max spendable funds to a TEX address recipient
/// checks that the transactions were stored and that the amounts involved are correct
#[cfg(feature = "transparent-inputs")]
pub fn spend_everything_multi_step_many_notes_proposed_transfer<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
        .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
        .build::<T>();

    let number_of_notes = 3u64;
    let note_value = Zatoshis::const_from_u64(100000);
    let value = (note_value * number_of_notes).unwrap();

    // Add funds to the wallet.
    for _ in 0..number_of_notes {
        st.add_a_single_note_checking_balance(note_value);
    }

    let initial_balance = value;
    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    assert_eq!(
        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
        initial_balance
    );

    let expected_step0_fee = (zip317::MARGINAL_FEE * 4u64).unwrap();
    let expected_step1_fee = zip317::MINIMUM_FEE;
    let expected_ephemeral_spend = (value - expected_step0_fee - expected_step1_fee).unwrap();
    let expected_ephemeral_balance = (value - expected_step0_fee).unwrap();
    let expected_step0_change = (value - expected_step0_fee).unwrap();

    let total_sent = (expected_step0_fee + expected_step1_fee + expected_ephemeral_spend).unwrap();

    // check that the napkin math is Ok. Total value send should be the whole
    // value of the wallet
    assert_eq!(total_sent, value);

    // Generate a ZIP 320 proposal, sending to an external TEX address.
    let tex_addr = Address::Tex([0x4; 20]);
    let fee_rule = StandardFeeRule::Zip317;

    // We use `st.propose_standard_transfer` here in order to also test round-trip
    // serialization of the proposal.
    let addy = tex_addr.to_zcash_address(st.network());
    let proposal = st
        .propose_send_max_transfer(
            account_id,
            &fee_rule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
    assert_eq!(steps.len(), 2);

    assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
    assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
    assert_eq!(
        steps[0].balance().proposed_change(),
        [ChangeValue::ephemeral_transparent(
            (total_sent - expected_step0_fee).expect("value is non-zero")
        ),]
    );
    assert_eq!(steps[1].balance().proposed_change(), []);

    let txids = st.create_proposed_expecting(&proposal, 2);

    // Mine the created transactions.
    for txid in txids.iter() {
        let (h, _) = st.generate_next_block_including(*txid);
        st.scan_cached_blocks(h, 1);
    }

    // Check that there are sent outputs with the correct values.
    let confirmed_sent: Vec<Vec<_>> = txids
        .iter()
        .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
        .collect();

    // Verify that a status request has been generated for the second transaction of
    // the ZIP 320 pair.
    let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
    assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));

    assert!(expected_step0_change > expected_ephemeral_spend);
    assert_eq!(confirmed_sent.len(), 2);
    assert_eq!(confirmed_sent[0].len(), 1);
    assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
    let OutputOfSentTx {
        value: ephemeral_v, ..
    } = confirmed_sent[0][0].clone();
    assert_eq!(ephemeral_v, expected_ephemeral_balance);

    assert_eq!(confirmed_sent[1].len(), 1);
    assert_matches!(
            &confirmed_sent[1][0],
            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
            if sent_v == &expected_ephemeral_spend && sent_to_addr == &Some(tex_addr));

    // Check that the transaction history matches what we expect.
    let tx_history = st.wallet().get_tx_history().unwrap();

    let tx_0 = tx_history
        .iter()
        .find(|tx| tx.txid() == *txids.first())
        .unwrap();
    let tx_1 = tx_history
        .iter()
        .find(|tx| tx.txid() == *txids.last())
        .unwrap();

    assert_eq!(tx_0.account_id(), &account_id);
    assert!(!tx_0.expired_unmined());
    assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
    assert!(!tx_0.is_shielding());
    assert_eq!(
        tx_0.account_value_delta(),
        -ZatBalance::from(expected_step0_fee),
    );

    assert_eq!(tx_1.account_id(), &account_id);
    assert!(!tx_1.expired_unmined());
    assert!(!tx_1.has_change());
    assert!(!tx_0.is_shielding());
    assert_eq!(
        tx_1.account_value_delta(),
        -ZatBalance::from(expected_ephemeral_balance),
    );

    let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
    assert_eq!(initial_balance - total_sent, ending_balance.into());
}

/// This test attempts to send the max spendable funds to a TEX address recipient.
/// The wallet contains many notes denominated with the marginal fee value.
/// Checks that the transactions were stored and that the amounts involved are correct
#[cfg(feature = "transparent-inputs")]
pub fn spend_everything_multi_step_with_marginal_notes_proposed_transfer<
    T: ShieldedPoolTester,
    Dsf,
>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
        .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
        .build::<T>();

    let number_of_notes = 10u64;
    let note_value = Zatoshis::const_from_u64(100000);
    let non_marginal_notes_value =
        (note_value * number_of_notes).expect("sum of notes should not fail.");

    for _ in 0..number_of_notes {
        st.add_a_single_note_checking_balance(note_value);
        st.add_a_single_note_checking_balance(zip317::MARGINAL_FEE);
    }

    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    assert_eq!(
        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
        non_marginal_notes_value
    );

    let expected_step0_fee = (zip317::MARGINAL_FEE * (number_of_notes + 1)).unwrap();
    let expected_step1_fee = zip317::MINIMUM_FEE;
    let expected_ephemeral_spend =
        (non_marginal_notes_value - expected_step0_fee - expected_step1_fee).unwrap();
    let expected_ephemeral_balance = (non_marginal_notes_value - expected_step0_fee).unwrap();
    let expected_step0_change = (non_marginal_notes_value - expected_step0_fee).unwrap();

    let total_sent = (expected_step0_fee + expected_step1_fee + expected_ephemeral_spend).unwrap();

    // check that the napkin math is Ok. Total value send should be the whole
    // value of the wallet
    assert_eq!(total_sent, non_marginal_notes_value);

    // Generate a ZIP 320 proposal, sending to an external TEX address.
    let tex_addr = Address::Tex([0x4; 20]);

    let fee_rule = StandardFeeRule::Zip317;

    // We use `st.propose_standard_transfer` here in order to also test round-trip
    // serialization of the proposal.
    let addy = tex_addr.to_zcash_address(st.network());
    let proposal = st
        .propose_send_max_transfer(
            account_id,
            &fee_rule,
            addy,
            None,
            MaxSpendMode::Everything,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
    assert_eq!(steps.len(), 2);

    assert_eq!(
        steps[0].shielded_inputs().unwrap().notes().len() as u64,
        number_of_notes
    );
    assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
    assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
    assert_eq!(
        steps[0].balance().proposed_change(),
        [ChangeValue::ephemeral_transparent(
            (total_sent - expected_step0_fee).expect("value is non-zero")
        ),]
    );
    assert_eq!(steps[1].balance().proposed_change(), []);

    let txids = st.create_proposed_expecting(&proposal, 2);

    // Mine the created transactions.
    for txid in txids.iter() {
        let (h, _) = st.generate_next_block_including(*txid);
        st.scan_cached_blocks(h, 1);
    }

    // Check that there are sent outputs with the correct values.
    let confirmed_sent: Vec<Vec<_>> = txids
        .iter()
        .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
        .collect();

    // Verify that a status request has been generated for the second transaction of
    // the ZIP 320 pair.
    let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
    assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));

    assert!(expected_step0_change > expected_ephemeral_spend);
    assert_eq!(confirmed_sent.len(), 2);
    assert_eq!(confirmed_sent[0].len(), 1);
    assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
    let OutputOfSentTx {
        value: ephemeral_v, ..
    } = confirmed_sent[0][0].clone();
    assert_eq!(ephemeral_v, expected_ephemeral_balance);

    assert_eq!(confirmed_sent[1].len(), 1);
    assert_matches!(
            &confirmed_sent[1][0],
            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
            if sent_v == &expected_ephemeral_spend && sent_to_addr == &Some(tex_addr));

    // Check that the transaction history matches what we expect.
    let tx_history = st.wallet().get_tx_history().unwrap();

    let tx_0 = tx_history
        .iter()
        .find(|tx| tx.txid() == *txids.first())
        .unwrap();
    let tx_1 = tx_history
        .iter()
        .find(|tx| tx.txid() == *txids.last())
        .unwrap();

    assert_eq!(tx_0.account_id(), &account_id);
    assert!(!tx_0.expired_unmined());
    assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
    assert!(!tx_0.is_shielding());
    assert_eq!(
        tx_0.account_value_delta(),
        -ZatBalance::from(expected_step0_fee),
    );

    assert_eq!(tx_1.account_id(), &account_id);
    assert!(!tx_1.expired_unmined());
    assert!(!tx_1.has_change());
    assert!(!tx_0.is_shielding());
    assert_eq!(
        tx_1.account_value_delta(),
        -ZatBalance::from(expected_ephemeral_balance),
    );

    let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
    assert_eq!(ending_balance, Zatoshis::ZERO); // ending balance should be zero
}

pub fn send_with_multiple_change_outputs<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note
    let value = Zatoshis::const_from_u64(650_0000);
    let (h, _, _) = st.add_a_single_note_checking_balance(value);

    let to_extsk = T::sk(&[0xf5; 32]);
    let to: Address = T::sk_default_address(&to_extsk);
    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        Zatoshis::const_from_u64(100_0000),
    )])
    .unwrap();

    let input_selector = GreedyInputSelector::new();
    let change_memo = "Test change memo".parse::<Memo>().unwrap();
    let change_strategy = fees::zip317::MultiOutputChangeStrategy::new(
        Zip317FeeRule::standard(),
        Some(change_memo.clone().into()),
        T::SHIELDED_PROTOCOL,
        DustOutputPolicy::default(),
        SplitPolicy::with_min_output_value(
            NonZeroUsize::new(2).unwrap(),
            Zatoshis::const_from_u64(100_0000),
        ),
    );

    let account = st.test_account().cloned().unwrap();
    let proposal = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request.clone(),
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let step = &proposal.steps().head;
    assert_eq!(step.balance().proposed_change().len(), 2);

    let create_proposed_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
        account.usk(),
        OvkPolicy::Sender,
        &proposal,
    );
    assert_matches!(&create_proposed_result, Ok(txids) if txids.len() == 1);

    let sent_tx_id = create_proposed_result.unwrap()[0];

    // Verify that the sent transaction was stored and that we can decrypt the memos
    let tx = st
        .wallet()
        .get_transaction(sent_tx_id)
        .unwrap()
        .expect("Created transaction was stored.");
    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
        .into_iter()
        .collect();
    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 3);

    let mut found_tx_change_memo = false;
    let mut found_tx_empty_memo = false;
    T::with_decrypted_pool_memos(&d_tx, |memo| {
        if Memo::try_from(memo).unwrap() == change_memo {
            found_tx_change_memo = true
        }
        if Memo::try_from(memo).unwrap() == Memo::Empty {
            found_tx_empty_memo = true
        }
    });
    assert!(found_tx_change_memo);
    assert!(found_tx_empty_memo);

    // Verify that the stored sent notes match what we're expecting
    let sent_note_ids = st
        .wallet()
        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(sent_note_ids.len(), 3);

    // The sent memo should be the empty memo for the sent output, and each
    // change output's memo should be as specified.
    let mut change_memo_count = 0;
    let mut found_sent_empty_memo = false;
    for sent_note_id in sent_note_ids {
        match st
            .wallet()
            .get_memo(sent_note_id)
            .expect("Note id is valid")
            .as_ref()
        {
            Some(m) if m == &change_memo => {
                change_memo_count += 1;
            }
            Some(m) if m == &Memo::Empty => {
                found_sent_empty_memo = true;
            }
            Some(other) => panic!("Unexpected memo value: {other:?}"),
            None => panic!("Memo should not be stored as NULL"),
        }
    }
    assert_eq!(change_memo_count, 2);
    assert!(found_sent_empty_memo);

    let tx_history = st.wallet().get_tx_history().unwrap();
    assert_eq!(tx_history.len(), 2);
    {
        let tx_0 = &tx_history[0];
        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(650_0000));
    }

    {
        let tx_1 = &tx_history[1];
        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(650_0000));
        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(548_5000));
        assert_eq!(tx_1.fee_paid(), Some(Zatoshis::const_from_u64(15000)));
    }

    let network = *st.network();
    assert_matches!(
        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
        Ok(_)
    );

    let (h, _) = st.generate_next_block_including(sent_tx_id);
    st.scan_cached_blocks(h, 1);

    // Now, create another proposal with more outputs requested. We have two change notes;
    // we'll spend one of them, and then we'll generate 7 splits.
    let change_strategy = fees::zip317::MultiOutputChangeStrategy::new(
        Zip317FeeRule::standard(),
        Some(change_memo.into()),
        T::SHIELDED_PROTOCOL,
        DustOutputPolicy::default(),
        SplitPolicy::with_min_output_value(
            NonZeroUsize::new(8).unwrap(),
            Zatoshis::const_from_u64(10_0000),
        ),
    );

    let proposal = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let step = &proposal.steps().head;
    assert_eq!(step.balance().proposed_change().len(), 7);
}

#[cfg(feature = "transparent-inputs")]
pub fn send_multi_step_proposed_transfer<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
    is_reached_gap_limit: impl Fn(&<Dsf::DataStore as WalletRead>::Error, Dsf::AccountId, u32) -> bool,
) where
    Dsf: DataStoreFactory,
{
    let gap_limits = GapLimits::new(10, 5, 3);
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
        .map(|builder| builder.with_gap_limits(gap_limits))
        .build::<T>();

    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    let dfvk = T::test_account_fvk(&st);
    let tex_addr = Address::Tex([0x4; 20]);

    let add_funds = |st: &mut TestState<_, Dsf::DataStore, _>, value| {
        let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
        st.scan_cached_blocks(h, 1);

        assert_eq!(
            st.wallet()
                .block_max_scanned()
                .unwrap()
                .unwrap()
                .block_height(),
            h
        );
        h
    };

    let value = Zatoshis::const_from_u64(100000);
    let transfer_amount = Zatoshis::const_from_u64(50000);

    let run_test = |st: &mut TestState<_, Dsf::DataStore, _>, expected_index, prior_balance| {
        // Add funds to the wallet.
        add_funds(st, value);
        let initial_balance: Option<Zatoshis> = prior_balance + value;
        assert_eq!(
            st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
            initial_balance.unwrap()
        );

        let expected_step0_fee = (zip317::MARGINAL_FEE * 3u64).unwrap();
        let expected_step1_fee = zip317::MINIMUM_FEE;
        let expected_ephemeral = (transfer_amount + expected_step1_fee).unwrap();
        let expected_step0_change =
            (initial_balance - expected_ephemeral - expected_step0_fee).expect("sufficient funds");
        assert!(expected_step0_change.is_positive());

        let total_sent = (expected_step0_fee + expected_step1_fee + transfer_amount).unwrap();

        // Generate a ZIP 320 proposal, sending to another wallet's default transparent address
        // expressed as a TEX address.
        let change_memo = Some(Memo::from_str("change").expect("valid memo").encode());

        // We use `st.propose_standard_transfer` here in order to also test round-trip
        // serialization of the proposal.
        let proposal = st
            .propose_standard_transfer::<Infallible>(
                account_id,
                StandardFeeRule::Zip317,
                ConfirmationsPolicy::MIN,
                &tex_addr,
                transfer_amount,
                None,
                change_memo.clone(),
                T::SHIELDED_PROTOCOL,
            )
            .unwrap();

        let steps: Vec<_> = proposal.steps().iter().cloned().collect();
        assert_eq!(steps.len(), 2);

        assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
        assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
        assert_eq!(
            steps[0].balance().proposed_change(),
            [
                ChangeValue::shielded(T::SHIELDED_PROTOCOL, expected_step0_change, change_memo),
                ChangeValue::ephemeral_transparent(expected_ephemeral),
            ]
        );
        assert_eq!(steps[1].balance().proposed_change(), []);

        // There should be no ephemeral addresses exposed at the current chain height
        let exposed_at_tip = st
            .wallet()
            .get_ephemeral_transparent_receivers(account.account().id(), 1, false)
            .unwrap();
        assert_eq!(exposed_at_tip.len(), 0);

        let create_proposed_result = st
            .create_proposed_transactions::<Infallible, _, Infallible, _>(
                account.usk(),
                OvkPolicy::Sender,
                &proposal,
            );
        assert_matches!(&create_proposed_result, Ok(txids) if txids.len() == 2);
        let txids = create_proposed_result.unwrap();

        // After creation, there should be a new ephemeral address exposed.
        let exposed_at_tip = st
            .wallet()
            .get_ephemeral_transparent_receivers(account.account().id(), 1, false)
            .unwrap();
        assert_eq!(exposed_at_tip.len(), 1);
        let cur_height = st.wallet().chain_height().unwrap().unwrap();
        assert_matches!(
            exposed_at_tip.values().next().map(|m0| m0.exposure()),
            Some(Exposure::Exposed { at_height, .. }) if at_height == cur_height
        );

        // There should be no unused transparent receivers in this range
        let exposed_at_tip = st
            .wallet()
            .get_ephemeral_transparent_receivers(account.account().id(), 1, true)
            .unwrap();
        assert!(exposed_at_tip.is_empty());

        // Mine the created transactions.
        for txid in txids.iter() {
            let (h, _) = st.generate_next_block_including(*txid);
            st.scan_cached_blocks(h, 1);
        }

        // Check that there are sent outputs with the correct values.
        let confirmed_sent: Vec<Vec<_>> = txids
            .iter()
            .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
            .collect();

        // Verify that a status request has been generated for the second transaction of
        // the ZIP 320 pair.
        let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
        assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));

        assert!(expected_step0_change < expected_ephemeral);
        assert_eq!(confirmed_sent.len(), 2);
        assert_eq!(confirmed_sent[0].len(), 2);
        assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
        let OutputOfSentTx {
            value: ephemeral_v,
            external_recipient: to_addr,
            ephemeral_address,
        } = confirmed_sent[0][1].clone();
        assert_eq!(ephemeral_v, expected_ephemeral);
        assert!(to_addr.is_some());
        assert_eq!(
            ephemeral_address,
            to_addr.map(|addr| (
                addr,
                NonHardenedChildIndex::const_from_index(expected_index)
            )),
        );

        assert_eq!(confirmed_sent[1].len(), 1);
        assert_matches!(
            &confirmed_sent[1][0],
            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
            if sent_v == &transfer_amount && sent_to_addr.as_ref() == Some(&tex_addr));

        // Check that the transaction history matches what we expect.
        let tx_history = st.wallet().get_tx_history().unwrap();

        let tx_0 = tx_history
            .iter()
            .find(|tx| tx.txid() == *txids.first())
            .unwrap();
        let tx_1 = tx_history
            .iter()
            .find(|tx| tx.txid() == *txids.last())
            .unwrap();

        assert_eq!(tx_0.account_id(), &account_id);
        assert!(!tx_0.expired_unmined());
        assert_eq!(tx_0.has_change(), expected_step0_change.is_positive());
        assert!(!tx_0.is_shielding());
        assert_eq!(
            tx_0.account_value_delta(),
            -ZatBalance::from(expected_step0_fee),
        );

        assert_eq!(tx_1.account_id(), &account_id);
        assert!(!tx_1.expired_unmined());
        assert!(!tx_1.has_change());
        assert!(!tx_0.is_shielding());
        assert_eq!(
            tx_1.account_value_delta(),
            -ZatBalance::from(expected_ephemeral),
        );

        let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
        assert_eq!(initial_balance - total_sent, ending_balance.into());

        (ephemeral_address.unwrap().0, txids, ending_balance)
    };

    // Each transfer should use a different ephemeral address.
    let (ephemeral0, _, bal_0) = run_test(&mut st, 0, Zatoshis::ZERO);
    let (ephemeral1, _, _) = run_test(&mut st, 1, bal_0);
    assert_ne!(ephemeral0, ephemeral1);

    add_funds(&mut st, value);

    assert_matches!(
        ephemeral0,
        Address::Transparent(TransparentAddress::PublicKeyHash(_))
    );

    // Simulate another wallet sending to an ephemeral address with an index
    // within the current gap limit.
    let known_addrs = st
        .wallet()
        .get_known_ephemeral_addresses(account_id, None)
        .unwrap();
    assert_eq!(
        known_addrs.len(),
        usize::try_from(gap_limits.ephemeral() + 2).unwrap()
    );

    // Check that the addresses are all distinct.
    let known_set: HashSet<_> = known_addrs.iter().map(|(addr, _)| addr).collect();
    assert_eq!(known_set.len(), known_addrs.len());
    // Check that the metadata is as expected.
    for (i, (_, meta)) in known_addrs.iter().enumerate() {
        assert_eq!(
            meta.source(),
            &TransparentAddressSource::Derived {
                scope: TransparentKeyScope::EPHEMERAL,
                address_index: NonHardenedChildIndex::from_index(i.try_into().unwrap()).unwrap(),
            }
        );
    }

    let (colliding_addr, _) = &known_addrs[usize::try_from(gap_limits.ephemeral() - 1).unwrap()];
    let utxo_value = (value - zip317::MINIMUM_FEE).unwrap();
    let to = Address::from(*colliding_addr);
    let proposal = st.propose_transfer_to(&to, utxo_value);

    // Create the transaction. This will cause the the gap start to move & a new
    // `gap_limits.ephemeral()` of addresses to be created.
    let txids = st
        .create_proposed_transactions::<Infallible, _, Infallible, _>(
            account.usk(),
            OvkPolicy::Sender,
            &proposal,
        )
        .unwrap();

    // Mine the transaction & update its status to advance the gap. We have to manually update the
    // status because scanning will not detect the transparent outputs.
    let (h, _) = st.generate_next_block_including(txids.head);
    st.scan_cached_blocks(h, 1);
    st.wallet_mut()
        .set_transaction_status(txids.head, TransactionStatus::Mined(h))
        .unwrap();

    // At this point the start of the gap should be at index `gap_limits.ephemeral()` and the new
    // size of the known address set should be `gap_limits.ephemeral() * 2`.
    let new_known_addrs = st
        .wallet()
        .get_known_ephemeral_addresses(account_id, None)
        .unwrap();
    assert_eq!(
        new_known_addrs.len(),
        usize::try_from(gap_limits.ephemeral() * 2).unwrap()
    );

    // check that known_addrs is a prefix of new_known_addrs; we have already checked their
    // lengths.
    assert!(
        new_known_addrs
            .iter()
            .map(|a| a.0)
            .zip(known_addrs.iter().map(|a| a.0))
            .all(|(a, b)| a == b),
        "new_known_addrs must have known_addrs as its prefix"
    );

    let reservation_should_succeed = |st: &mut TestState<_, Dsf::DataStore, _>, n: u32| {
        let reserved = st
            .wallet_mut()
            .reserve_next_n_ephemeral_addresses(account_id, n.try_into().unwrap())
            .unwrap();
        assert_eq!(reserved.len(), usize::try_from(n).unwrap());
        reserved
    };
    let reservation_should_fail =
        |st: &mut TestState<_, Dsf::DataStore, _>, n: u32, expected_bad_index| {
            assert_matches!(st
            .wallet_mut()
            .reserve_next_n_ephemeral_addresses(account_id, n.try_into().unwrap()),
            Err(e) if is_reached_gap_limit(&e, account_id, expected_bad_index));
        };

    assert_matches!(
        known_addrs[usize::try_from(gap_limits.ephemeral()).unwrap()]
            .1
            .exposure(),
        Exposure::Unknown
    );

    let next_reserved = reservation_should_succeed(&mut st, 1);

    // By reserving the address, its exposure has transitioned from "unknown" to "exposed".
    let gap_position = 0;
    let expected = &known_addrs[usize::try_from(gap_limits.ephemeral()).unwrap()];
    let actual = &next_reserved[usize::try_from(gap_position).unwrap()];
    assert_eq!(actual.0, expected.0);
    assert_eq!(actual.1.source(), expected.1.source());
    assert_eq!(expected.1.exposure(), Exposure::Unknown);
    assert_eq!(
        actual.1.exposure(),
        Exposure::Exposed {
            at_height: st.latest_block_height.unwrap(),
            gap_metadata: crate::wallet::GapMetadata::InGap {
                gap_position,
                gap_limit: gap_limits.ephemeral(),
            }
        }
    );

    // The range of address indices that are safe to reserve now is
    // 0..(gap_limits.ephemeral() * 2 - 1)`, and we have already reserved or used
    // `gap_limits.ephemeral() + 1`, addresses, so trying to reserve another
    // `gap_limits.ephemeral()` should fail.
    reservation_should_fail(&mut st, gap_limits.ephemeral(), gap_limits.ephemeral() * 2);
    reservation_should_succeed(&mut st, gap_limits.ephemeral() - 1);
    // Now we've reserved everything we can, we can't reserve one more
    reservation_should_fail(&mut st, 1, gap_limits.ephemeral() * 2);
}

/// Tests spending all funds within the given shielded pool in a single transaction.
///
/// The test:
/// - Adds funds to the wallet in a single note.
/// - Checks that the wallet balances are correct.
/// - Constructs a request to spend all of that balance to an external address in the
///   same pool.
/// - Builds the transaction.
/// - Checks that the transaction was stored, and that the outputs are decryptable and
///   have the expected details.
pub fn spend_all_funds_single_step_proposed_transfer<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in a single note
    let value = Zatoshis::const_from_u64(60000);
    let (h, _, _) = st.add_a_single_note_checking_balance(value);

    let spend_amount = Zatoshis::const_from_u64(50000);
    let to_extsk = T::sk(&[0xf5; 32]);
    let to: Address = T::sk_default_address(&to_extsk);
    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        spend_amount,
    )])
    .unwrap();

    let fee_rule = StandardFeeRule::Zip317;

    let change_memo = "Test change memo".parse::<Memo>().unwrap();
    let change_strategy = standard::SingleOutputChangeStrategy::new(
        fee_rule,
        Some(change_memo.clone().into()),
        T::SHIELDED_PROTOCOL,
        DustOutputPolicy::default(),
    );
    let input_selector = GreedyInputSelector::new();

    let account = st.test_account().cloned().unwrap();
    let proposal = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];

    // Verify that the sent transaction was stored and that we can decrypt the memos
    let tx = st
        .wallet()
        .get_transaction(sent_tx_id)
        .unwrap()
        .expect("Created transaction was stored.");
    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
        .into_iter()
        .collect();
    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 2);

    let mut found_tx_change_memo = false;
    let mut found_tx_empty_memo = false;
    T::with_decrypted_pool_memos(&d_tx, |memo| {
        if Memo::try_from(memo).unwrap() == change_memo {
            found_tx_change_memo = true
        }
        if Memo::try_from(memo).unwrap() == Memo::Empty {
            found_tx_empty_memo = true
        }
    });
    assert!(found_tx_change_memo);
    assert!(found_tx_empty_memo);

    // Verify that the stored sent notes match what we're expecting
    let sent_note_ids = st
        .wallet()
        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(sent_note_ids.len(), 2);

    // The sent memo should be the empty memo for the sent output, and the
    // change output's memo should be as specified.
    let mut found_sent_change_memo = false;
    let mut found_sent_empty_memo = false;
    for sent_note_id in sent_note_ids {
        match st
            .wallet()
            .get_memo(sent_note_id)
            .expect("Note id is valid")
            .as_ref()
        {
            Some(m) if m == &change_memo => {
                found_sent_change_memo = true;
            }
            Some(m) if m == &Memo::Empty => {
                found_sent_empty_memo = true;
            }
            Some(other) => panic!("Unexpected memo value: {other:?}"),
            None => panic!("Memo should not be stored as NULL"),
        }
    }
    assert!(found_sent_change_memo);
    assert!(found_sent_empty_memo);

    // Check that querying for a nonexistent sent note returns None
    assert_matches!(
        st.wallet()
            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
        Ok(None)
    );

    let tx_history = st.wallet().get_tx_history().unwrap();
    assert_eq!(tx_history.len(), 2);
    {
        let tx_0 = &tx_history[0];
        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
    }

    {
        let tx_1 = &tx_history[1];
        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
        assert_eq!(tx_1.total_received(), Zatoshis::ZERO);
    }

    let network = *st.network();
    assert_matches!(
        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
        Ok(_)
    );
}
/// Test attempts to sweep a wallet into a TEX address
///
/// 1. funds wallet with 100000 Zatoshis
/// 2. sets that spend amount will be 75000 Zatoshi
/// 3. proposes a transaction to a TEX address spending 75000 Zatoshi
/// 4. attempts to perform the proposal
/// 5. proposes the transaction
/// 6. "mines" the transaction.
/// 7. checks that all funds have been spent by the two involved transactions
///
/// Desired effects:
/// - all funds are spent
/// - Fees are the least possible: in this case 15000 for tr0 and 10000 Zats for tr1
#[cfg(feature = "transparent-inputs")]
pub fn spend_all_funds_multi_step_proposed_transfer<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
        .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
        .build::<T>();

    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    let dfvk = T::test_account_fvk(&st);

    let value = Zatoshis::const_from_u64(100000);
    let transfer_amount = Zatoshis::const_from_u64(75000);

    // Add funds to the wallet.
    let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
    st.scan_cached_blocks(h, 1);

    let initial_balance = value;
    assert_eq!(
        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
        initial_balance
    );

    let expected_step0_fee = (zip317::MARGINAL_FEE * 3u64).unwrap();
    let expected_step1_fee = zip317::MINIMUM_FEE;
    let expected_ephemeral = (transfer_amount + expected_step1_fee).unwrap();
    let expected_step0_change =
        (initial_balance - expected_ephemeral - expected_step0_fee).expect("sufficient funds");
    assert!(expected_step0_change.is_zero());

    let total_sent = (expected_step0_fee + expected_step1_fee + transfer_amount).unwrap();

    // Generate a ZIP 320 proposal, sending to an external TEX address.
    let tex_addr = Address::Tex([0x4; 20]);

    let change_memo: Option<MemoBytes> = None;
    // `propose_transfer_to` proposes a standard transfer, so this also tests
    // round-trip serialization of the proposal.
    let proposal = st.propose_transfer_to(&tex_addr, transfer_amount);

    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
    assert_eq!(steps.len(), 2);

    assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
    assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
    assert_eq!(
        steps[0].balance().proposed_change(),
        [
            ChangeValue::shielded(T::SHIELDED_PROTOCOL, expected_step0_change, change_memo),
            ChangeValue::ephemeral_transparent(expected_ephemeral),
        ]
    );
    assert_eq!(steps[1].balance().proposed_change(), []);

    let txids = st.create_proposed_expecting(&proposal, 2);

    // Mine the created transactions.
    for txid in txids.iter() {
        let (h, _) = st.generate_next_block_including(*txid);
        st.scan_cached_blocks(h, 1);
    }

    // Check that there are sent outputs with the correct values.
    let confirmed_sent: Vec<Vec<_>> = txids
        .iter()
        .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
        .collect();

    // Verify that a status request has been generated for the second transaction of
    // the ZIP 320 pair.
    let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
    assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));

    assert!(expected_step0_change < expected_ephemeral);
    assert_eq!(confirmed_sent.len(), 2);
    assert_eq!(confirmed_sent[0].len(), 2);
    assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
    let OutputOfSentTx {
        value: ephemeral_v,
        external_recipient: to_addr,
        ephemeral_address: _,
    } = confirmed_sent[0][1].clone();
    assert_eq!(ephemeral_v, expected_ephemeral);
    assert!(to_addr.is_some());

    assert_eq!(confirmed_sent[1].len(), 1);
    assert_matches!(
            &confirmed_sent[1][0],
            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
            if sent_v == &transfer_amount && sent_to_addr == &Some(tex_addr));

    // Check that the transaction history matches what we expect.
    let tx_history = st.wallet().get_tx_history().unwrap();

    let tx_0 = tx_history
        .iter()
        .find(|tx| tx.txid() == *txids.first())
        .unwrap();
    let tx_1 = tx_history
        .iter()
        .find(|tx| tx.txid() == *txids.last())
        .unwrap();

    assert_eq!(tx_0.account_id(), &account_id);
    assert!(!tx_0.expired_unmined());
    assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
    assert!(!tx_0.is_shielding());
    assert_eq!(
        tx_0.account_value_delta(),
        -ZatBalance::from(expected_step0_fee),
    );

    assert_eq!(tx_1.account_id(), &account_id);
    assert!(!tx_1.expired_unmined());
    assert!(!tx_1.has_change());
    assert!(!tx_0.is_shielding());
    assert_eq!(
        tx_1.account_value_delta(),
        -ZatBalance::from(expected_ephemeral),
    );

    let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
    assert_eq!(initial_balance - total_sent, ending_balance.into());
}

#[cfg(feature = "transparent-inputs")]
pub fn proposal_fails_if_not_all_ephemeral_outputs_consumed<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    let dfvk = T::test_account_fvk(&st);

    let add_funds = |st: &mut TestState<_, Dsf::DataStore, _>, value| {
        let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
        st.scan_cached_blocks(h, 1);

        assert_eq!(
            st.wallet()
                .block_max_scanned()
                .unwrap()
                .unwrap()
                .block_height(),
            h
        );
        assert_eq!(
            st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
            value
        );
    };

    let value = Zatoshis::const_from_u64(100000);
    let transfer_amount = Zatoshis::const_from_u64(50000);

    // Add funds to the wallet.
    add_funds(&mut st, value);

    // Generate a ZIP 320 proposal, sending to an external TEX address.
    let tex_addr = Address::Tex([0x4; 20]);
    let proposal = st.propose_transfer_to(&tex_addr, transfer_amount);

    // This is somewhat redundant with `send_multi_step_proposed_transfer`,
    // but tests the case with no change memo and ensures we haven't messed
    // up the test setup.
    let create_proposed_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
        account.usk(),
        OvkPolicy::Sender,
        &proposal,
    );
    assert_matches!(create_proposed_result, Ok(_));

    // Frobnicate the proposal to make it invalid because it does not consume
    // the ephemeral output, by truncating it to the first step.
    let frobbed_proposal = Proposal::multi_step(
        *proposal.fee_rule(),
        proposal.min_target_height(),
        proposal.confirmations_policy(),
        NonEmpty::singleton(proposal.steps().first().clone()),
    )
    .unwrap();

    let create_proposed_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
        account.usk(),
        OvkPolicy::Sender,
        &frobbed_proposal,
    );
    assert_matches!(
        create_proposed_result,
        Err(Error::Proposal(ProposalError::EphemeralOutputLeftUnspent(so)))
        if so == StepOutput::new(0, StepOutputIndex::Change(1))
    );
}

pub fn create_to_address_fails_on_incorrect_usk<T: ShieldedPoolTester, Dsf: DataStoreFactory>(
    ds_factory: Dsf,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, ()).build::<T>();
    let dfvk = T::test_account_fvk(&st);
    let to = T::fvk_default_address(&dfvk);

    // Create a USK that doesn't exist in the wallet
    let acct1 = zip32::AccountId::try_from(1).unwrap();
    let usk1 = UnifiedSpendingKey::from_seed(st.network(), &[1u8; 32], acct1).unwrap();

    let input_selector = GreedyInputSelector::<Dsf::DataStore>::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);

    let req = TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        Zatoshis::const_from_u64(1),
    )])
    .unwrap();

    // Attempting to spend with a USK that is not in the wallet results in an error
    assert_matches!(
        st.spend(
            &input_selector,
            &change_strategy,
            &usk1,
            req,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        ),
        Err(data_api::error::Error::KeyNotRecognized)
    );
}

pub fn proposal_fails_with_no_blocks<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf)
where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, ()).build::<T>();

    let account_id = st.test_account().unwrap().id();
    let dfvk = T::test_account_fvk(&st);
    let to = T::fvk_default_address(&dfvk);

    // Wallet summary is not yet available
    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);

    // We cannot do anything if we aren't synchronised
    assert_matches!(
        st.propose_standard_transfer::<Infallible>(
            account_id,
            StandardFeeRule::Zip317,
            ConfirmationsPolicy::MIN,
            &to,
            Zatoshis::const_from_u64(1),
            None,
            None,
            T::SHIELDED_PROTOCOL,
        ),
        Err(data_api::error::Error::ScanRequired)
    );
}

pub fn spend_fails_on_unverified_notes<T: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    let dfvk = T::test_account_fvk(&st);

    // Add funds to the wallet in a single note
    let value = Zatoshis::const_from_u64(50000);
    st.add_a_single_note_checking_balance(value);

    // Value is considered pending at 10 confirmations.
    assert_eq!(
        st.get_pending_shielded_balance(account_id, ConfirmationsPolicy::default()),
        value
    );
    assert_eq!(
        st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
        Zatoshis::ZERO
    );

    // If none of the wallet's accounts have a recover-until height, then there
    // is no recovery phase for the wallet, and therefore the denominator in the
    // resulting ratio (the number of notes in the recovery range) is zero.
    let no_recovery = Some(Ratio::new(0, 0));

    // Wallet is fully scanned
    let summary = st.get_wallet_summary(ConfirmationsPolicy::MIN);
    assert_eq!(
        summary.as_ref().and_then(|s| s.progress().recovery()),
        no_recovery,
    );
    assert_eq!(summary.map(|s| s.progress().scan()), Some(Ratio::new(1, 1)));

    // Add more funds to the wallet in a second note
    let (h2, _, _) = st.add_a_single_note_checking_balance(value);

    // Verified balance does not include the second note
    let total = (value + value).unwrap();
    assert_eq!(
        st.get_spendable_balance(
            account_id,
            ConfirmationsPolicy::new_symmetrical_unchecked(
                2,
                #[cfg(feature = "transparent-inputs")]
                false
            )
        ),
        value
    );
    assert_eq!(
        st.get_pending_shielded_balance(
            account_id,
            ConfirmationsPolicy::new_symmetrical_unchecked(
                2,
                #[cfg(feature = "transparent-inputs")]
                false
            )
        ),
        value
    );
    assert_eq!(st.get_total_balance(account_id), total);

    // Wallet is still fully scanned
    let summary = st.get_wallet_summary(ConfirmationsPolicy::MIN);
    assert_eq!(
        summary.as_ref().and_then(|s| s.progress().recovery()),
        no_recovery
    );
    assert_eq!(summary.map(|s| s.progress().scan()), Some(Ratio::new(2, 2)));

    // Spend fails because there are insufficient verified notes
    let extsk2 = T::sk(&[0xf5; 32]);
    let to = T::sk_default_address(&extsk2);
    st.expect_insufficient_funds_with(
        &to,
        Zatoshis::const_from_u64(70000),
        ConfirmationsPolicy::new_symmetrical_unchecked(
            2,
            #[cfg(feature = "transparent-inputs")]
            false,
        ),
        Zatoshis::const_from_u64(50000),
        Zatoshis::const_from_u64(80000),
    );

    // Mine blocks SAPLING_ACTIVATION_HEIGHT + 2 to 9 until just before the second
    // note is verified
    for _ in 2..10 {
        st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
    }
    st.scan_cached_blocks(h2 + 1, 8);

    // Total balance is value * number of blocks scanned (10).
    assert_eq!(st.get_total_balance(account_id), (value * 10u64).unwrap());

    // Spend still fails
    st.expect_insufficient_funds_with(
        &to,
        Zatoshis::const_from_u64(70000),
        ConfirmationsPolicy::default(),
        Zatoshis::const_from_u64(50000),
        Zatoshis::const_from_u64(80000),
    );

    // Mine block 11 so that the second note becomes verified
    let (h11, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
    st.scan_cached_blocks(h11, 1);

    // Total balance is value * number of blocks scanned (11).
    assert_eq!(st.get_total_balance(account_id), (value * 11u64).unwrap());
    // Spendable balance at 10 confirmations is value * 2.
    assert_eq!(
        st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
        (value * 2u64).unwrap()
    );
    assert_eq!(
        st.get_pending_shielded_balance(account_id, ConfirmationsPolicy::default()),
        (value * 9u64).unwrap()
    );

    // Should now be able to generate a proposal
    let amount_sent = Zatoshis::from_u64(70000).unwrap();
    let proposal = st
        .propose_standard_transfer::<Infallible>(
            account_id,
            StandardFeeRule::Zip317,
            ConfirmationsPolicy::default(),
            &to,
            amount_sent,
            None,
            None,
            T::SHIELDED_PROTOCOL,
        )
        .unwrap();

    // Executing the proposal should succeed
    let txid = st
        .create_proposed_transactions::<Infallible, _, Infallible, _>(
            account.usk(),
            OvkPolicy::Sender,
            &proposal,
        )
        .unwrap()[0];

    let (h, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(h, 1);

    // TODO: send to an account so that we can check its balance.
    assert_eq!(
        st.get_total_balance(account_id),
        ((value * 11u64).unwrap() - (amount_sent + Zatoshis::from_u64(10000).unwrap()).unwrap())
            .unwrap()
    );
}

pub fn ovk_policy_prevents_recovery_from_chain<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    let dfvk = T::test_account_fvk(&st);

    // Add funds to the wallet in a single note
    let value = Zatoshis::const_from_u64(50000);
    let (h1, _, _) = st.add_a_single_note_checking_balance(value);

    let extsk2 = T::sk(&[0xf5; 32]);
    let addr2 = T::sk_default_address(&extsk2);

    let fee_rule = StandardFeeRule::Zip317;

    #[allow(clippy::type_complexity)]
    let send_and_recover_with_policy = |st: &mut TestState<_, Dsf::DataStore, _>,
                                        ovk_policy|
     -> Result<
        Option<(Note, Address, MemoBytes)>,
        TransferErrT<
            Dsf::DataStore,
            GreedyInputSelector<Dsf::DataStore>,
            SingleOutputChangeStrategy<Dsf::DataStore>,
        >,
    > {
        let proposal = st.propose_standard_transfer(
            account_id,
            fee_rule,
            ConfirmationsPolicy::MIN,
            &addr2,
            Zatoshis::const_from_u64(15000),
            None,
            None,
            T::SHIELDED_PROTOCOL,
        )?;

        // Executing the proposal should succeed
        let txid = st.create_proposed_transactions(account.usk(), ovk_policy, &proposal)?[0];

        // Fetch the transaction from the database
        let tx = st
            .wallet()
            .get_transaction(txid)
            .map_err(Error::DataSource)?
            .unwrap();

        Ok(T::try_output_recovery(st.network(), h1, &tx, &dfvk))
    };

    // Send some of the funds to another address, keeping history.
    // The recipient output is decryptable by the sender.
    assert_matches!(
        send_and_recover_with_policy(&mut st, OvkPolicy::Sender),
        Ok(Some((_, recovered_to, _))) if recovered_to == addr2
    );

    // Mine blocks SAPLING_ACTIVATION_HEIGHT + 1 to 42 (that don't send us funds)
    // so that the first transaction expires
    for i in 1..=42 {
        st.generate_next_block(
            &T::sk_to_fvk(&T::sk(&[i as u8; 32])),
            AddressType::DefaultExternal,
            value,
        );
    }
    st.scan_cached_blocks(h1 + 1, 42);

    // Send the funds again, discarding history.
    // Neither transaction output is decryptable by the sender.
    assert_matches!(
        send_and_recover_with_policy(&mut st, OvkPolicy::Discard),
        Ok(None)
    );
}

pub fn spend_succeeds_to_t_addr_zero_change<T: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    // Add funds to the wallet in a single note
    let value = Zatoshis::const_from_u64(70000);
    st.add_a_single_note_checking_balance(value);

    // TODO: generate_next_block_from_tx does not currently support transparent outputs.
    let to = TransparentAddress::PublicKeyHash([7; 20]).into();
    let account = st.test_account().cloned().unwrap();
    let amount_sent = Zatoshis::const_from_u64(50000);
    let proposal = st.propose_transfer_to(&to, amount_sent);

    // Executing the proposal should succeed
    assert_matches!(
        st.create_proposed_transactions::<Infallible, _, Infallible, _>(account.usk(), OvkPolicy::Sender, &proposal),
        Ok(txids) if txids.len() == 1
    );
}

pub fn change_note_spends_succeed<T: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    // Add funds to the wallet in a single note owned by the internal spending key
    let value = Zatoshis::const_from_u64(70000);
    st.add_a_single_note_checking_balance(
        TestNoteConfig::from(value).with_address_type(AddressType::Internal),
    );

    // Value is considered pending at 10 confirmations.
    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    assert_eq!(
        st.get_pending_shielded_balance(account_id, ConfirmationsPolicy::default()),
        value
    );
    assert_eq!(
        st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
        Zatoshis::ZERO
    );

    let change_note_scope = st
        .wallet()
        .get_notes(T::SHIELDED_PROTOCOL)
        .unwrap()
        .iter()
        .find_map(|note| (note.note().value() == value).then_some(note.spending_key_scope()));
    assert_matches!(change_note_scope, Some(Scope::Internal));

    // TODO: generate_next_block_from_tx does not currently support transparent outputs.
    let to = TransparentAddress::PublicKeyHash([7; 20]).into();
    let amount_sent = Zatoshis::const_from_u64(50000);
    let proposal = st.propose_transfer_to(&to, amount_sent);

    // Executing the proposal should succeed
    assert_matches!(
        st.create_proposed_transactions::<Infallible, _, Infallible, _>(account.usk(), OvkPolicy::Sender, &proposal),
        Ok(txids) if txids.len() == 1
    );
}

pub fn account_deletion<T: ShieldedPoolTester, DSF>(ds_factory: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
    <DSF as DataStoreFactory>::DataStore: Reset,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .build();

    // Add two accounts to the wallet.
    let seed = Secret::new([0u8; 32].to_vec());
    let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
    let (account1, usk) = st
        .wallet_mut()
        .create_account("account1", &seed, &birthday, None)
        .unwrap();
    let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));

    let (account2, usk2) = st
        .wallet_mut()
        .create_account("account2", &seed, &birthday, None)
        .unwrap();
    let dfvk2 = T::sk_to_fvk(T::usk_to_sk(&usk2));

    // Add funds to the account 0 in a single note
    let value = Zatoshis::from_u64(100000).unwrap();
    let (h, b0_result, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
    st.scan_cached_blocks(h, 1);
    let txid0 = *b0_result
        .txids()
        .first()
        .expect("A transaction was created.");

    // Spendable balance matches total balance
    assert_eq!(st.get_total_balance(account1), value);
    assert_eq!(
        st.get_spendable_balance(account1, ConfirmationsPolicy::MIN),
        value
    );
    assert_eq!(st.get_total_balance(account2), Zatoshis::ZERO);

    let bal_2 = Zatoshis::from_u64(50000).unwrap();
    let addr2 = T::fvk_default_address(&dfvk2);
    let req = TransactionRequest::new(vec![
        // payment to an account 2
        Payment::without_memo(addr2.to_zcash_address(st.network()), bal_2),
    ])
    .unwrap();

    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
    let input_selector = GreedyInputSelector::new();

    let txid1 = st
        .spend(
            &input_selector,
            &change_strategy,
            &usk,
            req,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        )
        .unwrap()[0];

    let bal_1 = (value - (bal_2 + MINIMUM_FEE).unwrap()).unwrap();
    assert_eq!(st.get_total_balance(account1), bal_1);

    let (h, _) = st.generate_next_block_including(txid1);
    st.scan_cached_blocks(h, 1);

    assert_eq!(st.get_total_balance(account2), bal_2);
    assert_eq!(st.get_total_balance(account1), bal_1);

    // txid0 should exist; we haven't enhanced it so we'll have the mined height, but not the raw
    // transaction data.
    assert_matches!(st.wallet_mut().get_tx_height(txid0), Ok(Some(_)));

    // delete account 1
    assert_matches!(st.wallet_mut().delete_account(account1), Ok(_));

    // txid0 should no longer exist in the wallet at all, because it only involved account1
    assert_matches!(st.wallet_mut().get_tx_height(txid0), Ok(None));

    // txid1 should exist in the wallet, as it involves account 2
    assert_matches!(st.wallet_mut().get_transaction(txid1), Ok(Some(_)));

    let summary = st
        .wallet()
        .get_wallet_summary(ConfirmationsPolicy::MIN)
        .unwrap()
        .unwrap();
    assert!(summary.account_balances().get(&account1).is_none());
    assert_eq!(
        summary.account_balances().get(&account2).unwrap().total(),
        bal_2
    );
    assert_eq!(
        summary
            .account_balances()
            .get(&account2)
            .unwrap()
            .spendable_value(),
        bal_2
    );

    // Create a third account
    let (account3, usk3) = st
        .wallet_mut()
        .create_account("account3", &seed, &birthday, None)
        .unwrap();
    let dfvk3 = T::sk_to_fvk(T::usk_to_sk(&usk3));

    // Creating a new account with the original birthday forces a rescan.
    st.scan_cached_blocks(birthday.height(), 2);

    let bal_3 = Zatoshis::from_u64(20000).unwrap();
    let addr3 = T::fvk_default_address(&dfvk3);
    let req = TransactionRequest::new(vec![
        // payment to an account 3
        Payment::without_memo(addr3.to_zcash_address(st.network()), bal_3),
    ])
    .unwrap();

    let txid2 = st
        .spend(
            &input_selector,
            &change_strategy,
            &usk2,
            req,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        )
        .unwrap()[0];

    let bal_2_final = (bal_2 - (bal_3 + MINIMUM_FEE).unwrap()).unwrap();
    assert_eq!(st.get_total_balance(account2), bal_2_final);

    let (h, _) = st.generate_next_block_including(txid2);
    st.scan_cached_blocks(h, 1);

    assert_eq!(st.get_total_balance(account2), bal_2_final);
    assert_eq!(st.get_total_balance(account3), bal_3);

    // txid2 should exist; we haven't enhanced it so we'll have the mined height, but not the raw
    // transaction data.
    assert_matches!(st.wallet_mut().get_tx_height(txid2), Ok(Some(_)));

    // delete account 3
    assert_matches!(st.wallet_mut().delete_account(account3), Ok(_));

    // txid2 should still exist in the wallet, as it involves account 2
    assert_matches!(st.wallet_mut().get_transaction(txid2), Ok(Some(_)));

    let summary = st
        .wallet()
        .get_wallet_summary(ConfirmationsPolicy::default())
        .unwrap()
        .unwrap();
    assert!(summary.account_balances().get(&account3).is_none());
    assert_eq!(
        summary.account_balances().get(&account2).unwrap().total(),
        bal_2_final
    );
}

/// Regression test for a bug in which [`WalletWrite::delete_account`] failed with a
/// `rusqlite::Error::InvalidParameterName(":address")` panic when the account being
/// deleted was referenced by a `sent_notes` row via its `to_account_id` column.
///
/// The triggering state is reached when a transaction is sent from one account in the
/// wallet to an address belonging to a second account in the same wallet, and the
/// transaction is then decrypted via [`decrypt_and_store_transaction`] so that the
/// cross-account transfer is recorded with a non-null `to_account_id` and a received
/// output that has an associated address. Deleting the recipient account then exercises
/// the `sent_notes` update path inside `delete_account`.
///
/// [`WalletWrite::delete_account`]: crate::data_api::WalletWrite::delete_account
pub fn account_deletion_with_internal_transfer<T: ShieldedPoolTester, DSF>(
    ds_factory: DSF,
    cache: impl TestCache,
) where
    DSF: DataStoreFactory,
    <DSF as DataStoreFactory>::DataStore: Reset,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .build();

    // Add two accounts to the wallet, derived from the same seed.
    let seed = Secret::new([0u8; 32].to_vec());
    let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
    let (account1, usk1) = st
        .wallet_mut()
        .create_account("account1", &seed, &birthday, None)
        .unwrap();
    let dfvk1 = T::sk_to_fvk(T::usk_to_sk(&usk1));

    let (account2, usk2) = st
        .wallet_mut()
        .create_account("account2", &seed, &birthday, None)
        .unwrap();
    let dfvk2 = T::sk_to_fvk(T::usk_to_sk(&usk2));

    // Add funds to account 1 in a single note.
    let value = Zatoshis::from_u64(100000).unwrap();
    let (h, _, _) = st.generate_next_block(&dfvk1, AddressType::DefaultExternal, value);
    st.scan_cached_blocks(h, 1);

    assert_eq!(st.get_total_balance(account1), value);
    assert_eq!(st.get_total_balance(account2), Zatoshis::ZERO);

    // Send funds from account 1 to an address belonging to account 2.
    let bal_2 = Zatoshis::from_u64(50000).unwrap();
    let addr2 = T::fvk_default_address(&dfvk2);
    let req = TransactionRequest::new(vec![Payment::without_memo(
        addr2.to_zcash_address(st.network()),
        bal_2,
    )])
    .unwrap();

    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
    let input_selector = GreedyInputSelector::new();

    let txid = st
        .spend(
            &input_selector,
            &change_strategy,
            &usk1,
            req,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        )
        .unwrap()[0];

    let (h, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(h, 1);

    assert_eq!(st.get_total_balance(account2), bal_2);

    // Decrypt and store the transaction. Because the wallet owns the funding inputs
    // (account 1) and the output is received by account 2, this records the send as an
    // internal cross-account transfer, setting `sent_notes.to_account_id` to account 2
    // and associating the received output with account 2's address. This is the state
    // that triggers the `delete_account` bug.
    let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), &tx, Some(h)).unwrap();

    // Deleting account 2, the recipient of the internal transfer, must succeed. Prior to
    // the fix this failed with `rusqlite::Error::InvalidParameterName(":address")` because
    // the `sent_notes` update statement bound the wrong parameter name.
    assert_matches!(st.wallet_mut().delete_account(account2), Ok(_));

    // account 1 should still exist and retain its change balance.
    let summary = st
        .wallet()
        .get_wallet_summary(ConfirmationsPolicy::MIN)
        .unwrap()
        .unwrap();
    assert!(summary.account_balances().get(&account2).is_none());
    assert!(summary.account_balances().contains_key(&account1));
}

pub fn external_address_change_spends_detected_in_restore_from_seed<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::DataStore: Reset,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .build();

    // Add two accounts to the wallet.
    let seed = Secret::new([0u8; 32].to_vec());
    let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
    let (account1, usk) = st
        .wallet_mut()
        .create_account("account1", &seed, &birthday, None)
        .unwrap();
    let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));

    let (account2, usk2) = st
        .wallet_mut()
        .create_account("account2", &seed, &birthday, None)
        .unwrap();
    let dfvk2 = T::sk_to_fvk(T::usk_to_sk(&usk2));

    // Add funds to the wallet in a single note
    let value = Zatoshis::from_u64(100000).unwrap();
    let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
    st.scan_cached_blocks(h, 1);

    // Spendable balance matches total balance
    assert_eq!(st.get_total_balance(account1), value);
    assert_eq!(
        st.get_spendable_balance(account1, ConfirmationsPolicy::MIN),
        value
    );
    assert_eq!(st.get_total_balance(account2), Zatoshis::ZERO);

    let amount_sent = Zatoshis::from_u64(20000).unwrap();
    let amount_legacy_change = Zatoshis::from_u64(30000).unwrap();
    let addr = T::fvk_default_address(&dfvk);
    let addr2 = T::fvk_default_address(&dfvk2);
    let req = TransactionRequest::new(vec![
        // payment to an external recipient
        Payment::without_memo(addr2.to_zcash_address(st.network()), amount_sent),
        // payment back to the originating wallet, simulating legacy change
        Payment::without_memo(addr.to_zcash_address(st.network()), amount_legacy_change),
    ])
    .unwrap();

    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
    let input_selector = GreedyInputSelector::new();

    let txid = st
        .spend(
            &input_selector,
            &change_strategy,
            &usk,
            req,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        )
        .unwrap()[0];

    let amount_left = (value - (amount_sent + MINIMUM_FEE + MARGINAL_FEE).unwrap()).unwrap();
    let pending_change = (amount_left - amount_legacy_change).unwrap();

    // The "legacy change" is not counted by get_pending_change().
    assert_eq!(
        st.get_pending_change(account1, ConfirmationsPolicy::MIN),
        pending_change
    );
    // We spent the only note so we only have pending change.
    assert_eq!(st.get_total_balance(account1), pending_change);

    let (h, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(h, 1);

    assert_eq!(st.get_total_balance(account2), amount_sent,);
    assert_eq!(st.get_total_balance(account1), amount_left);

    st.reset();

    // Account creation and DFVK derivation should be deterministic.
    let (account1, restored_usk) = st
        .wallet_mut()
        .create_account("account1_restored", &seed, &birthday, None)
        .unwrap();
    assert!(T::fvks_equal(
        &T::sk_to_fvk(T::usk_to_sk(&restored_usk)),
        &dfvk,
    ));

    let (account2, restored_usk2) = st
        .wallet_mut()
        .create_account("account2_restored", &seed, &birthday, None)
        .unwrap();
    assert!(T::fvks_equal(
        &T::sk_to_fvk(T::usk_to_sk(&restored_usk2)),
        &dfvk2,
    ));

    st.scan_cached_blocks(st.sapling_activation_height(), 2);

    assert_eq!(st.get_total_balance(account2), amount_sent);
    assert_eq!(st.get_total_balance(account1), amount_left);
}

#[allow(dead_code)]
pub fn zip317_spend<T: ShieldedPoolTester, Dsf: DataStoreFactory>(
    ds_factory: Dsf,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    let dfvk = T::test_account_fvk(&st);

    // Add funds to the wallet
    st.add_notes_checking_balance([Some(Zatoshis::const_from_u64(50000))]);

    // Add 10 uneconomic (dust) notes to the wallet
    for _ in 1..=10 {
        st.add_notes_checking_balance([Some(Zatoshis::const_from_u64(1000))]);
    }

    // Spendable balance matches total balance
    let total = Zatoshis::const_from_u64(60000);
    assert_eq!(st.get_total_balance(account_id), total);
    assert_eq!(
        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
        total
    );

    let input_selector = GreedyInputSelector::<Dsf::DataStore>::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);

    // This first request will fail due to insufficient non-dust funds
    let req = TransactionRequest::new(vec![Payment::without_memo(
        T::fvk_default_address(&dfvk).to_zcash_address(st.network()),
        Zatoshis::const_from_u64(50000),
    )])
    .unwrap();

    assert_matches!(
        st.spend(
            &input_selector,
            &change_strategy,
            account.usk(),
            req,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        ),
        Err(Error::InsufficientFunds { available, required })
            if available == Zatoshis::const_from_u64(51000)
            && required == Zatoshis::const_from_u64(60000)
    );

    // This request will succeed, spending a single dust input to pay the 10000
    // ZAT fee in addition to the 41000 ZAT output to the recipient
    let req = TransactionRequest::new(vec![Payment::without_memo(
        T::fvk_default_address(&dfvk).to_zcash_address(st.network()),
        Zatoshis::const_from_u64(41000),
    )])
    .unwrap();

    let txid = st
        .spend(
            &input_selector,
            &change_strategy,
            account.usk(),
            req,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        )
        .unwrap()[0];

    let (h, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(h, 1);

    // TODO: send to an account so that we can check its balance.
    // We sent back to the same account so the amount_sent should be included
    // in the total balance.
    assert_eq!(
        st.get_total_balance(account_id),
        (total - Zatoshis::const_from_u64(10000)).unwrap()
    );
}

#[cfg(feature = "transparent-inputs")]
pub fn shield_transparent<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let dfvk = T::test_account_fvk(&st);

    let uaddr = st
        .wallet()
        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
        .unwrap()
        .unwrap();
    let taddr = uaddr.transparent().unwrap();

    // Ensure that the wallet has at least one block
    let (h, _, _) = st.generate_next_block(
        &dfvk,
        AddressType::Internal,
        Zatoshis::const_from_u64(50000),
    );
    st.scan_cached_blocks(h, 1);

    let spent_outpoint = OutPoint::fake();
    let utxo = WalletTransparentOutput::from_parts(
        spent_outpoint.clone(),
        TxOut::new(Zatoshis::const_from_u64(100000), taddr.script().into()),
        Some(h),
        Some(account.id()),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();

    let res0 = st.wallet_mut().put_received_transparent_utxo(&utxo);
    assert_matches!(res0, Ok(_));

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);

    let txids = st
        .shield_transparent_funds(
            &input_selector,
            &change_strategy,
            Zatoshis::from_u64(10000).unwrap(),
            account.usk(),
            &[*taddr],
            account.id(),
            ConfirmationsPolicy::MIN,
        )
        .unwrap();
    assert_eq!(txids.len(), 1);
    let shielding_txid = *txids.first();

    assert!(
        !st.wallet()
            .transaction_data_requests()
            .unwrap()
            .contains(&TransactionDataRequest::GetStatus(shielding_txid)),
        "a wallet-owned shielded output makes the transaction observable by scanning",
    );

    let tx_summary = st.get_tx_from_history(shielding_txid).unwrap().unwrap();
    assert_eq!(tx_summary.spent_note_count(), 1);
    assert!(tx_summary.has_change());
    assert_eq!(tx_summary.received_note_count(), 0);
    assert_eq!(tx_summary.sent_note_count(), 0);
    assert!(tx_summary.is_shielding());

    // Generate and scan the block including the transaction
    let (h, _) = st.generate_next_block_including(shielding_txid);
    let scan_result = st.scan_cached_blocks(h, 1);

    // Ensure that the transaction metadata is still correct after the update produced by scanning.
    let tx_summary = st.get_tx_from_history(shielding_txid).unwrap().unwrap();
    assert_eq!(tx_summary.spent_note_count(), 1);
    assert!(tx_summary.has_change());
    assert_eq!(tx_summary.received_note_count(), 0);
    assert_eq!(tx_summary.sent_note_count(), 0);
    assert!(tx_summary.is_shielding());

    // Verify that a transaction enhancement request for the transaction containing the spent
    // outpoint does not yet exist.
    let requests = st.wallet().transaction_data_requests().unwrap();
    assert!(
        !requests
            .iter()
            .any(|req| req == &TransactionDataRequest::Enhancement(*spent_outpoint.txid()))
    );

    // Use `decrypt_and_store_transaction` for the side effect of creating enhancement requests for
    // the transparent inputs of the transaction.
    let tx = st
        .wallet()
        .get_transaction(*txids.first())
        .unwrap()
        .unwrap();
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), &tx, Some(h)).unwrap();

    // Verify that a transaction enhancement request for the received transaction was created
    let requests = st.wallet().transaction_data_requests().unwrap();
    assert!(
        requests
            .iter()
            .any(|req| req == &TransactionDataRequest::Enhancement(*spent_outpoint.txid()))
    );

    // Now advance the chain by 40 blocks; even though a record for the transaction that created
    // `spent_outpoint` exists in the wallet database, the transaction can't be enhanced because
    // the outpoint was fake. Advancing the chain will cause the request for enhancement to expire.
    for _ in 0..DEFAULT_TX_EXPIRY_DELTA {
        st.generate_next_block(
            &dfvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10000),
        );
    }
    st.scan_cached_blocks(
        scan_result.scanned_range().end,
        usize::try_from(DEFAULT_TX_EXPIRY_DELTA).unwrap(),
    );

    // Simulate the situation where the enhancement request results in `TxidNotRecognized`
    st.wallet_mut()
        .set_transaction_status(
            *spent_outpoint.txid(),
            data_api::TransactionStatus::TxidNotRecognized,
        )
        .unwrap();

    // Verify that the transaction enhancement request for the invalid txid has been deleted.
    let requests = st.wallet().transaction_data_requests().unwrap();
    assert!(
        !requests
            .iter()
            .any(|req| req == &TransactionDataRequest::Enhancement(*spent_outpoint.txid()))
    );
}

// FIXME: This requires fixes to the test framework.
#[allow(dead_code)]
pub fn birthday_in_anchor_shard<T: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    // Set up the following situation:
    //
    //        |<------ 500 ------->|<--- 10 --->|<--- 10 --->|
    // last_shard_start   wallet_birthday  received_tx  anchor_height
    //
    // We set the Sapling and Orchard frontiers at the birthday block initial state to 1234
    // notes beyond the end of the first shard.
    let frontier_tree_size: u32 = (0x1 << 16) + 1234;
    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .with_initial_chain_state(|rng, network| {
            let birthday_height = network.activation_height(NetworkUpgrade::Nu5).unwrap() + 1000;

            // Construct a fake chain state for the end of the block with the given
            // birthday_offset from the Nu5 birthday.
            let (prior_sapling_roots, sapling_initial_tree) = random_sapling_frontier(
                rng,
                frontier_tree_size.into(),
                NonZeroU8::new(16).unwrap(),
            );
            // There will only be one prior root
            let prior_sapling_roots = prior_sapling_roots
                .into_iter()
                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
                .collect::<Vec<_>>();

            #[cfg(feature = "orchard")]
            let (prior_orchard_roots, orchard_initial_tree) = random_orchard_frontier(
                rng,
                frontier_tree_size.into(),
                NonZeroU8::new(16).unwrap(),
            );
            // There will only be one prior root
            #[cfg(feature = "orchard")]
            let prior_orchard_roots = prior_orchard_roots
                .into_iter()
                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
                .collect::<Vec<_>>();

            // Ironwood is not active at these test heights, so its tree is empty.
            #[cfg(feature = "orchard")]
            let ironwood_initial_tree = Frontier::empty();

            InitialChainState {
                chain_state: ChainState::new(
                    birthday_height - 1,
                    BlockHash([5; 32]),
                    sapling_initial_tree,
                    #[cfg(feature = "orchard")]
                    orchard_initial_tree,
                    #[cfg(feature = "orchard")]
                    ironwood_initial_tree,
                ),
                prior_sapling_roots,
                #[cfg(feature = "orchard")]
                prior_orchard_roots,
            }
        })
        .with_account_having_current_birthday()
        .build();

    // Generate 9 blocks that have no value for us, starting at the birthday height.
    let not_our_value = Zatoshis::const_from_u64(10000);
    let not_our_key = T::random_fvk(st.rng_mut());
    let (initial_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..9 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }

    // Now, generate a block that belongs to our wallet
    let (received_tx_height, _, _) = st.generate_next_block(
        &T::test_account_fvk(&st),
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(500000),
    );

    // Generate some more blocks to get above our anchor height
    for _ in 0..15 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }

    // Scan a block range that includes our received note, but skips some blocks we need to
    // make it spendable.
    st.scan_cached_blocks(initial_height + 5, 20);

    // Verify that the received note is not considered spendable
    let account = st.test_account().unwrap();
    let account_id = account.id();
    let spendable = T::select_spendable_notes(
        &st,
        account_id,
        TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
        TargetHeight::from(received_tx_height + 10),
        ConfirmationsPolicy::default(),
        &[],
    )
    .unwrap();

    assert_eq!(spendable.len(), 0);

    // Scan the blocks we skipped
    st.scan_cached_blocks(initial_height, 5);

    // Verify that the received note is now considered spendable
    let spendable = T::select_spendable_notes(
        &st,
        account_id,
        TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
        TargetHeight::from(received_tx_height + 10),
        ConfirmationsPolicy::default(),
        &[],
    )
    .unwrap();

    assert_eq!(spendable.len(), 1);
}

pub fn checkpoint_gaps<T: ShieldedPoolTester, Dsf: DataStoreFactory>(
    ds_factory: Dsf,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    // Generate a block with funds belonging to our wallet.
    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500000));

    // Create a gap of 10 blocks having no shielded outputs, then add a block that doesn't
    // belong to us so that we can get a checkpoint in the tree.
    let account = st.test_account().cloned().unwrap();
    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
    let not_our_value = Zatoshis::const_from_u64(10000);
    let sapling_end_size = st.latest_cached_block().unwrap().sapling_end_size();
    let orchard_end_size = st.latest_cached_block().unwrap().orchard_end_size();
    let ironwood_end_size = st.latest_cached_block().unwrap().ironwood_end_size();
    st.generate_block_at(
        account.birthday().height() + 10,
        BlockHash([0; 32]),
        &[FakeCompactOutput::new(
            &not_our_key,
            AddressType::DefaultExternal,
            not_our_value,
        )],
        sapling_end_size,
        orchard_end_size,
        ironwood_end_size,
        false,
    );

    // Scan the block
    st.scan_cached_blocks(account.birthday().height() + 10, 1);

    // Verify that our note is considered spendable
    let spendable = T::select_spendable_notes(
        &st,
        account.id(),
        TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
        TargetHeight::from(account.birthday().height() + 5),
        ConfirmationsPolicy::new_unchecked(
            1,
            5,
            #[cfg(feature = "transparent-inputs")]
            false,
        ),
        &[],
    )
    .unwrap();
    assert_eq!(spendable.len(), 1);

    let input_selector = GreedyInputSelector::<Dsf::DataStore>::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);

    let to = T::fvk_default_address(&not_our_key);
    let req = TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        Zatoshis::const_from_u64(10000),
    )])
    .unwrap();

    // Attempt to spend the note with 5 confirmations
    assert_matches!(
        st.spend(
            &input_selector,
            &change_strategy,
            account.usk(),
            req,
            OvkPolicy::Sender,
            ConfirmationsPolicy::new_symmetrical_unchecked(
                5,
                #[cfg(feature = "transparent-inputs")]
                false
            ),
        ),
        Ok(_)
    );
}

/// Reads, from any pool's note commitment tree, whether a witness for `note_position` as of
/// `anchor_height` is still constructible, the set of surviving checkpoint heights, and the set
/// of retained-anchor heights.
#[allow(clippy::type_complexity)]
fn tree_anchor_state<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
    tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
    note_position: Position,
    anchor_height: BlockHeight,
) -> Result<(bool, BTreeSet<BlockHeight>, BTreeSet<BlockHeight>), ShardTreeError<S::Error>>
where
    S: ShardStore<CheckpointId = BlockHeight>,
    S::H: Hashable + Clone + PartialEq,
{
    let witness_computable = tree
        .witness_at_checkpoint_id(note_position, &anchor_height)?
        .is_some();
    let retained = tree
        .store()
        .retained_checkpoints()
        .map_err(ShardTreeError::Storage)?;
    let checkpoint_count = tree
        .store()
        .checkpoint_count()
        .map_err(ShardTreeError::Storage)?;
    let mut survivors = BTreeSet::new();
    tree.store()
        .for_each_checkpoint(checkpoint_count, |cid, _| {
            survivors.insert(*cid);
            Ok(())
        })
        .map_err(ShardTreeError::Storage)?;
    Ok((witness_computable, survivors, retained))
}

/// A wallet-level test for note-commitment-tree *anchor retention*: once NU6.3 (Ironwood) is
/// active, checkpoints on the anchor-retention interval are retained as durable anchors, exempt
/// from the ordinary `PRUNING_DEPTH`-checkpoint pruning budget, so that their roots and the
/// witnesses anchored to them remain computable even after they age far behind the chain tip.
///
/// The interval is supplied by the caller (the pruning depth is read from
/// `crate::data_api::ll::wallet`, so this test tracks whatever value the implementation defines).
/// Passing a short interval keeps the test cheap: the scan must reach a boundary more than
/// `PRUNING_DEPTH` checkpoints behind the tip, which at the ZIP 318 interval means generating
/// several hundred blocks.
///
/// The test:
/// - Activates NU6.3 from the Sapling activation height, so anchor retention is live and its
///   floor equals the account birthday.
/// - Receives a single note early, capturing its note-commitment-tree position.
/// - Scans forward in a single batch until an interval-aligned anchor has aged *more than
///   `PRUNING_DEPTH` checkpoints* behind the chain tip — so it would have been pruned to enforce
///   the checkpoint budget had it not been retained.
/// - Proves survival behaviorally: a witness for the received note *as of that buried anchor* is
///   still constructible (it would be `None` if the anchor checkpoint had been pruned).
/// - Confirms the anchors did not consume the pruning budget: the ordinary checkpoint immediately
///   above the buried anchor *was* pruned, exactly the interval-aligned anchors at/above the floor
///   are retained, and the full `PRUNING_DEPTH` window of checkpoints at the chain tip survives.
pub fn anchor_checkpoints_retained_across_deep_scan<
    T: ShieldedPoolTester,
    Dsf: DataStoreFactory,
>(
    ds_factory: Dsf,
    cache: impl TestCache,
    interval: AnchorRetentionInterval,
) {
    let interval_blocks = interval.block_count().get();

    // A network on which NU6.3 (Ironwood) is active from the Sapling activation height, so anchor
    // retention is live with its floor at the account birthday.
    let activation = BlockHeight::from_u32(100_000);
    let ironwood_active_network = LocalNetwork {
        nu6: Some(activation),
        nu6_1: Some(activation),
        nu6_2: Some(activation),
        nu6_3: Some(activation),
        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(ironwood_active_network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_anchor_retention_interval(interval)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<T>();

    // Receive a single note; its position is captured after it is deeply confirmed, below.
    let (received_height, _, _) =
        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
    let received = u32::from(received_height);
    let floor = u32::from(activation);

    // The first interval-aligned anchor height at or above the retention floor and strictly above
    // the received note, so the note's position precedes the anchor's checkpoint.
    let mut anchor = u32::from(interval.boundary_at_or_above(BlockHeight::from(floor)));
    while anchor <= received {
        anchor += interval_blocks;
    }

    // Scan forward in a single batch so the anchor ages more than `PRUNING_DEPTH` checkpoints
    // behind the tip: without retention it would be pruned to enforce the checkpoint budget.
    let tip = anchor + PRUNING_DEPTH + 10;

    // Fillers pay a non-wallet key, so each block still adds a commitment (and thus a checkpoint)
    // without changing the received note's position or the wallet's spendable set.
    let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
    let filler_count = tip - received;
    for _ in 0..filler_count {
        st.generate_next_block(
            &not_our_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10_000),
        );
    }
    st.scan_cached_blocks(received_height + 1, filler_count as usize);

    // Capture the received note's commitment-tree position now that it is deeply confirmed.
    let account_id = st.get_account().id();
    let spendable = T::select_spendable_notes(
        &st,
        account_id,
        TargetValue::AtLeast(Zatoshis::const_from_u64(1)),
        TargetHeight::from(BlockHeight::from(tip + 1)),
        ConfirmationsPolicy::MIN,
        &[],
    )
    .unwrap();
    let note_position = spendable
        .first()
        .expect("the received note is spendable")
        .note_commitment_tree_position();

    let anchor_height = BlockHeight::from(anchor);
    let (witness_computable, survivors, retained) = match T::SHIELDED_PROTOCOL {
        ShieldedPool::Sapling => st
            .wallet_mut()
            .with_sapling_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
            .unwrap(),
        #[cfg(feature = "orchard")]
        ShieldedPool::Orchard => st
            .wallet_mut()
            .with_orchard_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
            .unwrap(),
        other => {
            unreachable!("anchor retention test covers only Sapling and Orchard, got {other:?}")
        }
    };

    // The witness for the received note, anchored at the buried anchor, must still be computable —
    // impossible if that checkpoint had been pruned.
    assert!(
        witness_computable,
        "a witness for the received note as of the retained anchor at height {anchor} \
         must still be constructible",
    );

    // Exactly the interval-aligned checkpoints at or above the retention floor are retained.
    let expected_anchors: BTreeSet<BlockHeight> = (floor..=tip)
        .map(BlockHeight::from)
        .filter(|h| interval.is_boundary(*h))
        .collect();
    assert_eq!(
        retained, expected_anchors,
        "only the interval-aligned anchors at/above the NU6.3 floor should be retained",
    );

    // The buried anchor survives, but the ordinary checkpoint immediately above it was pruned — so
    // its survival is due to retention, not to pruning having failed to run.
    assert!(
        survivors.contains(&anchor_height),
        "the buried anchor checkpoint must survive",
    );
    assert!(
        !survivors.contains(&BlockHeight::from(anchor + 1)),
        "the ordinary checkpoint just above the buried anchor must have been pruned",
    );

    // The anchors did not consume the pruning budget: the full `PRUNING_DEPTH` window of
    // checkpoints at the chain tip is still retained.
    for h in (tip - PRUNING_DEPTH + 1)..=tip {
        assert!(
            survivors.contains(&BlockHeight::from(h)),
            "checkpoint at tip-window height {h} must be retained",
        );
    }
}

/// A grid boundary that lands on a block containing no note commitments in ANY pool must still be
/// checkpointed and retained. Scanning checkpoints a block only at its last note commitment, so
/// such a block produces no checkpoint of its own in any tree and the cross-pool ensure step has
/// nothing to copy; unless the retained heights are ensured explicitly, the retained grid gains a
/// permanent hole there — on mainnet a sizeable fraction of blocks carry no shielded outputs —
/// and a ZIP 318 crossing anchored to the hole can never be proved.
///
/// The scan must cover the boundaries in a SINGLE batch: scanning block-by-block masks the gap,
/// because every batch checkpoints its starting frontier, so each height gets a checkpoint as the
/// next block's batch begins.
#[cfg(feature = "orchard")]
pub fn empty_boundary_blocks_are_checkpointed_and_retained<
    T: ShieldedPoolTester,
    Dsf: DataStoreFactory,
>(
    ds_factory: Dsf,
    cache: impl TestCache,
    interval: AnchorRetentionInterval,
) {
    let interval_blocks = interval.block_count().get();

    // A network on which NU6.3 (Ironwood) is active from the Sapling activation height, so anchor
    // retention is live with its floor at the account birthday.
    let activation = BlockHeight::from_u32(100_000);
    let ironwood_active_network = LocalNetwork {
        nu6: Some(activation),
        nu6_1: Some(activation),
        nu6_2: Some(activation),
        nu6_3: Some(activation),
        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(ironwood_active_network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_anchor_retention_interval(interval)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<T>();

    // Receive a single note; its position is captured after the batch scan, below.
    let (received_height, _, _) =
        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
    let received = u32::from(received_height);

    // The first two boundaries strictly above the received note, plus slack so neither boundary
    // is the final block of the batch.
    let first_boundary = {
        let mut b = u32::from(interval.boundary_at_or_above(activation));
        while b <= received {
            b += interval_blocks;
        }
        b
    };
    let boundaries = [first_boundary, first_boundary + interval_blocks];
    let tip = boundaries[1] + 2;

    // Fillers pay a non-wallet key so that ordinary blocks each carry a commitment, but every
    // BOUNDARY block is generated empty: no note commitments in any pool, and so no checkpoint
    // of its own.
    let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
    for height in (received + 1)..=tip {
        let generated = if interval.is_boundary(BlockHeight::from_u32(height)) {
            st.generate_empty_block().0
        } else {
            st.generate_next_block(
                &not_our_fvk,
                AddressType::DefaultExternal,
                Zatoshis::const_from_u64(10_000),
            )
            .0
        };
        assert_eq!(u32::from(generated), height, "cache height must track");
    }
    // One batch, covering both boundaries.
    st.scan_cached_blocks(received_height + 1, (tip - received) as usize);

    // Capture the received note's commitment-tree position.
    let account_id = st.get_account().id();
    let spendable = T::select_spendable_notes(
        &st,
        account_id,
        TargetValue::AtLeast(Zatoshis::const_from_u64(1)),
        TargetHeight::from(BlockHeight::from_u32(tip + 1)),
        ConfirmationsPolicy::MIN,
        &[],
    )
    .unwrap();
    let note_position = spendable
        .first()
        .expect("the received note is spendable")
        .note_commitment_tree_position();

    for boundary in boundaries {
        let anchor_height = BlockHeight::from_u32(boundary);
        let (witness_computable, survivors, retained) = match T::SHIELDED_PROTOCOL {
            ShieldedPool::Sapling => st
                .wallet_mut()
                .with_sapling_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
                .unwrap(),
            ShieldedPool::Orchard => st
                .wallet_mut()
                .with_orchard_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
                .unwrap(),
            other => {
                unreachable!("this test covers only Sapling and Orchard, got {other:?}")
            }
        };

        assert!(
            survivors.contains(&anchor_height),
            "the empty boundary block at height {boundary} must be checkpointed",
        );
        assert!(
            retained.contains(&anchor_height),
            "the checkpoint at the empty boundary height {boundary} must be retained",
        );
        // The checkpoint must be USABLE as an anchor: it commits to the tree state as of the last
        // note commitment at or before the boundary, so the received note has a witness there.
        assert!(
            witness_computable,
            "a witness for the received note as of the empty boundary at height {boundary} \
             must be constructible",
        );
    }

    // The pool-crossing destination tree gains the same retained checkpoints even though it holds
    // no commitments at all, keeping the cross-pool checkpoint sets consistent.
    let ironwood_retained = st
        .wallet_mut()
        .with_ironwood_tree_mut(|tree| {
            tree.store()
                .retained_checkpoints()
                .map_err(ShardTreeError::Storage)
        })
        .unwrap()
        .expect("the data store maintains an Ironwood tree");
    for boundary in boundaries {
        assert!(
            ironwood_retained.contains(&BlockHeight::from_u32(boundary)),
            "the Ironwood tree must retain the empty boundary at height {boundary}",
        );
    }
}

#[cfg(feature = "orchard")]
pub fn pool_crossing_required<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    // TODO: Allow for Orchard activation after Sapling
    // Here we choose P0, but this has no effect since we supply the viewing keys
    // and generate the blocks directly on the state.
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();

    let account = st.test_account().cloned().unwrap();

    let p0_fvk = P0::test_account_fvk(&st);

    let p1_fvk = P1::test_account_fvk(&st);
    let p1_to = P1::fvk_default_address(&p1_fvk);

    let note_value = Zatoshis::const_from_u64(350000);
    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
    st.scan_cached_blocks(account.birthday().height(), 2);

    let initial_balance = note_value;
    assert_eq!(st.get_total_balance(account.id()), initial_balance);
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        initial_balance
    );

    let transfer_amount = Zatoshis::const_from_u64(200000);
    let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
        p1_to.to_zcash_address(st.network()),
        transfer_amount,
    )])
    .unwrap();

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, P1::SHIELDED_PROTOCOL);
    let proposal0 = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            p0_to_p1,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let _min_target_height = proposal0.min_target_height();
    assert_eq!(proposal0.steps().len(), 1);
    let step0 = &proposal0.steps().head;

    // We expect 4 logical actions, two per pool (due to padding).
    let expected_fee = Zatoshis::const_from_u64(20000);
    assert_eq!(step0.balance().fee_required(), expected_fee);

    let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
    let proposed_change = step0.balance().proposed_change();
    assert_eq!(proposed_change.len(), 1);
    let change_output = proposed_change.first().unwrap();
    // Since this is a cross-pool transfer, change will be sent to the preferred pool.
    assert_eq!(
        change_output.output_pool(),
        PoolType::Shielded(std::cmp::max(ShieldedPool::Sapling, ShieldedPool::Orchard))
    );
    assert_eq!(change_output.value(), expected_change);

    let txids = st.create_proposed_expecting(&proposal0, 1);

    let (h, _) = st.generate_next_block_including(txids[0]);
    st.scan_cached_blocks(h, 1);

    assert_eq!(
        st.get_total_balance(account.id()),
        (initial_balance - expected_fee).unwrap()
    );
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        (initial_balance - expected_fee).unwrap()
    );
}

#[cfg(feature = "orchard")]
pub fn fully_funded_fully_private<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    // TODO: Allow for Orchard activation after Sapling
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();

    let account = st.test_account().cloned().unwrap();

    let p0_fvk = P0::test_account_fvk(&st);

    let p1_fvk = P1::test_account_fvk(&st);
    let p1_to = P1::fvk_default_address(&p1_fvk);

    let note_value = Zatoshis::const_from_u64(350000);
    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
    st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
    st.scan_cached_blocks(account.birthday().height(), 2);

    let initial_balance = (note_value * 2u64).unwrap();
    assert_eq!(st.get_total_balance(account.id()), initial_balance);
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        initial_balance
    );

    let transfer_amount = Zatoshis::const_from_u64(200000);
    let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
        p1_to.to_zcash_address(st.network()),
        transfer_amount,
    )])
    .unwrap();

    let input_selector = GreedyInputSelector::new();
    // We set the default change output pool to P0, because we want to verify later that
    // change is actually sent to P1 (as the transaction is fully fundable from P1).
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, P0::SHIELDED_PROTOCOL);
    let proposal0 = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            p0_to_p1,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let _min_target_height = proposal0.min_target_height();
    assert_eq!(proposal0.steps().len(), 1);
    let step0 = &proposal0.steps().head;

    // We expect 2 logical actions, since either pool can pay the full balance required
    // and note selection should choose the fully-private path.
    let expected_fee = Zatoshis::const_from_u64(10000);
    assert_eq!(step0.balance().fee_required(), expected_fee);

    let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
    let proposed_change = step0.balance().proposed_change();
    assert_eq!(proposed_change.len(), 1);
    let change_output = proposed_change.first().unwrap();
    // Since there are sufficient funds in either pool, change is kept in the same pool as
    // the source note (the target pool), and does not necessarily follow preference order.
    assert_eq!(
        change_output.output_pool(),
        PoolType::Shielded(P1::SHIELDED_PROTOCOL)
    );
    assert_eq!(change_output.value(), expected_change);

    let txids = st.create_proposed_expecting(&proposal0, 1);

    let (h, _) = st.generate_next_block_including(txids[0]);
    st.scan_cached_blocks(h, 1);

    assert_eq!(
        st.get_total_balance(account.id()),
        (initial_balance - expected_fee).unwrap()
    );
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        (initial_balance - expected_fee).unwrap()
    );
}

#[cfg(all(feature = "orchard", feature = "transparent-inputs"))]
pub fn fully_funded_send_to_t<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    // TODO: Allow for Orchard activation after Sapling
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();

    let account = st.test_account().cloned().unwrap();

    let p0_fvk = P0::test_account_fvk(&st);
    let p1_fvk = P1::test_account_fvk(&st);
    let (p1_to, _) = account.usk().default_transparent_address();

    let note_value = Zatoshis::const_from_u64(350000);
    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
    st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
    st.scan_cached_blocks(account.birthday().height(), 2);

    let initial_balance = (note_value * 2u64).unwrap();
    assert_eq!(st.get_total_balance(account.id()), initial_balance);
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        initial_balance
    );

    let transfer_amount = Zatoshis::const_from_u64(200000);
    let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
        Address::Transparent(p1_to).to_zcash_address(st.network()),
        transfer_amount,
    )])
    .unwrap();

    let input_selector = GreedyInputSelector::new();
    // We set the default change output pool to P0, because we want to verify later that
    // change is actually sent to P1 (as the transaction is fully fundable from P1).
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, P0::SHIELDED_PROTOCOL);
    let proposal0 = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            p0_to_p1,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let _min_target_height = proposal0.min_target_height();
    assert_eq!(proposal0.steps().len(), 1);
    let step0 = &proposal0.steps().head;

    // We expect 3 logical actions, one for the transparent output and two for the source pool.
    let expected_fee = Zatoshis::const_from_u64(15000);
    assert_eq!(step0.balance().fee_required(), expected_fee);

    let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
    let proposed_change = step0.balance().proposed_change();
    assert_eq!(proposed_change.len(), 1);
    let change_output = proposed_change.first().unwrap();
    // Since there are sufficient funds in either pool, change is kept in the same pool as
    // the source note (the target pool), and does not necessarily follow preference order.
    // The source note will always be sapling, as we spend Sapling funds preferentially.
    assert_eq!(change_output.output_pool(), PoolType::SAPLING);
    assert_eq!(change_output.value(), expected_change);

    let txids = st.create_proposed_expecting(&proposal0, 1);

    let (h, _) = st.generate_next_block_including(txids[0]);
    st.scan_cached_blocks(h, 1);

    // Since the recipient address is in the same account, the total balance includes the transfer
    // amount.
    assert_eq!(
        st.get_total_balance(account.id()),
        (initial_balance - expected_fee).unwrap()
    );
    // The spendable balance doesn't include the transparent value, so it excludes the transfer
    // amount.
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        (initial_balance - transfer_amount - expected_fee).unwrap()
    );
}

#[cfg(feature = "orchard")]
pub fn multi_pool_checkpoint<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    // TODO: Allow for Orchard activation after Sapling
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();

    let account = st.test_account().cloned().unwrap();
    let acct_id = account.id();

    let p0_fvk = P0::test_account_fvk(&st);
    let p1_fvk = P1::test_account_fvk(&st);

    // Add some funds to the wallet; we add two notes to allow successive spends. Also,
    // we will generate a note in the P1 pool to ensure that we have some tree state.
    let note_value = Zatoshis::const_from_u64(500000);
    let (start_height, _, _) =
        st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
    st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
    let scanned = st.scan_cached_blocks(start_height, 3);

    let next_to_scan = scanned.scanned_range().end;

    let initial_balance = (note_value * 3u64).unwrap();
    assert_eq!(st.get_total_balance(acct_id), initial_balance);
    assert_eq!(
        st.get_spendable_balance(acct_id, ConfirmationsPolicy::MIN),
        initial_balance
    );

    // Generate several empty blocks
    for _ in 0..10 {
        st.generate_empty_block();
    }

    // Scan into the middle of the empty range
    let scanned = st.scan_cached_blocks(next_to_scan, 5);
    let next_to_scan = scanned.scanned_range().end;

    // The initial balance should be unchanged.
    assert_eq!(st.get_total_balance(acct_id), initial_balance);
    assert_eq!(
        st.get_spendable_balance(acct_id, ConfirmationsPolicy::MIN),
        initial_balance
    );

    // Set up the fee rule and input selector we'll use for all the transfers.
    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, P1::SHIELDED_PROTOCOL);

    // First, send funds just to P0
    let transfer_amount = Zatoshis::const_from_u64(200000);
    let p0_transfer = TransactionRequest::new(vec![Payment::without_memo(
        P0::random_address(st.rng_mut()).to_zcash_address(st.network()),
        transfer_amount,
    )])
    .unwrap();
    let res = st
        .spend(
            &input_selector,
            &change_strategy,
            account.usk(),
            p0_transfer,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();
    st.generate_next_block_including(*res.first());

    let expected_fee = Zatoshis::const_from_u64(10000);
    let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
    assert_eq!(
        st.get_total_balance(acct_id),
        ((note_value * 2u64).unwrap() + expected_change).unwrap()
    );
    assert_eq!(
        st.get_pending_change(acct_id, ConfirmationsPolicy::MIN),
        expected_change
    );

    // In the next block, send funds to both P0 and P1
    let both_transfer = TransactionRequest::new(vec![
        Payment::without_memo(
            P0::random_address(st.rng_mut()).to_zcash_address(st.network()),
            transfer_amount,
        ),
        Payment::without_memo(
            P1::random_address(st.rng_mut()).to_zcash_address(st.network()),
            transfer_amount,
        ),
    ])
    .unwrap();
    let res = st
        .spend(
            &input_selector,
            &change_strategy,
            account.usk(),
            both_transfer,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();
    st.generate_next_block_including(*res.first());

    // Generate a few more empty blocks
    for _ in 0..5 {
        st.generate_empty_block();
    }

    // Generate another block with funds for us
    let (max_height, _, _) =
        st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);

    // Scan everything.
    st.scan_cached_blocks(
        next_to_scan,
        usize::try_from(u32::from(max_height) - u32::from(next_to_scan) + 1).unwrap(),
    );

    let expected_final = (initial_balance + note_value
        - (transfer_amount * 3u64).unwrap()
        - (expected_fee * 3u64).unwrap())
    .unwrap();
    assert_eq!(st.get_total_balance(acct_id), expected_final);

    let expected_checkpoints_p0: Vec<(BlockHeight, Option<Position>)> = [
        (99999, None),
        (100000, Some(0)),
        (100001, Some(1)),
        (100002, Some(1)),
        (100007, Some(1)), // synthetic checkpoint in empty span from scan start
        (100013, Some(3)),
        (100014, Some(5)),
        (100020, Some(6)),
    ]
    .into_iter()
    .map(|(h, pos)| (BlockHeight::from(h), pos.map(Position::from)))
    .collect();

    let expected_checkpoints_p1: Vec<(BlockHeight, Option<Position>)> = [
        (99999, None),
        (100000, None),
        (100001, None),
        (100002, Some(0)),
        (100007, Some(0)), // synthetic checkpoint in empty span from scan start
        (100013, Some(0)),
        (100014, Some(2)),
        (100020, Some(2)),
    ]
    .into_iter()
    .map(|(h, pos)| (BlockHeight::from(h), pos.map(Position::from)))
    .collect();

    let p0_checkpoints = st
        .wallet()
        .get_checkpoint_history(&P0::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(p0_checkpoints.to_vec(), expected_checkpoints_p0);

    let p1_checkpoints = st
        .wallet()
        .get_checkpoint_history(&P1::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(p1_checkpoints.to_vec(), expected_checkpoints_p1);
}

#[cfg(feature = "orchard")]
pub fn multi_pool_checkpoints_with_pruning<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    // TODO: Allow for Orchard activation after Sapling
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();

    let account = st.test_account().cloned().unwrap();

    let p0_fvk = P0::random_fvk(st.rng_mut());
    let p1_fvk = P1::random_fvk(st.rng_mut());

    let note_value = Zatoshis::const_from_u64(10000);
    // Generate 100 P0 blocks, then 100 P1 blocks, then another 100 P0 blocks.
    for _ in 0..10 {
        for _ in 0..10 {
            st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
        }
        for _ in 0..10 {
            st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
        }
    }
    st.scan_cached_blocks(account.birthday().height(), 200);
    for _ in 0..100 {
        st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
        st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
    }
    st.scan_cached_blocks(account.birthday().height() + 200, 200);
}

pub fn valid_chain_states<T: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let dfvk = T::test_account_fvk(&st);

    // Empty chain should return None
    assert_matches!(st.wallet().chain_height(), Ok(None));

    // Create a fake CompactBlock sending value to the address
    let (h1, _, _) = st.generate_next_block(
        &dfvk,
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(5),
    );

    // Scan the cache
    st.scan_cached_blocks(h1, 1);

    // Create a second fake CompactBlock sending more value to the address
    let (h2, _, _) = st.generate_next_block(
        &dfvk,
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(7),
    );

    // Scanning should detect no inconsistencies
    st.scan_cached_blocks(h2, 1);
}

// FIXME: This requires fixes to the test framework.
#[allow(dead_code)]
pub fn invalid_chain_cache_disconnected<T: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let dfvk = T::test_account_fvk(&st);

    // Create some fake CompactBlocks
    let (h, _, _) = st.generate_next_block(
        &dfvk,
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(5),
    );
    let (last_contiguous_height, _, _) = st.generate_next_block(
        &dfvk,
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(7),
    );

    // Scanning the cache should find no inconsistencies
    st.scan_cached_blocks(h, 2);

    // Create more fake CompactBlocks that don't connect to the scanned ones
    let disconnect_height = last_contiguous_height + 1;
    st.generate_block_at(
        disconnect_height,
        BlockHash([1; 32]),
        &[FakeCompactOutput::new(
            &dfvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(8),
        )],
        2,
        2,
        0,
        true,
    );
    st.generate_next_block(
        &dfvk,
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(3),
    );

    // Data+cache chain should be invalid at the data/cache boundary
    assert_matches!(
        st.try_scan_cached_blocks(
            disconnect_height,
            2
        ),
        Err(chain::error::Error::Scan(ScanError::PrevHashMismatch { at_height }))
            if at_height == disconnect_height
    );
}

pub fn data_db_truncation<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let dfvk = T::test_account_fvk(&st);

    // Wallet summary is not yet available
    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);

    // Create fake CompactBlocks sending value to the address
    let value = Zatoshis::const_from_u64(50000);
    let value2 = Zatoshis::const_from_u64(70000);
    let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
    st.generate_next_block(&dfvk, AddressType::DefaultExternal, value2);

    // Scan the cache
    st.scan_cached_blocks(h, 2);

    // Spendable balance should reflect both received notes
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        (value + value2).unwrap()
    );

    // "Rewind" to height of last scanned block (this is a no-op)
    st.wallet_mut().truncate_to_height(h + 1).unwrap();

    // Spendable balance should be unaltered
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        (value + value2).unwrap()
    );

    // Rewind so that one block is dropped
    st.wallet_mut().truncate_to_height(h).unwrap();

    // Spendable balance should only contain the first received note;
    // the rest should be pending.
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        value
    );
    assert_eq!(
        st.get_pending_shielded_balance(account.id(), ConfirmationsPolicy::MIN),
        value2
    );

    // Scan the cache again
    st.scan_cached_blocks(h, 2);

    // Account balance should again reflect both received notes
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        (value + value2).unwrap()
    );
}

pub fn truncate_to_chain_state<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    // Test plan:
    // 1. Set up test environment with account
    // 2. Generate and scan initial blocks to populate the note commitment tree
    // 3. Capture the chain state at a specific height
    // 4. Generate and scan blocks beyond PRUNING_DEPTH to ensure early checkpoints are pruned
    // 5. Verify that normal truncate_to_height fails due to missing checkpoints
    // 6. Test that truncate_to_chain_state succeeds using the captured chain state
    // 7. Verify wallet state after truncation

    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let sapling_activation = st
        .network()
        .activation_height(consensus::NetworkUpgrade::Sapling)
        .unwrap();

    // Step 2: Generate and scan initial blocks to populate the note commitment tree.
    // The first block pays the wallet's own account, so the wallet holds a witnessed note
    // below the capture height; without one, a store may satisfy the step-5 truncation by
    // emptying the pool's tree outright (which is tolerated when no witness data would be
    // lost). The remaining blocks use an "other" fvk so that their notes won't be tracked
    // by the wallet (keeping the test focused on tree state rather than wallet balances).
    let account_fvk = T::test_account_fvk(&st);
    let seed = [1u8; 32];
    let other_sk = T::sk(&seed);
    let other_fvk = T::sk_to_fvk(&other_sk);

    let initial_block_count = 8u32;
    st.generate_next_block(
        &account_fvk,
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(10000),
    );
    for _ in 1..initial_block_count {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10000),
        );
    }
    let scan_start = sapling_activation;
    st.scan_cached_blocks(scan_start, initial_block_count as usize);

    // Step 3: Capture the chain state at the current tip. The CachedBlock tracks the
    // exact frontier that corresponds to the end of each generated block.
    let capture_height = sapling_activation + initial_block_count - 1;
    let captured_chain_state = st
        .latest_cached_block()
        .expect("should have cached blocks")
        .chain_state()
        .clone();
    assert_eq!(captured_chain_state.block_height(), capture_height);

    // Step 4: Generate and scan blocks well beyond PRUNING_DEPTH so that the checkpoint
    // at capture_height is pruned from the note commitment tree.
    let extra_blocks = PRUNING_DEPTH + 10;
    for _ in 0..extra_blocks {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(5000),
        );
    }
    st.scan_cached_blocks(capture_height + 1, extra_blocks as usize);

    let tip = st
        .wallet()
        .chain_height()
        .unwrap()
        .expect("chain tip should be set");
    assert!(
        tip >= capture_height + PRUNING_DEPTH,
        "tip should be beyond pruning depth from capture height"
    );

    // Step 5: Verify that truncate_to_height fails at capture_height: the checkpoint there
    // has been pruned, and the wallet holds a witnessed note below that height, so the
    // truncation cannot be satisfied by emptying the tree either.
    let truncation_result = st.wallet_mut().truncate_to_height(capture_height);
    assert!(
        truncation_result.is_err(),
        "truncate_to_height should fail when checkpoint has been pruned"
    );

    // Step 6: truncate_to_chain_state should succeed because it inserts the frontier
    // as a checkpoint before truncating.
    st.wallet_mut()
        .truncate_to_chain_state(captured_chain_state.clone())
        .expect("truncate_to_chain_state should succeed");

    // Step 7: Verify wallet state after truncation.
    // The chain tip should now be at the capture height.
    let new_tip = st
        .wallet()
        .chain_height()
        .unwrap()
        .expect("chain tip should still be set after truncation");
    assert_eq!(new_tip, capture_height);

    // The block hash at capture_height should match what was in the captured chain state.
    let hash_at_capture = st
        .wallet()
        .get_block_hash(capture_height)
        .unwrap()
        .expect("block hash should exist at capture height");
    assert_eq!(hash_at_capture, captured_chain_state.block_hash());

    // Blocks above the capture height should have been removed.
    assert_eq!(
        st.wallet().get_block_hash(capture_height + 1).unwrap(),
        None,
        "blocks above capture height should be removed"
    );
}

pub fn truncate_to_chain_state_below_birthday<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    // Regression test: truncate_to_chain_state should succeed when truncating to a height
    // below the wallet birthday (where no entry exists in the blocks table). Previously,
    // this would fail with RequestedRewindInvalid because select_truncation_height requires
    // the target height to have an entry in the blocks table.

    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .with_initial_chain_state(|rng, network| {
            let birthday_height = network.activation_height(NetworkUpgrade::Sapling).unwrap() + 200;

            let (prior_sapling_roots, sapling_initial_tree) =
                random_sapling_frontier(rng, 1u64, NonZeroU8::new(16).unwrap());
            let prior_sapling_roots = prior_sapling_roots
                .into_iter()
                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 100, root))
                .collect::<Vec<_>>();

            #[cfg(feature = "orchard")]
            let (prior_orchard_roots, orchard_initial_tree) =
                random_orchard_frontier(rng, 1u64, NonZeroU8::new(16).unwrap());
            #[cfg(feature = "orchard")]
            let prior_orchard_roots = prior_orchard_roots
                .into_iter()
                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 100, root))
                .collect::<Vec<_>>();

            // Ironwood is not active at these test heights, so its tree is empty.
            #[cfg(feature = "orchard")]
            let ironwood_initial_tree = Frontier::empty();

            InitialChainState {
                chain_state: ChainState::new(
                    birthday_height - 1,
                    BlockHash([5; 32]),
                    sapling_initial_tree,
                    #[cfg(feature = "orchard")]
                    orchard_initial_tree,
                    #[cfg(feature = "orchard")]
                    ironwood_initial_tree,
                ),
                prior_sapling_roots,
                #[cfg(feature = "orchard")]
                prior_orchard_roots,
            }
        })
        .with_account_having_current_birthday()
        .build();

    // Generate and scan a few initial blocks from the birthday height.
    let other_fvk = T::random_fvk(st.rng_mut());
    let birthday_height = st.test_account().unwrap().birthday().height();

    for _ in 0..5 {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10000),
        );
    }
    st.scan_cached_blocks(birthday_height, 5);

    // Generate and scan blocks well beyond PRUNING_DEPTH to ensure early checkpoints
    // are pruned from the note commitment tree.
    let extra_blocks = PRUNING_DEPTH + 10;
    for _ in 0..extra_blocks {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(5000),
        );
    }
    st.scan_cached_blocks(birthday_height + 5, extra_blocks as usize);

    // Get the prior chain state from the account birthday. This chain state is at
    // birthday_height - 1, which has valid tree frontiers but NO entry in the blocks
    // table (since the wallet never scanned a block at that height).
    let prior_chain_state = st
        .test_account()
        .unwrap()
        .birthday()
        .prior_chain_state()
        .clone();

    // This should succeed. On the buggy code, this fails with RequestedRewindInvalid
    // because select_truncation_height cannot find an entry in the blocks table at the
    // target height.
    let _target_height = prior_chain_state.block_height();
    st.wallet_mut()
        .truncate_to_chain_state(prior_chain_state)
        .expect("truncate_to_chain_state below birthday should succeed");

    // All blocks were above the target height, so they should have been removed.
    assert_eq!(
        st.wallet().get_block_hash(birthday_height).unwrap(),
        None,
        "blocks at birthday height should be removed after truncating below birthday"
    );
}

pub fn truncate_to_chain_state_above_scanned<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    // Regression test: when truncate_to_chain_state is called with a target height above
    // the max scanned height, the frontier insertion must be skipped (it would introduce
    // a subtree root discontinuity) but the scan queue must still be trimmed. Without the
    // fix, inserting a frontier in shard 2 when the wallet only has shard 0 fails because
    // shard 1's subtree root is unknown.

    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let birthday_height = st.test_account().unwrap().birthday().height();

    // Generate and scan initial blocks, then scan beyond PRUNING_DEPTH to ensure
    // early checkpoints are pruned.
    let other_fvk = T::random_fvk(st.rng_mut());
    let initial_blocks = 5u32;
    for _ in 0..initial_blocks {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10000),
        );
    }
    st.scan_cached_blocks(birthday_height, initial_blocks as usize);

    let extra_blocks = PRUNING_DEPTH + 10;
    for _ in 0..extra_blocks {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(5000),
        );
    }
    st.scan_cached_blocks(birthday_height + initial_blocks, extra_blocks as usize);
    let max_scanned = birthday_height + initial_blocks + extra_blocks - 1;

    // Simulate downloading subtree roots from the network: add a known subtree root
    // for shard 0 only. This creates a state where shard 0 exists in the shard store
    // but shard 1 does not.
    T::put_subtree_roots(
        &mut st,
        0,
        &[CommitmentTreeRoot::from_parts(
            birthday_height,
            T::empty_tree_leaf(),
        )],
    )
    .unwrap();

    // Extend the scan queue beyond max_scanned.
    let chain_tip = max_scanned + 500;
    st.wallet_mut().update_chain_tip(chain_tip).unwrap();

    // Construct a ChainState above max_scanned with a frontier in shard 2. The wallet
    // has shard 0 (from put_subtree_roots above) but does NOT have shard 1. Inserting a
    // frontier in shard 2 introduces a discontinuity because shard 1's subtree root is
    // unknown.
    let target_height = max_scanned + 50;
    let shard_2_tree_size: u64 = (0x2 << 16) + 2;
    let (_, shard2_sapling_frontier) =
        random_sapling_frontier(st.rng_mut(), shard_2_tree_size, NonZeroU8::new(16).unwrap());
    #[cfg(feature = "orchard")]
    let (_, shard2_orchard_frontier) =
        random_orchard_frontier(st.rng_mut(), shard_2_tree_size, NonZeroU8::new(16).unwrap());
    // Ironwood is not active at these test heights, so its tree is empty.
    #[cfg(feature = "orchard")]
    let shard2_ironwood_frontier = Frontier::empty();

    let target_chain_state = ChainState::new(
        target_height,
        BlockHash([7; 32]),
        shard2_sapling_frontier,
        #[cfg(feature = "orchard")]
        shard2_orchard_frontier,
        #[cfg(feature = "orchard")]
        shard2_ironwood_frontier,
    );

    // Verify the scan queue extends beyond the target.
    let pre_truncation_tip = st
        .wallet()
        .chain_height()
        .unwrap()
        .expect("chain tip should be set");
    assert!(pre_truncation_tip > target_height);

    // Truncate to the target height, which is above max_scanned. With the fix, this
    // skips the frontier insertion (avoiding the discontinuity) and trims the scan queue.
    // Without the fix, this would fail because inserting a frontier in shard 2 requires
    // shard 1's subtree root, which is unknown.
    st.wallet_mut()
        .truncate_to_chain_state(target_chain_state)
        .expect("truncate_to_chain_state above max scanned should succeed");

    // The scan queue should have been trimmed to the target height.
    let post_truncation_tip = st
        .wallet()
        .chain_height()
        .unwrap()
        .expect("chain tip should still be set after truncation");
    assert_eq!(
        post_truncation_tip, target_height,
        "scan queue should be trimmed to target height, not extend to the old chain tip"
    );

    // Existing blocks below max_scanned should be preserved.
    assert!(
        st.wallet().get_block_hash(max_scanned).unwrap().is_some(),
        "blocks at max_scanned should be preserved"
    );
}

pub fn rewind_to_chain_state_deep<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    // Deep-rewind test plan:
    // 1. Set up a birthday-aligned account.
    // 2. Generate and scan initial blocks to populate the note commitment tree.
    // 3. Pick a rewind target well below the future prune floor.
    // 4. Generate and scan more than PRUNING_DEPTH extra blocks so that the checkpoint at the
    //    target is pruned AND the target lies below `tip - PRUNING_DEPTH` (the "deep" branch).
    // 5. Call `rewind_to_chain_state(target)` and verify:
    //    - the scan queue is rewound all the way to `target`;
    //    - blocks, transactions, tx_locator_map entries, and note commitment trees are
    //      only rewound to `tip - (PRUNING_DEPTH - 1)` (the oldest retained checkpoint).

    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let sapling_activation = st
        .network()
        .activation_height(consensus::NetworkUpgrade::Sapling)
        .unwrap();

    // Generate and scan initial blocks using an "other" fvk so notes are not tracked
    // by the wallet.
    let seed = [1u8; 32];
    let other_fvk = T::sk_to_fvk(&T::sk(&seed));

    let initial_block_count = 8u32;
    for _ in 0..initial_block_count {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10000),
        );
    }
    st.scan_cached_blocks(sapling_activation, initial_block_count as usize);

    // The rewind target is the tip of the initial range.
    let rewind_target = sapling_activation + initial_block_count - 1;

    // Scan more than PRUNING_DEPTH extra blocks so that the checkpoint at rewind_target is pruned
    // AND rewind_target is below `tip - PRUNING_DEPTH`.
    let extra_blocks = PRUNING_DEPTH + 10;
    for _ in 0..extra_blocks {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(5000),
        );
    }
    st.scan_cached_blocks(rewind_target + 1, extra_blocks as usize);

    let pre_rewind_tip = st
        .wallet()
        .chain_height()
        .unwrap()
        .expect("chain tip should be set");
    assert!(
        pre_rewind_tip > rewind_target + PRUNING_DEPTH,
        "tip should be strictly beyond pruning depth from the rewind target"
    );

    // Capture the block hash at the prune boundary so we can assert it survives the rewind
    // unchanged (rather than merely that something exists at that height).
    let prune_boundary = pre_rewind_tip - (PRUNING_DEPTH - 1);
    let boundary_hash_before = st
        .wallet()
        .get_block_hash(prune_boundary)
        .unwrap()
        .expect("block at prune boundary should be present before rewind");

    // `rewind_to_chain_state` must succeed at the same target.
    st.wallet_mut()
        .rewind_to_chain_state(
            ChainState::empty(rewind_target, BlockHash([0; 32])),
            HashSet::new(),
        )
        .expect("rewind_to_chain_state should succeed for a deep target");

    // The chain tip (derived from scan_queue) should still report the pre-rewind tip:
    // `rewind_to_chain_state` overwrites the scan-queue range above the rewind target
    // with a `Historic` rescan range that extends up to the pre-rewind tip.
    let new_tip = st
        .wallet()
        .chain_height()
        .unwrap()
        .expect("chain tip should still be set after rewind");
    assert_eq!(new_tip, pre_rewind_tip);

    // A deep rewind preserves block, transaction, tx_locator_map, and note commitment tree
    // data only as far back as the oldest retained checkpoint at `tip - (PRUNING_DEPTH - 1)`.
    // Data at that boundary is kept (so stabilized notes remain spendable); data above it is
    // removed.
    let wallet = st.wallet();
    assert_eq!(
        wallet.get_block_hash(prune_boundary).unwrap(),
        Some(boundary_hash_before),
        "block hash at (tip - (PRUNING_DEPTH - 1)) should be preserved unchanged by a deep rewind"
    );
    assert!(
        wallet.get_block_hash(prune_boundary + 1).unwrap().is_none(),
        "block entries above (tip - (PRUNING_DEPTH - 1)) must be removed by a deep rewind"
    );
    assert!(
        wallet.get_block_hash(pre_rewind_tip).unwrap().is_none(),
        "block entries up to the pre-rewind tip must be removed by a deep rewind"
    );
    assert_eq!(
        wallet
            .block_max_scanned()
            .unwrap()
            .map(|m| m.block_height()),
        Some(prune_boundary),
        "block_max_scanned should equal (tip - (PRUNING_DEPTH - 1)) after a deep rewind"
    );
}

pub fn rewind_to_chain_state_shallow<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    // Shallow-rewind test plan:
    // 1. Set up a birthday-aligned account.
    // 2. Generate and scan initial blocks to populate the note commitment tree.
    // 3. Pick a rewind target.
    // 4. Generate and scan `PRUNING_DEPTH - 1` extra blocks so that the target sits at
    //    the shallow boundary (`target == tip - (PRUNING_DEPTH - 1)`, exactly the oldest
    //    retained checkpoint).
    // 5. Call `rewind_to_chain_state(target)` and verify all wallet data is rewound to the
    //    target: data at the target is preserved, anything above is removed.

    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let sapling_activation = st
        .network()
        .activation_height(consensus::NetworkUpgrade::Sapling)
        .unwrap();

    let seed = [1u8; 32];
    let other_fvk = T::sk_to_fvk(&T::sk(&seed));

    let initial_block_count = 8u32;
    for _ in 0..initial_block_count {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10000),
        );
    }
    st.scan_cached_blocks(sapling_activation, initial_block_count as usize);

    let rewind_target = sapling_activation + initial_block_count - 1;

    // Scan `PRUNING_DEPTH - 1` extra blocks so the target sits at the shallow boundary
    // (`target == tip - (PRUNING_DEPTH - 1)`, exactly the oldest retained checkpoint
    // given the tree's `max_checkpoints = PRUNING_DEPTH`).
    let extra_blocks = PRUNING_DEPTH - 1;
    for _ in 0..extra_blocks {
        st.generate_next_block(
            &other_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(5000),
        );
    }
    st.scan_cached_blocks(rewind_target + 1, extra_blocks as usize);

    let tip = st
        .wallet()
        .chain_height()
        .unwrap()
        .expect("chain tip should be set");
    assert_eq!(
        tip,
        rewind_target + (PRUNING_DEPTH - 1),
        "tip should be exactly at the shallow boundary from the rewind target"
    );

    let target_hash_before = st
        .wallet()
        .get_block_hash(rewind_target)
        .unwrap()
        .expect("block at the rewind target should be present before rewind");

    st.wallet_mut()
        .rewind_to_chain_state(
            ChainState::empty(rewind_target, BlockHash([0; 32])),
            HashSet::new(),
        )
        .expect("rewind_to_chain_state should succeed for a shallow target");

    // The chain tip (derived from scan_queue) should still report the pre-rewind tip:
    // `rewind_to_chain_state` overwrites the scan-queue range above the rewind target with
    // a `Historic` rescan range that extends up to the pre-rewind tip.
    let new_tip = st
        .wallet()
        .chain_height()
        .unwrap()
        .expect("chain tip should still be set after rewind");
    assert_eq!(new_tip, tip);

    // A shallow rewind truncates blocks, tx_locator_map, and note commitment trees
    // directly to the rewind target: data at the target is preserved (with the same
    // content it had before), anything above is removed.
    let wallet = st.wallet();
    assert_eq!(
        wallet.get_block_hash(rewind_target).unwrap(),
        Some(target_hash_before),
        "block hash at the rewind target should be preserved unchanged"
    );
    assert!(
        wallet.get_block_hash(rewind_target + 1).unwrap().is_none(),
        "block entries above the rewind target should be removed by a shallow rewind"
    );
    assert_eq!(
        wallet
            .block_max_scanned()
            .unwrap()
            .map(|m| m.block_height()),
        Some(rewind_target),
        "block_max_scanned should equal the rewind target after a shallow rewind"
    );
}

pub fn rewind_after_non_contiguous_scan<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    // Regression test: after the scan scheduler processes a `ChainTip` range before a
    // lower `Historic` range, `MAX(height) FROM blocks` points into one scanned region
    // while `last_scanned - (PRUNING_DEPTH - 1)` lands inside the unscanned gap between
    // the two regions. `rewind_to_chain_state` must still succeed: an implementation that
    // expected a checkpoint at exactly the PD floor would return `CorruptedData` via
    // `truncate_to_checkpoint`; clamping forward to the lowest checkpoint inside the
    // prune window keeps us aligned with a real checkpoint.

    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let sapling_activation = st
        .network()
        .activation_height(consensus::NetworkUpgrade::Sapling)
        .unwrap();

    // Scan is always sequential in cache order, but `scan_cached_blocks` is happy to be
    // invoked on subranges out of order. We pre-generate a contiguous chain of blocks
    // and scan it in two disjoint segments with a gap in between.
    let seed = [1u8; 32];
    let other_fvk = T::sk_to_fvk(&T::sk(&seed));
    let filler_value = Zatoshis::const_from_u64(10_000);

    let low_count: u32 = 10;
    let gap_size: u32 = PRUNING_DEPTH + 5; // must exceed PD so the PD floor lands in the gap
    let high_count: u32 = 10;
    let total_generated = low_count + gap_size + high_count;

    for _ in 0..total_generated {
        st.generate_next_block(&other_fvk, AddressType::DefaultExternal, filler_value);
    }

    let low_start = sapling_activation;
    let low_end_inclusive = low_start + low_count - 1;
    let high_start = low_end_inclusive + gap_size + 1;

    // Scan the low range first (simulating a historic range).
    st.scan_cached_blocks(low_start, low_count as usize);

    // Scan the high range next (simulating a chain-tip range), leaving `gap_size` blocks
    // in the middle unscanned. Because `high_start > low_end_inclusive + PRUNING_DEPTH`,
    // the PD floor after this scan (`high_end_inclusive - (PRUNING_DEPTH - 1)`) lands
    // inside the unscanned gap.
    st.scan_cached_blocks(high_start, high_count as usize);

    let max_scanned_height = st
        .wallet()
        .block_max_scanned()
        .unwrap()
        .map(|m| m.block_height())
        .expect("block_max_scanned should report the high-range tip");
    let high_end_inclusive = high_start + high_count - 1;
    assert_eq!(max_scanned_height, high_end_inclusive);
    let pd_floor = max_scanned_height - (PRUNING_DEPTH - 1);
    assert!(
        pd_floor > low_end_inclusive && pd_floor < high_start,
        "test invariant: PD floor must lie in the unscanned gap (got {pd_floor}, \
         gap is ({low_end_inclusive}, {high_start}))"
    );

    // `rewind_to_chain_state` must return `Ok(_)` rather than `CorruptedData`: clamping
    // forward to the lowest checkpoint inside the window (which sits at `high_start`)
    // keeps us aligned with a real checkpoint.
    st.wallet_mut()
        .rewind_to_chain_state(
            ChainState::empty(low_end_inclusive, BlockHash([0; 32])),
            HashSet::new(),
        )
        .expect("rewind_to_chain_state should succeed across a non-contiguous scan");
}

/// Multiple wallet notes in a stabilized shard remain spendable after a deep
/// `rewind_to_chain_state` moves the scan queue below them.
pub fn stabilized_note_spendable_after_deep_rewind<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
where
    T: ShieldedPoolTester,
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    // Test plan:
    // 1. Set up a wallet with an initial chain state whose tree has shard 0 fully
    //    cached and shard 1 one position short of full (frontier at position
    //    `2 * 2^16 - 2 = 131070`). The frontier lives in a partial shard 1 rather
    //    than at a shard boundary; a boundary-aligned frontier would cause
    //    `prior_subtree_roots` to cache shard 1 and then `insert_frontier` would
    //    fail trying to reinstall its leaf into the cached-leaf-form shard.
    // 2. Scan a single block of 65537 outputs. The first output finishes shard 1
    //    (position 131071) and the remaining 65536 outputs fill all of shard 2
    //    (positions 131072..196607). Three of those outputs are wallet-owned and
    //    land at the first, middle, and last slots of shard 2 (tree positions
    //    131072, 163840, and 196607); every other slot is non-wallet filler.
    // 3. Declare shard 2 complete at `note_height` via `put_subtree_roots(2, ...)`
    //    so `mark_stabilized_notes` has the `subtree_end_height` it needs to flip
    //    the shard 2 notes' `witness_stabilized` flag once the pruning floor rises
    //    above the shard.
    // 4. Scan `PRUNING_DEPTH + 10` one-output post-note blocks. They land in shard
    //    3 (positions 196608+), pushing the pruning-floor checkpoint's tree
    //    position into shard 3 so `shardtree::truncate_shards(3)` — invoked by the
    //    upcoming rewind — preserves shard 2 and every row it indexes.
    // 5. Deep-rewind to a height below `note_height` and verify `scan_queue` is
    //    rewound all the way to the target.
    // 6. Before restoring the chain tip: the balance path reads the witness_stabilized
    //    flag directly, so `get_spendable_balance` must return the full
    //    three-note sum; the spend path requires a chain tip for the anchor, so
    //    `propose_transfer` must fail with `ScanRequired`/`InsufficientFunds`.
    // 7. Call `update_chain_tip(pre_rewind_tip)` and re-verify the balance.
    // 8. Build and sign an actual spend — exercising the full note-selection and
    //    witness-construction path — and assert it produces exactly one tx.

    const SHARD_HEIGHT: u32 = 16;
    const SHARD_POSITIONS: u32 = 1 << SHARD_HEIGHT; // 65536

    // Step 1: set up the wallet with shard 0 cached + frontier in a partial shard 1.
    let initial_tree_size: u32 = 2 * SHARD_POSITIONS - 1;

    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .with_initial_chain_state(|rng, network| {
            // The birthday is anchored at NU5 + 1000 rather than the more common
            // Sapling-activation baseline because the orchard variant of this test
            // pre-populates an orchard commitment-tree frontier; that requires
            // Orchard to be active at the birthday height, which isn't true at
            // Sapling activation. `+ 1000` is an arbitrary buffer past NU5 so
            // heights like `birthday_height - 500` (see below) stay comfortably
            // within the activated range.
            let birthday_height = network.activation_height(NetworkUpgrade::Nu5).unwrap() + 1000;

            let (prior_sapling_roots, sapling_initial_tree) = random_sapling_frontier(
                rng,
                initial_tree_size.into(),
                NonZeroU8::new(SHARD_HEIGHT as u8).unwrap(),
            );
            // Shard 0 is the only complete shard at this tree size.
            let prior_sapling_roots = prior_sapling_roots
                .into_iter()
                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
                .collect::<Vec<_>>();

            #[cfg(feature = "orchard")]
            let (prior_orchard_roots, orchard_initial_tree) = random_orchard_frontier(
                rng,
                initial_tree_size.into(),
                NonZeroU8::new(SHARD_HEIGHT as u8).unwrap(),
            );
            #[cfg(feature = "orchard")]
            let prior_orchard_roots = prior_orchard_roots
                .into_iter()
                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
                .collect::<Vec<_>>();

            // Ironwood is not active at these test heights, so its tree is empty.
            #[cfg(feature = "orchard")]
            let ironwood_initial_tree = Frontier::empty();

            InitialChainState {
                chain_state: ChainState::new(
                    birthday_height - 1,
                    BlockHash([5; 32]),
                    sapling_initial_tree,
                    #[cfg(feature = "orchard")]
                    orchard_initial_tree,
                    #[cfg(feature = "orchard")]
                    ironwood_initial_tree,
                ),
                prior_sapling_roots,
                #[cfg(feature = "orchard")]
                prior_orchard_roots,
            }
        })
        .with_account_having_current_birthday()
        .build();

    let dfvk = T::test_account_fvk(&st);
    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
    let filler_value = Zatoshis::const_from_u64(1000);

    // Step 2: scan a single block whose outputs finish shard 1 and fill all of
    // shard 2. Three wallet outputs at the first, middle, and last slots of
    // shard 2; everything else is non-wallet filler. Distinct wallet-output
    // values keep failures easier to diagnose.
    let note_values = [
        Zatoshis::const_from_u64(100_000),
        Zatoshis::const_from_u64(200_000),
        Zatoshis::const_from_u64(150_000),
    ];
    let total_note_value = note_values.iter().sum::<Option<Zatoshis>>().unwrap();
    // Shard 2 spans tree positions 2 * 2^16 .. 3 * 2^16 - 1 = 131072..196607.
    let note_tree_positions: [u32; 3] = [
        2 * SHARD_POSITIONS,                       // first slot of shard 2
        2 * SHARD_POSITIONS + SHARD_POSITIONS / 2, // middle slot of shard 2
        3 * SHARD_POSITIONS - 1,                   // last slot of shard 2
    ];

    let scan_block_size: u32 = SHARD_POSITIONS + 1; // finish shard 1 + fill shard 2
    let first_scanned_position: u32 = initial_tree_size; // = 131071
    let mut outputs = Vec::with_capacity(scan_block_size as usize);
    let mut next_wallet_ix = 0;
    for offset in 0..scan_block_size {
        let tree_pos = first_scanned_position + offset;
        if next_wallet_ix < note_tree_positions.len()
            && tree_pos == note_tree_positions[next_wallet_ix]
        {
            outputs.push(FakeCompactOutput::new(
                dfvk.clone(),
                AddressType::DefaultExternal,
                note_values[next_wallet_ix],
            ));
            next_wallet_ix += 1;
        } else {
            outputs.push(FakeCompactOutput::new(
                not_our_key.clone(),
                AddressType::DefaultExternal,
                filler_value,
            ));
        }
    }
    let (note_height, _, _) = st.generate_next_block_multi(&outputs);
    st.scan_cached_blocks(note_height, 1);

    // Pick a rewind target well below the wallet's birthday so the rewind
    // drops every initially-seeded scan_queue row — exercising the case where
    // stabilized-shard metadata is the only thing keeping the notes spendable.
    let birthday_height = st
        .wallet()
        .get_wallet_birthday()
        .unwrap()
        .expect("account birthday should be set");
    let rewind_target = birthday_height - 100;

    // Step 3: declare shard 2 complete at `note_height`. We must pass shard 2's
    // actual computed root (not an arbitrary placeholder) because the cap already
    // contains annotations inherited from the initial chain state's frontier, and
    // `put_subtree_roots` refuses to install a conflicting root.
    let shard_2_root = T::shard_root(&mut st, 2).unwrap();
    T::put_subtree_roots(
        &mut st,
        2,
        &[CommitmentTreeRoot::from_parts(note_height, shard_2_root)],
    )
    .unwrap();

    // Step 4: scan more than `PRUNING_DEPTH` blocks past the note-filled block
    // into shard 3, so the rewind's truncation position is in shard 3 and the
    // ensuing `truncate_shards(3)` leaves shard 2 intact.
    let extra_blocks = PRUNING_DEPTH + 10;
    for _ in 0..extra_blocks {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
    }
    st.scan_cached_blocks(note_height + 1, extra_blocks as usize);

    let account = st.test_account().unwrap().clone();

    // Step 5: deep-rewind to the target. The rewind target is below the account birthday,
    // so the account must be included in the reset set for the birthday to be lowered.
    // `rewind_to_chain_state` overwrites the scan-queue range above the rewind target with
    // a `Historic` rescan range, so the chain tip remains observable as the pre-rewind tip
    // and notes whose `witness_stabilized = 1` flag survives can still be spent.
    st.wallet_mut()
        .rewind_to_chain_state(
            ChainState::empty(rewind_target, BlockHash([0; 32])),
            HashSet::from([account.id()]),
        )
        .expect("rewind_to_chain_state should succeed");

    // Step 6: balance reflects all three stabilized notes, and a spend can be proposed
    // immediately because the chain tip is preserved by the rewind.
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        total_note_value,
        "all stabilized notes should remain spendable after deep rewind"
    );

    // Step 7: build and sign a real spend end-to-end.
    let to_extsk = T::sk(&[0xcc; 32]);
    let to: Address = T::sk_default_address(&to_extsk);
    let send_value = Zatoshis::const_from_u64(10_000);
    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        send_value,
    )])
    .unwrap();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
    let input_selector = GreedyInputSelector::new();
    let proposal = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .expect("proposal should succeed with stabilized note after deep rewind");
    let txids = st
        .create_proposed_transactions::<std::convert::Infallible, _, std::convert::Infallible, _>(
            account.usk(),
            OvkPolicy::Sender,
            &proposal,
        )
        .expect("spend construction should succeed");
    assert_eq!(
        txids.len(),
        1,
        "the spend should produce exactly one transaction"
    );
}

/// Verifies that when a new account is imported into a fully-scanned wallet,
/// the ensuing re-scan discovers the new account's previously-unknown notes
/// and `scan_complete → mark_stabilized_notes` flags them `witness_stabilized`
/// on the fly, so they remain spendable across a subsequent deep
/// `rewind_to_chain_state`.
pub fn newly_discovered_notes_become_stabilized<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
where
    T: ShieldedPoolTester,
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    // Test plan:
    //
    // 1. Build a fully-scanned wallet containing account A:
    //    (a) install an initial chain state whose commitment tree has shard 0
    //        cached and a frontier sitting in a partial shard 1 (the same
    //        setup used by `stabilized_note_spendable_after_deep_rewind`);
    //    (b) generate one note-containing block at `birthday_height` that
    //        finishes shard 1 and fills shard 2, with three A-owned outputs
    //        and three outputs for a not-yet-imported account B, non-wallet
    //        filler elsewhere;
    //    (c) generate `PRUNING_DEPTH + 10` filler blocks past the note block
    //        to push the pruning floor past shard 2;
    //    (d) scan the note block, declare shard 2 complete via
    //        `put_subtree_roots`, then scan the filler blocks — the
    //        second-batch `mark_stabilized_notes` call flips A's three notes
    //        to `witness_stabilized = 1`. B's outputs are in the cached
    //        blocks but produce no `*_received_notes` rows because B is not
    //        yet in the wallet.
    // 2. Confirm A's notes are spendable (sanity check on the initial
    //    stabilization).
    // 3. Import account B from the same seed at zip32 index 1, sharing A's
    //    `AccountBirthday`. `add_account` rewrites `scan_queue` to replace
    //    the post-birthday `Scanned` range with `Historic`, forcing a
    //    re-scan.
    // 4. Re-scan the cached blocks from the birthday through the chain tip.
    //    The blocks are now processed against both A and B; three new
    //    `*_received_notes` rows get inserted at B's shard-2 positions.
    //    Confirm both accounts' balances reflect their respective totals.
    // 5. Deep-rewind to well below the birthday. A non-stabilized note
    //    cannot pass the post-rewind scan-state gate in
    //    `select_spendable_notes_matching_value`, so if B's notes remain
    //    spendable after this rewind, they *must* have been flagged
    //    `witness_stabilized` during the re-scan of step 4. Assert that both
    //    A's and B's full totals are spendable.

    const SHARD_HEIGHT: u32 = 16;
    const SHARD_POSITIONS: u32 = 1 << SHARD_HEIGHT; // 65536

    // Matches the hard-coded seed used by
    // `TestBuilder::with_account_having_current_birthday`. Re-using it at
    // zip32 index 1 lets us deterministically derive B's viewing key before
    // B is imported, and guarantees that the later `import_account_hd(index=1)`
    // call recovers the same key (zip32 derivation is deterministic).
    const TEST_SEED: [u8; 32] = [0u8; 32];

    // Step 1a: initial tree state — shard 0 fully cached, frontier at one
    // position short of shard 1's last slot. A boundary-aligned frontier
    // would cause `prior_subtree_roots` to cache shard 1 and then
    // `insert_frontier` would fail trying to reinstall its leaf into the
    // cached-leaf-form shard.
    let initial_tree_size: u32 = 2 * SHARD_POSITIONS - 1;

    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .with_initial_chain_state(|rng, network| {
            // The birthday is anchored at NU5 + 1000 rather than the more common
            // Sapling-activation baseline because the orchard variant of this test
            // pre-populates an orchard commitment-tree frontier; that requires
            // Orchard to be active at the birthday height, which isn't true at
            // Sapling activation. `+ 1000` is an arbitrary buffer past NU5 so
            // heights like `birthday_height - 500` (see below) stay comfortably
            // within the activated range.
            let birthday_height = network.activation_height(NetworkUpgrade::Nu5).unwrap() + 1000;

            let (prior_sapling_roots, sapling_initial_tree) = random_sapling_frontier(
                rng,
                initial_tree_size.into(),
                NonZeroU8::new(SHARD_HEIGHT as u8).unwrap(),
            );
            // Each prior subtree root is attached to one arbitrary height
            // well before the birthday. 500 is a round buffer past NU5 but
            // strictly below `birthday_height`; the exact value doesn't
            // matter because stabilization only cares about shard *end*
            // heights.
            let prior_sapling_roots = prior_sapling_roots
                .into_iter()
                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
                .collect::<Vec<_>>();

            #[cfg(feature = "orchard")]
            let (prior_orchard_roots, orchard_initial_tree) = random_orchard_frontier(
                rng,
                initial_tree_size.into(),
                NonZeroU8::new(SHARD_HEIGHT as u8).unwrap(),
            );
            #[cfg(feature = "orchard")]
            let prior_orchard_roots = prior_orchard_roots
                .into_iter()
                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
                .collect::<Vec<_>>();

            // Ironwood is not active at these test heights, so its tree is empty.
            #[cfg(feature = "orchard")]
            let ironwood_initial_tree = Frontier::empty();

            InitialChainState {
                chain_state: ChainState::new(
                    birthday_height - 1,
                    BlockHash([5; 32]),
                    sapling_initial_tree,
                    #[cfg(feature = "orchard")]
                    orchard_initial_tree,
                    #[cfg(feature = "orchard")]
                    ironwood_initial_tree,
                ),
                prior_sapling_roots,
                #[cfg(feature = "orchard")]
                prior_orchard_roots,
            }
        })
        .with_account_having_current_birthday()
        .build();

    let dfvk_a = T::test_account_fvk(&st);
    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
    let filler_value = Zatoshis::const_from_u64(1000);

    // Derive account B's viewing key from the same seed at zip32 index 1.
    // This must run before any scanning so the note block below can place
    // B-destined outputs even though B is absent from the wallet.
    let zip32_index_b = zip32::AccountId::ZERO.next().unwrap();
    let usk_b = UnifiedSpendingKey::from_seed(st.network(), &TEST_SEED, zip32_index_b)
        .expect("account B USK derivation from seed should succeed");
    let fvk_b = T::sk_to_fvk(T::usk_to_sk(&usk_b));

    // Step 1b: build the note block. A's three outputs sit at the first,
    // middle, and last slots of shard 2; B's three outputs occupy adjacent
    // (but distinct) slots. Everything else is non-wallet filler.
    let a_positions: [u32; 3] = [
        2 * SHARD_POSITIONS,                       // first slot of shard 2
        2 * SHARD_POSITIONS + SHARD_POSITIONS / 2, // middle slot of shard 2
        3 * SHARD_POSITIONS - 1,                   // last slot of shard 2
    ];
    let b_positions: [u32; 3] = [
        2 * SHARD_POSITIONS + 1,                       // one after A's first
        2 * SHARD_POSITIONS + SHARD_POSITIONS / 2 + 1, // one after A's middle
        3 * SHARD_POSITIONS - 2,                       // one before A's last
    ];
    let a_values = [
        Zatoshis::const_from_u64(100_000),
        Zatoshis::const_from_u64(200_000),
        Zatoshis::const_from_u64(150_000),
    ];
    let b_values = [
        Zatoshis::const_from_u64(70_000),
        Zatoshis::const_from_u64(80_000),
        Zatoshis::const_from_u64(90_000),
    ];
    let total_a = a_values.iter().sum::<Option<Zatoshis>>().unwrap();
    let total_b = b_values.iter().sum::<Option<Zatoshis>>().unwrap();

    // `scan_block_size = SHARD_POSITIONS + 1`: one slot finishes shard 1,
    // the remaining 65 536 fill all of shard 2.
    let scan_block_size: u32 = SHARD_POSITIONS + 1;
    let first_scanned_position: u32 = initial_tree_size;
    let mut outputs = Vec::with_capacity(scan_block_size as usize);
    for offset in 0..scan_block_size {
        let tree_pos = first_scanned_position + offset;
        let output = if let Some(ix) = a_positions.iter().position(|&p| p == tree_pos) {
            FakeCompactOutput::new(dfvk_a.clone(), AddressType::DefaultExternal, a_values[ix])
        } else if let Some(ix) = b_positions.iter().position(|&p| p == tree_pos) {
            FakeCompactOutput::new(fvk_b.clone(), AddressType::DefaultExternal, b_values[ix])
        } else {
            FakeCompactOutput::new(
                not_our_key.clone(),
                AddressType::DefaultExternal,
                filler_value,
            )
        };
        outputs.push(output);
    }
    let (note_height, _, _) = st.generate_next_block_multi(&outputs);

    // Step 1c: filler blocks past the note block, sized to put the pruning
    // floor past shard 2's end height in step 1d.
    let extra_blocks = PRUNING_DEPTH + 10;
    for _ in 0..extra_blocks {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
    }

    // Step 1d: scan the note block, declare shard 2 complete, scan the
    // filler blocks. The batch ordering mirrors
    // `stabilized_note_spendable_after_deep_rewind`: shard 2's root can
    // only be computed after its leaves are in the wallet's tree, and
    // `put_subtree_roots` must run before the next scan batch so
    // `mark_stabilized_notes` sees shard 2's `subtree_end_height`.
    st.scan_cached_blocks(note_height, 1);
    let shard_2_root = T::shard_root(&mut st, 2).unwrap();
    T::put_subtree_roots(
        &mut st,
        2,
        &[CommitmentTreeRoot::from_parts(note_height, shard_2_root)],
    )
    .unwrap();
    st.scan_cached_blocks(note_height + 1, extra_blocks as usize);

    let account_a = st.test_account().unwrap().clone();

    // Step 2: baseline. A's notes are discovered and stabilized; B's
    // outputs have no corresponding wallet rows (B absent).
    assert_eq!(
        st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
        total_a,
        "A's three notes must be spendable after the initial scan + stabilization",
    );

    // Step 3: import account B, sharing A's birthday so `add_account`
    // rewrites the post-birthday `Scanned` range to `Historic` (forcing
    // a re-scan).
    let b_birthday = account_a.birthday().clone();
    let seed = Secret::new(TEST_SEED.to_vec());
    let (account_b, _usk_b) = st
        .wallet_mut()
        .import_account_hd("account B", &seed, zip32_index_b, &b_birthday, None)
        .expect("account B import should succeed");

    // Step 4: re-scan every cached block at or after the birthday. The
    // blocks were previously processed only against A; now they're
    // processed against B too, inserting three new `*_received_notes`
    // rows at B's shard-2 positions. After this batch
    // `mark_stabilized_notes` runs and should flip B's new rows to
    // `witness_stabilized = 1`.
    st.scan_cached_blocks(note_height, (1 + extra_blocks) as usize);

    assert_eq!(
        st.get_spendable_balance(account_b.id(), ConfirmationsPolicy::MIN),
        total_b,
        "B's three newly-discovered notes must be spendable after the re-scan",
    );
    assert_eq!(
        st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
        total_a,
        "A's notes must remain spendable across B's import and re-scan",
    );

    // Step 5: deep-rewind. The rewind target sits well below the wallet's
    // birthday so `scan_queue` is rewound all the way out of any range
    // covering shard 2. Only notes flagged `witness_stabilized = 1` can
    // pass the post-rewind scan-state gate in
    // `select_spendable_notes_matching_value`; any B note that was never
    // stabilized would drop out of the balance here.
    let rewind_target = account_a.birthday().height() - 100;
    st.wallet_mut()
        .rewind_to_chain_state(
            ChainState::empty(rewind_target, BlockHash([0; 32])),
            HashSet::from([account_a.id(), account_b.id()]),
        )
        .expect("rewind_to_chain_state should succeed");

    assert_eq!(
        st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
        total_a,
        "A's notes must survive the deep rewind, confirming they were and \
         remain witness_stabilized",
    );
    assert_eq!(
        st.get_spendable_balance(account_b.id(), ConfirmationsPolicy::MIN),
        total_b,
        "B's three re-scan-discovered notes must survive the deep rewind, \
         confirming that mark_stabilized_notes fired on the freshly-inserted \
         B rows during the re-scan",
    );
}

pub fn reorg_to_checkpoint<T: ShieldedPoolTester, Dsf, C>(ds_factory: Dsf, cache: C)
where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
    C: TestCache,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();

    // Create a sequence of blocks to serve as the foundation of our chain state.
    let p0_fvk = T::random_fvk(st.rng_mut());
    let gen_random_block = |st: &mut TestState<C, Dsf::DataStore, LocalNetwork>,
                            output_count: usize| {
        let fake_outputs =
            std::iter::repeat_with(|| FakeCompactOutput::random(st.rng_mut(), p0_fvk.clone()))
                .take(output_count)
                .collect::<Vec<_>>();
        st.generate_next_block_multi(&fake_outputs[..]);
        output_count
    };

    // The stable portion of the tree will contain 20 notes.
    for _ in 0..10 {
        gen_random_block(&mut st, 4);
    }

    // We will reorg to this height.
    let reorg_height = account.birthday().height() + 4;
    let reorg_position = Position::from(19);

    // Scan the first 5 blocks. The last block in this sequence will be where we simulate a
    // reorg.
    st.scan_cached_blocks(account.birthday().height(), 5);
    assert_eq!(
        st.wallet()
            .block_max_scanned()
            .unwrap()
            .unwrap()
            .block_height(),
        reorg_height
    );

    // There will be 6 checkpoints: one for the prior block frontier, and then one for each scanned
    // block.
    let checkpoints = st
        .wallet()
        .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(checkpoints.len(), 6);
    assert_eq!(
        checkpoints.last(),
        Some(&(reorg_height, Some(reorg_position)))
    );

    // Scan another block, then simulate a reorg.
    st.scan_cached_blocks(reorg_height + 1, 1);
    assert_eq!(
        st.wallet()
            .block_max_scanned()
            .unwrap()
            .unwrap()
            .block_height(),
        reorg_height + 1
    );
    let checkpoints = st
        .wallet()
        .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(checkpoints.len(), 7);
    assert_eq!(
        checkpoints.last(),
        Some(&(reorg_height + 1, Some(reorg_position + 4)))
    );

    //        /\  /\  /\
    //  .... /\/\/\/\/\/\
    //          c   d   e

    // Truncate back to the reorg height, but retain the block cache.
    st.truncate_to_height_retaining_cache(reorg_height);

    // The following error-prone tree state is generated by the a previous (buggy) truncate
    // implementation:
    //        /\  /\
    //  .... /\/\/\/\
    //          c

    // We have pruned back to the original checkpoints & tree state.
    let checkpoints = st
        .wallet()
        .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
        .unwrap();
    assert_eq!(checkpoints.len(), 6);
    assert_eq!(
        checkpoints.last(),
        Some(&(reorg_height, Some(reorg_position)))
    );

    // Skip two blocks, then (re) scan the same block.
    st.scan_cached_blocks(reorg_height + 2, 1);

    // Given the buggy truncation, this would result in this the following tree state:
    //        /\  /\   \  /\
    //  .... /\/\/\/\   \/\/\
    //          c       e   f

    let checkpoints = st
        .wallet()
        .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
        .unwrap();
    // Even though we only scanned one block, we get a checkpoint at both the start and the end of
    // the block due to the insertion of the prior block frontier.
    assert_eq!(checkpoints.len(), 8);
    assert_eq!(
        checkpoints.last(),
        Some(&(reorg_height + 2, Some(reorg_position + 8)))
    );

    // Now, fully truncate back to the reorg height. This should leave the tree in a state
    // where it can be added to with arbitrary notes.
    st.truncate_to_height(reorg_height);

    // Generate some new random blocks
    for _ in 0..10 {
        let output_count = st.rng_mut().gen_range(2..10);
        gen_random_block(&mut st, output_count);
    }

    // The previous truncation retained the cache, so re-scanning the same blocks would have
    // resulted in the same note commitment tree state, and hence no conflicts; could occur. Now
    // that we have cleared the cache and generated a different sequence blocks, if truncation did
    // not completely clear the tree state this would generates a note commitment tree conflict.
    st.scan_cached_blocks(reorg_height + 1, 1);
}

pub fn scan_cached_blocks_allows_blocks_out_of_order<T: ShieldedPoolTester>(
    ds_factory: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let dfvk = T::test_account_fvk(&st);

    let value = Zatoshis::const_from_u64(50000);
    let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
    st.scan_cached_blocks(h1, 1);
    assert_eq!(st.get_total_balance(account.id()), value);

    // Create blocks to reach height + 2
    let (h2, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
    let (h3, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);

    // Scan the later block first
    st.scan_cached_blocks(h3, 1);

    // Now scan the block of height height + 1
    st.scan_cached_blocks(h2, 1);
    assert_eq!(
        st.get_total_balance(account.id()),
        Zatoshis::const_from_u64(150_000)
    );

    // We can spend the received notes
    let req = TransactionRequest::new(vec![Payment::without_memo(
        T::fvk_default_address(&dfvk).to_zcash_address(st.network()),
        Zatoshis::const_from_u64(110_000),
    )])
    .unwrap();

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);

    assert_matches!(
        st.spend(
            &input_selector,
            &change_strategy,
            account.usk(),
            req,
            OvkPolicy::Sender,
            ConfirmationsPolicy::MIN,
        ),
        Ok(_)
    );
}

pub fn scan_cached_blocks_finds_received_notes<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let dfvk = T::test_account_fvk(&st);

    // Wallet summary is not yet available
    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);

    // Create a fake CompactBlock sending value to the address
    let value = Zatoshis::const_from_u64(50000);
    let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);

    // Scan the cache
    let summary = st.scan_cached_blocks(h1, 1);
    assert_eq!(summary.scanned_range().start, h1);
    assert_eq!(summary.scanned_range().end, h1 + 1);
    assert_eq!(T::received_note_count(&summary), 1);

    // Account balance should reflect the received note
    assert_eq!(st.get_total_balance(account.id()), value);

    // Create a second fake CompactBlock sending more value to the address
    let value2 = Zatoshis::const_from_u64(70000);
    let (h2, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value2);

    // Scan the cache again
    let summary = st.scan_cached_blocks(h2, 1);
    assert_eq!(summary.scanned_range().start, h2);
    assert_eq!(summary.scanned_range().end, h2 + 1);
    assert_eq!(T::received_note_count(&summary), 1);

    // Account balance should reflect both received notes
    assert_eq!(
        st.get_total_balance(account.id()),
        (value + value2).unwrap()
    );
}

pub fn scan_cached_blocks_finds_change_notes<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let dfvk = T::test_account_fvk(&st);

    // Wallet summary is not yet available
    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);

    // Create a fake CompactBlock sending value to the address
    let value = Zatoshis::const_from_u64(50000);
    let (_, _, nf) = st.add_a_single_note_checking_balance(value);

    // Create a second fake CompactBlock spending value from the address
    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
    let to2 = T::fvk_default_address(&not_our_key);
    let value2 = Zatoshis::const_from_u64(20000);
    let (spent_height, _) = st.generate_next_block_spending(&dfvk, (nf, value), to2, value2);

    // Scan the cache again
    st.scan_cached_blocks(spent_height, 1);

    // Account balance should equal the change
    assert_eq!(
        st.get_total_balance(account.id()),
        (value - value2).unwrap()
    );
}

pub fn scan_cached_blocks_detects_spends_out_of_order<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let account = st.test_account().cloned().unwrap();
    let dfvk = T::test_account_fvk(&st);

    // Wallet summary is not yet available
    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);

    // Create a fake CompactBlock sending value to the address
    let value = Zatoshis::const_from_u64(50000);
    let (received_height, _, nf) =
        st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);

    // Create a second fake CompactBlock spending value from the address
    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
    let to2 = T::fvk_default_address(&not_our_key);
    let value2 = Zatoshis::const_from_u64(20000);
    let (spent_height, _) = st.generate_next_block_spending(&dfvk, (nf, value), to2, value2);

    // Scan the spending block first.
    st.scan_cached_blocks(spent_height, 1);

    // Account balance should equal the change
    assert_eq!(
        st.get_total_balance(account.id()),
        (value - value2).unwrap()
    );

    // Now scan the block in which we received the note that was spent.
    st.scan_cached_blocks(received_height, 1);

    // Account balance should be the same.
    assert_eq!(
        st.get_total_balance(account.id()),
        (value - value2).unwrap()
    );
}

/// Note selection draws the OLDEST eligible notes first, where age is chain order — the note's
/// commitment tree position — not discovery order. Priority scanning discovers recent blocks
/// before back-filling history, so a restored wallet's newest notes carry its lowest row ids;
/// ordering by id would spend fresh change while far older notes sat idle. The ordering must
/// therefore survive scanning blocks out of order.
pub fn oldest_note_is_selected_first<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
    let account = st.test_account().cloned().unwrap();
    let dfvk = T::test_account_fvk(&st);

    // Two notes; the OLDER one is larger, so which note a small selection returns identifies
    // the ordering in use.
    let older_value = Zatoshis::const_from_u64(500_000);
    let newer_value = Zatoshis::const_from_u64(300_000);
    let (older_height, _, _) =
        st.generate_next_block(&dfvk, AddressType::DefaultExternal, older_value);
    let (newer_height, _, _) =
        st.generate_next_block(&dfvk, AddressType::DefaultExternal, newer_value);

    // Scan the NEWER block first: its note is discovered first and takes the lower row id,
    // exactly as happens to recent notes when a restored wallet syncs tip-first.
    st.scan_cached_blocks(newer_height, 1);
    st.scan_cached_blocks(older_height, 1);

    // Either note alone covers the target, so selection returns exactly one — the OLDER.
    let selected = T::select_spendable_notes(
        &st,
        account.id(),
        TargetValue::AtLeast(Zatoshis::const_from_u64(200_000)),
        TargetHeight::from(newer_height + 1),
        ConfirmationsPolicy::MIN,
        &[],
    )
    .unwrap();
    assert_eq!(selected.len(), 1, "a single note covers the target");
    assert_eq!(
        T::note_value(selected.first().expect("nonempty").note()),
        older_value,
        "the oldest sufficient note must be drawn first, not the first-discovered"
    );
}

pub fn metadata_queries_exclude_unwanted_notes<T: ShieldedPoolTester, Dsf, TC>(
    ds_factory: Dsf,
    cache: TC,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
    TC: TestCache,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    // Create 10 blocks with successively increasing value
    let note_values = (1..=10)
        .map(|i| Zatoshis::const_from_u64(i * 100_0000))
        .collect::<Vec<_>>();
    let h0 = st
        .add_notes_checking_balance(note_values.clone().into_iter().map(Some))
        .first_block_height()
        .unwrap();

    let target_height = TargetHeight::from(h0 + 10);
    let account = st.test_account().cloned().unwrap();
    let test_meta = |st: &TestState<TC, Dsf::DataStore, LocalNetwork>, query, expected_count| {
        let metadata = st
            .wallet()
            .get_account_metadata(
                account.id(),
                &query,
                target_height,
                &[],
                LockFilter::Unfiltered,
            )
            .unwrap();

        assert_eq!(metadata.note_count(T::SHIELDED_PROTOCOL), expected_count);
    };

    test_meta(
        &st,
        NoteFilter::ExceedsMinValue(Zatoshis::const_from_u64(1000_0000)),
        Some(0),
    );
    test_meta(
        &st,
        NoteFilter::ExceedsMinValue(Zatoshis::const_from_u64(500_0000)),
        Some(5),
    );
    test_meta(
        &st,
        NoteFilter::ExceedsBalancePercentage(BoundedU8::new_const(10)),
        Some(5),
    );

    // We haven't sent any funds yet, so we can't evaluate this query
    test_meta(
        &st,
        NoteFilter::ExceedsPriorSendPercentile(BoundedU8::new_const(50)),
        None,
    );

    // Spend half of each one of our notes, so that we can get a distribution of sent note values.
    // FIXME: This test is currently excessively specialized to the `zcash_client_sqlite::WalletDb`
    // implmentation of the `InputSource` trait. A better approach would be to create a test input
    // source that can select a set of notes directly based upon their nullifiers.
    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
    let to = T::fvk_default_address(&not_our_key).to_zcash_address(st.network());
    let nz2 = NonZeroU64::new(2).unwrap();

    for value in &note_values {
        let txids = st
            .create_standard_transaction(&account, to.clone(), *value / nz2)
            .unwrap();
        st.generate_next_block_including(txids.head);
    }
    st.scan_cached_blocks(h0 + 10, 10);

    // Since we've spent half our notes, our remaining notes each have approximately half their
    // original value. The 50th percentile of our spends should be 250_0000 ZAT, and half of our
    // remaining notes should have value greater than that.
    test_meta(
        &st,
        NoteFilter::ExceedsPriorSendPercentile(BoundedU8::new_const(50)),
        Some(5),
    );
}

#[cfg(feature = "pczt")]
pub fn pczt_single_step<P0: ShieldedPoolTester, P1: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
    pin_expiry_above_target: Option<u32>,
) where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: serde::Serialize + serde::de::DeserializeOwned,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .with_initial_chain_state(|_, network| {
            // Initialize the chain state to after ZIP 212 became enforced.
            let birthday_height = std::cmp::max(
                network.activation_height(NetworkUpgrade::Nu5).unwrap(),
                network.activation_height(NetworkUpgrade::Canopy).unwrap() + ZIP212_GRACE_PERIOD,
            );

            // Ironwood is not active at these test heights, so its tree is empty.
            #[cfg(feature = "orchard")]
            let ironwood_initial_tree = Frontier::empty();

            InitialChainState {
                chain_state: ChainState::new(
                    birthday_height - 1,
                    BlockHash([5; 32]),
                    Frontier::empty(),
                    #[cfg(feature = "orchard")]
                    Frontier::empty(),
                    #[cfg(feature = "orchard")]
                    ironwood_initial_tree,
                ),
                prior_sapling_roots: vec![],
                #[cfg(feature = "orchard")]
                prior_orchard_roots: vec![],
            }
        })
        .with_account_having_current_birthday()
        .build();

    let account = st.test_account().cloned().unwrap();

    let p0_fvk = P0::test_account_fvk(&st);

    let p1_fvk = P1::test_account_fvk(&st);
    let p1_to = P1::fvk_default_address(&p1_fvk);

    // Only mine a block in P0 to ensure the transactions source is there.
    let note_value = Zatoshis::const_from_u64(350000);
    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
    st.scan_cached_blocks(account.birthday().height(), 1);

    assert_eq!(st.get_total_balance(account.id()), note_value);
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        note_value
    );

    let transfer_amount = Zatoshis::const_from_u64(200000);
    let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
        p1_to.to_zcash_address(st.network()),
        transfer_amount,
    )])
    .unwrap();

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, P0::SHIELDED_PROTOCOL);
    let proposal0 = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            p0_to_p1,
            ConfirmationsPolicy::MIN,
        )
        .unwrap();

    let min_target_height = proposal0.min_target_height();
    assert_eq!(proposal0.steps().len(), 1);

    let expiry_height =
        pin_expiry_above_target.map(|delta| BlockHeight::from(min_target_height) + delta);

    if expiry_height.is_some() {
        // This is rejected before transaction building, so the successful call below
        // can reuse the same proposal.
        assert_matches!(
            st.create_pczt_from_proposal::<Infallible, _, Infallible>(
                account.id(),
                OvkPolicy::Sender,
                &proposal0,
                Some(min_target_height.saturating_sub(1)),
            ),
            Err(Error::ExpiryHeightBelowTargetHeight { .. })
        );
    }

    let create_proposed_result = st.create_pczt_from_proposal::<Infallible, _, Infallible>(
        account.id(),
        OvkPolicy::Sender,
        &proposal0,
        expiry_height,
    );
    assert_matches!(&create_proposed_result, Ok(_));
    let pczt_created = create_proposed_result.unwrap();
    let pczt_branch_id =
        consensus::BranchId::try_from(*pczt_created.global().consensus_branch_id())
            .expect("the PCZT carries a valid consensus branch ID");

    // Signability invariant: the test account's derivation is known, so every
    // shielded spend must be signable by SOME party: already signed
    // (IO-finalized protocol dummies), carrying the dummy key that lets the IO
    // Finalizer sign it, or exposing the ZIP 32 derivation metadata by which
    // an external Signer identifies the spend as its own. A spend meeting none
    // of these is unsignable and dooms transaction extraction.
    fn assert_signable_orchard_bundle(bundle: &orchard::pczt::Bundle) {
        for action in bundle.actions() {
            assert!(
                action.spend().spend_auth_sig().is_some()
                    || action.spend().dummy_sk().is_some()
                    || action.spend().zip32_derivation().is_some(),
                "unsignable Orchard-protocol spend: no signature, dummy key, or derivation",
            );
        }
    }
    pczt::roles::verifier::Verifier::new(pczt_created.clone())
        .with_orchard::<Infallible, _>(|bundle| {
            assert_signable_orchard_bundle(bundle);
            Ok(())
        })
        .unwrap()
        .with_ironwood::<Infallible, _>(|bundle| {
            assert_signable_orchard_bundle(bundle);
            Ok(())
        })
        .unwrap()
        .with_sapling::<Infallible, _>(|bundle| {
            for spend in bundle.spends() {
                assert!(
                    spend.spend_auth_sig().is_some()
                        || spend.proof_generation_key().is_some()
                        || spend.zip32_derivation().is_some(),
                    "unsignable Sapling spend: no signature, dummy proving material, or derivation",
                );
            }
            Ok(())
        })
        .unwrap();

    // If we don't create proofs or signatures, we will fail to extract a transaction.
    assert_matches!(
        st.extract_and_store_transaction_from_pczt(pczt_created.clone()),
        Err(Error::Pczt(data_api::error::PcztError::Extraction(_)))
    );

    // Add proof generation keys to Sapling spends.
    let pczt_updated = P0::add_proof_generation_keys(pczt_created, account.usk()).unwrap();

    // Create proofs, using the circuit that governs the Orchard pool under the
    // consensus branch the PCZT was created for. (The test network's most recent
    // upgrade is NU5, so this is currently the historical pre-NU6.2 circuit;
    // modernizing the test network fixture is part of the broader Ironwood test
    // coverage work.)
    let sapling_prover = LocalTxProver::bundled();
    let orchard_pk = zcash_primitives::transaction::builder::cached_orchard_proving_key(
        zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
            pczt_branch_id,
            ::orchard::ValuePool::Orchard,
        )
        .expect("the PCZT's consensus branch supports the Orchard pool")
        .circuit_version(),
    );
    let pczt_proven = Prover::new(pczt_updated)
        .create_orchard_proof(orchard_pk)
        .unwrap()
        .create_sapling_proofs(&sapling_prover, &sapling_prover)
        .unwrap()
        .finish();

    // The signer view of a v5 PCZT commits to the same transaction effects. V5
    // anchors are retained, while Orchard effecting fields are compacted using
    // the v2 PCZT encoding. Passing the proof-bearing authoritative copy also
    // exercises redaction of data that the external Signer does not need.
    let original_sighash = Signer::new(pczt_proven.clone()).unwrap().shielded_sighash();
    let original_len = pczt_proven.clone().serialize().unwrap().len();
    let signer_view = redact_pczt_for_signer(&pczt_proven, SignerView::Compact);
    assert_eq!(
        *signer_view.global().tx_version(),
        zcash_protocol::constants::V5_TX_VERSION,
    );
    assert_eq!(
        signer_view.sapling().anchor(),
        pczt_proven.sapling().anchor()
    );
    assert_eq!(
        signer_view.orchard().anchor(),
        pczt_proven.orchard().anchor()
    );
    if !signer_view.orchard().actions().is_empty() {
        assert!(pczt::v1::Pczt::try_from(signer_view.clone()).is_err());
        assert!(
            signer_view
                .orchard()
                .actions()
                .iter()
                .all(|action| action.cv_net().is_none() && action.output().cmx().is_none())
        );
    }

    let signer_view_bytes = signer_view.serialize().unwrap();
    assert!(signer_view_bytes.len() < original_len);
    let signer_view = pczt::Pczt::parse(&signer_view_bytes).unwrap();
    assert_eq!(
        Signer::new(signer_view.clone()).unwrap().shielded_sighash(),
        original_sighash,
    );

    // The full signer view is for receivers that predate the compact view:
    // it commits to the same transaction effects, retains proofs and anchors,
    // clears witnesses and dummy signing keys, and (for v5 transactions)
    // remains representable in the v1 PCZT encoding.
    let full_view = redact_pczt_for_signer(&pczt_proven, SignerView::Full);
    assert_eq!(
        Signer::new(full_view.clone()).unwrap().shielded_sighash(),
        original_sighash,
    );
    assert_eq!(full_view.orchard().anchor(), pczt_proven.orchard().anchor());
    assert_eq!(full_view.sapling().anchor(), pczt_proven.sapling().anchor());
    assert_eq!(
        full_view.orchard().zkproof().is_some(),
        pczt_proven.orchard().zkproof().is_some(),
    );
    assert!(full_view.orchard().actions().iter().all(|action| {
        action.spend().witness().is_none() && action.spend().dummy_sk().is_none()
    }));
    assert!(
        full_view
            .sapling()
            .spends()
            .iter()
            .all(|spend| spend.witness().is_none())
    );
    // Redaction's primary purpose is removing the wallet's proprietary metadata,
    // which the Signer has no use for and should never see.
    assert!(
        !full_view
            .global()
            .proprietary()
            .contains_key("zcash_client_backend:proposal_info")
    );
    for bundle in [full_view.orchard(), full_view.ironwood()] {
        assert!(bundle.actions().iter().all(|action| {
            !action
                .output()
                .proprietary()
                .contains_key("zcash_client_backend:output_info")
        }));
    }
    assert!(full_view.sapling().outputs().iter().all(|output| {
        !output
            .proprietary()
            .contains_key("zcash_client_backend:output_info")
    }));
    assert!(full_view.transparent().outputs().iter().all(|output| {
        !output
            .proprietary()
            .contains_key("zcash_client_backend:output_info")
    }));
    if *full_view.global().tx_version() == zcash_protocol::constants::V5_TX_VERSION {
        let full_view_bytes = full_view.clone().serialize().unwrap();
        assert!(pczt::v1::Pczt::try_from(full_view).is_ok());
        assert_eq!(
            u32::from_le_bytes(full_view_bytes[4..8].try_into().unwrap()),
            1,
            "the full signer view of a v5 PCZT serializes in the v1 encoding",
        );
    }

    // Apply signatures to the transported signer view, then combine the
    // contribution with the proof-bearing authoritative copy.
    let mut signer = Signer::new(signer_view).unwrap();
    P0::apply_signatures_to_pczt(&mut signer, account.usk()).unwrap();
    let pczt_authorized = Combiner::new(vec![pczt_proven, signer.finish()])
        .combine()
        .unwrap();

    // Now we can extract the transaction.
    let extract_and_store_result = st.extract_and_store_transaction_from_pczt(pczt_authorized);
    assert_matches!(&extract_and_store_result, Ok(_));
    let txid = extract_and_store_result.unwrap();

    if let Some(expiry_height) = expiry_height {
        let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
        assert_eq!(tx.expiry_height(), expiry_height);
    }

    let (h, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(h, 1);
}

/// Ensure that wallet recovery recomputes fees.
///
/// Callers must provide an `intervene` function that deletes fee information for the specified
/// txid from the database. This deletion is checked and the test will fail if fee information is
/// not deleted.
#[cfg(feature = "transparent-inputs")]
pub fn wallet_recovery_computes_fees<T: ShieldedPoolTester, DsF: DataStoreFactory>(
    ds_factory: DsF,
    cache: impl TestCache,
    mut intervene: impl FnMut(&mut DsF::DataStore, TxId) -> Result<(), DsF::DsError>,
) {
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();

    let seed = Secret::new(st.test_seed().unwrap().expose_secret().clone());
    let source_account = st.test_account().cloned().unwrap();
    let (dest_account_id, dest_usk) = st
        .wallet_mut()
        .create_account("dest", &seed, source_account.birthday(), None)
        .unwrap();

    let (to, _) = dest_usk.default_transparent_address();

    // Get some funds in the source account
    let note_value = Zatoshis::const_from_u64(350000);
    let _summary = st.add_notes_checking_balance([Some(note_value), Some(note_value)]);

    // Create two transactions sending from the source account to a transparent address in the
    // destination account.
    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
    let transfer_amount = Zatoshis::const_from_u64(200000);
    let request = TransactionRequest::new(vec![Payment::without_memo(
        Address::from(to).to_zcash_address(st.network()),
        transfer_amount,
    )])
    .unwrap();

    let mut send_transparent = || {
        let p0 = st
            .propose_transfer(
                source_account.id(),
                &input_selector,
                &change_strategy,
                request.clone(),
                ConfirmationsPolicy::MIN,
            )
            .unwrap();
        let result0 = st
            .create_proposed_transactions::<Infallible, _, Infallible, _>(
                source_account.usk(),
                OvkPolicy::Sender,
                &p0,
            )
            .unwrap();
        assert_eq!(result0.len(), 1);
        let txid = result0[0];
        let (h, _) = st.generate_next_block_including(txid);
        st.scan_cached_blocks(h, 1);

        // Make the destination account aware of the received UTXOs
        let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
        let t_bundle = tx.transparent_bundle().unwrap();
        assert_eq!(t_bundle.vout.len(), 1);

        let outpoint = OutPoint::new(*txid.as_ref(), 0);
        let utxo = WalletTransparentOutput::from_parts(
            outpoint,
            t_bundle.vout[0].clone(),
            Some(h),
            Some(dest_account_id),
            Some(TransparentKeyScope::EXTERNAL),
            None,
        )
        .unwrap();
        st.wallet_mut()
            .put_received_transparent_utxo(&utxo)
            .unwrap();

        (txid, h)
    };

    send_transparent();
    let (input_tx_1_txid, input_tx_1_height) = send_transparent();

    assert_eq!(
        st.get_total_balance(dest_account_id),
        (transfer_amount + transfer_amount).unwrap()
    );

    // Shield the funds in the destination account
    let p1 = st
        .propose_shielding(
            &input_selector,
            &change_strategy,
            Zatoshis::const_from_u64(10000),
            &[to],
            dest_account_id,
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::AllTransparentOutputs,
        )
        .unwrap();
    let result1 = st
        .create_proposed_transactions::<Infallible, _, Infallible, _>(
            &dest_usk,
            OvkPolicy::Sender,
            &p1,
        )
        .unwrap();
    assert_eq!(result1.len(), 1);
    let txid = result1[0];
    let (h, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(h, 1);

    // Since our wallet constructed the transaction, we have the fee information;
    // we will need to wipe it out via a backend-level intervention in order to simulate
    // what happens in recovery.
    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
    assert_matches!(shielding_tx.fee_paid, Some(_));
    let created_fee = shielding_tx.fee_paid.unwrap();

    intervene(st.wallet_mut(), txid).unwrap();

    // Verify that the intervention removed the fee information for the transaction.
    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
    assert_matches!(shielding_tx.fee_paid, None);

    // Run `decrypt_and_store_transaction; this should restore the fee, since the wallet has all of
    // the necessary input and output data.
    let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
    let network = *st.network();
    decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(h)).unwrap();

    // Verify that the fee information has been restored.
    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
    assert_eq!(shielding_tx.fee_paid, Some(created_fee));

    // Wipe the fee information again; calling `decrypt_and_store_transaction` with the *input* tx
    // should also cause the fees to be restored.
    intervene(st.wallet_mut(), txid).unwrap();

    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
    assert_matches!(shielding_tx.fee_paid, None);

    // Run `decrypt_and_store_transaction with one of the inputs; this should also restore the fee,
    // since the wallet has all of the necessary input and output data.
    let tx = st
        .wallet()
        .get_transaction(input_tx_1_txid)
        .unwrap()
        .unwrap();
    let network = *st.network();
    decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(input_tx_1_height)).unwrap();

    // Verify that the fee information has been restored.
    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
    assert_eq!(shielding_tx.fee_paid, Some(created_fee));
}

/// Tests that the wallet correctly reports balance with two notes that are identical
/// other than their note randomness.
pub fn receive_two_notes_with_same_value<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Add funds to the wallet in two identical notes
    let value = Zatoshis::const_from_u64(60000);
    let h = st
        .add_notes_checking_balance([[value, value]])
        .block_height()
        .unwrap();

    // Spendable balance matches total balance.
    let account = st.test_account().cloned().unwrap();
    let total_value = (value + value).unwrap();
    assert_eq!(
        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
        total_value
    );

    let target_height = (h + 1).into();

    // Both notes are unspent.
    let unspent_notes = T::select_unspent_notes(&st, account.id(), target_height, &[]).unwrap();
    assert_eq!(unspent_notes.len(), 2);
    for note in unspent_notes {
        assert_eq!(T::note_value(note.note()), value);
    }

    // Both notes are spendable with 1 confirmation.
    let spendable_notes = T::select_spendable_notes(
        &st,
        account.id(),
        TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
        target_height,
        ConfirmationsPolicy::MIN,
        &[],
    )
    .unwrap();
    assert_eq!(spendable_notes.len(), 2);
    for note in spendable_notes {
        assert_eq!(T::note_value(note.note()), value);
    }
}

/// `PreferConsolidation` uses a deterministic minimum-cardinality funding set.
pub fn prefer_consolidation_uses_fewest_funding_notes<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    let small = Zatoshis::const_from_u64(180_000);
    let large = Zatoshis::const_from_u64(600_000);
    st.add_notes_checking_balance([
        [small],
        [small],
        [small],
        [small],
        [small],
        [small],
        [large],
        [large],
        [large],
    ]);

    assert_eq!(
        selected_notes_for_transfer(
            &mut st,
            Zatoshis::const_from_u64(1_000_000),
            NoteSelection::Accumulate,
        )
        .len(),
        6,
        "the default policy remains oldest-first accumulation",
    );

    let mut selected = selected_notes_for_transfer(
        &mut st,
        Zatoshis::const_from_u64(1_000_000),
        NoteSelection::PreferConsolidation,
    );
    selected.sort_unstable();
    assert_eq!(selected, [large, large]);
}

/// Necessary funding remains uncapped when a payment requires more than five notes.
pub fn prefer_consolidation_allows_more_than_five_funding_notes<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
    let values =
        [300_000, 250_000, 200_000, 150_000, 100_000, 90_000, 10_000].map(Zatoshis::const_from_u64);
    st.add_notes_checking_balance(values.map(|value| [value]));

    let mut selected = selected_notes_for_transfer(
        &mut st,
        Zatoshis::const_from_u64(1_050_000),
        NoteSelection::PreferConsolidation,
    );
    selected.sort_unstable();
    assert_eq!(
        selected,
        [90_000, 100_000, 150_000, 200_000, 250_000, 300_000].map(Zatoshis::const_from_u64),
    );
}

/// Fee iteration refreshes consolidation funding when a five-input estimate becomes insufficient.
pub fn prefer_consolidation_refreshes_funding_after_fee_growth<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
    st.add_notes_checking_balance(
        [220_000, 200_000, 200_000, 200_000, 200_000, 50_000, 10_000]
            .map(Zatoshis::const_from_u64)
            .map(|value| [value]),
    );

    assert_eq!(
        selected_notes_for_transfer(
            &mut st,
            Zatoshis::const_from_u64(1_000_000),
            NoteSelection::PreferConsolidation,
        )
        .len(),
        6,
    );
}

/// Consolidation selection filters candidates before applying either value ordering.
pub fn consolidation_selection_skips_unconfirmed_and_excluded_notes<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
    let values = [[600_000, 500_000], [20_000, 30_000], [2_000_000, 10_000]]
        .map(|block| block.map(Zatoshis::const_from_u64));
    st.add_notes_checking_balance(values);

    let account_id = st.test_account().unwrap().id();
    let target_height = TargetHeight::from(
        st.wallet()
            .chain_height()
            .unwrap()
            .expect("the chain has been scanned")
            + 1,
    );

    // The largest and smallest notes are in the newest block and therefore do not satisfy the
    // two-confirmation policy. Selection must continue through the ordered candidates instead of
    // letting either ineligible extreme consume the query's funding or additional-note budget.
    let (funding, additional) = st
        .wallet()
        .select_spendable_notes_for_consolidation(
            account_id,
            Zatoshis::const_from_u64(1_000_000),
            T::SHIELDED_PROTOCOL,
            target_height,
            ConfirmationsPolicy::new_symmetrical_unchecked(
                2,
                #[cfg(feature = "transparent-inputs")]
                true,
            ),
            &[],
            LockFilter::Policy(&Default::default()),
            2,
        )
        .unwrap()
        .into_parts();
    assert_eq!(
        funding.total_value().unwrap(),
        Zatoshis::const_from_u64(1_100_000)
    );
    assert_eq!(
        additional.total_value().unwrap(),
        Zatoshis::const_from_u64(50_000)
    );

    let excluded = st
        .wallet()
        .get_notes(T::SHIELDED_PROTOCOL)
        .unwrap()
        .into_iter()
        .filter(|note| matches!(u64::from(note.note().value()), 2_000_000 | 10_000 | 20_000))
        .map(|note| *note.internal_note_id())
        .collect::<Vec<_>>();
    let (funding, additional) = st
        .wallet()
        .select_spendable_notes_for_consolidation(
            account_id,
            Zatoshis::const_from_u64(1_000_000),
            T::SHIELDED_PROTOCOL,
            target_height,
            ConfirmationsPolicy::MIN,
            &excluded,
            LockFilter::Policy(&Default::default()),
            1,
        )
        .unwrap()
        .into_parts();
    assert_eq!(
        funding.total_value().unwrap(),
        Zatoshis::const_from_u64(1_100_000)
    );
    assert_eq!(
        additional.total_value().unwrap(),
        Zatoshis::const_from_u64(30_000)
    );
}

/// Sapling inputs are not added merely because ZIP 317's grace actions keep the fee unchanged.
pub fn prefer_consolidation_does_not_grow_sapling_spends(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache)
        .build::<super::sapling::SaplingPoolTester>();
    st.add_notes_checking_balance([
        [Zatoshis::const_from_u64(2_000_000)],
        [Zatoshis::const_from_u64(10_000)],
    ]);

    assert_eq!(
        selected_notes_for_transfer(
            &mut st,
            Zatoshis::const_from_u64(100_000),
            NoteSelection::PreferConsolidation,
        ),
        [Zatoshis::const_from_u64(2_000_000)],
    );
}

/// Pre-NU6.3 Orchard can replace a dummy spend side without growing the action count.
#[cfg(feature = "orchard")]
pub fn prefer_consolidation_fills_existing_orchard_actions(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<OrchardPoolTester>();
    st.add_notes_checking_balance([
        [Zatoshis::const_from_u64(2_000_000)],
        [Zatoshis::const_from_u64(20_000)],
        [Zatoshis::const_from_u64(10_000)],
    ]);

    let mut selected = selected_notes_for_transfer(
        &mut st,
        Zatoshis::const_from_u64(100_000),
        NoteSelection::PreferConsolidation,
    );
    selected.sort_unstable();
    assert_eq!(
        selected,
        [
            Zatoshis::const_from_u64(10_000),
            Zatoshis::const_from_u64(2_000_000),
        ],
    );
}

#[cfg(feature = "pczt")]
fn build_transparent_coinbase_tx(
    network: &LocalNetwork,
    target_height: TargetHeight,
    value: Zatoshis,
    recipient: TransparentAddress,
    miner_data: Option<PushValue>,
) -> zcash_primitives::transaction::builder::BuildResult {
    let build_config = BuildConfig::Coinbase { miner_data };
    let mut builder = Builder::new(*network, BlockHeight::from(target_height), build_config);

    // Add transparent output to recipient
    builder.add_transparent_output(&recipient, value).unwrap();

    // Build the transaction (coinbase transactions don't need provers)
    builder
        .build(
            // unused internally
            &TransparentSigningSet::new(),
            // unused internally
            &[],
            // unused internally
            &[],
            OsRng,
            &LocalTxProver::bundled(),
            &LocalTxProver::bundled(),
            // unused internally
            &StandardFeeRule::Zip317,
        )
        .unwrap()
}

#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
/// Tests that immature coinbase outputs are excluded from note selection.
pub fn immature_coinbase_outputs_are_excluded_from_note_selection<T: ShieldedPoolTester>(
    dsf: impl DataStoreFactory,
    cache: impl TestCache,
) {
    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();

    // Get the default transparent address
    let (t_addr, _) = st.get_account().usk().default_transparent_address();

    let coinbase_value = Zatoshis::const_from_u64(50000);

    // Get the height where the coinbase tx will be mined
    let coinbase_height = st.sapling_activation_height();

    // Construct the coinbase transaction and mine the block
    let coinbase_build_result = build_transparent_coinbase_tx(
        st.network(),
        TargetHeight::from(coinbase_height),
        coinbase_value,
        t_addr,
        None,
    );
    let coinbase_tx = coinbase_build_result.transaction();
    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
    st.scan_cached_blocks(h, 1);

    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();

    for i in 1..=99 {
        let latest_block_height = st.add_empty_blocks(1);

        // Verify the coinbase UTXO is **not** spendable
        let spendable_utxos = st
            .wallet()
            .get_spendable_transparent_outputs(
                &t_addr,
                TargetHeight::from(h + i),
                ConfirmationsPolicy::default(),
                CoinbaseFilter::AllTransparentOutputs,
                LockFilter::Policy(&LockedInputPolicy::Exclude),
            )
            .unwrap();
        let confirmations = latest_block_height - h;
        assert!(
            spendable_utxos.is_empty(),
            "{i}: Immature coinbase output is spendable at blockheight {latest_block_height} \
            with {confirmations} confirmations \
            (should only be spendable at 100):\n \
            {spendable_utxos:#?}"
        );
    }

    // Add the last block and ensure that the coinbase transaction is spendable
    let latest_height = st.add_empty_blocks(1);
    let confirmations = latest_height - h;
    let target_height = TargetHeight::from(latest_height + 1);
    let spendable_utxos = st
        .wallet()
        .get_spendable_transparent_outputs(
            &t_addr,
            target_height,
            ConfirmationsPolicy::default(),
            CoinbaseFilter::AllTransparentOutputs,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .unwrap();
    assert!(
        !spendable_utxos.is_empty(),
        "Coinbase output should be spendable at blockheight {latest_height} \
        with {confirmations} confirmations since the coinbase tx was mined (at {h})\n \
        target_height {target_height:?} - coinbase_tx.mined_height {h} = {}",
        u32::from(target_height) - u32::from(h)
    );

    // Verify we can propose shielding the coinbase utxo
    let account = st.get_account().id();
    let _proposal = st
        .propose_shielding(
            &GreedyInputSelector::new(),
            &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
            Zatoshis::from_u64(10000).unwrap(),
            &[t_addr],
            account,
            ConfirmationsPolicy::default(),
            CoinbaseFilter::AllTransparentOutputs,
        )
        .unwrap();
}

#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
/// Tests that `CoinbaseFilter::CoinbaseOnly` excludes non-coinbase outputs and
/// `CoinbaseFilter::NonCoinbaseOnly` excludes coinbase outputs from UTXO selection and
/// shielding proposals, and that `CoinbaseOnly` still allows proposing shielding when only
/// coinbase UTXOs are available.
pub fn coinbase_only_filtering<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
    let (t_addr, _) = st.get_account().usk().default_transparent_address();
    let account = st.get_account().id();

    // 1. Create a coinbase UTXO (50,000 zats)
    let coinbase_value = Zatoshis::const_from_u64(50000);
    let coinbase_height = st.sapling_activation_height();
    let coinbase_build_result = build_transparent_coinbase_tx(
        st.network(),
        TargetHeight::from(coinbase_height),
        coinbase_value,
        t_addr,
        None,
    );
    let coinbase_tx = coinbase_build_result.transaction();
    // The coinbase transaction has a single transparent output at index 0.
    let coinbase_outpoint = OutPoint::new(coinbase_tx.txid().into(), 0);
    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
    st.scan_cached_blocks(h, 1);
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();

    // 2. Create a non-coinbase UTXO (60,000 zats)
    // Inserted via put_received_transparent_utxo, which sets tx_index = NULL.
    // NULL tx_index is treated as non-coinbase by the filter.
    let non_coinbase_value = Zatoshis::const_from_u64(60000);
    let non_coinbase_outpoint = OutPoint::fake();
    let utxo = WalletTransparentOutput::from_parts(
        non_coinbase_outpoint.clone(),
        TxOut::new(non_coinbase_value, t_addr.script().into()),
        Some(h),
        Some(account),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    // 3. Wait for coinbase maturity (100 confirmations)
    st.add_empty_blocks(100);
    let target_height = TargetHeight::from(h + 101);

    // 4. CoinbaseFilter::All returns both UTXOs
    let all_utxos = st
        .wallet()
        .get_spendable_transparent_outputs(
            &t_addr,
            target_height,
            ConfirmationsPolicy::default(),
            CoinbaseFilter::AllTransparentOutputs,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .unwrap();
    assert_eq!(
        all_utxos.len(),
        2,
        "Expected both coinbase and non-coinbase UTXOs with CoinbaseFilter::AllTransparentOutputs"
    );
    let all_utxos_value = all_utxos
        .iter()
        .map(|utxo| utxo.value().into_u64())
        .sum::<u64>();
    assert_eq!(
        all_utxos_value,
        coinbase_value.into_u64() + non_coinbase_value.into_u64(),
        "Unexpected total UTXO value when querying for all transparent transactions"
    );

    // 5. CoinbaseFilter::CoinbaseOnly returns only the coinbase UTXO
    let coinbase_utxos = st
        .wallet()
        .get_spendable_transparent_outputs(
            &t_addr,
            target_height,
            ConfirmationsPolicy::default(),
            CoinbaseFilter::CoinbaseOnly,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .unwrap();
    assert_eq!(
        coinbase_utxos.len(),
        1,
        "Expected only the coinbase UTXO with CoinbaseFilter::CoinbaseOnly"
    );
    assert_eq!(coinbase_utxos[0].value(), coinbase_value);
    assert_eq!(coinbase_utxos[0].outpoint(), &coinbase_outpoint);

    // 5b. CoinbaseFilter::NonCoinbaseOnly returns only the non-coinbase UTXO.
    // The non-coinbase UTXO was inserted with tx_index = NULL, which the filter treats as
    // non-coinbase, so it must be included here.
    let non_coinbase_utxos = st
        .wallet()
        .get_spendable_transparent_outputs(
            &t_addr,
            target_height,
            ConfirmationsPolicy::default(),
            CoinbaseFilter::NonCoinbaseOnly,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .unwrap();
    assert_eq!(
        non_coinbase_utxos.len(),
        1,
        "Expected only the non-coinbase UTXO with CoinbaseFilter::NonCoinbaseOnly"
    );
    assert_eq!(non_coinbase_utxos[0].value(), non_coinbase_value);
    assert_eq!(non_coinbase_utxos[0].outpoint(), &non_coinbase_outpoint);

    // 6. propose_shielding with CoinbaseOnly includes only the coinbase input
    let proposal = st
        .propose_shielding(
            &GreedyInputSelector::new(),
            &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
            Zatoshis::from_u64(10000).unwrap(),
            &[t_addr],
            account,
            ConfirmationsPolicy::default(),
            CoinbaseFilter::CoinbaseOnly,
        )
        .unwrap();
    let coinbase_inputs = proposal.steps().first().transparent_inputs();
    assert_eq!(
        coinbase_inputs.len(),
        1,
        "CoinbaseOnly proposal should contain exactly one transparent input"
    );
    assert_eq!(coinbase_inputs[0].value(), coinbase_value);
    assert_eq!(coinbase_inputs[0].outpoint(), &coinbase_outpoint);

    // 6b. propose_shielding with NonCoinbaseOnly includes only the non-coinbase input
    let proposal_non_coinbase = st
        .propose_shielding(
            &GreedyInputSelector::new(),
            &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
            Zatoshis::from_u64(10000).unwrap(),
            &[t_addr],
            account,
            ConfirmationsPolicy::default(),
            CoinbaseFilter::NonCoinbaseOnly,
        )
        .unwrap();
    let non_coinbase_inputs = proposal_non_coinbase.steps().first().transparent_inputs();
    assert_eq!(
        non_coinbase_inputs.len(),
        1,
        "NonCoinbaseOnly proposal should contain exactly one transparent input"
    );
    assert_eq!(non_coinbase_inputs[0].value(), non_coinbase_value);
    assert_eq!(non_coinbase_inputs[0].outpoint(), &non_coinbase_outpoint);

    // 7. propose_shielding with All includes both inputs
    let proposal_all = st
        .propose_shielding(
            &GreedyInputSelector::new(),
            &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
            Zatoshis::from_u64(10000).unwrap(),
            &[t_addr],
            account,
            ConfirmationsPolicy::default(),
            CoinbaseFilter::AllTransparentOutputs,
        )
        .unwrap();
    let all_inputs = proposal_all.steps().first().transparent_inputs();
    assert_eq!(
        all_inputs.len(),
        2,
        "All proposal should contain both transparent inputs"
    );
    // Input ordering is not guaranteed, so compare the set of outpoints.
    let all_outpoints = all_inputs
        .iter()
        .map(|input| input.outpoint().clone())
        .collect::<BTreeSet<_>>();
    assert_eq!(
        all_outpoints,
        BTreeSet::from([coinbase_outpoint, non_coinbase_outpoint]),
        "All proposal should contain both the coinbase and non-coinbase outpoints"
    );
}

/// Verifies that `propose_shielding_coinbase` with a shielded destination produces
/// a proposal containing a single ZIP-321 payment to the supplied address for the
/// full available value (input total minus fee), with no change.
#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
pub fn propose_shielding_coinbase_succeeds<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
    let (t_addr, _) = st.get_account().usk().default_transparent_address();
    let coinbase_value = Zatoshis::const_from_u64(50000);
    let coinbase_build_result = build_transparent_coinbase_tx(
        st.network(),
        TargetHeight::from(st.sapling_activation_height()),
        coinbase_value,
        t_addr,
        None,
    );
    let coinbase_tx = coinbase_build_result.transaction();
    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
    st.scan_cached_blocks(h, 1);
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
    // Coinbase outputs require 100 confirmations.
    st.add_empty_blocks(100);

    // The destination is a shielded address controlled by a separate spending key
    // (i.e. potentially in a different wallet).
    let to_extsk = T::sk(&[0xab; 32]);
    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());

    let proposal = st
        .propose_shielding_coinbase(
            &GreedyInputSelector::new(),
            &StandardFeeRule::Zip317,
            Zatoshis::ZERO,
            &[t_addr],
            to_address.clone(),
            None,
            None,
        )
        .expect("propose_shielding_coinbase with a shielded destination should succeed");

    let step = proposal.steps().first();
    assert_eq!(
        step.transparent_inputs().len(),
        1,
        "Expected exactly one coinbase transparent input"
    );
    let payments = step.transaction_request().payments();
    assert_eq!(
        payments.len(),
        1,
        "Expected exactly one payment in proposal"
    );
    let (idx, payment) = payments.iter().next().unwrap();
    assert_eq!(*idx, 0);
    assert_eq!(payment.recipient_address(), &to_address);
    assert_eq!(
        step.balance().proposed_change().len(),
        0,
        "Coinbase shielding must produce no change"
    );

    let fee = step.balance().fee_required();
    let payment_amount = payment.amount().expect("payment must have an amount");
    assert_eq!(
        (payment_amount + fee).unwrap(),
        coinbase_value,
        "payment_amount + fee must equal coinbase input value"
    );
}

/// A newly constructed shielding proposal preserves the checkpoint selected by the wallet, even
/// though it spends no shielded notes. A proposal serialized without the confirmations-policy
/// field (as an older library version would have produced) decodes using the default policy and,
/// because it still carries that real anchor, builds. Separately, a shielding step produces a
/// shielded bundle, so a proposal that encodes such a step with the zero anchor sentinel is
/// rejected at the parse boundary.
#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
pub fn proposal_without_confirmations_policy_builds<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
    let (t_addr, _) = st.get_account().usk().default_transparent_address();
    let coinbase_value = Zatoshis::const_from_u64(50000);
    let coinbase_build_result = build_transparent_coinbase_tx(
        st.network(),
        TargetHeight::from(st.sapling_activation_height()),
        coinbase_value,
        t_addr,
        None,
    );
    let coinbase_tx = coinbase_build_result.transaction();
    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
    st.scan_cached_blocks(h, 1);
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
    // Coinbase outputs require 100 confirmations.
    st.add_empty_blocks(100);

    let to_extsk = T::sk(&[0xab; 32]);
    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());

    let proposal = st
        .propose_shielding_coinbase(
            &GreedyInputSelector::new(),
            &StandardFeeRule::Zip317,
            Zatoshis::ZERO,
            &[t_addr],
            to_address,
            None,
            None,
        )
        .expect("coinbase shielding proposal should succeed");

    // The shielding step keeps the checkpoint selected by input selection.
    let selected_anchor = proposal
        .steps()
        .first()
        .anchor_height()
        .expect("a shielding step must preserve its selected checkpoint");

    let proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
    assert_eq!(
        proto.steps[0].anchor_height,
        u32::from(selected_anchor),
        "a shielding step must serialize its selected checkpoint",
    );

    // The zero anchor is the wire sentinel for "no anchor". A shielding step produces a shielded
    // bundle, so decoding must reject a zero anchor at the parse boundary rather than accepting a
    // step whose dummy spends would commit to no real anchor. (Checked before building below, which
    // spends the input the proposal decodes against.)
    let mut zero_anchor = proto.clone();
    zero_anchor.steps[0].anchor_height = 0;
    assert_matches!(
        zero_anchor.try_into_standard_proposal(&params, st.wallet()),
        Err(crate::proto::ProposalDecodingError::MissingShieldedAnchor)
    );

    // A proposal serialized before the confirmations-policy field existed omits it, so decoding
    // must fall back to the default policy. The real anchor is preserved, so the step still builds.
    let mut without_policy = proto;
    without_policy.confirmations_policy = None;
    let decoded = without_policy
        .try_into_standard_proposal(&params, st.wallet())
        .expect("a proposal without a confirmations policy must decode");
    assert_eq!(
        decoded.confirmations_policy(),
        ConfirmationsPolicy::default(),
        "a missing confirmations policy must decode as the default",
    );
    assert_eq!(
        decoded.steps().first().anchor_height(),
        Some(selected_anchor),
        "decoding must preserve the serialized anchor",
    );

    let usk = st.get_account().usk().clone();
    st.create_proposed_transactions::<Infallible, _, Infallible, _>(
        &usk,
        OvkPolicy::Sender,
        &decoded,
    )
    .expect("a proposal that carries its selected anchor must build");
}

/// Verifies that `propose_shielding_coinbase` rejects a transparent destination
/// with [`ProposalError::ShieldingRequiresShieldedRecipient`].
#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
pub fn propose_shielding_coinbase_transparent_recipient_rejected<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
    let (t_addr, _) = st.get_account().usk().default_transparent_address();
    let coinbase_value = Zatoshis::const_from_u64(50000);
    let coinbase_build_result = build_transparent_coinbase_tx(
        st.network(),
        TargetHeight::from(st.sapling_activation_height()),
        coinbase_value,
        t_addr,
        None,
    );
    let coinbase_tx = coinbase_build_result.transaction();
    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
    st.scan_cached_blocks(h, 1);
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
    st.add_empty_blocks(100);

    let bad_to_address = Address::Transparent(TransparentAddress::PublicKeyHash([7; 20]))
        .to_zcash_address(st.network());

    let result = st.propose_shielding_coinbase(
        &GreedyInputSelector::new(),
        &StandardFeeRule::Zip317,
        Zatoshis::ZERO,
        &[t_addr],
        bad_to_address,
        None,
        None,
    );

    assert_matches!(
        result,
        Err(Error::Proposal(
            ProposalError::ShieldingRequiresShieldedRecipient
        ))
    );
}

/// Verifies that `propose_shielding_coinbase` propagates the supplied `memo`
/// into the resulting payment's memo field.
#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
pub fn propose_shielding_coinbase_with_memo_succeeds<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
    let (t_addr, _) = st.get_account().usk().default_transparent_address();
    let coinbase_value = Zatoshis::const_from_u64(50000);
    let coinbase_build_result = build_transparent_coinbase_tx(
        st.network(),
        TargetHeight::from(st.sapling_activation_height()),
        coinbase_value,
        t_addr,
        None,
    );
    let coinbase_tx = coinbase_build_result.transaction();
    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
    st.scan_cached_blocks(h, 1);
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
    st.add_empty_blocks(100);

    let to_extsk = T::sk(&[0xcd; 32]);
    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());

    let memo_text = "shielding to external wallet";
    let memo_bytes = MemoBytes::from(memo_text.parse::<Memo>().unwrap());

    let proposal = st
        .propose_shielding_coinbase(
            &GreedyInputSelector::new(),
            &StandardFeeRule::Zip317,
            Zatoshis::ZERO,
            &[t_addr],
            to_address,
            Some(memo_bytes.clone()),
            None,
        )
        .expect("propose_shielding_coinbase with memo should succeed");

    let payments = proposal.steps().first().transaction_request().payments();
    let (_, payment) = payments.iter().next().unwrap();
    assert_eq!(payment.memo(), Some(&memo_bytes));
}

/// Verifies that `propose_shielding_coinbase` with `limit = Some(n)` selects at
/// most `n` UTXOs, preferring the highest-value coinbase outputs.
#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
pub fn propose_shielding_coinbase_with_limit_truncates_inputs<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
    let (t_addr, _) = st.get_account().usk().default_transparent_address();

    // Mine three coinbase transactions to the same recipient at successive heights,
    // with distinct values so we can verify the highest-value-first selection.
    let values = [
        Zatoshis::const_from_u64(30000),
        Zatoshis::const_from_u64(70000),
        Zatoshis::const_from_u64(50000),
    ];
    let mut first_h = None;
    for v in values {
        let coinbase_height = if let Some(h) = first_h {
            h + values.len() as u32 // arbitrary; only first_h matters for maturity
        } else {
            st.sapling_activation_height()
        };
        let build = build_transparent_coinbase_tx(
            st.network(),
            TargetHeight::from(coinbase_height),
            v,
            t_addr,
            None,
        );
        let tx = build.transaction();
        let (h, _) = st.generate_next_block_from_tx(0, tx);
        st.scan_cached_blocks(h, 1);
        let params = *st.network();
        decrypt_and_store_transaction(&params, st.wallet_mut(), tx, Some(h)).unwrap();
        if first_h.is_none() {
            first_h = Some(h);
        }
    }
    // Mature all three.
    st.add_empty_blocks(100);

    let to_extsk = T::sk(&[0x55; 32]);
    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());

    let proposal = st
        .propose_shielding_coinbase(
            &GreedyInputSelector::new(),
            &StandardFeeRule::Zip317,
            Zatoshis::ZERO,
            &[t_addr],
            to_address,
            None,
            Some(2),
        )
        .expect("propose_shielding_coinbase with limit=Some(2) should succeed");

    let inputs = proposal.steps().first().transparent_inputs();
    assert_eq!(
        inputs.len(),
        2,
        "limit=Some(2) should select exactly 2 inputs"
    );

    // The two highest-value coinbase UTXOs are 70000 and 50000.
    let mut selected_values: Vec<u64> = inputs.iter().map(|i| i.value().into_u64()).collect();
    selected_values.sort_unstable_by(|a, b| b.cmp(a));
    assert_eq!(selected_values, vec![70000, 50000]);
}

/// Verifies that `propose_shielding_coinbase` with `limit = Some(0)` selects no
/// inputs, returning [`InputSelectorError::InsufficientFunds`].
///
/// [`InputSelectorError::InsufficientFunds`]: crate::data_api::wallet::input_selection::InputSelectorError::InsufficientFunds
#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
pub fn propose_shielding_coinbase_with_zero_limit_insufficient_funds<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
    let (t_addr, _) = st.get_account().usk().default_transparent_address();
    let coinbase_value = Zatoshis::const_from_u64(50000);
    let coinbase_build_result = build_transparent_coinbase_tx(
        st.network(),
        TargetHeight::from(st.sapling_activation_height()),
        coinbase_value,
        t_addr,
        None,
    );
    let coinbase_tx = coinbase_build_result.transaction();
    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
    st.scan_cached_blocks(h, 1);
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
    st.add_empty_blocks(100);

    let to_extsk = T::sk(&[0x66; 32]);
    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());

    let shielding_threshold = Zatoshis::const_from_u64(10000);
    let result = st.propose_shielding_coinbase(
        &GreedyInputSelector::new(),
        &StandardFeeRule::Zip317,
        shielding_threshold,
        &[t_addr],
        to_address,
        None,
        Some(0),
    );

    // With no inputs selected, `payment_amount = input_total - fee` underflows
    // (input_total = 0, fee > 0), producing `Error::InsufficientFunds` with
    // `available: 0, required: fee`.
    assert_matches!(result, Err(Error::InsufficientFunds { .. }));
}

/// Regression test for the propose-fee/build-fee mismatch fixed in #2376.
///
/// Both `sapling::builder::BundleType::DEFAULT` and
/// `orchard::builder::BundleType::DEFAULT` pad up to a minimum of 2
/// outputs/actions (`MIN_SHIELDED_OUTPUTS` / `MIN_ACTIONS`). Before the fix,
/// `propose_shielding_coinbase` hardcoded `(1, 0)` / `(0, 1)` when asking the
/// fee rule what fee to charge, so the proposal underestimated the fee by
/// exactly one ZIP-317 marginal unit (5000 zat). The proposal succeeded, but
/// `create_proposed_transactions` then failed at build time with
/// `Insufficient funds for transaction construction; need an additional ZatBalance(5000) zatoshis`.
///
/// This test verifies the propose-and-build round trip succeeds for both
/// Sapling and Orchard destinations (parameterized by `T`).
#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
pub fn propose_and_build_shielding_coinbase_succeeds<T: ShieldedPoolTester, Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
    let account = st.get_account();
    let (t_addr, _) = account.usk().default_transparent_address();
    let coinbase_value = Zatoshis::const_from_u64(50000);
    let coinbase_build_result = build_transparent_coinbase_tx(
        st.network(),
        TargetHeight::from(st.sapling_activation_height()),
        coinbase_value,
        t_addr,
        None,
    );
    let coinbase_tx = coinbase_build_result.transaction();
    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
    st.scan_cached_blocks(h, 1);
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
    // Coinbase outputs require 100 confirmations.
    st.add_empty_blocks(COINBASE_MATURITY_BLOCKS as usize);

    // The destination is a shielded address controlled by a separate spending key.
    let to_extsk = T::sk(&[0xcd; 32]);
    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());

    let proposal = st
        .propose_shielding_coinbase(
            &GreedyInputSelector::new(),
            &StandardFeeRule::Zip317,
            Zatoshis::ZERO,
            &[t_addr],
            to_address,
            None,
            None,
        )
        .expect("propose_shielding_coinbase should succeed");

    // Prior to #2376 this would fail at build time with `Insufficient funds for transaction
    // construction; need an additional ZatBalance(5000) zatoshis` because the proposal-stage fee
    // was computed assuming N output/action slots but the builder materializes N+1 (after `MIN_*`
    // padding).
    let build_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
        account.usk(),
        OvkPolicy::Sender,
        &proposal,
    );
    assert_matches!(
        &build_result,
        Ok(txids) if txids.len() == 1,
        "create_proposed_transactions must succeed for proposal {:?}",
        proposal,
    );
}

/// Verifies that once Ironwood is active, `propose_shielding_coinbase` resolves a destination
/// with an Orchard receiver to the Ironwood pool — the payment is delivered to the Orchard
/// receiver via the Ironwood bundle — and that the proposed transaction builds.
#[cfg(all(feature = "orchard", feature = "pczt", feature = "transparent-inputs"))]
pub fn shielding_coinbase_to_orchard_receiver_delivers_via_ironwood<Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    // A network on which Ironwood (NU6.3) is active from the Sapling activation height.
    let ironwood_active_network = {
        let activation = BlockHeight::from_u32(100_000);
        LocalNetwork {
            nu6: Some(activation),
            nu6_1: Some(activation),
            nu6_2: Some(activation),
            nu6_3: Some(activation),
            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
        }
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(ironwood_active_network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();
    let account = st.get_account();
    let (t_addr, _) = account.usk().default_transparent_address();
    let coinbase_value = Zatoshis::const_from_u64(100000);
    let coinbase_build_result = build_transparent_coinbase_tx(
        st.network(),
        TargetHeight::from(st.sapling_activation_height()),
        coinbase_value,
        t_addr,
        None,
    );
    let coinbase_tx = coinbase_build_result.transaction();
    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
    st.scan_cached_blocks(h, 1);
    let params = *st.network();
    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
    // Coinbase outputs require 100 confirmations.
    st.add_empty_blocks(COINBASE_MATURITY_BLOCKS as usize);

    // The destination has an Orchard receiver controlled by a separate spending key.
    let to_extsk = OrchardPoolTester::sk(&[0xcd; 32]);
    let to_address =
        OrchardPoolTester::sk_default_address(&to_extsk).to_zcash_address(st.network());

    let proposal = st
        .propose_shielding_coinbase(
            &GreedyInputSelector::new(),
            &StandardFeeRule::Zip317,
            Zatoshis::ZERO,
            &[t_addr],
            to_address,
            None,
            None,
        )
        .expect("propose_shielding_coinbase to an Orchard receiver should succeed post-NU6.3");

    // The Orchard-receiver payment is represented as an Ironwood-pool output, matching the
    // bundle the builder will deliver it through; an Orchard-pool payment would violate the
    // Orchard turnstile.
    assert_eq!(
        proposal.steps().head.payment_pools().get(&0),
        Some(&PoolType::IRONWOOD),
    );

    let build_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
        account.usk(),
        OvkPolicy::Sender,
        &proposal,
    );
    assert_matches!(
        &build_result,
        Ok(txids) if txids.len() == 1,
        "create_proposed_transactions must succeed for proposal {:?}",
        proposal,
    );
    let sent_txid = build_result.unwrap().head;

    // This transaction has a shielded bundle, but it is not observable by this wallet through
    // compact-block scanning: it has only transparent wallet inputs, its shielded output belongs
    // to another wallet, and it has no change. The sender therefore requires a txid-based status
    // request to learn its outcome.
    assert!(
        st.wallet()
            .transaction_data_requests()
            .unwrap()
            .contains(&TransactionDataRequest::GetStatus(sent_txid))
    );

    let (mined_height, _) = st.generate_next_block_including(sent_txid);
    st.scan_cached_blocks(mined_height, 1);
    assert_eq!(
        st.get_tx_from_history(sent_txid)
            .unwrap()
            .expect("sent transaction is in history")
            .mined_height(),
        None,
        "compact scanning cannot detect an external shielding transaction",
    );

    st.wallet_mut()
        .set_transaction_status(sent_txid, TransactionStatus::Mined(mined_height))
        .unwrap();
    assert_eq!(
        st.get_tx_from_history(sent_txid)
            .unwrap()
            .expect("sent transaction is in history")
            .mined_height(),
        Some(mined_height),
    );
    assert!(
        !st.wallet()
            .transaction_data_requests()
            .unwrap()
            .contains(&TransactionDataRequest::GetStatus(sent_txid)),
        "status intent is dormant while the transaction is mined",
    );

    st.truncate_to_height(mined_height - 1);
    assert_eq!(
        st.get_tx_from_history(sent_txid)
            .unwrap()
            .expect("sent transaction is retained across the rewind")
            .mined_height(),
        None,
    );
    assert!(
        st.wallet()
            .transaction_data_requests()
            .unwrap()
            .contains(&TransactionDataRequest::GetStatus(sent_txid)),
        "rewinding the mined block reactivates the durable status intent",
    );
}

/// After NU6.3 activation, a payment to an Orchard receiver must be delivered through the
/// Ironwood pool, which requires a version 6 transaction. Explicitly requesting a version 5
/// transaction — which has no Ironwood bundle — for such a payment must be rejected at proposal
/// time with [`ProposalError::OrchardReceiverRequiresIronwood`], rather than producing a proposal
/// that could only fail later at build time.
#[cfg(feature = "orchard")]
pub fn propose_v5_payment_to_orchard_receiver_is_rejected<Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
{
    // A network on which Ironwood (NU6.3) is active from the Sapling activation height.
    let ironwood_active_network = {
        let activation = BlockHeight::from_u32(100_000);
        LocalNetwork {
            nu6: Some(activation),
            nu6_1: Some(activation),
            nu6_2: Some(activation),
            nu6_3: Some(activation),
            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
        }
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(ironwood_active_network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    // Fund the wallet with a single spendable Orchard note.
    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60_000));

    // The destination has an Orchard receiver controlled by a separate spending key.
    let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
    let to = OrchardPoolTester::sk_default_address(&to_extsk);
    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        Zatoshis::const_from_u64(10_000),
    )])
    .unwrap();

    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let input_selector = GreedyInputSelector::new();

    let account = st.get_account();
    let network = *st.network();
    let result = propose_transfer::<_, _, _, _, Infallible>(
        st.wallet_mut(),
        &network,
        account.id(),
        &input_selector,
        &change_strategy,
        request,
        ConfirmationsPolicy::MIN,
        &SpendPolicy::default(),
        None,
        Some(TxVersion::V5),
    );

    assert_matches!(
        result,
        Err(Error::Proposal(
            ProposalError::OrchardReceiverRequiresIronwood(TxVersion::V5)
        ))
    );
}

/// PCZT construction supports the version 6 transaction format, including its Ironwood bundle.
/// After NU6.3 a payment to an Orchard receiver is delivered through the Ironwood pool, so
/// `create_pczt_from_proposal` realizes such a proposal as a version 6 PCZT that carries a
/// populated Ironwood bundle.
#[cfg(all(feature = "orchard", feature = "pczt"))]
pub fn create_pczt_supports_ironwood_output<Dsf>(ds_factory: Dsf, cache: impl TestCache)
where
    Dsf: DataStoreFactory,
    <Dsf as DataStoreFactory>::AccountId: serde::Serialize + serde::de::DeserializeOwned,
{
    // A network on which NU6.3 — the version 6 transaction format — is active from height 100_000.
    let ironwood_active_network = {
        let activation = BlockHeight::from_u32(100_000);
        LocalNetwork {
            nu6: Some(activation),
            nu6_1: Some(activation),
            nu6_2: Some(activation),
            nu6_3: Some(activation),
            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
        }
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(ironwood_active_network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    // Fund the wallet with a single spendable Orchard note.
    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60_000));

    // The destination has an Orchard receiver controlled by a separate spending key; post-NU6.3 the
    // payment is routed through the Ironwood pool.
    let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
    let to = OrchardPoolTester::sk_default_address(&to_extsk);
    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        Zatoshis::const_from_u64(10_000),
    )])
    .unwrap();

    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let input_selector = GreedyInputSelector::new();

    let account_id = st.get_account().id();
    let proposal = st
        .propose_transfer(
            account_id,
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .expect("proposal construction succeeds; the Orchard-receiver payment routes to Ironwood");

    // The payment routes to the Ironwood pool, so the resulting PCZT must carry an Ironwood bundle.
    assert_eq!(
        proposal.steps().head.payment_pools().get(&0),
        Some(&PoolType::IRONWOOD),
    );

    let pczt = st
        .create_pczt_from_proposal::<Infallible, _, Infallible>(
            account_id,
            OvkPolicy::Sender,
            &proposal,
            None,
        )
        .expect("an Ironwood-routed payment builds as a version 6 PCZT");

    // The PCZT is a version 6 transaction carrying a populated Ironwood bundle.
    assert_eq!(
        *pczt.global().tx_version(),
        zcash_protocol::constants::V6_TX_VERSION,
    );
    assert!(
        !pczt.ironwood().actions().is_empty(),
        "the PCZT carries an Ironwood bundle for the Ironwood-routed payment",
    );

    // The Ironwood output carries the wallet's recipient metadata (the only proprietary field set
    // on Ironwood outputs), confirming the bundle is populated during construction rather than left
    // as an empty shell.
    assert!(
        pczt.ironwood()
            .actions()
            .iter()
            .any(|action| !action.output().proprietary().is_empty()),
        "the Ironwood output carries recipient metadata",
    );

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct SpendState {
        has_fvk: bool,
        has_signature: bool,
        has_alpha: bool,
        has_derivation: bool,
        value: Option<u64>,
    }

    fn spend_states(pczt: pczt::Pczt) -> (Vec<SpendState>, Vec<SpendState>) {
        fn for_bundle(bundle: &orchard::pczt::Bundle) -> Vec<SpendState> {
            bundle
                .actions()
                .iter()
                .map(|action| SpendState {
                    has_fvk: action.spend().fvk().is_some(),
                    has_signature: action.spend().spend_auth_sig().is_some(),
                    has_alpha: action.spend().alpha().is_some(),
                    has_derivation: action.spend().zip32_derivation().is_some(),
                    value: action.spend().value().as_ref().map(|value| value.inner()),
                })
                .collect()
        }

        let mut orchard = vec![];
        let mut ironwood = vec![];
        pczt::roles::verifier::Verifier::new(pczt)
            .with_orchard::<Infallible, _>(|bundle| {
                orchard = for_bundle(bundle);
                Ok(())
            })
            .unwrap()
            .with_ironwood::<Infallible, _>(|bundle| {
                ironwood = for_bundle(bundle);
                Ok(())
            })
            .unwrap();
        (orchard, ironwood)
    }

    let original_sighash = Signer::new(pczt.clone()).unwrap().shielded_sighash();
    let original_spend_states = spend_states(pczt.clone());

    // Every action in both bundles is either already signed (a pre-signed protocol padding
    // dummy, cleared by the IO Finalizer) or carries ZIP 32 derivation metadata so that an
    // external Signer that matches by derivation path can identify and sign it. Real spends
    // and the wallet-controlled zero-value spends the builder pairs with vanilla-pool change
    // outputs (post-NU6.3 cross-address rule) both need the derivation; only the pre-signed
    // dummies are allowed to lack it.
    for state in original_spend_states
        .0
        .iter()
        .chain(original_spend_states.1.iter())
    {
        assert!(
            state.has_signature || state.has_derivation,
            "every action must be either pre-signed or identifiable by an external signer \
             via ZIP 32 derivation: {state:?}",
        );
    }
    // Confirm this scenario actually exercises a wallet-controlled zero-value spend: the
    // vanilla Orchard-pool bundle pairs a zero-value dummy spend (unsigned, carrying `alpha`)
    // with the change output, and it is this spend that regressed by being left unsignable.
    assert!(
        original_spend_states
            .0
            .iter()
            .any(|state| state.value == Some(0) && !state.has_signature),
        "expected at least one unsigned zero-value Orchard spend (the wallet-controlled \
         change-pairing dummy)",
    );

    let original_len = pczt.clone().serialize().unwrap().len();
    let signer_view = redact_pczt_for_signer(&pczt, SignerView::Compact);
    let signer_view_bytes = signer_view.serialize().unwrap();
    assert!(signer_view_bytes.len() < original_len);
    let signer_view = pczt::Pczt::parse(&signer_view_bytes).unwrap();
    assert_eq!(spend_states(signer_view.clone()), original_spend_states);

    // The backend metadata belongs to the authoritative wallet copy, not the
    // external Signer.
    assert!(
        signer_view
            .global()
            .proprietary()
            .get("zcash_client_backend:proposal_info")
            .is_none()
    );
    assert!(
        pczt.global()
            .proprietary()
            .contains_key("zcash_client_backend:proposal_info")
    );

    // V6 signatures do not commit to shielded anchors. Orchard action fields
    // that resolve_fields can restore are omitted from the signer view.
    assert!(signer_view.sapling().anchor().is_none());
    assert!(signer_view.orchard().anchor().is_none());
    assert!(signer_view.ironwood().anchor().is_none());

    let assert_redacted_bundle =
        |original: &pczt::orchard::Bundle, redacted: &pczt::orchard::Bundle| {
            assert_eq!(redacted.actions().len(), original.actions().len());
            let mut memo_plaintexts = 0;
            for (redacted, original) in redacted.actions().iter().zip(original.actions()) {
                assert!(redacted.cv_net().is_none());
                assert!(redacted.output().cmx().is_none());
                assert_eq!(redacted.spend().nullifier(), original.spend().nullifier());
                assert_eq!(redacted.spend().rk(), original.spend().rk());
                assert_eq!(
                    redacted.spend().spend_auth_sig(),
                    original.spend().spend_auth_sig()
                );
                assert_eq!(
                    redacted.output().ephemeral_key(),
                    original.output().ephemeral_key()
                );
                assert_eq!(
                    redacted.output().out_ciphertext(),
                    original.output().out_ciphertext()
                );
                assert_eq!(
                    redacted.output().user_address(),
                    original.output().user_address()
                );
                assert!(
                    redacted
                        .output()
                        .proprietary()
                        .get("zcash_client_backend:output_info")
                        .is_none()
                );
                if matches!(
                    redacted.output().enc_ciphertext(),
                    pczt::orchard::EncCiphertext::MemoPlaintext(_)
                ) {
                    memo_plaintexts += 1;
                }
            }
            memo_plaintexts
        };

    let memo_plaintexts = assert_redacted_bundle(pczt.orchard(), signer_view.orchard())
        + assert_redacted_bundle(pczt.ironwood(), signer_view.ironwood());
    assert!(memo_plaintexts > 0);

    // The full signer view (for receivers that predate the compact view) commits to
    // the same transaction effects and, unlike the compact view, retains v6 anchors.
    let full_view = redact_pczt_for_signer(&pczt, SignerView::Full);
    assert_eq!(
        Signer::new(full_view.clone()).unwrap().shielded_sighash(),
        original_sighash,
    );
    assert!(full_view.ironwood().actions().iter().all(|action| {
        action.spend().witness().is_none() && action.spend().dummy_sk().is_none()
    }));
    assert_eq!(full_view.ironwood().anchor(), pczt.ironwood().anchor());
    assert!(
        !full_view
            .global()
            .proprietary()
            .contains_key("zcash_client_backend:proposal_info")
    );
    for bundle in [full_view.orchard(), full_view.ironwood()] {
        assert!(bundle.actions().iter().all(|action| {
            !action
                .output()
                .proprietary()
                .contains_key("zcash_client_backend:output_info")
        }));
    }
    assert!(full_view.sapling().outputs().iter().all(|output| {
        !output
            .proprietary()
            .contains_key("zcash_client_backend:output_info")
    }));
    assert!(full_view.transparent().outputs().iter().all(|output| {
        !output
            .proprietary()
            .contains_key("zcash_client_backend:output_info")
    }));

    let batch_view = redact_pczt_for_batch_signer(&pczt);
    let batch_view_bytes = batch_view.serialize().unwrap();
    assert!(batch_view_bytes.len() < signer_view_bytes.len());
    let batch_view = pczt::Pczt::parse(&batch_view_bytes).unwrap();
    let batch_spend_states = spend_states(batch_view.clone());

    let mut preauthorized_actions = 0;
    let mut unsigned_zero_value_actions = 0;
    for (original_bundle, batch_bundle) in [
        (&original_spend_states.0, &batch_spend_states.0),
        (&original_spend_states.1, &batch_spend_states.1),
    ] {
        assert_eq!(batch_bundle.len(), original_bundle.len());
        for (original, batch) in original_bundle.iter().zip(batch_bundle) {
            assert!(!batch.has_fvk);
            assert!(!batch.has_signature);
            assert_eq!(
                batch.has_alpha,
                original.has_alpha && !original.has_signature
            );

            if original.has_signature {
                preauthorized_actions += 1;
            } else if original.value == Some(0) && original.has_alpha {
                unsigned_zero_value_actions += 1;
            }
        }
    }
    assert!(preauthorized_actions > 0);
    assert!(unsigned_zero_value_actions > 0);

    // Resolving either compact representation restores byte-identical effecting
    // fields and therefore the same shielded signature digest.
    for compact_view in [&signer_view, &batch_view] {
        let mut resolved = (*compact_view).clone();
        resolved.resolve_fields().unwrap();
        for (resolved_bundle, original_bundle) in [
            (resolved.orchard(), pczt.orchard()),
            (resolved.ironwood(), pczt.ironwood()),
        ] {
            for (resolved, original) in resolved_bundle
                .actions()
                .iter()
                .zip(original_bundle.actions())
            {
                assert_eq!(resolved.cv_net(), original.cv_net());
                assert_eq!(resolved.output().cmx(), original.output().cmx());
                assert_eq!(
                    resolved.output().enc_ciphertext(),
                    original.output().enc_ciphertext()
                );
            }
        }
        assert_eq!(
            Signer::new((*compact_view).clone())
                .unwrap()
                .shielded_sighash(),
            original_sighash,
        );
    }

    let signable_indices = |states: &[SpendState]| {
        states
            .iter()
            .enumerate()
            .filter_map(|(index, state)| (!state.has_signature && state.has_alpha).then_some(index))
            .collect::<Vec<_>>()
    };
    let orchard_signable = signable_indices(&original_spend_states.0);
    let ironwood_signable = signable_indices(&original_spend_states.1);
    assert!(
        orchard_signable
            .iter()
            .any(|&index| original_spend_states.0[index].value == Some(0))
    );

    // The transported request contains no existing signatures. The batch Signer
    // contributes signatures for every unsigned action, including the wallet
    // controlled zero value spend, and returns only those new signatures.
    let request = pczt::roles::signer::batch::BatchSignRequest::new(vec![batch_view]);
    let request =
        pczt::roles::signer::batch::BatchSignRequest::parse(&request.serialize().unwrap()).unwrap();
    assert_eq!(request.pczts().len(), 1);
    let transported_view = request.pczts()[0].clone();
    assert_eq!(spend_states(transported_view.clone()), batch_spend_states);

    let usk = st.get_account().usk().clone();
    let ask = orchard::keys::SpendAuthorizingKey::from(OrchardPoolTester::usk_to_sk(&usk));
    let signed_view = pczt::roles::low_level_signer::Signer::new(transported_view)
        .sign_orchard_with::<pczt::roles::low_level_signer::OrchardParseError, _>(|_, bundle, _| {
            for &index in &orchard_signable {
                bundle.actions_mut()[index]
                    .sign(original_sighash, &ask, OsRng)
                    .unwrap();
            }
            Ok(())
        })
        .unwrap()
        .sign_ironwood_with::<pczt::roles::low_level_signer::OrchardParseError, _>(
            |_, bundle, _| {
                for &index in &ironwood_signable {
                    bundle.actions_mut()[index]
                        .sign(original_sighash, &ask, OsRng)
                        .unwrap();
                }
                Ok(())
            },
        )
        .unwrap()
        .finish();

    let signatures = pczt::roles::signer::extract_orchard_spend_auth_signatures(&signed_view);
    let expected_signature_positions = orchard_signable
        .iter()
        .copied()
        .map(|index| (orchard::ValuePool::Orchard, index))
        .chain(
            ironwood_signable
                .iter()
                .copied()
                .map(|index| (orchard::ValuePool::Ironwood, index)),
        )
        .collect::<Vec<_>>();
    let signature_positions = signatures
        .iter()
        .map(|signature| (signature.value_pool(), signature.action_index()))
        .collect::<Vec<_>>();
    assert_eq!(signature_positions, expected_signature_positions);

    let response = pczt::roles::signer::batch::BatchSignResponse::new(vec![signatures]);
    let response =
        pczt::roles::signer::batch::BatchSignResponse::parse(&response.serialize().unwrap())
            .unwrap();
    assert_eq!(response.signatures().len(), 1);

    let mut signer = Signer::new(pczt.clone()).unwrap();
    for signature in &response.signatures()[0] {
        signer
            .apply_orchard_spend_auth_signature(signature)
            .unwrap();
    }
    let authorized = signer.finish();
    assert_eq!(
        authorized.global().proprietary(),
        pczt.global().proprietary()
    );

    let authorized_spend_states = spend_states(authorized.clone());
    for (original_bundle, authorized_bundle) in [
        (&original_spend_states.0, &authorized_spend_states.0),
        (&original_spend_states.1, &authorized_spend_states.1),
    ] {
        for (original, authorized) in original_bundle.iter().zip(authorized_bundle) {
            assert_eq!(authorized.has_fvk, original.has_fvk);
            assert_eq!(authorized.has_alpha, original.has_alpha);
            assert!(authorized.has_signature);
        }
    }
    for (authorized, original) in authorized
        .orchard()
        .actions()
        .iter()
        .zip(pczt.orchard().actions())
        .chain(
            authorized
                .ironwood()
                .actions()
                .iter()
                .zip(pczt.ironwood().actions()),
        )
    {
        if original.spend().spend_auth_sig().is_some() {
            assert_eq!(
                authorized.spend().spend_auth_sig(),
                original.spend().spend_auth_sig()
            );
        }
        assert_eq!(
            authorized.output().proprietary(),
            original.output().proprietary()
        );
    }

    // Prove both bundles — a single Orchard proving key governs both pools post-NU6.3, selected
    // by the circuit version the PCZT's consensus branch implies — then extract the final
    // transaction and store it. The stored record must carry the IRONWOOD payment output (the
    // payment itself, which post-NU6.3 travels in the Ironwood bundle) alongside the Orchard
    // change; the Ironwood outputs were previously dropped from the stored `SentTransaction`
    // entirely (issue #2890).
    let pczt_branch_id = consensus::BranchId::try_from(*authorized.global().consensus_branch_id())
        .expect("the PCZT carries a valid consensus branch ID");
    let orchard_pk = zcash_primitives::transaction::builder::cached_orchard_proving_key(
        zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
            pczt_branch_id,
            ::orchard::ValuePool::Orchard,
        )
        .expect("the PCZT's consensus branch supports the Orchard pool")
        .circuit_version(),
    );
    let proven = Prover::new(authorized)
        .create_orchard_proof(orchard_pk)
        .unwrap()
        .create_ironwood_proof(orchard_pk)
        .unwrap()
        .finish();

    let txid = st
        .extract_and_store_transaction_from_pczt(proven)
        .expect("extracts, verifies, and stores the finalized transaction");

    // The Ironwood payment output is recorded among the transaction's sent outputs, carrying the
    // payment value and the external recipient address.
    let sent_outputs = st.wallet().get_sent_outputs(&txid).unwrap();
    assert!(
        sent_outputs.iter().any(|output| {
            output.value() == Zatoshis::const_from_u64(10_000)
                && output.external_recipient().is_some()
        }),
        "the Ironwood payment output is recorded among the sent outputs: {sent_outputs:?}",
    );
    assert!(
        !st.wallet()
            .get_sent_note_ids(&txid, ShieldedPool::Ironwood)
            .unwrap()
            .is_empty(),
        "the payment's sent-note record belongs to the Ironwood pool",
    );
}

/// The transaction history entry for a payment funded from the Orchard pool and delivered
/// through the Ironwood pool reports the amount that left the account (payment plus fee) as
/// its balance delta, not the total value of the notes spent, which would ignore the change
/// returned to the wallet.
#[cfg(feature = "orchard")]
pub fn orchard_to_ironwood_payment_reports_net_value_delta<Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
{
    // A network on which NU6.3, the version 6 transaction format, is active from height 100_000.
    let ironwood_active_network = {
        let activation = BlockHeight::from_u32(100_000);
        LocalNetwork {
            nu6: Some(activation),
            nu6_1: Some(activation),
            nu6_2: Some(activation),
            nu6_3: Some(activation),
            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
        }
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(ironwood_active_network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    // Fund the wallet with a single spendable Orchard note.
    let note_value = Zatoshis::const_from_u64(60_000);
    st.add_a_single_note_checking_balance(note_value);

    // The destination has an Orchard receiver controlled by a separate spending key; post-NU6.3 the
    // payment is routed through the Ironwood pool.
    let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
    let to = OrchardPoolTester::sk_default_address(&to_extsk);
    let transfer_amount = Zatoshis::const_from_u64(10_000);
    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        transfer_amount,
    )])
    .unwrap();

    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let input_selector = GreedyInputSelector::new();

    let account = st.get_account();
    let account_id = account.id();
    let usk = account.usk().clone();
    let proposal = st
        .propose_transfer(
            account_id,
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .expect("proposal construction succeeds; the Orchard-receiver payment routes to Ironwood");

    // The payment crosses from the Orchard pool into the Ironwood pool.
    assert_eq!(
        proposal.steps().head.payment_pools().get(&0),
        Some(&PoolType::IRONWOOD),
    );
    let fee = proposal.steps().head.balance().fee_required();
    let expected_change = (note_value - transfer_amount - fee).unwrap();

    let txids = st
        .create_proposed_transactions::<Infallible, _, Infallible, _>(
            &usk,
            OvkPolicy::Sender,
            &proposal,
        )
        .expect("an Ironwood-routed payment builds successfully");
    let txid = *txids.first();

    // The amount that left the account is the payment plus the fee; the value of the change
    // note returned to the wallet must not be counted as spent.
    let expected_delta = -zcash_protocol::value::ZatBalance::from((transfer_amount + fee).unwrap());
    macro_rules! check_history {
        ($phase:literal) => {{
            let tx_history = st.wallet().get_tx_history().unwrap();
            let tx = tx_history
                .iter()
                .find(|tx| tx.txid() == txid)
                .expect("the created transaction appears in the transaction history");
            assert_eq!(
                tx.account_value_delta(),
                expected_delta,
                "account_value_delta ({}) reflects the payment plus fee",
                $phase,
            );
            assert_eq!(
                tx.total_spent(),
                note_value,
                "total_spent ({}) is the total value of the notes spent",
                $phase,
            );
            assert_eq!(
                tx.total_received(),
                expected_change,
                "total_received ({}) is the change returned to the wallet",
                $phase,
            );
            assert!(tx.has_change(), "the transaction has change ({})", $phase);
            // The payment has an external recipient, so it is not a pool crossing even though
            // its value moves from the Orchard pool into the Ironwood pool.
            assert_eq!(
                tx.pool_crossing_value(),
                None,
                "a payment to an external recipient is not a pool crossing ({})",
                $phase,
            );
        }};
    }

    // The history entry is correct as soon as the transaction is stored...
    check_history!("before mining");

    // ...and remains correct once the transaction is mined and scanned...
    let (h, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(h, 1);
    check_history!("after mining");

    // ...and remains correct after transaction enhancement, in which the wallet retrieves the
    // full transaction and re-stores it via `decrypt_and_store_transaction` (as the mobile
    // SDKs do to recover memos and fee information).
    let tx = st
        .wallet()
        .get_transaction(txid)
        .unwrap()
        .expect("the created transaction can be retrieved");
    let network = *st.network();
    decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(h)).unwrap();
    check_history!("after enhancement");
}

/// A migration of the wallet's own funds from the Orchard pool to the Ironwood pool, namely a
/// payment to the wallet's own external Orchard receiver delivered through the Ironwood pool, leaves
/// the account balance unchanged except for the fee. The payment output returned to the wallet
/// is not recorded at transaction-creation time (it is an address payment, which the wallet
/// expects to detect by scanning), so this exercises detection of the wallet's own Ironwood
/// outputs in the scanning path.
#[cfg(feature = "orchard")]
pub fn orchard_to_ironwood_self_migration_reports_fee_only_delta<Dsf>(
    ds_factory: Dsf,
    cache: impl TestCache,
) where
    Dsf: DataStoreFactory,
{
    // A network on which NU6.3, the version 6 transaction format, is active from height 100_000.
    let ironwood_active_network = {
        let activation = BlockHeight::from_u32(100_000);
        LocalNetwork {
            nu6: Some(activation),
            nu6_1: Some(activation),
            nu6_2: Some(activation),
            nu6_3: Some(activation),
            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
        }
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(ironwood_active_network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    // Fund the wallet with a single spendable Orchard note.
    let note_value = Zatoshis::const_from_u64(60_000);
    st.add_a_single_note_checking_balance(note_value);

    // The payment destination is the wallet's own external Orchard receiver; post-NU6.3 the
    // payment is routed through the Ironwood pool.
    let own_fvk = OrchardPoolTester::test_account_fvk(&st);
    let own_address = OrchardPoolTester::fvk_default_address(&own_fvk);
    let transfer_amount = Zatoshis::const_from_u64(40_000);
    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
        own_address.to_zcash_address(st.network()),
        transfer_amount,
    )])
    .unwrap();

    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let input_selector = GreedyInputSelector::new();

    let account = st.get_account();
    let account_id = account.id();
    let usk = account.usk().clone();
    let proposal = st
        .propose_transfer(
            account_id,
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .expect("proposal construction succeeds; the Orchard-receiver payment routes to Ironwood");

    // The payment crosses from the Orchard pool into the Ironwood pool.
    assert_eq!(
        proposal.steps().head.payment_pools().get(&0),
        Some(&PoolType::IRONWOOD),
    );
    let fee = proposal.steps().head.balance().fee_required();

    let txids = st
        .create_proposed_transactions::<Infallible, _, Infallible, _>(
            &usk,
            OvkPolicy::Sender,
            &proposal,
        )
        .expect("an Ironwood-routed payment builds successfully");
    let txid = *txids.first();

    // Once the transaction is mined and scanned, every non-fee output has returned to the
    // wallet: the payment output via scanning, and the change output. The account has lost
    // only the fee.
    let (h, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(h, 1);

    macro_rules! check_history {
        ($phase:literal) => {{
            let tx_history = st.wallet().get_tx_history().unwrap();
            let tx = tx_history
                .iter()
                .find(|tx| tx.txid() == txid)
                .expect("the created transaction appears in the transaction history");
            assert_eq!(
                tx.total_spent(),
                note_value,
                "total_spent ({}) is the total value of the notes spent",
                $phase,
            );
            assert_eq!(
                tx.total_received(),
                (note_value - fee).unwrap(),
                "total_received ({}) covers both the migrated value and the change",
                $phase,
            );
            assert_eq!(
                tx.account_value_delta(),
                -zcash_protocol::value::ZatBalance::from(fee),
                "the migration ({}) reduces the account balance only by the fee",
                $phase,
            );
            // Once the wallet has observed the payment output returning to its own account
            // (the scanner marks such outputs as change), the transaction presents as a
            // wallet-internal transfer between pools, and is classified as a pool crossing
            // whose crossing value is the migrated payment amount, the quantity a wallet
            // should display for it.
            assert!(
                tx.is_pool_crossing(),
                "a mined payment to the wallet's own address is a pool crossing ({})",
                $phase,
            );
            assert_eq!(
                tx.pool_crossing_value(),
                Some(transfer_amount),
                "pool_crossing_value ({}) is the migrated payment amount",
                $phase,
            );
        }};
    }

    check_history!("after mining");
    assert_eq!(
        st.get_total_balance(account_id),
        (note_value - fee).unwrap(),
        "the account retains all funds except the fee",
    );

    // The history entry remains correct after transaction enhancement, in which the wallet
    // retrieves the full transaction and re-stores it via `decrypt_and_store_transaction`
    // (as the mobile SDKs do to recover memos and fee information).
    let tx = st
        .wallet()
        .get_transaction(txid)
        .unwrap()
        .expect("the created transaction can be retrieved");
    let network = *st.network();
    decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(h)).unwrap();
    check_history!("after enhancement");
}

/// The transaction version requested at proposal time is recorded on the proposal and preserved
/// across serialization, so that transaction building honors it. A proposal serialized without a
/// version request (as older serializers produced) decodes with no requested version and falls
/// back to the target-height version at build time.
#[cfg(feature = "orchard")]
pub fn proposal_records_and_serializes_proposed_version<Dsf>(ds_factory: Dsf, cache: impl TestCache)
where
    Dsf: DataStoreFactory,
{
    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    // Fund the wallet with a single spendable Orchard note.
    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60_000));

    let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
    let to = OrchardPoolTester::sk_default_address(&to_extsk);
    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
        to.to_zcash_address(st.network()),
        Zatoshis::const_from_u64(10_000),
    )])
    .unwrap();

    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let input_selector = GreedyInputSelector::new();

    let account_id = st.get_account().id();
    let network = *st.network();
    // The test network's most recent upgrade is NU5, so version 5 is a valid explicit request.
    let proposal = propose_transfer::<_, _, _, _, Infallible>(
        st.wallet_mut(),
        &network,
        account_id,
        &input_selector,
        &change_strategy,
        request,
        ConfirmationsPolicy::MIN,
        &SpendPolicy::default(),
        None,
        Some(TxVersion::V5),
    )
    .expect("proposal construction succeeds");

    // The requested version is recorded on the proposal.
    assert_eq!(proposal.proposed_version(), Some(TxVersion::V5));

    // ... and is preserved across a round-trip through the proposal's serialized (proto) form.
    let proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
    let decoded = proto
        .try_into_standard_proposal(&network, st.wallet())
        .expect("the serialized proposal decodes");
    assert_eq!(decoded.proposed_version(), Some(TxVersion::V5));

    // A proposal serialized without the field (as an older serializer produced) decodes with no
    // requested version.
    let mut legacy_proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
    legacy_proto.proposed_version = None;
    let decoded_legacy = legacy_proto
        .try_into_standard_proposal(&network, st.wallet())
        .expect("a legacy proposal without a requested version must decode");
    assert_eq!(decoded_legacy.proposed_version(), None);
}

/// A payment whose value is a canonical ZIP 318 denomination, fundable from a single Orchard note,
/// is proposed against a bucketed anchor and built with a single unpadded Ironwood action — the
/// shape of a ZIP 318 migration transfer. Everything else keeps the ordinary anchor and the
/// two-action floor.
#[cfg(feature = "orchard")]
pub fn canonical_crossing_is_bucketed_and_unpadded<Dsf: DataStoreFactory>(
    ds_factory: Dsf,
    cache: impl TestCache,
) {
    // A short grid, so the test need not mine 144 blocks to cross a boundary.
    let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
    let activation = BlockHeight::from_u32(100_000);
    let ironwood_active_network = LocalNetwork {
        nu6: Some(activation),
        nu6_1: Some(activation),
        nu6_2: Some(activation),
        nu6_3: Some(activation),
        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(ironwood_active_network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_anchor_retention_interval(interval)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    let account = st.test_account().cloned().unwrap();
    let fvk = OrchardPoolTester::test_account_fvk(&st);
    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());

    // One Orchard note, comfortably larger than a canonical denomination plus fees.
    let note_value = Zatoshis::const_from_u64(10_000_000);
    let (received_height, _, _) = st.add_a_single_note_checking_balance(note_value);

    // Mine well past the next boundary, so the note is spendable at the bucketed anchor and a
    // usable boundary exists at or below the ordinary anchor. This is a COUNTED loop over a
    // precomputed block count: `generate_next_block` appends to the block cache, whereas
    // `chain_height` reads the wallet and only advances on `scan_cached_blocks`, so looping until
    // the wallet's height reaches a target would never terminate.
    let received = u32::from(received_height);
    let interval_blocks = interval.block_count().get();
    // Deliberately OFF a boundary: the ordinary anchor must not be a grid boundary by accident,
    // or an assertion that a canonical crossing was bucketed would pass trivially.
    let tip = u32::from(interval.boundary_at_or_above(received_height)) + 3 * interval_blocks + 5;
    let filler_count = tip - received;

    // Fillers pay a non-wallet key, so each block adds a commitment (and thus a checkpoint)
    // without changing the wallet's spendable set.
    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
    for _ in 0..filler_count {
        st.generate_next_block(
            &not_our_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10_000),
        );
    }
    st.scan_cached_blocks(received_height + 1, filler_count as usize);

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);

    let propose = |st: &mut TestState<_, _, _>, amount: Zatoshis| {
        let request =
            TransactionRequest::new(vec![Payment::without_memo(recipient.clone(), amount)])
                .unwrap();
        st.propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
    };

    // (1) A canonical denomination: bucketed anchor, one Orchard input, one Ironwood action.
    let canonical = propose(&mut st, MAX_RESIDUAL_VALUE).expect("the wallet can fund this");
    assert_eq!(canonical.steps().len(), 1);
    let canonical_fee = crate::fees::canonical_crossing_fee(
        st.network(),
        BlockHeight::from(canonical.min_target_height()),
    )
    .expect("the canonical shape is a valid input to the ZIP 317 rule");

    let step = canonical.steps().first();
    let anchor = step
        .anchor_height()
        .expect("a shielded step binds an anchor");
    assert!(
        interval.is_boundary(anchor),
        "a canonical crossing must anchor to a grid boundary, got {anchor:?}"
    );
    assert_eq!(step.input_count_in_pool(PoolType::ORCHARD), 1);
    assert_eq!(step.input_count_in_pool(PoolType::IRONWOOD), 0);
    assert!(step.is_canonical_crossing(&st.wallet().pool_migration_params(), canonical_fee));
    assert_eq!(
        step.ironwood_action_count(
            step.ironwood_bundle_padding(),
            ::orchard::bundle::BundleVersion::ironwood_v3()
        ),
        Ok(1),
        "the Ironwood bundle must be a single unpadded action"
    );

    // (2) One zatoshi off a canonical denomination: ordinary anchor, padded Ironwood bundle.
    let off_by_one = propose(
        &mut st,
        (MAX_RESIDUAL_VALUE + Zatoshis::const_from_u64(1)).unwrap(),
    )
    .unwrap();
    let step = off_by_one.steps().first();
    assert!(!step.is_canonical_crossing(&st.wallet().pool_migration_params(), canonical_fee));
    assert_eq!(
        step.ironwood_action_count(
            step.ironwood_bundle_padding(),
            ::orchard::bundle::BundleVersion::ironwood_v3()
        ),
        Ok(2)
    );
    assert!(
        !interval.is_boundary(step.anchor_height().unwrap()),
        "a non-canonical payment must not pay for a bucketed anchor"
    );

    // Building the canonical proposal is left until last: it spends the wallet's only note, so the
    // comparison above must be proposed while funds remain. The built transaction takes the ZIP 318
    // rolling expiry rather than the builder's per-transaction one — every crossing in the same
    // modulus period shares it, so it identifies nothing.
    // ROUND TRIP. The proposal records the exact dummy outputs costed by the fee model; the
    // builder reads that transaction shape back rather than deciding again.
    assert_eq!(
        canonical
            .steps()
            .first()
            .balance()
            .dummy_outputs()
            .expect("the fee model records dummy outputs")
            .ironwood(),
        0,
        "a canonical crossing has no Ironwood dummy output"
    );
    assert_eq!(
        canonical.steps().first().ironwood_bundle_padding(),
        BundlePadding::UNPADDED,
        "and the step must report the recorded value to the builder"
    );

    // The proposal crosses the FFI boundary before it is built as a PCZT. Preserve all per-pool
    // dummy-output counts through that serialization round-trip.
    let proto = crate::proto::proposal::Proposal::from_standard_proposal(&canonical);
    let serialized_dummy_outputs = proto.steps[0]
        .balance
        .as_ref()
        .expect("a proposal step carries a balance")
        .dummy_outputs
        .as_ref()
        .expect("new proposals serialize their dummy outputs");
    assert_eq!(
        (
            serialized_dummy_outputs.sapling,
            serialized_dummy_outputs.orchard,
            serialized_dummy_outputs.ironwood,
        ),
        (0, 1, 0)
    );
    let canonical = proto
        .try_into_standard_proposal(st.network(), st.wallet())
        .expect("the canonical proposal must deserialize");
    assert_eq!(
        canonical
            .steps()
            .first()
            .balance()
            .dummy_outputs()
            .expect("dummy outputs survive proposal decoding")
            .ironwood(),
        0,
        "the PCZT proposal round-trip must preserve the Ironwood dummy-output count"
    );

    let txids = st.create_proposed_expecting(&canonical, 1);
    let built = st
        .wallet()
        .get_transaction(txids[0])
        .unwrap()
        .expect("the transaction was stored");
    assert_eq!(
        built
            .ironwood_bundle()
            .expect("a crossing carries an Ironwood bundle")
            .actions()
            .len(),
        1,
        "the BUILT Ironwood bundle must have the single action the fee was charged for"
    );

    let tx = st.get_tx_from_history(txids[0]).unwrap().unwrap();
    assert_eq!(
        tx.expiry_height(),
        Some(zcash_protocol::zip318::expiry_height(BlockHeight::from(
            canonical.min_target_height()
        ))),
        "a canonical crossing must carry the ZIP 318 rolling expiry"
    );
    assert_eq!(
        tx.fee_paid(),
        Some(canonical_fee),
        "and the canonical ZIP 317 fee that shape costs"
    );
}

/// A canonical crossing whose bucketed anchor falls on a block with no shielded outputs must
/// still build. Note eligibility at the bucketed anchor is a height comparison, so the proposal
/// selects and anchors there regardless; unless the boundary checkpoint was ensured at scan time
/// — the boundary block itself contributed no note commitment to create one — building would
/// fail attempting to construct witnesses at a checkpoint that does not exist.
#[cfg(feature = "orchard")]
pub fn canonical_crossing_builds_at_empty_boundary_block<Dsf: DataStoreFactory>(
    ds_factory: Dsf,
    cache: impl TestCache,
) {
    // A short grid, so the test need not mine 144 blocks to cross a boundary.
    let interval = AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero"));
    let activation = BlockHeight::from_u32(100_000);
    let ironwood_active_network = LocalNetwork {
        nu6: Some(activation),
        nu6_1: Some(activation),
        nu6_2: Some(activation),
        nu6_3: Some(activation),
        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(ironwood_active_network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_anchor_retention_interval(interval)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    let account = st.test_account().cloned().unwrap();
    let fvk = OrchardPoolTester::test_account_fvk(&st);
    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());

    // One Orchard note, comfortably larger than a canonical denomination plus fees.
    let note_value = Zatoshis::const_from_u64(10_000_000);
    let (received_height, _, _) = st.add_a_single_note_checking_balance(note_value);
    let received = u32::from(received_height);
    let interval_blocks = interval.block_count().get();

    // Mine well past the next boundary, deliberately ending OFF a boundary, exactly as in
    // `canonical_crossing_is_bucketed_and_unpadded` — but here every BOUNDARY block is generated
    // empty, while the other fillers pay a non-wallet key. The bucketed anchor the proposal picks
    // is a boundary, and every boundary in the range is an empty block, so the anchor necessarily
    // lands on one.
    let tip = u32::from(interval.boundary_at_or_above(received_height)) + 3 * interval_blocks + 5;
    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
    let mut empty_heights = Vec::new();
    for height in (received + 1)..=tip {
        if interval.is_boundary(BlockHeight::from_u32(height)) {
            let (h, _) = st.generate_empty_block();
            empty_heights.push(h);
        } else {
            st.generate_next_block(
                &not_our_fvk,
                AddressType::DefaultExternal,
                Zatoshis::const_from_u64(10_000),
            );
        }
    }
    // One batch: block-by-block scanning would checkpoint every height via batch frontiers,
    // masking the missing-boundary-checkpoint condition this test exercises.
    st.scan_cached_blocks(received_height + 1, (tip - received) as usize);

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let request = TransactionRequest::new(vec![Payment::without_memo(
        recipient.clone(),
        MAX_RESIDUAL_VALUE,
    )])
    .unwrap();
    let canonical = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .expect("the wallet can fund this");

    let canonical_fee = crate::fees::canonical_crossing_fee(
        st.network(),
        BlockHeight::from(canonical.min_target_height()),
    )
    .expect("the canonical shape is a valid input to the ZIP 317 rule");
    let step = canonical.steps().first();
    let anchor = step
        .anchor_height()
        .expect("a shielded step binds an anchor");
    assert!(
        step.is_canonical_crossing(&st.wallet().pool_migration_params(), canonical_fee),
        "the payment must be recognized as a canonical crossing"
    );
    assert!(
        empty_heights.contains(&anchor),
        "the bucketed anchor {anchor:?} must be one of the empty boundary blocks {empty_heights:?}"
    );

    // Building must succeed: the anchor's checkpoint was ensured when the batch was scanned, even
    // though the boundary block itself contributed no commitment.
    let txids = st.create_proposed_expecting(&canonical, 1);
    let built = st
        .wallet()
        .get_transaction(txids[0])
        .unwrap()
        .expect("the transaction was stored");
    assert_eq!(
        built
            .ironwood_bundle()
            .expect("a crossing carries an Ironwood bundle")
            .actions()
            .len(),
        1,
        "the BUILT Ironwood bundle must have the single action of the canonical shape"
    );
}

/// A canonical amount that cannot be funded from a single Orchard note is NOT a canonical
/// crossing, and must not pay for a bucketed anchor it gains nothing from.
///
/// A migration transfer spends exactly one note, so a multi-input transaction resembles none. The
/// decision is therefore made before the proposal is kept: had it been made by falling back only
/// on insufficient funds, this transaction would have funded perfectly well from several notes and
/// been left carrying an anchor up to a full interval older than necessary, for no benefit.
#[cfg(feature = "orchard")]
pub fn multi_note_crossing_is_not_bucketed<Dsf: DataStoreFactory>(
    ds_factory: Dsf,
    cache: impl TestCache,
) {
    let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
    let activation = BlockHeight::from_u32(100_000);
    let network = LocalNetwork {
        nu6: Some(activation),
        nu6_1: Some(activation),
        nu6_2: Some(activation),
        nu6_3: Some(activation),
        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_anchor_retention_interval(interval)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    let account = st.test_account().cloned().unwrap();
    let fvk = OrchardPoolTester::test_account_fvk(&st);
    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());

    // Three notes, none individually able to cover the payment plus its fee.
    let note_value = Zatoshis::const_from_u64(400_000);
    let (first_height, _, _) = st.add_a_single_note_checking_balance(note_value);
    for _ in 0..2 {
        st.generate_next_block(&fvk, AddressType::DefaultExternal, note_value);
    }
    st.scan_cached_blocks(first_height + 1, 2);

    let interval_blocks = interval.block_count().get();
    let tip = u32::from(interval.boundary_at_or_above(first_height)) + 3 * interval_blocks + 5;
    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
    let filler_count = tip - u32::from(first_height) - 2;
    for _ in 0..filler_count {
        st.generate_next_block(
            &not_our_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10_000),
        );
    }
    st.scan_cached_blocks(first_height + 3, filler_count as usize);

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let request =
        TransactionRequest::new(vec![Payment::without_memo(recipient, MAX_RESIDUAL_VALUE)])
            .unwrap();

    let proposal = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .expect("three notes together can fund the payment");

    let step = proposal.steps().first();
    let zip318 = st.wallet().pool_migration_params();
    let canonical_fee = crate::fees::canonical_crossing_fee(
        st.network(),
        BlockHeight::from(proposal.min_target_height()),
    )
    .expect("the canonical shape is a valid input to the ZIP 317 rule");
    assert!(
        step.input_count_in_pool(PoolType::ORCHARD) > 1,
        "this scenario is only meaningful if funding needs several notes"
    );
    assert!(!step.is_canonical_crossing(&zip318, canonical_fee));
    assert!(
        !interval.is_boundary(step.anchor_height().unwrap()),
        "a multi-input transaction must not pay for a bucketed anchor"
    );
    assert_eq!(
        step.ironwood_action_count(
            step.ironwood_bundle_padding(),
            ::orchard::bundle::BundleVersion::ironwood_v3()
        ),
        Ok(2)
    );
}

/// A canonical payment is funded from the single oldest covering note even when accumulation
/// would have reached the target through several smaller notes first.
///
/// Oldest-first accumulation crosses the target through small notes whenever the oldest notes
/// are small, funding the payment while losing the single-input canonical shape. The canonical
/// attempt therefore PREFERS single-note funding ([`NoteSelection::PreferSingle`]): when any
/// single eligible note covers the payment and its fee, that note is chosen and the transaction
/// takes the migration shape. Ordinary (non-canonical) payments keep accumulating.
///
/// [`NoteSelection::PreferSingle`]:
///     crate::data_api::wallet::input_selection::NoteSelection::PreferSingle
#[cfg(feature = "orchard")]
pub fn canonical_crossing_prefers_single_note<Dsf: DataStoreFactory>(
    ds_factory: Dsf,
    cache: impl TestCache,
) {
    let interval = AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero"));
    let activation = BlockHeight::from_u32(100_000);
    let network = LocalNetwork {
        nu6: Some(activation),
        nu6_1: Some(activation),
        nu6_2: Some(activation),
        nu6_3: Some(activation),
        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_anchor_retention_interval(interval)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    let account = st.test_account().cloned().unwrap();
    let fvk = OrchardPoolTester::test_account_fvk(&st);
    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());

    // Two OLDER notes that together cover the payment, then one LARGER note that covers it
    // alone. Accumulation reaches the target at the second note and never touches the third,
    // so which shape the proposal takes distinguishes the two selection behaviors.
    let small_value = Zatoshis::const_from_u64(600_000);
    let large_value = Zatoshis::const_from_u64(1_200_000);
    let (first_height, _, _) = st.add_a_single_note_checking_balance(small_value);
    st.generate_next_block(&fvk, AddressType::DefaultExternal, small_value);
    st.generate_next_block(&fvk, AddressType::DefaultExternal, large_value);
    st.scan_cached_blocks(first_height + 1, 2);

    let interval_blocks = interval.block_count().get();
    let tip = u32::from(interval.boundary_at_or_above(first_height)) + 3 * interval_blocks + 5;
    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
    let filler_count = tip - u32::from(first_height) - 2;
    for _ in 0..filler_count {
        st.generate_next_block(
            &not_our_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10_000),
        );
    }
    st.scan_cached_blocks(first_height + 3, filler_count as usize);

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let propose = |st: &mut TestState<_, _, _>, amount: Zatoshis| {
        let request =
            TransactionRequest::new(vec![Payment::without_memo(recipient.clone(), amount)])
                .unwrap();
        st.propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
    };

    // The canonical payment takes the single-note shape, spending the LARGE note.
    let canonical = propose(&mut st, MAX_RESIDUAL_VALUE).expect("the wallet can fund this");
    let step = canonical.steps().first();
    let zip318 = st.wallet().pool_migration_params();
    let canonical_fee = crate::fees::canonical_crossing_fee(
        st.network(),
        BlockHeight::from(canonical.min_target_height()),
    )
    .expect("the canonical shape is a valid input to the ZIP 317 rule");
    assert_eq!(
        step.input_count_in_pool(PoolType::ORCHARD),
        1,
        "the canonical payment must be funded from a single note"
    );
    assert!(step.is_canonical_crossing(&zip318, canonical_fee));
    let spent = step
        .shielded_inputs()
        .expect("a shielded step spends notes")
        .notes()
        .first()
        .note()
        .value();
    assert_eq!(
        spent, large_value,
        "the single covering note funds the payment, not the older small notes"
    );

    // An ordinary payment of a NON-canonical amount still accumulates the oldest notes.
    let ordinary = propose(
        &mut st,
        (MAX_RESIDUAL_VALUE + Zatoshis::const_from_u64(1)).unwrap(),
    )
    .expect("the wallet can fund this too");
    let step = ordinary.steps().first();
    assert!(
        step.input_count_in_pool(PoolType::ORCHARD) > 1,
        "single-note preference must not leak into ordinary selection"
    );
}

/// A canonical payment whose bucketed anchor checkpoint is MISSING from the wallet falls back to
/// an ordinary crossing instead of failing at build time.
///
/// A wallet that scanned past NU6.3 activation before boundary checkpointing was repaired is
/// permanently missing the grid boundaries whose blocks carried no shielded outputs, and the
/// holes cannot be backfilled from local state: the tree prunes node data that no retained
/// checkpoint references, so reconstruction would require refetching subtree data from a light
/// wallet server. Note eligibility at the bucketed anchor is a height comparison, so without a
/// checkpoint-existence gate the canonical proposal is kept and the BUILD fails with
/// `ProposalError::AnchorNotFound` — a hard send failure where every other miss in the canonical
/// path degrades gracefully.
///
/// `remove_checkpoint` deletes the wallet's checkpoint records at the given height, simulating
/// the legacy wallet state; it is supplied by the backend-specific caller because corrupting
/// stored state is necessarily a backend-level operation.
#[cfg(feature = "orchard")]
pub fn canonical_crossing_abandoned_without_anchor_checkpoint<Dsf, TC>(
    ds_factory: Dsf,
    cache: TC,
    remove_checkpoint: impl FnOnce(&mut TestState<TC, Dsf::DataStore, LocalNetwork>, BlockHeight),
) where
    Dsf: DataStoreFactory,
    TC: TestCache,
{
    let interval = AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero"));
    let activation = BlockHeight::from_u32(100_000);
    let network = LocalNetwork {
        nu6: Some(activation),
        nu6_1: Some(activation),
        nu6_2: Some(activation),
        nu6_3: Some(activation),
        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_anchor_retention_interval(interval)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    let account = st.test_account().cloned().unwrap();
    let fvk = OrchardPoolTester::test_account_fvk(&st);
    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());

    // One Orchard note, comfortably larger than a canonical denomination plus fees, mined well
    // before the bucketed anchor.
    let (received_height, _, _) =
        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(10_000_000));
    let received = u32::from(received_height);
    let interval_blocks = interval.block_count().get();
    let tip = u32::from(interval.boundary_at_or_above(received_height)) + 3 * interval_blocks + 5;
    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
    let filler_count = tip - received;
    for _ in 0..filler_count {
        st.generate_next_block(
            &not_our_fvk,
            AddressType::DefaultExternal,
            Zatoshis::const_from_u64(10_000),
        );
    }
    st.scan_cached_blocks(received_height + 1, filler_count as usize);

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let propose = |st: &mut TestState<_, _, _>| {
        let request = TransactionRequest::new(vec![Payment::without_memo(
            recipient.clone(),
            MAX_RESIDUAL_VALUE,
        )])
        .unwrap();
        st.propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .expect("the wallet can fund this")
    };

    // With the checkpoint intact the payment is canonical; the anchor it binds is the boundary
    // whose checkpoint the second half of the test removes. Reading it off the proposal keeps
    // the test's idea of "the bucketed anchor" identical to production's, rather than
    // reimplementing the arithmetic.
    let canonical = propose(&mut st);
    let step = canonical.steps().first();
    let zip318 = st.wallet().pool_migration_params();
    let canonical_fee = crate::fees::canonical_crossing_fee(
        st.network(),
        BlockHeight::from(canonical.min_target_height()),
    )
    .expect("the canonical shape is a valid input to the ZIP 317 rule");
    assert!(step.is_canonical_crossing(&zip318, canonical_fee));
    let boundary = step
        .anchor_height()
        .expect("a shielded step binds an anchor");
    assert!(
        st.wallet()
            .anchor_computable(ShieldedPool::Orchard, boundary)
            .unwrap(),
        "an anchor is computable at the boundary before removal"
    );

    // Simulate the legacy wallet: the boundary's checkpoint records are gone.
    remove_checkpoint(&mut st, boundary);
    assert!(
        !st.wallet()
            .anchor_computable(ShieldedPool::Orchard, boundary)
            .unwrap(),
        "no anchor is computable at the boundary after removal"
    );

    // The payment now falls back to an ordinary crossing: proposed against the ordinary anchor,
    // padded, and — decisively — BUILDABLE. Without the gate the canonical proposal would be
    // kept and building would fail with `AnchorNotFound`.
    let fallback = propose(&mut st);
    let step = fallback.steps().first();
    assert!(
        !step.is_canonical_crossing(&zip318, canonical_fee),
        "the attempt must be abandoned when its anchor cannot be proved"
    );
    assert_ne!(
        step.anchor_height()
            .expect("a shielded step binds an anchor"),
        boundary,
        "the fallback anchors at the ordinary height, not the unprovable boundary"
    );
    st.create_proposed_expecting(&fallback, 1);
}

/// Self-migration does not stall once the wallet holds Ironwood notes.
///
/// A user moving their own funds across the turnstile sends themselves canonical amounts
/// repeatedly. After the first crossing the wallet holds an Ironwood note, and the ordinary
/// selector — which prefers to avoid crossing pools — would fund the next Ironwood-destined
/// payment from Ironwood, crossing nothing and capping the total that can ever be migrated. The
/// canonical path selects from Orchard only, so each transfer keeps moving value across.
#[cfg(feature = "orchard")]
pub fn self_migration_keeps_spending_orchard<Dsf: DataStoreFactory>(
    ds_factory: Dsf,
    cache: impl TestCache,
) {
    let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
    let activation = BlockHeight::from_u32(100_000);
    let network = LocalNetwork {
        nu6: Some(activation),
        nu6_1: Some(activation),
        nu6_2: Some(activation),
        nu6_3: Some(activation),
        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
    };

    let mut st = TestDsl::from(
        TestBuilder::new()
            .with_network(network)
            .with_data_store_factory(ds_factory)
            .with_block_cache(cache)
            .with_anchor_retention_interval(interval)
            .with_account_from_sapling_activation(BlockHash([0; 32])),
    )
    .build::<OrchardPoolTester>();

    let account = st.test_account().cloned().unwrap();
    let fvk = OrchardPoolTester::test_account_fvk(&st);
    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());

    let (received_height, _, _) =
        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(10_000_000));

    let interval_blocks = interval.block_count().get();
    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
    let advance = |st: &mut TestState<_, _, _>, from: BlockHeight, count: u32| {
        for _ in 0..count {
            st.generate_next_block(
                &not_our_fvk,
                AddressType::DefaultExternal,
                Zatoshis::const_from_u64(10_000),
            );
        }
        st.scan_cached_blocks(from, count as usize);
    };

    let tip = u32::from(interval.boundary_at_or_above(received_height)) + 3 * interval_blocks + 5;
    advance(
        &mut st,
        received_height + 1,
        tip - u32::from(received_height),
    );

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
    let zip318 = st.wallet().pool_migration_params();

    // First crossing: funded from the original Orchard note.
    let request = TransactionRequest::new(vec![Payment::without_memo(
        recipient.clone(),
        MAX_RESIDUAL_VALUE,
    )])
    .unwrap();
    let first = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .expect("the wallet can fund the first crossing");
    let canonical_fee = crate::fees::canonical_crossing_fee(
        st.network(),
        BlockHeight::from(first.min_target_height()),
    )
    .expect("the canonical shape is a valid input to the ZIP 317 rule");
    assert!(
        first
            .steps()
            .first()
            .is_canonical_crossing(&zip318, canonical_fee)
    );

    // Mine it, so the wallet now holds an Ironwood note alongside its Orchard change.
    let txids = st.create_proposed_expecting(&first, 1);
    let (mined_height, _) = st.generate_next_block_including(txids[0]);
    st.scan_cached_blocks(mined_height, 1);

    // Advance past another boundary so a bucketed anchor is available for the second crossing.
    advance(&mut st, mined_height + 1, 2 * interval_blocks + 1);

    // The precondition this test exists to exercise: the wallet really does hold an Ironwood note
    // now, so the assertion below that none is spent is not vacuously true.
    let summary = st
        .get_wallet_summary(ConfirmationsPolicy::MIN)
        .expect("the wallet is synced");
    let balances = summary
        .account_balances()
        .get(&account.id())
        .expect("the account is known");
    assert!(
        balances.ironwood_balance().total().is_positive(),
        "the first crossing must have left an Ironwood note for the selector to prefer"
    );
    assert!(
        balances.orchard_balance().total().is_positive(),
        "and Orchard change to fund the second crossing from"
    );

    // Second crossing: the wallet now holds Ironwood, which the ordinary selector would prefer.
    let request =
        TransactionRequest::new(vec![Payment::without_memo(recipient, MAX_RESIDUAL_VALUE)])
            .unwrap();
    let second = st
        .propose_transfer(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
        )
        .expect("the wallet can fund the second crossing");

    let step = second.steps().first();
    assert_eq!(
        step.input_count_in_pool(PoolType::IRONWOOD),
        0,
        "the Ironwood note must be left alone, or self-migration stalls here"
    );
    assert_eq!(step.input_count_in_pool(PoolType::ORCHARD), 1);
    assert!(
        step.is_canonical_crossing(&zip318, canonical_fee),
        "the second crossing must still be canonical"
    );
}