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
use std::{
    collections::{BTreeMap, HashSet},
    convert::Infallible,
};

use assert_matches::assert_matches;

use sapling::zip32::ExtendedSpendingKey;
use transparent::{
    address::{Script, TransparentAddress},
    bundle::{Authorized, Bundle, OutPoint, TxIn, TxOut},
    keys::{NonHardenedChildIndex, TransparentKeyScope},
};
use zcash_keys::{
    address::Address,
    keys::{UnifiedAddressRequest, transparent::gap_limits::GapLimits},
};
use zcash_primitives::{
    block::BlockHash,
    transaction::{Transaction, TransactionData, TxVersion, fees::zip317},
};
use zcash_protocol::{
    consensus::{BlockHeight, BranchId, COINBASE_MATURITY_BLOCKS},
    local_consensus::LocalNetwork,
    value::Zatoshis,
};
use zip321::{Payment, TransactionRequest};

#[cfg(feature = "transparent-key-import")]
use {
    crate::{
        data_api::{
            AccountBirthday,
            chain::ChainState,
            wallet::{self, SpendingKeys},
        },
        wallet::TransparentAddressSource,
    },
    secp256k1::{Secp256k1, SecretKey},
    secrecy::Secret,
    std::collections::HashMap,
    zcash_protocol::consensus::{NetworkUpgrade, Parameters},
    zcash_script::{descriptor::sh, pattern::check_multisig, script},
};

use super::TestAccount;
use crate::{
    data_api::{
        Account as _, AccountBalance, Balance, CoinbaseFilter, InputSource as _, MaxSpendMode,
        TargetValue, WalletRead as _, WalletTest as _, WalletWrite,
        testing::{
            AddressType, DataStoreFactory, ShieldedPool, TestBuilder, TestCache, TestState,
            single_output_change_strategy,
        },
        wallet::{
            ConfirmationsPolicy, TargetHeight, decrypt_and_store_transaction,
            input_selection::{
                GreedyInputSelector, LockFilter, LockedInputPolicy, NoteSelection, SpendPolicy,
                TransparentSpendPolicy,
            },
        },
    },
    fees::{ChangeValue, StandardFeeRule, TransparentChangePolicy},
    wallet::{Exposure, OvkPolicy, WalletTransparentOutput},
};

pub use super::pool::locking::transparent_note_locking;

/// Checks whether the transparent balance of the given test `account` is as `expected`
/// considering the `confirmations_policy`.
fn check_balance<DSF>(
    st: &TestState<impl TestCache, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
    account: &TestAccount<<DSF as DataStoreFactory>::Account>,
    taddr: &TransparentAddress,
    confirmations_policy: ConfirmationsPolicy,
    expected: &Balance,
) where
    DSF: DataStoreFactory,
{
    // Check the wallet summary returns the expected transparent balance.
    let summary = st
        .wallet()
        .get_wallet_summary(confirmations_policy)
        .unwrap()
        .unwrap();
    let balance = summary.account_balances().get(&account.id()).unwrap();

    #[allow(deprecated)]
    let old_unshielded_value = balance.unshielded();
    assert_eq!(old_unshielded_value, expected.total());
    assert_eq!(balance.unshielded_regular_balance(), expected);
    assert_eq!(balance.unshielded_coinbase_balance(), &Balance::ZERO);
    assert_eq!(balance.unshielded_balance(), *expected);

    // Check the older APIs for consistency.
    let target_height = TargetHeight::from(st.wallet().chain_height().unwrap().unwrap() + 1);
    assert_eq!(
        st.wallet()
            .get_transparent_balances(account.id(), target_height, confirmations_policy)
            .unwrap()
            .get(taddr)
            .cloned()
            .map_or(Zatoshis::ZERO, |(_, b)| b.spendable_value()),
        expected.total(),
    );
    assert_eq!(
        st.wallet()
            .get_spendable_transparent_outputs(
                taddr,
                target_height,
                confirmations_policy,
                CoinbaseFilter::AllTransparentOutputs,
                LockFilter::Policy(&LockedInputPolicy::Exclude),
            )
            .unwrap()
            .into_iter()
            .map(|utxo| utxo.value())
            .sum::<Option<Zatoshis>>(),
        Some(expected.spendable_value()),
    );
}

pub fn put_received_transparent_utxo<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
    <<DSF as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug + PartialEq,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let birthday = st.test_account().unwrap().birthday().height();
    let account_id = st.test_account().unwrap().id();
    let uaddr = st
        .wallet()
        .get_last_generated_address_matching(account_id, UnifiedAddressRequest::AllAvailableKeys)
        .unwrap()
        .unwrap();
    let taddr = uaddr.transparent().unwrap();

    let height_1 = birthday + 12345;
    st.wallet_mut().update_chain_tip(height_1).unwrap();

    let bal_absent = st
        .wallet()
        .get_transparent_balances(
            account_id,
            TargetHeight::from(height_1 + 1),
            ConfirmationsPolicy::MIN,
        )
        .unwrap();
    assert!(bal_absent.is_empty());

    // Create a fake transparent output.
    let value = Zatoshis::const_from_u64(100000);
    let outpoint = OutPoint::fake();
    let txout = TxOut::new(value, taddr.script().into());

    // Pretend the output's transaction was mined at `height_1`.
    let utxo = WalletTransparentOutput::from_parts(
        outpoint.clone(),
        txout.clone(),
        Some(height_1),
        Some(account_id),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();
    let res0 = st.wallet_mut().put_received_transparent_utxo(&utxo);
    assert_matches!(res0, Ok(_));

    let target_height = TargetHeight::from(height_1 + 1);
    // Confirm that we see the output unspent as of `height_1`.
    assert_matches!(
        st.wallet().get_spendable_transparent_outputs(
            taddr,
            target_height,
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::AllTransparentOutputs,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        ).as_deref(),
        Ok([ret])
        if (ret.outpoint(), ret.txout(), ret.mined_height()) == (utxo.outpoint(), utxo.txout(), Some(height_1))
    );
    assert_matches!(
        st.wallet()
            .get_unspent_transparent_output(utxo.outpoint(), target_height),
        Ok(Some(ret))
        if (ret.outpoint(), ret.txout(), ret.mined_height()) == (utxo.outpoint(), utxo.txout(), Some(height_1))
    );

    // Change the mined height of the UTXO and upsert; we should get back
    // the same `UtxoId`.
    let height_2 = birthday + 34567;
    st.wallet_mut().update_chain_tip(height_2).unwrap();
    let utxo2 = WalletTransparentOutput::from_parts(
        outpoint,
        txout,
        Some(height_2),
        Some(account_id),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();
    let res1 = st.wallet_mut().put_received_transparent_utxo(&utxo2);
    assert_matches!(res1, Ok(id) if id == res0.unwrap());

    // Confirm that we no longer see any unspent outputs as of `height_1`.
    assert_matches!(
        st.wallet()
            .get_spendable_transparent_outputs(
                taddr,
                target_height,
                ConfirmationsPolicy::MIN,
                CoinbaseFilter::AllTransparentOutputs,
                LockFilter::Policy(&LockedInputPolicy::Exclude)
            )
            .as_deref(),
        Ok(&[])
    );

    // We can still look up the specific output, and it has the expected height.
    assert_matches!(
        st.wallet()
            .get_unspent_transparent_output(utxo2.outpoint(), target_height),
        Ok(Some(ret))
        if (ret.outpoint(), ret.txout(), ret.mined_height()) == (utxo2.outpoint(), utxo2.txout(), Some(height_2))
    );

    // If we include `height_2` then the output is returned.
    assert_matches!(
        st.wallet()
            .get_spendable_transparent_outputs(taddr, TargetHeight::from(height_2 + 1), ConfirmationsPolicy::MIN, CoinbaseFilter::AllTransparentOutputs, LockFilter::Policy(&LockedInputPolicy::Exclude))
            .as_deref(),
        Ok([ret]) if (ret.outpoint(), ret.txout(), ret.mined_height()) == (utxo.outpoint(), utxo.txout(), Some(height_2))
    );

    assert_matches!(
        st.wallet().get_transparent_balances(
            account_id,
            TargetHeight::from(height_2 + 1),
            ConfirmationsPolicy::MIN
        ),
        Ok(h) if h.get(taddr).map(|(_, b)| b.spendable_value()) == Some(value)
    );
}

pub fn transparent_balance_across_shielding<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Initialize the wallet with chain data that has no shielded notes for us.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // The wallet starts out with zero balance.
    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::MIN,
        &Balance::ZERO,
    );

    // Create a fake transparent output.
    let value = Zatoshis::from_u64(100000).unwrap();
    let txout = TxOut::new(value, taddr.script().into());

    // Pretend the output was received in the chain tip.
    let height = st.wallet().chain_height().unwrap().unwrap();
    let utxo = WalletTransparentOutput::from_parts(
        OutPoint::fake(),
        txout,
        Some(height),
        Some(account.id()),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    // The wallet should detect the balance as available
    let mut zero_or_one_conf_value = Balance::ZERO;

    // add the spendable value to the expected balance
    zero_or_one_conf_value.add_spendable_value(value).unwrap();

    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::MIN,
        &zero_or_one_conf_value,
    );

    // Shield the output.
    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
    let txid = st
        .shield_transparent_funds(
            &input_selector,
            &change_strategy,
            value,
            account.usk(),
            &[*taddr],
            account.id(),
            ConfirmationsPolicy::MIN,
        )
        .unwrap()[0];

    // The wallet should have zero transparent balance, because the shielding
    // transaction can be mined.
    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::MIN,
        &Balance::ZERO,
    );

    // Mine the shielding transaction.
    let (mined_height, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(mined_height, 1);

    // The wallet should still have zero transparent balance.
    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::MIN,
        &Balance::ZERO,
    );

    // Unmine the shielding transaction via a reorg.
    st.wallet_mut()
        .truncate_to_height(mined_height - 1)
        .unwrap();
    assert_eq!(st.wallet().chain_height().unwrap(), Some(mined_height - 1));

    // The wallet should still have zero transparent balance.
    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::MIN,
        &Balance::ZERO,
    );

    // Expire the shielding transaction.
    let expiry_height = st
        .wallet()
        .get_transaction(txid)
        .unwrap()
        .expect("Transaction exists in the wallet.")
        .expiry_height();
    st.wallet_mut().update_chain_tip(expiry_height).unwrap();

    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::MIN,
        &zero_or_one_conf_value,
    );
}

/// Regression test for [PRO-291]: shielding a transparent balance composed of many P2PKH
/// UTXOs must not fail with `ChangeRequired` due to fee disagreement between the proposal
/// and builder layers.
///
/// At 150 P2PKH inputs the proposal-time fee computation (which uses
/// `STANDARD_P2PKH = 150` bytes per input) starts to diverge from the builder-time
/// fee computation (which historically used the actual serialized size, 149 bytes per
/// input) due to the `ceildiv(t_in_total_size, 150)` term in the ZIP 317 fee formula.
/// The discrepancy grows by one logical action (5000 zats) for every additional 150
/// inputs.
///
/// [PRO-291]: https://linear.app/zodl/issue/PRO-291
pub fn shielding_many_transparent_utxos<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    // Choose enough UTXOs to cross the first ceildiv(_, 150) boundary.
    const NUM_UTXOS: usize = 160;
    // Per-UTXO value comfortably above the marginal fee so none are treated as dust.
    const PER_UTXO: u64 = 100_000;

    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Initialize the wallet with chain data that has no shielded notes for us.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10_000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // Add many distinct P2PKH UTXOs to the wallet, all at the same transparent address.
    let value = Zatoshis::const_from_u64(PER_UTXO);
    let txout = TxOut::new(value, taddr.script().into());
    let height = st.wallet().chain_height().unwrap().unwrap();
    for i in 0..NUM_UTXOS {
        let mut hash = [0u8; 32];
        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
        let outpoint = OutPoint::new(hash, 0);
        let utxo = WalletTransparentOutput::from_parts(
            outpoint,
            txout.clone(),
            Some(height),
            Some(account.id()),
            Some(TransparentKeyScope::EXTERNAL),
            None,
        )
        .unwrap();
        st.wallet_mut()
            .put_received_transparent_utxo(&utxo)
            .unwrap();
    }

    // Shield the transparent balance.
    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
    let txids = st
        .shield_transparent_funds(
            &input_selector,
            &change_strategy,
            value,
            account.usk(),
            &[*taddr],
            account.id(),
            ConfirmationsPolicy::MIN,
        )
        .expect("shielding many P2PKH UTXOs should succeed");
    assert_eq!(txids.len(), 1);

    // After shielding, the transparent balance should be zero.
    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::MIN,
        &Balance::ZERO,
    );
}

/// Verifies that `InputSource::get_spendable_transparent_outputs_for_addresses` returns the
/// spendable outputs for a *set* of addresses in a single call, equivalent to the union of
/// per-address queries, and honours subset and empty requests.
pub fn get_spendable_transparent_outputs_for_addresses<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account_id = st.test_account().unwrap().id();
    let birthday = st.test_account().unwrap().birthday().height();

    let height_1 = birthday + 12345;
    st.wallet_mut().update_chain_tip(height_1).unwrap();

    // Obtain three distinct transparent receivers for the account.
    let mut taddrs = Vec::new();
    while taddrs.len() < 3 {
        let (ua, _) = st
            .wallet_mut()
            .get_next_available_address(account_id, UnifiedAddressRequest::AllAvailableKeys)
            .unwrap()
            .expect("an address should be available within the gap limit");
        if let Some(taddr) = ua.transparent() {
            taddrs.push(*taddr);
        }
    }

    // Place one distinct UTXO at each address.
    let value = Zatoshis::const_from_u64(100_000);
    for (i, taddr) in taddrs.iter().enumerate() {
        let mut hash = [0u8; 32];
        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
        let utxo = WalletTransparentOutput::from_parts(
            OutPoint::new(hash, 0),
            TxOut::new(value, taddr.script().into()),
            Some(height_1),
            Some(account_id),
            Some(TransparentKeyScope::EXTERNAL),
            None,
        )
        .unwrap();
        st.wallet_mut()
            .put_received_transparent_utxo(&utxo)
            .unwrap();
    }

    let target_height = TargetHeight::from(height_1 + 1);
    let sorted = |mut v: Vec<TransparentAddress>| {
        v.sort();
        v
    };

    // The batched query over all three addresses returns one output per address.
    let all = st
        .wallet()
        .get_spendable_transparent_outputs_for_addresses(
            &taddrs,
            target_height,
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::AllTransparentOutputs,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .unwrap();
    assert_eq!(all.len(), 3);
    assert_eq!(
        sorted(all.iter().map(|u| *u.recipient_address()).collect()),
        sorted(taddrs.clone()),
    );

    // It is equivalent to the union of per-address queries.
    let mut per_address = Vec::new();
    for taddr in &taddrs {
        per_address.extend(
            st.wallet()
                .get_spendable_transparent_outputs(
                    taddr,
                    target_height,
                    ConfirmationsPolicy::MIN,
                    CoinbaseFilter::AllTransparentOutputs,
                    LockFilter::Policy(&LockedInputPolicy::Exclude),
                )
                .unwrap(),
        );
    }
    assert_eq!(
        sorted(all.iter().map(|u| *u.recipient_address()).collect()),
        sorted(per_address.iter().map(|u| *u.recipient_address()).collect()),
    );

    // A subset request returns only the requested address's output.
    let subset = st
        .wallet()
        .get_spendable_transparent_outputs_for_addresses(
            &taddrs[..1],
            target_height,
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::AllTransparentOutputs,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .unwrap();
    assert_eq!(subset.len(), 1);
    assert_eq!(subset[0].recipient_address(), &taddrs[0]);

    // An empty request returns no outputs.
    assert!(
        st.wallet()
            .get_spendable_transparent_outputs_for_addresses(
                &[],
                target_height,
                ConfirmationsPolicy::MIN,
                CoinbaseFilter::AllTransparentOutputs,
                LockFilter::Policy(&LockedInputPolicy::Exclude),
            )
            .unwrap()
            .is_empty()
    );
}

/// Verifies that a shielding proposal caps the number of transparent inputs in a single
/// transaction to the selector's configured fraction of block space, selecting the highest-value
/// UTXOs first and leaving the remainder unspent.
pub fn shielding_transparent_input_cap<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    // At 1% of block space the cap is (2_000_000 * 1 / 100) / 150 = 133 inputs.
    const BLOCK_SPACE_PERCENT: u32 = 1;
    const CAP: usize = 133;
    const NUM_UTXOS: usize = CAP + 7; // 140; the 7 smallest must be dropped.
    const BASE: u64 = 100_000;
    const STEP: u64 = 1_000;

    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Initialize the wallet with chain data that has no shielded notes for us.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10_000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // Add `NUM_UTXOS` distinct-value P2PKH UTXOs at the same transparent address, so that
    // largest-first selection is unambiguous.
    let height = st.wallet().chain_height().unwrap().unwrap();
    for i in 0..NUM_UTXOS {
        let value = Zatoshis::const_from_u64(BASE + (i as u64) * STEP);
        let mut hash = [0u8; 32];
        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
        let utxo = WalletTransparentOutput::from_parts(
            OutPoint::new(hash, 0),
            TxOut::new(value, taddr.script().into()),
            Some(height),
            Some(account.id()),
            Some(TransparentKeyScope::EXTERNAL),
            None,
        )
        .unwrap();
        st.wallet_mut()
            .put_received_transparent_utxo(&utxo)
            .unwrap();
    }

    // Propose shielding with a 1%-of-block-space input cap.
    let input_selector =
        GreedyInputSelector::new().with_shielding_block_space_percent(BLOCK_SPACE_PERCENT);
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
    let proposal = st
        .propose_shielding(
            &input_selector,
            &change_strategy,
            Zatoshis::const_from_u64(BASE),
            &[*taddr],
            account.id(),
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::AllTransparentOutputs,
        )
        .expect("shielding proposal should succeed");

    let inputs = proposal.steps().first().transparent_inputs();
    assert_eq!(
        inputs.len(),
        CAP,
        "the number of transparent inputs should be capped",
    );

    // The selected inputs must be the `CAP` highest-value UTXOs: the `NUM_UTXOS - CAP` smallest
    // are dropped, so the smallest selected value is `BASE + (NUM_UTXOS - CAP) * STEP`.
    let min_selected = inputs.iter().map(|u| u.value()).min().unwrap();
    assert_eq!(
        min_selected,
        Zatoshis::const_from_u64(BASE + ((NUM_UTXOS - CAP) as u64) * STEP),
        "the lowest-value UTXOs should be the ones left unspent",
    );
}

/// This test attempts to verify that transparent funds spendability is
/// accounted for properly given the different minimum confirmations values
/// that can be set when querying for balances.
pub fn transparent_balance_spendability<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Initialize the wallet with chain data that has no shielded notes for us.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // The wallet starts out with zero balance.
    check_balance::<DSF>(
        &st as &TestState<_, DSF::DataStore, _>,
        &account,
        taddr,
        ConfirmationsPolicy::MIN,
        &Balance::ZERO,
    );

    // Create a fake transparent output.
    let value = Zatoshis::from_u64(100000).unwrap();
    let txout = TxOut::new(value, taddr.script().into());

    // Pretend the output was received in the chain tip.
    let height = st.wallet().chain_height().unwrap().unwrap();
    let utxo = WalletTransparentOutput::from_parts(
        OutPoint::fake(),
        txout,
        Some(height),
        Some(account.id()),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    // The wallet should detect the balance as available
    let mut zero_or_one_conf_value = Balance::ZERO;

    // add the spendable value to the expected balance
    zero_or_one_conf_value.add_spendable_value(value).unwrap();

    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::MIN,
        &zero_or_one_conf_value,
    );

    // now if we increase the number of confirmations our spendable balance should
    // be zero and the total balance equal to `value`
    let mut not_confirmed_yet_value = Balance::ZERO;

    not_confirmed_yet_value
        .add_pending_spendable_value(value)
        .unwrap();

    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::new_symmetrical_unchecked(2, false),
        &not_confirmed_yet_value,
    );

    // Add one extra block
    st.generate_empty_block();

    // Scan that block
    st.scan_cached_blocks(height, 1);

    // now we generate one more block and the balance should be the same as when the
    // check_balance function was called with zero or one confirmation.
    st.generate_empty_block();
    st.scan_cached_blocks(height + 1, 1);

    check_balance::<DSF>(
        &st,
        &account,
        taddr,
        ConfirmationsPolicy::new_symmetrical_unchecked(2, true),
        &zero_or_one_conf_value,
    );
}

/// Constructs a fake transparent-only coinbase transaction paying `value` to `taddr`.
///
/// The result is a structurally valid coinbase transaction (a single input spending the null
/// outpoint), which causes the receiving wallet to classify it as coinbase when it is stored
/// via [`decrypt_and_store_transaction`]. The `lock_time` parameter has no consensus meaning
/// here; distinct values may be used to give otherwise-identical coinbase transactions
/// distinct txids.
fn fake_transparent_coinbase_tx(
    lock_time: u32,
    value: Zatoshis,
    taddr: &TransparentAddress,
) -> Transaction {
    let coinbase_bundle = Bundle {
        vin: vec![TxIn::from_parts(
            OutPoint::NULL,
            Script::default(),
            u32::MAX,
        )],
        vout: vec![TxOut::new(value, taddr.script().into())],
        authorization: Authorized,
    };

    TransactionData::<zcash_primitives::transaction::Authorized>::from_parts(
        TxVersion::V5,
        BranchId::Nu5,
        lock_time,
        // Coinbase transactions do not expire.
        BlockHeight::from(0),
        // Coinbase transactions burn nothing.
        #[cfg(all(zcash_unstable = "nu7", feature = "zip-233"))]
        Zatoshis::ZERO,
        Some(coinbase_bundle),
        None,
        None,
        None,
    )
    .freeze()
    .unwrap()
}

/// Retrieves the [`AccountBalance`] for the given test account from the wallet summary.
fn get_account_balance<DSF>(
    st: &TestState<impl TestCache, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
    account: &TestAccount<<DSF as DataStoreFactory>::Account>,
    confirmations_policy: ConfirmationsPolicy,
) -> AccountBalance
where
    DSF: DataStoreFactory,
{
    let summary = st
        .wallet()
        .get_wallet_summary(confirmations_policy)
        .unwrap()
        .unwrap();
    *summary.account_balances().get(&account.id()).unwrap()
}

/// Verifies that transparent funds are reported in the correct `AccountBalance` bucket
/// (regular vs. coinbase), that immature coinbase value is reported as pending rather than
/// spendable, and that it becomes spendable upon reaching coinbase maturity.
pub fn transparent_coinbase_balance_split<DSF>(ds_factory: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Mine a coinbase output paying the wallet's transparent address at tx index 0.
    let coinbase_value = Zatoshis::const_from_u64(625_000_000);
    let coinbase_tx = fake_transparent_coinbase_tx(0, coinbase_value, taddr);
    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();

    // Immature coinbase: the value is pending spendability in the coinbase bucket, not
    // spendable; the regular bucket is untouched.
    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
    assert_eq!(
        balance.unshielded_coinbase_balance().spendable_value(),
        Zatoshis::ZERO
    );
    assert_eq!(
        balance
            .unshielded_coinbase_balance()
            .value_pending_spendability(),
        coinbase_value
    );
    assert_eq!(balance.unshielded_regular_balance(), &Balance::ZERO);

    // The same holds when the confirmations policy itself is not yet satisfied (the coinbase
    // output has only one confirmation here), which exercises the pending-balance query.
    let balance = get_account_balance::<DSF>(
        &st,
        &account,
        ConfirmationsPolicy::new_symmetrical_unchecked(2, false),
    );
    assert_eq!(
        balance.unshielded_coinbase_balance().spendable_value(),
        Zatoshis::ZERO
    );
    assert_eq!(
        balance
            .unshielded_coinbase_balance()
            .value_pending_spendability(),
        coinbase_value
    );
    assert_eq!(balance.unshielded_regular_balance(), &Balance::ZERO);

    // Receive a regular (non-coinbase) UTXO. This output's transaction has no known tx_index,
    // so it must be classified as regular (non-coinbase) funds.
    let regular_value = Zatoshis::const_from_u64(100_000);
    let utxo = WalletTransparentOutput::from_parts(
        OutPoint::fake(),
        TxOut::new(regular_value, taddr.script().into()),
        Some(h),
        Some(account.id()),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    // Mixed state: the regular value is spendable, the coinbase value remains pending, and the
    // combined accessors report the sums of the two buckets.
    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
    assert_eq!(
        balance.unshielded_regular_balance().spendable_value(),
        regular_value
    );
    assert_eq!(
        balance
            .unshielded_coinbase_balance()
            .value_pending_spendability(),
        coinbase_value
    );
    assert_eq!(
        balance.unshielded_balance(),
        (*balance.unshielded_regular_balance() + *balance.unshielded_coinbase_balance()).unwrap()
    );
    #[allow(deprecated)]
    let unshielded = balance.unshielded();
    assert_eq!(unshielded, (regular_value + coinbase_value).unwrap());
    assert_eq!(balance.total(), (regular_value + coinbase_value).unwrap());

    // Once the coinbase output reaches maturity, its value moves from pending to spendable.
    for _ in 0..COINBASE_MATURITY_BLOCKS {
        st.generate_empty_block();
    }
    st.scan_cached_blocks(h + 1, COINBASE_MATURITY_BLOCKS as usize);

    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
    assert_eq!(
        balance.unshielded_coinbase_balance().spendable_value(),
        coinbase_value
    );
    assert_eq!(
        balance
            .unshielded_coinbase_balance()
            .value_pending_spendability(),
        Zatoshis::ZERO
    );
    assert_eq!(
        balance.unshielded_regular_balance().spendable_value(),
        regular_value
    );
    assert_eq!(balance.total(), (regular_value + coinbase_value).unwrap());
}

/// Verifies that dust-valued (uneconomic) transparent outputs are reported in the
/// `uneconomic_value` field of the correct `AccountBalance` bucket (regular vs. coinbase).
pub fn transparent_coinbase_balance_dust<DSF>(ds_factory: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let dust_value = Zatoshis::const_from_u64(1000);
    assert!(dust_value <= zip317::MARGINAL_FEE);

    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Mine a dust coinbase output paying the wallet's transparent address at tx index 0.
    let coinbase_tx = fake_transparent_coinbase_tx(0, dust_value, taddr);
    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();

    // Receive a dust regular (non-coinbase) UTXO.
    let utxo = WalletTransparentOutput::from_parts(
        OutPoint::fake(),
        TxOut::new(dust_value, taddr.script().into()),
        Some(h),
        Some(account.id()),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    // Each dust output lands in the uneconomic value of its own bucket, and contributes to
    // neither spendable nor pending value.
    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
    assert_eq!(
        balance.unshielded_regular_balance().uneconomic_value(),
        dust_value
    );
    assert_eq!(
        balance.unshielded_coinbase_balance().uneconomic_value(),
        dust_value
    );
    assert_eq!(
        balance.uneconomic_value(),
        (dust_value + dust_value).unwrap()
    );
    assert_eq!(
        balance.unshielded_balance().spendable_value(),
        Zatoshis::ZERO
    );
    assert_eq!(
        balance.unshielded_balance().value_pending_spendability(),
        Zatoshis::ZERO
    );
    assert_eq!(balance.total(), Zatoshis::ZERO);

    // Dust classification takes precedence over coinbase maturity: after the coinbase output
    // matures, its value remains uneconomic rather than becoming spendable.
    for _ in 0..COINBASE_MATURITY_BLOCKS {
        st.generate_empty_block();
    }
    st.scan_cached_blocks(h + 1, COINBASE_MATURITY_BLOCKS as usize);

    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
    assert_eq!(
        balance.unshielded_coinbase_balance().uneconomic_value(),
        dust_value
    );
    assert_eq!(
        balance.unshielded_coinbase_balance().spendable_value(),
        Zatoshis::ZERO
    );
}

pub fn gap_limits<DSF>(ds_factory: DSF, cache: impl TestCache, gap_limits: GapLimits)
where
    DSF: DataStoreFactory,
    <DSF as DataStoreFactory>::AccountId: std::fmt::Debug,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(ds_factory)
        .with_block_cache(cache)
        .with_gap_limits(gap_limits)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let test_account = st.test_account().cloned().unwrap();
    let account_uuid = test_account.account().id();
    let ufvk = test_account.account().ufvk().unwrap().clone();

    let external_taddrs = st
        .wallet()
        .get_transparent_receivers(account_uuid, false, true)
        .unwrap();
    assert_eq!(
        u32::try_from(external_taddrs.len()).unwrap(),
        gap_limits.external()
    );
    let internal_taddrs = st
        .wallet()
        .get_transparent_receivers(account_uuid, true, false)
        .unwrap();
    assert_eq!(
        u32::try_from(internal_taddrs.len()).unwrap(),
        gap_limits.external() + gap_limits.internal()
    );
    let ephemeral_taddrs = st
        .wallet()
        .get_known_ephemeral_addresses(account_uuid, None)
        .unwrap();
    assert_eq!(
        u32::try_from(ephemeral_taddrs.len()).unwrap(),
        gap_limits.ephemeral()
    );

    // Add some funds to the wallet
    let (h0, _, _) = st.generate_next_block(
        &ufvk.sapling().unwrap(),
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(1000000),
    );
    st.scan_cached_blocks(h0, 1);

    // The previous operation was shielded-only, but unified address usage within the
    // valid transparent child index range still count towards the gap limit, so this
    // updates the gap limit by the index of the default Sapling receiver
    let external_taddrs = st
        .wallet()
        .get_transparent_receivers(account_uuid, false, true)
        .unwrap();
    assert_eq!(
        u32::try_from(external_taddrs.len()).unwrap(),
        gap_limits.external()
            + (u32::try_from(ufvk.sapling().unwrap().default_address().0).unwrap() + 1)
    );

    // Pick an address half way through the set of external taddrs
    let external_taddrs_sorted = external_taddrs
        .into_iter()
        .filter_map(|(addr, meta)| meta.address_index().map(|i| (i, addr)))
        .collect::<BTreeMap<_, _>>();
    let to = Address::from(
        *external_taddrs_sorted
            .get(&transparent::keys::NonHardenedChildIndex::from_index(4).unwrap())
            .expect("An address exists at index 4."),
    )
    .to_zcash_address(st.network());

    // Create a transaction & scan the block. Since the txid corresponds to one our wallet
    // generated, this should cause the gap limit to be bumped (generating addresses with index
    // 10..15)
    let txids = st
        .create_standard_transaction(&test_account, to, Zatoshis::const_from_u64(20000))
        .unwrap();
    let (h1, _) = st.generate_next_block_including(txids.head);

    // At this point, the transaction has been created, but since it has not been mined it does
    // not cause an update to the gap limit; we have to wait for the transaction to actually be
    // mined or we could bump the gap limit too soon and start generating addresses that will
    // never be inspected on wallet recovery.
    let external_taddrs = st
        .wallet()
        .get_transparent_receivers(account_uuid, false, true)
        .unwrap();
    assert_eq!(
        u32::try_from(external_taddrs.len()).unwrap(),
        gap_limits.external()
            + (u32::try_from(ufvk.sapling().unwrap().default_address().0).unwrap() + 1)
    );

    // Mine the block, then use `decrypt_and_store_transaction` to ensure that the wallet sees
    // the transaction as mined (since transparent handling doesn't get this from
    // `scan_cached_blocks`)
    st.scan_cached_blocks(h1, 1);
    let tx = st.wallet().get_transaction(txids.head).unwrap().unwrap();
    decrypt_and_store_transaction(&st.network().clone(), st.wallet_mut(), &tx, Some(h1)).unwrap();

    // Now that the transaction has been mined, the gap limit should have increased.
    let external_taddrs = st
        .wallet()
        .get_transparent_receivers(account_uuid, false, true)
        .unwrap();
    assert_eq!(
        u32::try_from(external_taddrs.len()).unwrap(),
        gap_limits.external() + 5
    );

    // The utxo query height should be equal to the minimum mined height among transactions
    // sent to any of the set of {addresses in the gap limit range | address prior to the gap}.
    let query_height = st.wallet().utxo_query_height(account_uuid).unwrap();
    assert_eq!(query_height, h0);
}

/// Builds a test 1-of-1 multisig redeem script from a single keypair.
#[cfg(feature = "transparent-key-import")]
fn build_test_redeem_script() -> (script::Redeem, secp256k1::SecretKey) {
    let secp = Secp256k1::new();
    let secret_key = SecretKey::from_slice(&[1u8; 32]).expect("valid secret key");
    let pubkey = secret_key.public_key(&secp);
    let redeem_script = script::Component(
        check_multisig(1, &[&pubkey.serialize()], false)
            .unwrap()
            .into_iter()
            .collect(),
    );
    (redeem_script, secret_key)
}

/// Tests that importing a standalone transparent public key succeeds.
#[cfg(feature = "transparent-key-import")]
pub fn import_standalone_transparent_pubkey<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    let secp = Secp256k1::new();
    let secret_key = SecretKey::from_slice(&[1u8; 32]).expect("valid secret key");
    let pubkey = secret_key.public_key(&secp);
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_pubkey(account_id, pubkey),
        Ok(_)
    );
}

/// Tests that importing the same pubkey twice to the same account is idempotent.
#[cfg(feature = "transparent-key-import")]
pub fn import_standalone_transparent_pubkey_idempotent<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    let secp = Secp256k1::new();
    let secret_key = SecretKey::from_slice(&[1u8; 32]).expect("valid secret key");
    let pubkey = secret_key.public_key(&secp);

    // First import
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_pubkey(account_id, pubkey),
        Ok(_)
    );

    // Snapshot state after first import
    let receivers_before = st
        .wallet()
        .get_transparent_receivers(account_id, false, true)
        .unwrap();

    // Second import to same account should also succeed (idempotent)
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_pubkey(account_id, pubkey),
        Ok(_)
    );

    // Verify wallet state is unchanged
    let receivers_after = st
        .wallet()
        .get_transparent_receivers(account_id, false, true)
        .unwrap();

    assert_eq!(receivers_before.len(), receivers_after.len());

    let taddr = TransparentAddress::from_pubkey(&pubkey);
    let metadata = receivers_after
        .get(&taddr)
        .expect("address should be present");
    assert!(matches!(
        metadata.source(),
        TransparentAddressSource::StandalonePubkey(_)
    ));
}

/// Tests that importing the same pubkey to a different account fails.
#[cfg(feature = "transparent-key-import")]
pub fn import_standalone_transparent_pubkey_conflict<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account1_id = st.test_account().unwrap().id();

    let secp = Secp256k1::new();
    let secret_key = SecretKey::from_slice(&[1u8; 32]).expect("valid secret key");
    let pubkey = secret_key.public_key(&secp);

    // Import to first account
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_pubkey(account1_id, pubkey),
        Ok(_)
    );

    // Create a second account
    let birthday = AccountBirthday::from_parts(
        ChainState::empty(
            st.network()
                .activation_height(NetworkUpgrade::Sapling)
                .unwrap()
                - 1,
            BlockHash([0; 32]),
        ),
        None,
    );
    let seed2 = Secret::new(vec![42u8; 32]);
    let (account2_id, _) = st
        .wallet_mut()
        .create_account("account2", &seed2, &birthday, None)
        .unwrap();

    // Import same pubkey to second account should fail
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_pubkey(account2_id, pubkey),
        Err(_)
    );
}

/// Tests that a UTXO received at a standalone P2PKH address is reflected in the wallet balance.
#[cfg(feature = "transparent-key-import")]
pub fn import_standalone_transparent_pubkey_balance<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
    <<DSF as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account_id = st.test_account().unwrap().id();
    let birthday = st.test_account().unwrap().birthday().height();

    let secp = Secp256k1::new();
    let secret_key = SecretKey::from_slice(&[1u8; 32]).expect("valid secret key");
    let pubkey = secret_key.public_key(&secp);

    // Import the public key.
    st.wallet_mut()
        .import_standalone_transparent_pubkey(account_id, pubkey)
        .unwrap();

    // Derive the P2PKH address.
    let taddr = TransparentAddress::from_pubkey(&pubkey);

    let height = birthday + 1000;
    st.wallet_mut().update_chain_tip(height).unwrap();

    // Create a fake UTXO at the P2PKH address.
    let value = Zatoshis::const_from_u64(50_000);
    let outpoint = OutPoint::fake();
    let txout = TxOut::new(value, taddr.script().into());
    let utxo = WalletTransparentOutput::from_parts(
        outpoint,
        txout,
        Some(height),
        Some(account_id),
        None,
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    // Verify the balance is reflected via get_transparent_balances.
    let target_height = TargetHeight::from(height + 1);
    let balances = st
        .wallet()
        .get_transparent_balances(account_id, target_height, ConfirmationsPolicy::MIN)
        .unwrap();
    assert_eq!(
        balances.get(&taddr).map(|(_, b)| b.spendable_value()),
        Some(value),
    );

    // Verify the UTXO is returned by get_spendable_transparent_outputs.
    let utxos = st
        .wallet()
        .get_spendable_transparent_outputs(
            &taddr,
            target_height,
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::AllTransparentOutputs,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .unwrap();
    assert_eq!(utxos.len(), 1);
    assert_eq!(utxos[0].value(), value);
}

/// Tests spending from a standalone P2PKH address by shielding its balance.
#[cfg(feature = "transparent-key-import")]
pub fn spend_from_standalone_pubkey<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Create a keypair and derive the P2PKH address.
    let secp = Secp256k1::new();
    let secret_key = SecretKey::from_slice(&[1u8; 32]).expect("valid secret key");
    let pubkey = secret_key.public_key(&secp);

    // Import the public key.
    st.wallet_mut()
        .import_standalone_transparent_pubkey(account_id, pubkey)
        .unwrap();

    // Derive the P2PKH address.
    let taddr = TransparentAddress::from_pubkey(&pubkey);

    // Initialize chain data with blocks (needed for shielding transaction creation).
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // Create a fake UTXO at the P2PKH address.
    let value = Zatoshis::from_u64(100000).unwrap();
    let height = st.wallet().chain_height().unwrap().unwrap();
    let txout = TxOut::new(value, taddr.script().into());
    let utxo = WalletTransparentOutput::from_parts(
        OutPoint::fake(),
        txout,
        Some(height),
        Some(account_id),
        None,
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    // Build SpendingKeys with the standalone key for the P2PKH address.
    let mut standalone_keys = HashMap::new();
    standalone_keys.insert(taddr, vec![secret_key]);
    let spending_keys = SpendingKeys::new(
        account.usk().clone(),
        #[cfg(feature = "transparent-key-import")]
        standalone_keys,
    );

    // Shield the P2PKH UTXO.
    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);

    let prover = ::zcash_proofs::prover::LocalTxProver::bundled();
    let network = *st.network();
    let txids = wallet::shield_transparent_funds(
        st.wallet_mut(),
        &network,
        &prover,
        &prover,
        &input_selector,
        &change_strategy,
        value,
        &spending_keys,
        &[taddr],
        account_id,
        ConfirmationsPolicy::MIN,
    )
    .unwrap();

    assert!(!txids.is_empty());

    // The wallet should have zero transparent balance after shielding.
    check_balance::<DSF>(
        &st,
        &account,
        &taddr,
        ConfirmationsPolicy::MIN,
        &Balance::ZERO,
    );

    // The shielded balance should now include the value minus the fee.
    let fee = st
        .get_tx_from_history(*txids.first())
        .unwrap()
        .unwrap()
        .fee_paid()
        .expect("fee should be known for wallet-created transactions");
    let summary = st
        .wallet()
        .get_wallet_summary(ConfirmationsPolicy::MIN)
        .unwrap()
        .unwrap();
    let account_balance = summary.account_balances().get(&account_id).unwrap();
    assert_eq!(
        account_balance
            .sapling_balance()
            .change_pending_confirmation(),
        (value - fee).unwrap(),
    );
}

/// Tests that importing a standalone P2SH address succeeds and the address appears
/// in `get_transparent_receivers` with the correct `TransparentAddressSource`.
#[cfg(feature = "transparent-key-import")]
pub fn import_standalone_transparent_p2sh<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account_id = st.test_account().unwrap().id();
    let (redeem_script, _) = build_test_redeem_script();

    // Import should succeed
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_script(account_id, redeem_script.clone()),
        Ok(_)
    );

    // Verify the address appears in get_transparent_receivers
    let receivers = st
        .wallet()
        .get_transparent_receivers(account_id, false, true)
        .unwrap();

    // The P2SH address derived from the redeem script should be present
    let script_pubkey = sh(&redeem_script);
    let expected_addr =
        TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid P2SH address");

    let metadata = receivers
        .get(&expected_addr)
        .expect("address should be present");
    assert!(matches!(
        metadata.source(),
        TransparentAddressSource::StandaloneScript(_)
    ));
}

/// Tests that importing the same P2SH address twice to the same account is idempotent.
#[cfg(feature = "transparent-key-import")]
pub fn import_standalone_transparent_p2sh_idempotent<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account_id = st.test_account().unwrap().id();
    let (redeem_script, _) = build_test_redeem_script();

    // First import
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_script(account_id, redeem_script.clone()),
        Ok(_)
    );

    // Snapshot state after first import
    let receivers_before = st
        .wallet()
        .get_transparent_receivers(account_id, false, true)
        .unwrap();

    // Second import to same account should also succeed (idempotent)
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_script(account_id, redeem_script.clone()),
        Ok(_)
    );

    // Verify wallet state is unchanged
    let receivers_after = st
        .wallet()
        .get_transparent_receivers(account_id, false, true)
        .unwrap();

    assert_eq!(receivers_before.len(), receivers_after.len());

    let script_pubkey = sh(&redeem_script);
    let expected_addr =
        TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid P2SH address");
    let metadata = receivers_after
        .get(&expected_addr)
        .expect("address should be present");
    assert!(matches!(
        metadata.source(),
        TransparentAddressSource::StandaloneScript(_)
    ));
}

/// Tests that importing the same P2SH address to a different account fails.
#[cfg(feature = "transparent-key-import")]
pub fn import_standalone_transparent_p2sh_conflict<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account1_id = st.test_account().unwrap().id();
    let (redeem_script, _) = build_test_redeem_script();

    // Import to first account
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_script(account1_id, redeem_script.clone()),
        Ok(_)
    );

    // Create a second account
    let birthday = AccountBirthday::from_parts(
        ChainState::empty(
            st.network()
                .activation_height(NetworkUpgrade::Sapling)
                .unwrap()
                - 1,
            BlockHash([0; 32]),
        ),
        None,
    );
    let seed2 = Secret::new(vec![42u8; 32]);
    let (account2_id, _) = st
        .wallet_mut()
        .create_account("account2", &seed2, &birthday, None)
        .unwrap();

    // Import same redeem script to second account should fail
    assert_matches!(
        st.wallet_mut()
            .import_standalone_transparent_script(account2_id, redeem_script),
        Err(_)
    );
}

/// Tests that a UTXO received at a standalone P2SH address is reflected in the wallet balance.
#[cfg(feature = "transparent-key-import")]
pub fn import_standalone_transparent_p2sh_balance<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
    <<DSF as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account_id = st.test_account().unwrap().id();
    let birthday = st.test_account().unwrap().birthday().height();

    let (redeem_script, _) = build_test_redeem_script();

    // Import the P2SH address.
    st.wallet_mut()
        .import_standalone_transparent_script(account_id, redeem_script.clone())
        .unwrap();

    // Derive the expected transparent address from the redeem script.
    let script_pubkey = sh(&redeem_script);
    let taddr = TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid P2SH address");

    let height = birthday + 1000;
    st.wallet_mut().update_chain_tip(height).unwrap();

    // Create a fake UTXO at the P2SH address.
    let value = Zatoshis::const_from_u64(50_000);
    let outpoint = OutPoint::fake();
    let txout = TxOut::new(value, taddr.script().into());
    let utxo = WalletTransparentOutput::from_parts(
        outpoint,
        txout,
        Some(height),
        Some(account_id),
        None,
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    // Verify the balance is reflected via get_transparent_balances.
    let target_height = TargetHeight::from(height + 1);
    let balances = st
        .wallet()
        .get_transparent_balances(account_id, target_height, ConfirmationsPolicy::MIN)
        .unwrap();
    assert_eq!(
        balances.get(&taddr).map(|(_, b)| b.spendable_value()),
        Some(value),
    );

    // Verify the UTXO is returned by get_spendable_transparent_outputs.
    let utxos = st
        .wallet()
        .get_spendable_transparent_outputs(
            &taddr,
            target_height,
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::AllTransparentOutputs,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .unwrap();
    assert_eq!(utxos.len(), 1);
    assert_eq!(utxos[0].value(), value);
}

/// Tests spending from a standalone P2SH (multisig) address by shielding its balance.
#[cfg(feature = "transparent-key-import")]
pub fn spend_from_standalone_p2sh<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account = st.test_account().cloned().unwrap();
    let account_id = account.id();
    // Build the redeem script and get the signing key.
    let (redeem_script, secret_key) = build_test_redeem_script();

    // Import the P2SH address.
    st.wallet_mut()
        .import_standalone_transparent_script(account_id, redeem_script.clone())
        .unwrap();

    // Derive the P2SH address.
    let script_pubkey = sh(&redeem_script);
    let taddr = TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid P2SH address");

    // Initialize chain data with blocks (needed for shielding transaction creation).
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // Create a fake UTXO at the P2SH address.
    let value = Zatoshis::from_u64(100000).unwrap();
    let height = st.wallet().chain_height().unwrap().unwrap();
    let txout = TxOut::new(value, taddr.script().into());
    let utxo = WalletTransparentOutput::from_parts(
        OutPoint::fake(),
        txout,
        Some(height),
        Some(account_id),
        None,
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    // Build SpendingKeys with the standalone key for the P2SH address.
    let mut standalone_keys = HashMap::new();
    standalone_keys.insert(taddr, vec![secret_key]);
    let spending_keys = SpendingKeys::new(
        account.usk().clone(),
        #[cfg(feature = "transparent-key-import")]
        standalone_keys,
    );

    // Shield the P2SH UTXO.
    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);

    let prover = ::zcash_proofs::prover::LocalTxProver::bundled();
    let network = *st.network();
    let txids = wallet::shield_transparent_funds(
        st.wallet_mut(),
        &network,
        &prover,
        &prover,
        &input_selector,
        &change_strategy,
        value,
        &spending_keys,
        &[taddr],
        account_id,
        ConfirmationsPolicy::MIN,
    )
    .unwrap();

    assert!(!txids.is_empty());

    // The wallet should have zero transparent balance after shielding.
    check_balance::<DSF>(
        &st,
        &account,
        &taddr,
        ConfirmationsPolicy::MIN,
        &Balance::ZERO,
    );

    // The shielded balance should now include the value minus the fee.
    let fee = st
        .get_tx_from_history(*txids.first())
        .unwrap()
        .unwrap()
        .fee_paid()
        .expect("fee should be known for wallet-created transactions");
    let summary = st
        .wallet()
        .get_wallet_summary(ConfirmationsPolicy::MIN)
        .unwrap()
        .unwrap();
    let account_balance = summary.account_balances().get(&account_id).unwrap();
    assert_eq!(
        account_balance
            .sapling_balance()
            .change_pending_confirmation(),
        (value - fee).unwrap(),
    );
}

/// Tests [`WalletWrite::mark_transparent_addresses_exposed`] by observing the effect on the
/// address's exposure metadata via
/// [`WalletRead::get_transparent_address_metadata`](crate::data_api::WalletRead::get_transparent_address_metadata).
pub fn mark_transparent_addresses_exposed<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account_id = st.test_account().unwrap().id();
    let taddr = *st
        .wallet()
        .get_last_generated_address_matching(account_id, UnifiedAddressRequest::AllAvailableKeys)
        .unwrap()
        .unwrap()
        .transparent()
        .unwrap();

    let exposure_of = |st: &TestState<_, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
                       addr: &TransparentAddress|
     -> Exposure {
        st.wallet()
            .get_transparent_address_metadata(account_id, addr)
            .unwrap()
            .unwrap()
            .exposure()
    };

    // Calling with a very high height does not raise an already-recorded exposure,
    // and records the provided height if no prior exposure was tracked.
    let initial = exposure_of(&st, &taddr);
    let very_high = BlockHeight::from(u32::MAX);
    st.wallet_mut()
        .mark_transparent_addresses_exposed(&[(taddr, very_high)])
        .unwrap();
    match initial {
        Exposure::Exposed { at_height, .. } => assert_matches!(
            exposure_of(&st, &taddr),
            Exposure::Exposed { at_height: h, .. } if h == at_height
        ),
        Exposure::Unknown | Exposure::CannotKnow => assert_matches!(
            exposure_of(&st, &taddr),
            Exposure::Exposed { at_height: h, .. } if h == very_high
        ),
    }

    // Calling with a lower height lowers the recorded exposure.
    st.wallet_mut()
        .mark_transparent_addresses_exposed(&[(taddr, BlockHeight::from(0))])
        .unwrap();
    assert_matches!(
        exposure_of(&st, &taddr),
        Exposure::Exposed { at_height, .. } if at_height == BlockHeight::from(0)
    );

    // Calling with a higher height does not raise the recorded exposure.
    st.wallet_mut()
        .mark_transparent_addresses_exposed(&[(taddr, BlockHeight::from(100))])
        .unwrap();
    assert_matches!(
        exposure_of(&st, &taddr),
        Exposure::Exposed { at_height, .. } if at_height == BlockHeight::from(0)
    );

    // An address not tracked by the wallet must return an error.
    let unknown = TransparentAddress::PublicKeyHash([0u8; 20]);
    assert!(
        st.wallet_mut()
            .mark_transparent_addresses_exposed(&[(unknown, BlockHeight::from(1))])
            .is_err()
    );

    // An empty input is a no-op.
    st.wallet_mut()
        .mark_transparent_addresses_exposed(&[])
        .unwrap();
}

/// Tests that [`WalletWrite::mark_transparent_addresses_exposed`] correctly handles bulk
/// input: all addresses in a successful call must be marked, and an unrecognized address
/// must cause the entire call to be rolled back.
pub fn mark_transparent_addresses_exposed_bulk<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let gap_limits = GapLimits::new(5, 2, 2);
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_gap_limits(gap_limits)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    let mut receivers = st
        .wallet()
        .get_transparent_receivers(account_id, false, true)
        .unwrap()
        .into_iter()
        .filter_map(|(addr, meta)| {
            let exposure = meta.exposure();
            meta.address_index().map(|i| (i.index(), addr, exposure))
        })
        .collect::<Vec<_>>();
    receivers.sort_by_key(|(i, _, _)| *i);

    // Use known-unexposed receivers for the bulk-success test, so that the post-call
    // recorded height is exactly the one we pass in regardless of any default exposure
    // that address generation may set on other receivers.
    let unexposed = receivers
        .iter()
        .copied()
        .filter(|(_, _, exposure)| matches!(exposure, Exposure::Unknown))
        .collect::<Vec<_>>();
    assert!(
        unexposed.len() >= 2,
        "account should have at least 2 unexposed derived receivers"
    );

    // Mark two unexposed addresses at distinct heights in a single bulk call.
    let (_idx_a, addr_a, _) = unexposed[0];
    let (_idx_b, addr_b, _) = unexposed[1];
    let height_a = BlockHeight::from(10);
    let height_b = BlockHeight::from(20);
    st.wallet_mut()
        .mark_transparent_addresses_exposed(&[(addr_a, height_a), (addr_b, height_b)])
        .unwrap();

    let exposure_of = |st: &TestState<_, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
                       addr: &TransparentAddress|
     -> Exposure {
        st.wallet()
            .get_transparent_address_metadata(account_id, addr)
            .unwrap()
            .unwrap()
            .exposure()
    };
    assert_matches!(
        exposure_of(&st, &addr_a),
        Exposure::Exposed { at_height, .. } if at_height == height_a
    );
    assert_matches!(
        exposure_of(&st, &addr_b),
        Exposure::Exposed { at_height, .. } if at_height == height_b
    );

    // Now attempt a bulk call where the second entry is unrecognized. The whole call must
    // fail, and the first entry must not have been partially applied. Pick a third
    // receiver distinct from `addr_a`/`addr_b` — its prior exposure state is irrelevant
    // since the assertion is preservation, not a specific height.
    let (idx_c, addr_c, _) = *receivers
        .iter()
        .find(|(_, addr, _)| *addr != addr_a && *addr != addr_b)
        .expect("account should have a third derived receiver");
    let before = exposure_of(&st, &addr_c);
    let unknown = TransparentAddress::PublicKeyHash([0x7u8; 20]);
    assert!(
        st.wallet_mut()
            .mark_transparent_addresses_exposed(&[
                (addr_c, BlockHeight::from(5)),
                (unknown, BlockHeight::from(5)),
            ])
            .is_err()
    );
    assert_eq!(
        exposure_of(&st, &addr_c),
        before,
        "exposure at index {idx_c} must not change when bulk call fails atomically"
    );
}

/// Tests that [`WalletWrite::mark_transparent_addresses_exposed`] returns an error when
/// asked to mark an address that the wallet does not track.
pub fn mark_transparent_addresses_exposed_unknown_address<DSF>(dsf: DSF)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let unknown = TransparentAddress::PublicKeyHash([0u8; 20]);
    assert!(
        st.wallet_mut()
            .mark_transparent_addresses_exposed(&[(unknown, BlockHeight::from(1))])
            .is_err()
    );
}

/// Sets up a wallet whose account holds no shielded notes and a single spendable
/// transparent UTXO at its default external transparent receiver, returning the test
/// state, the account, the funding outpoint, and the UTXO value.
///
/// The chain is seeded with blocks containing notes that do *not* belong to the wallet,
/// so that target/anchor heights resolve while the account remains shielded-empty. This
/// isolates the transparent-UTXO selection path.
#[allow(clippy::type_complexity)]
fn setup_transparent_only_account<DSF>(
    dsf: DSF,
    cache: impl TestCache,
    utxo_value: Zatoshis,
) -> (
    TestState<impl TestCache, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
    TestAccount<<DSF as DataStoreFactory>::Account>,
    OutPoint,
)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Seed the chain with notes that do not belong to us so that heights resolve while
    // the account remains without any shielded notes.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // Fund the account with a single transparent UTXO well above the marginal fee.
    let txout = TxOut::new(utxo_value, taddr.script().into());
    let height = st.wallet().chain_height().unwrap().unwrap();
    let outpoint = OutPoint::fake();
    let utxo = WalletTransparentOutput::from_parts(
        outpoint.clone(),
        txout,
        Some(height),
        Some(account.id()),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    (st, account, outpoint)
}

/// Builds a single-payment t->t [`TransactionRequest`] paying `amount` to a fixed
/// external transparent recipient.
fn t2t_request(network: &LocalNetwork, amount: Zatoshis) -> TransactionRequest {
    let recipient = TransparentAddress::PublicKeyHash([7u8; 20]);
    TransactionRequest::new(vec![Payment::without_memo(
        Address::Transparent(recipient).to_zcash_address(network),
        amount,
    )])
    .unwrap()
}

/// Regression test enforcing the privacy invariant: with the default
/// default spend policy (which permits no transparent spending), a transfer must NOT silently spend
/// the account's transparent UTXOs as a fallback. An account holding only transparent
/// funds must fail with [`InsufficientFunds`] rather than producing a t->t proposal.
///
/// [`InsufficientFunds`]: crate::data_api::error::Error::InsufficientFunds
pub fn propose_t2t_shielded_only_is_insufficient<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let utxo_value = Zatoshis::const_from_u64(100_000);
    let (mut st, account, _outpoint) = setup_transparent_only_account(dsf, cache, utxo_value);

    let network = *st.network();
    let request = t2t_request(&network, Zatoshis::const_from_u64(40_000));

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);

    let result = st.propose_transfer_with_policy(
        account.id(),
        &input_selector,
        &change_strategy,
        request,
        ConfirmationsPolicy::MIN,
        &SpendPolicy::default(),
    );

    assert_matches!(
        result,
        Err(crate::data_api::error::Error::InsufficientFunds { .. }),
        "shielded-only policy must not spend transparent UTXOs as a fallback",
    );
}

/// With `TransparentSpendPolicy::any_account_addr` (the legacy `ANY_TADDR` behavior), a
/// transfer may spend the account's transparent UTXOs. Verifies that the funding UTXO is
/// selected as a transparent input and that the proposal balance is consistent.
pub fn propose_t2t_any_account_taddr<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let utxo_value = Zatoshis::const_from_u64(100_000);
    let transfer_amount = Zatoshis::const_from_u64(40_000);
    let (mut st, account, outpoint) = setup_transparent_only_account(dsf, cache, utxo_value);

    let network = *st.network();
    let request = t2t_request(&network, transfer_amount);

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);

    let proposal = st
        .propose_transfer_with_policy(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
            &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
        )
        .expect("transparent spend must succeed under any-account-address transparent spending");

    // A pure t->t transfer is a single step (no ZIP-320 ephemeral roundtrip).
    assert_eq!(proposal.steps().len(), 1);
    let step = &proposal.steps().head;

    assert_eq!(
        step.transparent_inputs().len(),
        1,
        "expected exactly one transparent input selected from the account's UTXOs",
    );
    assert_eq!(step.transparent_inputs()[0].outpoint(), &outpoint);
    assert_eq!(step.transparent_inputs()[0].txout().value(), utxo_value);

    // `TransactionBalance::total()` is `change + fee`, which by the balance equation equals
    // input total minus the explicit payment.
    assert_eq!(
        step.balance().total(),
        (utxo_value - transfer_amount).unwrap(),
    );
    assert!(step.balance().fee_required() > Zatoshis::ZERO);
    assert!(!step.balance().proposed_change().is_empty());
}

/// Verifies that `GreedyInputSelector::propose_transaction` successfully re-gathers
/// transparent inputs when the initial fee-aware gather's estimate (which accounts only
/// for the transparent side of the transaction) turns out to be insufficient once the
/// real change strategy accounts for the additional shielded action required by a
/// shielded payment recipient.
///
/// This exercises the `ChangeError::InsufficientFunds` fallback path in
/// `GreedyInputSelector::propose_transaction`, which re-invokes
/// `InputSource::select_spendable_transparent_outputs` with a corrected `TargetValue`
/// when the first gather's reservation proves too small. Funding many small transparent
/// UTXOs forces the initial gather to stop with just enough inputs to cover the payment
/// under its own (transparent-only) fee estimate; the shielded payment output then pushes
/// the real required fee higher, so satisfying the request is only possible by gathering
/// additional inputs beyond that initial estimate.
pub fn propose_t2shielded_requires_transparent_regather<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Seed the chain with notes that do not belong to us so that heights resolve.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10_000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // Fund the account with many small transparent UTXOs, none of which alone are
    // remotely close to the payment amount, so that gathering enough of them to satisfy
    // the (larger, corrected) real requirement remains possible.
    let dust_value = Zatoshis::const_from_u64(10_000);
    let n_dust = 30;
    let height = st.wallet().chain_height().unwrap().unwrap();
    for i in 0..n_dust {
        let mut hash = [0u8; 32];
        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
        let utxo = WalletTransparentOutput::from_parts(
            OutPoint::new(hash, 0),
            TxOut::new(dust_value, taddr.script().into()),
            Some(height),
            Some(account.id()),
            Some(TransparentKeyScope::EXTERNAL),
            None,
        )
        .unwrap();
        st.wallet_mut()
            .put_received_transparent_utxo(&utxo)
            .unwrap();
    }

    // Pay a shielded recipient. The initial transparent gather's fee estimate accounts
    // only for the transparent inputs it selects; it does not (and cannot, since the
    // shielded payment output isn't known to `InputSource::select_spendable_transparent_outputs`)
    // account for the additional sapling action this payment requires, so the first pass
    // undershoots and a re-gather is required to actually satisfy the request.
    let network = *st.network();
    let recipient = ExtendedSpendingKey::master(&[1u8; 32])
        .to_diversifiable_full_viewing_key()
        .default_address()
        .1;
    let payment_amount = Zatoshis::const_from_u64(50_000);
    let request = TransactionRequest::new(vec![Payment::without_memo(
        Address::Sapling(recipient).to_zcash_address(&network),
        payment_amount,
    )])
    .unwrap();

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);

    // Independently reproduce the initial gather that `GreedyInputSelector` will perform
    // (bounded only by the payment amount, since that's the only information available
    // before the shielded payment output's fee contribution is known). Comparing this to
    // the transparent inputs actually used by the successful proposal below demonstrates
    // that the proposal could only have succeeded via the re-gather fallback: the initial
    // gather's own reservation ignores the extra sapling action the payment requires, so
    // it cannot by itself have covered the real, higher requirement.
    let initial_gather = st
        .wallet()
        .select_spendable_transparent_outputs(
            account.id(),
            TargetHeight::from(height + 1),
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::NonCoinbaseOnly,
            None,
            TargetValue::AtLeast(payment_amount),
            usize::MAX,
            &StandardFeeRule::Zip317,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .expect("initial gather should succeed");
    let initial_gather_value: Zatoshis = initial_gather
        .iter()
        .map(|u| u.value())
        .fold(Zatoshis::ZERO, |acc, v| (acc + v).unwrap());

    let proposal = st
        .propose_transfer_with_policy(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
            &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
        )
        .expect(
            "transparent spend should succeed via the re-gather fallback despite the \
             initial gather's fee estimate being insufficient",
        );

    let step = &proposal.steps().head;
    let gathered_value: Zatoshis = step
        .transparent_inputs()
        .iter()
        .map(|i| i.txout().value())
        .fold(Zatoshis::ZERO, |acc, v| (acc + v).unwrap());
    assert!(
        gathered_value > initial_gather_value,
        "the successful proposal should have gathered more transparent value ({}) than \
         the insufficient initial gather ({})",
        u64::from(gathered_value),
        u64::from(initial_gather_value),
    );
    assert!(step.balance().fee_required() > Zatoshis::ZERO);
}

/// Consolidation subtracts already-selected transparent value from the shielded funding target.
pub fn prefer_consolidation_accounts_for_selected_transparent_value<DSF>(
    dsf: DSF,
    cache: impl TestCache,
) where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

    let account = st.test_account().cloned().unwrap();
    let ufvk = account.account().ufvk().unwrap();
    let sapling_fvk = ufvk.sapling().unwrap();
    let (start_height, _, _) = st.generate_next_block(
        &sapling_fvk,
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(600_000),
    );
    st.generate_next_block(
        &sapling_fvk,
        AddressType::DefaultExternal,
        Zatoshis::const_from_u64(500_000),
    );
    st.scan_cached_blocks(start_height, 2);

    let uaddr = st
        .wallet()
        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
        .unwrap()
        .unwrap();
    let taddr = *uaddr.transparent().unwrap();
    let utxo = WalletTransparentOutput::from_parts(
        OutPoint::fake(),
        TxOut::new(Zatoshis::const_from_u64(600_000), taddr.script().into()),
        st.wallet().chain_height().unwrap(),
        Some(account.id()),
        Some(TransparentKeyScope::EXTERNAL),
        None,
    )
    .unwrap();
    st.wallet_mut()
        .put_received_transparent_utxo(&utxo)
        .unwrap();

    let recipient = ExtendedSpendingKey::master(&[1u8; 32])
        .to_diversifiable_full_viewing_key()
        .default_address()
        .1;
    let request = TransactionRequest::new(vec![Payment::without_memo(
        Address::Sapling(recipient).to_zcash_address(st.network()),
        Zatoshis::const_from_u64(1_000_000),
    )])
    .unwrap();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
    let spend_policy = SpendPolicy::default()
        .with_transparent(TransparentSpendPolicy::any_account_addr())
        .with_note_selection(NoteSelection::PreferConsolidation);

    let proposal = st
        .propose_transfer_with_policy(
            account.id(),
            &GreedyInputSelector::new(),
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
            &spend_policy,
        )
        .expect("the mixed transparent and shielded inputs cover the payment and fee");
    let step = &proposal.steps().head;
    assert_eq!(step.transparent_inputs().len(), 1);
    assert_eq!(
        step.shielded_inputs()
            .expect("the proposal spends a shielded note")
            .notes()
            .len(),
        1,
    );
}

/// Verifies that `GreedyInputSelector::with_shielding_block_space_percent` also bounds the
/// transparent gather performed for general (non-shielding) transfers, not just shielding.
///
/// Funds more dust UTXOs than fit within a 1%-of-block-space cap, and requests a payment
/// whose post-fee cost can only be met by exceeding that cap. The gather must stop at the
/// cap rather than consuming every eligible UTXO, so the proposal fails with
/// [`InsufficientFunds`] instead of succeeding with an uncapped number of transparent inputs.
///
/// [`InsufficientFunds`]: crate::data_api::error::Error::InsufficientFunds
pub fn propose_transfer_transparent_input_cap<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    // At 1% of block space the cap is (2_000_000 * 1 / 100) / 150 = 133 inputs.
    const BLOCK_SPACE_PERCENT: u32 = 1;
    const CAP: usize = 133;
    const NUM_UTXOS: usize = CAP + 7; // 140; more than enough to exceed the cap.
    const DUST_VALUE: u64 = 10_000;

    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Seed the chain with notes that do not belong to us so that heights resolve.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10_000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // Fund the account with more dust UTXOs than fit within the cap.
    let height = st.wallet().chain_height().unwrap().unwrap();
    for i in 0..NUM_UTXOS {
        let mut hash = [0u8; 32];
        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
        let utxo = WalletTransparentOutput::from_parts(
            OutPoint::new(hash, 0),
            TxOut::new(Zatoshis::const_from_u64(DUST_VALUE), taddr.script().into()),
            Some(height),
            Some(account.id()),
            Some(TransparentKeyScope::EXTERNAL),
            None,
        )
        .unwrap();
        st.wallet_mut()
            .put_received_transparent_utxo(&utxo)
            .unwrap();
    }

    // Request a post-fee amount that is only reachable by gathering more than `CAP` inputs
    // (with the cap, `CAP` inputs net `DUST_VALUE * CAP - 5_000 * CAP = 5_000 * CAP`
    // post-fee; requesting exactly that much would succeed, so request more).
    let payment_amount = Zatoshis::const_from_u64(5_000 * (CAP as u64) + DUST_VALUE);

    let network = *st.network();
    let request = t2t_request(&network, payment_amount);

    let input_selector =
        GreedyInputSelector::new().with_shielding_block_space_percent(BLOCK_SPACE_PERCENT);
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);

    let result = st.propose_transfer_with_policy(
        account.id(),
        &input_selector,
        &change_strategy,
        request,
        ConfirmationsPolicy::MIN,
        &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
    );

    assert_matches!(
        result,
        Err(crate::data_api::error::Error::InsufficientFunds { .. }),
        "the transparent gather should stop at the input cap rather than consuming every \
         eligible dust UTXO, so the request should fail rather than succeed with an \
         uncapped number of inputs",
    );
}

/// With a `TransparentSource::FromAddresses` transparent source, only the explicitly named transparent
/// addresses are eligible. Funds two of the account's external receivers but names only
/// one; the proposal must select solely from the named address.
pub fn propose_t2t_from_addresses<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Seed the chain with notes that do not belong to us so heights resolve.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // Enumerate two distinct external transparent receivers belonging to the account.
    let external_taddrs = st
        .wallet()
        .get_transparent_receivers(account.id(), false, true)
        .unwrap();
    let mut taddrs_by_index = external_taddrs
        .into_iter()
        .filter_map(|(addr, meta)| meta.address_index().map(|i| (i, addr)))
        .collect::<BTreeMap<_, _>>()
        .into_values();
    let addr_named = taddrs_by_index.next().expect("at least one external taddr");
    let addr_other = taddrs_by_index
        .next()
        .expect("at least two external taddrs");

    // Fund both receivers with a spendable UTXO each. The unnamed address's UTXO is
    // inserted first AND holds strictly more value than the named address's, so that if
    // the address filter were not enforced, the value-descending gather would select the
    // unnamed address's UTXO (which alone covers the payment) and stop -- making this test
    // fail. The named UTXO must be selected by policy, not merely by gather order.
    let named_value = Zatoshis::const_from_u64(100_000);
    let other_value = Zatoshis::const_from_u64(150_000);
    let height = st.wallet().chain_height().unwrap().unwrap();
    let named_outpoint = OutPoint::new([1u8; 32], 0);
    let other_outpoint = OutPoint::new([2u8; 32], 0);
    for (addr, outpoint, value) in [
        (addr_other, other_outpoint.clone(), other_value),
        (addr_named, named_outpoint.clone(), named_value),
    ] {
        let utxo = WalletTransparentOutput::from_parts(
            outpoint,
            TxOut::new(value, addr.script().into()),
            Some(height),
            Some(account.id()),
            Some(TransparentKeyScope::EXTERNAL),
            None,
        )
        .unwrap();
        st.wallet_mut()
            .put_received_transparent_utxo(&utxo)
            .unwrap();
    }

    let network = *st.network();
    let request = t2t_request(&network, Zatoshis::const_from_u64(40_000));

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);

    let proposal = st
        .propose_transfer_with_policy(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
            &SpendPolicy::default()
                .with_transparent(TransparentSpendPolicy::from_one_address(addr_named)),
        )
        .expect("transparent spend from named address must succeed");

    let step = &proposal.steps().head;
    let selected: Vec<&OutPoint> = step
        .transparent_inputs()
        .iter()
        .map(|i| i.outpoint())
        .collect();
    assert!(
        selected.contains(&&named_outpoint),
        "the named address's UTXO must be selected",
    );
    assert!(
        !selected.contains(&&other_outpoint),
        "an unnamed address's UTXO must not be selected",
    );
}

/// Verifies that the value-bounded `select_spendable_transparent_outputs` gather returns
/// only enough UTXOs to cover the requested `TargetValue`, rather than every spendable
/// output held by the account. This is the behavior that prevents wallets with large
/// numbers of small transparent UTXOs (e.g. recovered `zcashd` imports) from falling over
/// when a small transfer is requested.
pub fn value_bounded_transparent_gather<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();

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

    // Seed the chain with notes that do not belong to us so that heights resolve.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10_000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    for _ in 1..10 {
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    }
    st.scan_cached_blocks(start_height, 10);

    // Fund the account with many small dust UTXOs. Each is well above the marginal fee
    // (1_000 zats) so it's spendable, but tiny relative to the total. A naive "return
    // everything" gather would load all of these into memory; the value-bounded gather
    // should only return enough to cover the request.
    let dust_value = Zatoshis::const_from_u64(10_000);
    let n_dust = 50;
    let height = st.wallet().chain_height().unwrap().unwrap();
    for i in 0..n_dust {
        let mut hash = [0u8; 32];
        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
        let utxo = WalletTransparentOutput::from_parts(
            OutPoint::new(hash, 0),
            TxOut::new(dust_value, taddr.script().into()),
            Some(height),
            Some(account.id()),
            Some(TransparentKeyScope::EXTERNAL),
            None,
        )
        .unwrap();
        st.wallet_mut()
            .put_received_transparent_utxo(&utxo)
            .unwrap();
    }

    // Request 30_000 zats — 3x a single dust UTXO, but a small fraction of the total.
    let target = Zatoshis::const_from_u64(30_000);
    let target_height = TargetHeight::from(height + 1);

    let bound = st
        .wallet()
        .select_spendable_transparent_outputs(
            account.id(),
            target_height,
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::AllTransparentOutputs,
            None,
            TargetValue::AtLeast(target),
            usize::MAX,
            &StandardFeeRule::Zip317,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .expect("value-bounded gather should succeed");

    // The gather should return enough UTXOs to cover the target post-fee, not all 50.
    // Each UTXO is 10_000 zats. Under ZIP 317, `k` P2PKH inputs cost
    // `5_000 * max(2, k)` zats in marginal fee, so the post-fee value of the first `k`
    // gathered UTXOs is `10_000 * k - 5_000 * max(2, k)`. This first reaches the
    // 30_000-zat target at `k = 6` (60_000 - 30_000 = 30_000), one more than the 5
    // UTXOs (50_000 - 25_000 = 25_000) that would still fall short.
    assert!(
        !bound.is_empty(),
        "value-bounded gather should return at least one UTXO",
    );
    assert_eq!(
        bound.len(),
        6,
        "value-bounded gather should return exactly 6 UTXOs (10_000 zats each) to cover \
         30_000 zats net of the ZIP 317 marginal fee for 6 P2PKH inputs",
    );
    assert!(
        bound.len() < n_dust,
        "value-bounded gather should not return all {n_dust} UTXOs (returned {})",
        bound.len(),
    );
    // The summed value should meet the target.
    let total: Zatoshis = bound
        .iter()
        .map(|u| u.value())
        .fold(Zatoshis::ZERO, |acc, v| (acc + v).unwrap());
    assert!(
        total >= target,
        "value-bounded gather should cover the target (got {}, want >= {})",
        u64::from(total),
        u64::from(target),
    );

    // AllFunds should return all eligible UTXOs.
    let all = st
        .wallet()
        .select_spendable_transparent_outputs(
            account.id(),
            target_height,
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::AllTransparentOutputs,
            None,
            TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
            usize::MAX,
            &StandardFeeRule::Zip317,
            LockFilter::Policy(&LockedInputPolicy::Exclude),
        )
        .expect("AllFunds gather should succeed");
    assert_eq!(all.len(), n_dust);
}

/// Tests that [`WalletWrite::reserve_next_n_internal_addresses`] reserves sequential
/// internal-scope (change) addresses, that reservation observes the internal-scope gap
/// limit, and that internal-scope reservations are accounted independently of
/// ephemeral-scope reservations.
///
/// This test expects the data store to be configured with the default gap limits, under
/// which the internal-scope gap limit is 5.
///
/// The `is_reached_gap_limit` predicate must return `true` if and only if the provided
/// error is the backend's exact "reached gap limit" error variant, the scope reported by
/// that error is [`TransparentKeyScope::INTERNAL`], and the address index reported by that
/// error equals the provided expected index. It must not match any other error. (A
/// predicate is used because this test cannot name the backend's concrete error type
/// without inverting the crate dependency.)
pub fn reserve_next_n_internal_addresses_gap_limit<DSF>(
    dsf: DSF,
    cache: impl TestCache,
    is_reached_gap_limit: impl Fn(
        &<DSF::DataStore as crate::data_api::WalletRead>::Error,
        DSF::AccountId,
        u32,
    ) -> bool,
) where
    DSF: DataStoreFactory,
{
    let mut st = TestBuilder::new()
        .with_data_store_factory(dsf)
        .with_block_cache(cache)
        .with_account_from_sapling_activation(BlockHash([0; 32]))
        .build();
    let account_id = st.test_account().cloned().unwrap().id();

    // Seed the chain so that a chain height is known; address reservation records the
    // exposure height of each reserved address.
    let not_our_key = ExtendedSpendingKey::master(&[]).to_diversifiable_full_viewing_key();
    let not_our_value = Zatoshis::const_from_u64(10000);
    let (start_height, _, _) =
        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
    st.scan_cached_blocks(start_height, 1);

    // Reserving internal addresses yields distinct, sequentially-indexed addresses derived
    // under the internal (change) key scope.
    let reserved = st
        .wallet_mut()
        .reserve_next_n_internal_addresses(account_id, 3)
        .unwrap();
    assert_eq!(reserved.len(), 3);
    for (i, (_, meta)) in reserved.iter().enumerate() {
        assert_eq!(meta.scope(), Some(TransparentKeyScope::INTERNAL));
        assert_eq!(
            meta.address_index(),
            Some(NonHardenedChildIndex::const_from_index(
                u32::try_from(i).unwrap()
            )),
        );
    }
    // None of the reserved addresses have received funds, so the gap cannot advance: with
    // the default internal-scope gap limit of 5, only two more addresses may be reserved.
    // Reservation continues at the next sequential indices, so the returned addresses are
    // distinct from those of the first batch.
    let more = st
        .wallet_mut()
        .reserve_next_n_internal_addresses(account_id, 2)
        .unwrap();
    assert_eq!(more.len(), 2);
    for (i, (_, meta)) in more.iter().enumerate() {
        assert_eq!(meta.scope(), Some(TransparentKeyScope::INTERNAL));
        assert_eq!(
            meta.address_index(),
            Some(NonHardenedChildIndex::const_from_index(
                u32::try_from(reserved.len() + i).unwrap()
            )),
        );
    }
    let unique_addrs = reserved
        .iter()
        .chain(more.iter())
        .map(|(a, _)| *a)
        .collect::<HashSet<_>>();
    assert_eq!(unique_addrs.len(), reserved.len() + more.len());

    assert_matches!(
        st.wallet_mut().reserve_next_n_internal_addresses(account_id, 1),
        Err(e) if is_reached_gap_limit(&e, account_id, 5)
    );

    // Internal-scope reservations must not consume ephemeral-scope gap space.
    let ephemeral = st
        .wallet_mut()
        .reserve_next_n_ephemeral_addresses(account_id, 1)
        .unwrap();
    assert_eq!(ephemeral[0].1.scope(), Some(TransparentKeyScope::EPHEMERAL),);
    assert_eq!(
        ephemeral[0].1.address_index(),
        Some(NonHardenedChildIndex::const_from_index(0)),
    );
}

/// Tests the full lifecycle of a t->t transfer with transparent change: a change strategy
/// configured with [`TransparentChangePolicy::TransparentChangeAllowed`] must propose a
/// non-ephemeral transparent change output, and transaction creation must send that change
/// to a previously-unexposed internal-scope (change) transparent address of the spending
/// account, where it is recorded as received and becomes spendable once mined.
///
/// [`TransparentChangePolicy::TransparentChangeAllowed`]: crate::fees::TransparentChangePolicy::TransparentChangeAllowed
pub fn propose_t2t_with_transparent_change<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    let utxo_value = Zatoshis::const_from_u64(100_000);
    let transfer_amount = Zatoshis::const_from_u64(40_000);
    let (mut st, account, outpoint) = setup_transparent_only_account(dsf, cache, utxo_value);

    let network = *st.network();
    let request = t2t_request(&network, transfer_amount);

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling)
            .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);

    let proposal = st
        .propose_transfer_with_policy(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
            &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
        )
        .expect("t->t proposal with transparent change must succeed");

    // A t->t transfer with non-ephemeral transparent change is a single step.
    assert_eq!(proposal.steps().len(), 1);
    let step = &proposal.steps().head;
    assert_eq!(step.transparent_inputs().len(), 1);
    assert_eq!(step.transparent_inputs()[0].outpoint(), &outpoint);
    assert!(step.shielded_inputs().is_none());

    // Under ZIP 317, one P2PKH input and two P2PKH outputs (the payment plus the change
    // output) require `5_000 * max(1, 2) = 10_000` zats in fees.
    let expected_fee = Zatoshis::const_from_u64(10_000);
    let expected_change = ((utxo_value - transfer_amount).unwrap() - expected_fee).unwrap();
    assert_eq!(step.balance().fee_required(), expected_fee);
    assert_eq!(
        step.balance().proposed_change(),
        [ChangeValue::transparent(expected_change)],
    );
    assert!(!step.balance().proposed_change()[0].is_ephemeral());

    // A proposal containing a transparent change output must survive a serialization
    // round trip.
    super::check_proposal_serialization_roundtrip(&network, st.wallet(), &proposal);

    // Creating the transaction should reserve an internal-scope address for the change.
    let txids = st
        .create_proposed_transactions::<Infallible, _, Infallible, _>(
            account.usk(),
            OvkPolicy::Sender,
            &proposal,
        )
        .expect("transaction creation must succeed");
    assert_eq!(txids.len(), 1);
    let txid = txids.head;

    // The transaction must be fully transparent, with exactly the payment and change outputs.
    let tx = st
        .wallet()
        .get_transaction(txid)
        .unwrap()
        .expect("the created transaction is retrievable");
    assert!(tx.sapling_bundle().is_none());
    #[cfg(feature = "orchard")]
    assert!(tx.orchard_bundle().is_none());
    let bundle = tx
        .transparent_bundle()
        .expect("the transaction has a transparent bundle");
    assert_eq!(bundle.vin.len(), 1);
    assert_eq!(bundle.vout.len(), 2);

    // Identify the change output as the output that does not pay the external recipient.
    let payment_recipient = TransparentAddress::PublicKeyHash([7u8; 20]);
    let change_outputs: Vec<_> = bundle
        .vout
        .iter()
        .filter(|out| out.recipient_address() != Some(payment_recipient))
        .collect();
    assert_eq!(change_outputs.len(), 1);
    let change_output = change_outputs[0];
    assert_eq!(change_output.value(), expected_change);
    let change_address = change_output
        .recipient_address()
        .expect("the change output pays a standard P2PKH address");

    // The change address must be an internal-scope (change) address of the spending account,
    // exposed at the current chain height by having been reserved for change.
    let receivers = st
        .wallet()
        .get_transparent_receivers(account.id(), true, false)
        .unwrap();
    let change_meta = receivers
        .get(&change_address)
        .expect("the change address belongs to the spending account");
    assert_eq!(change_meta.scope(), Some(TransparentKeyScope::INTERNAL));
    let cur_height = st.wallet().chain_height().unwrap().unwrap();
    assert_matches!(
        change_meta.exposure(),
        Exposure::Exposed { at_height, .. } if at_height == cur_height
    );

    // Mine the transaction; the change output should then be spendable at the change address.
    let (h, _) = st.generate_next_block_including(txid);
    st.scan_cached_blocks(h, 1);

    let mut expected_balance = Balance::ZERO;
    expected_balance
        .add_spendable_value(expected_change)
        .unwrap();
    check_balance::<DSF>(
        &st,
        &account,
        &change_address,
        ConfirmationsPolicy::MIN,
        &expected_balance,
    );
}

/// Tests that when a fully-transparent transaction balances exactly (input value equals
/// payments plus the minimum fee), no transparent change output is produced even when the
/// change strategy is configured with [`TransparentChangePolicy::TransparentChangeAllowed`].
///
/// [`TransparentChangePolicy::TransparentChangeAllowed`]: crate::fees::TransparentChangePolicy::TransparentChangeAllowed
pub fn propose_t2t_transparent_change_exact_match<DSF>(dsf: DSF, cache: impl TestCache)
where
    DSF: DataStoreFactory,
{
    // Under ZIP 317, one P2PKH input and one P2PKH output require the minimum fee of
    // 10_000 zats, so a 50_000-zat UTXO exactly covers a 40_000-zat payment.
    let utxo_value = Zatoshis::const_from_u64(50_000);
    let transfer_amount = Zatoshis::const_from_u64(40_000);
    let (mut st, account, _outpoint) = setup_transparent_only_account(dsf, cache, utxo_value);

    let network = *st.network();
    let request = t2t_request(&network, transfer_amount);

    let input_selector = GreedyInputSelector::new();
    let change_strategy =
        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling)
            .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);

    let proposal = st
        .propose_transfer_with_policy(
            account.id(),
            &input_selector,
            &change_strategy,
            request,
            ConfirmationsPolicy::MIN,
            &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
        )
        .expect("exactly-balanced t->t proposal must succeed");

    assert_eq!(proposal.steps().len(), 1);
    let step = &proposal.steps().head;
    assert_eq!(
        step.balance().fee_required(),
        Zatoshis::const_from_u64(10_000),
    );
    assert_eq!(step.balance().proposed_change(), []);
}