zakura-client-backend 0.1.0-rc2

APIs for creating shielded Zcash light clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
//! # Utilities for Zcash wallet construction
//!
//! This module defines a set of APIs for wallet data persistence, and provides a suite of methods
//! based upon these APIs that can be used to implement a fully functional Zcash wallet. At
//! present, the interfaces provided here are built primarily around the use of a source of
//! [`CompactBlock`] data such as the Zcash Light Client Protocol as defined in
//! [ZIP 307](https://zips.z.cash/zip-0307) but they may be generalized to full-block use cases in
//! the future.
//!
//! ## Important Concepts
//!
//! There are several important operations that a Zcash wallet must perform that distinguish Zcash
//! wallet design from wallets for other cryptocurrencies.
//!
//! * Viewing Keys: Wallets based upon this module are built around the capabilities of Zcash
//!   [`UnifiedFullViewingKey`]s; the wallet backend provides no facilities for the storage
//!   of spending keys, and spending keys must be provided by the caller (or delegated to external
//!   devices via the provided [`pczt`] functionality) in order to perform transaction creation
//!   operations.
//! * Blockchain Scanning: A Zcash wallet must download and trial-decrypt each transaction on the
//!   Zcash blockchain using one or more Viewing Keys in order to find new shielded transaction
//!   outputs (generally termed "notes") belonging to the wallet. The primary entrypoint for this
//!   functionality is the [`scan_cached_blocks`] method. See the [`chain`] module for additional
//!   details.
//! * Witness Updates: In order to spend a shielded note, the wallet must be able to compute the
//!   Merkle path to that note in the global note commitment tree. When [`scan_cached_blocks`] is
//!   used to process a range of blocks, the note commitment tree is updated with the note
//!   commitments for the blocks in that range.
//! * Transaction Construction: The [`wallet`] module provides functions for creating Zcash
//!   transactions that spend funds belonging to the wallet. Input selection for transaction
//!   construction is performed automatically. When spending funds received at transparent
//!   addresses, the caller is required to explicitly specify the set of addresses from which to
//!   spend funds, in order to prevent inadvertent commingling of funds received at different
//!   addresses; allowing such commingling would enable chain observers to identify those
//!   addresses as belonging to the same user.
//!
//! ## Core Traits
//!
//! The utility functions described above depend upon four important traits defined in this
//! module, which between them encompass the data storage requirements of a light wallet.
//! The relevant traits are [`InputSource`], [`WalletRead`], [`WalletWrite`], and
//! [`WalletCommitmentTrees`]. A complete implementation of the data storage layer for a wallet
//! will include an implementation of all four of these traits. See the [`zcash_client_sqlite`]
//! crate for a complete example of the implementation of these traits.
//!
//! ## Accounts
//!
//! The operation of the [`InputSource`], [`WalletRead`] and [`WalletWrite`] traits is built around
//! the concept of a wallet having one or more accounts, with a unique `AccountId` for each
//! account.
//!
//! An account identifier corresponds to at most a single [`UnifiedSpendingKey`]'s worth of spend
//! authority, with the received and spent notes of that account tracked via the corresponding
//! [`UnifiedFullViewingKey`]. Both received notes and change spendable by that spending authority
//! (both the external and internal parts of that key, as defined by
//! [ZIP 316](https://zips.z.cash/zip-0316)) will be interpreted as belonging to that account.
//!
//! [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
//! [`scan_cached_blocks`]: crate::data_api::chain::scan_cached_blocks
//! [`zcash_client_sqlite`]: https://docs.rs/zcash_client_sqlite
//! [`TransactionRequest`]: crate::zip321::TransactionRequest
//! [`propose_shielding`]: crate::data_api::wallet::propose_shielding
//! [`pczt`]: https://docs.rs/pczt

use nonempty::NonEmpty;
use secrecy::SecretVec;
use std::{
    collections::{HashMap, HashSet},
    fmt::{self, Debug},
    hash::Hash,
    io,
    num::{NonZeroU32, TryFromIntError},
};

use incrementalmerkletree::{Retention, frontier::Frontier};
use shardtree::{ShardTree, error::ShardTreeError, store::ShardStore};

use zcash_keys::{
    address::{Address, UnifiedAddress},
    keys::{
        UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedIncomingViewingKey, UnifiedSpendingKey,
    },
};
use zcash_primitives::{block::BlockHash, transaction::Transaction};
use zcash_protocol::{
    PoolType, ShieldedPool, TxId,
    consensus::{self, BlockHeight, TxIndex},
    memo::{Memo, MemoBytes},
    value::{BalanceError, Zatoshis},
};
use zip32::{DiversifierIndex, fingerprint::SeedFingerprint};

use self::{
    chain::{ChainState, CommitmentTreeRoot},
    scanning::{ScanPriority, ScanRange},
};
use crate::{
    data_api::{
        error::RewindError,
        wallet::{ConfirmationsPolicy, TargetHeight, input_selection::LockFilter},
    },
    decrypt::DecryptedOutput,
    proto::service::TreeState,
    wallet::{Note, NoteId, ReceivedNote, Recipient, WalletTransparentOutput, WalletTx},
};

#[cfg(feature = "transparent-inputs")]
use {
    crate::{fees::StandardFeeRule, wallet::TransparentAddressMetadata},
    getset::{CopyGetters, Getters},
    std::time::SystemTime,
    transparent::{address::TransparentAddress, bundle::OutPoint, keys::TransparentKeyScope},
};

#[cfg(all(
    feature = "transparent-inputs",
    any(test, feature = "test-dependencies")
))]
use {std::ops::Range, transparent::keys::NonHardenedChildIndex};

#[cfg(feature = "zcashd-compat")]
use zcash_keys::keys::zcashd;

#[cfg(feature = "test-dependencies")]
use ambassador::delegatable_trait;

#[cfg(any(test, feature = "test-dependencies"))]
use zcash_protocol::consensus::NetworkUpgrade;

pub mod anchor_retention;
pub mod chain;
pub mod defaults;
pub mod error;
pub mod ll;
pub mod locking;
pub use locking::OutputLockStore;
#[cfg(feature = "test-dependencies")]
pub use locking::ambassador_impl_OutputLockStore;
pub mod scanning;
pub mod wallet;
#[cfg(feature = "orchard")]
pub mod zip318;

#[cfg(any(test, feature = "test-dependencies"))]
pub mod testing;

/// The origin of a transparent address within a wallet.
#[cfg(feature = "transparent-inputs")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransparentKeyOrigin {
    /// The address was imported standalone (no HD derivation scope).
    Imported,
    /// The address was derived from the account's HD key tree.
    Derived { scope: TransparentKeyScope },
}

/// A mapping from transparent addresses to their key origin and balance.
#[cfg(feature = "transparent-inputs")]
pub type TransparentBalances = HashMap<TransparentAddress, (TransparentKeyOrigin, Balance)>;

/// The height of subtree roots in the Sapling note commitment tree.
///
/// This conforms to the structure of subtree data returned by
/// `lightwalletd` when using the `GetSubtreeRoots` GRPC call.
pub const SAPLING_SHARD_HEIGHT: u8 = sapling::NOTE_COMMITMENT_TREE_DEPTH / 2;

/// The height of subtree roots in the Orchard note commitment tree.
///
/// This conforms to the structure of subtree data returned by
/// `lightwalletd` when using the `GetSubtreeRoots` GRPC call.
#[cfg(feature = "orchard")]
pub const ORCHARD_SHARD_HEIGHT: u8 = { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 } / 2;

/// The height of subtree roots in the Ironwood note commitment tree.
///
/// This conforms to the structure of subtree data returned by
/// `lightwalletd` when using the `GetSubtreeRoots` GRPC call.
#[cfg(feature = "orchard")]
pub const IRONWOOD_SHARD_HEIGHT: u8 = { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 } / 2;

/// An enumeration of constraints that can be applied when querying for nullifiers for notes
/// belonging to the wallet.
pub enum NullifierQuery {
    Unspent,
    All,
}

/// An intent of representing spendable value to reach a certain targeted
/// amount.
///
/// `AtLeast(Zatoshis)` refers to the amount of `Zatoshis` that can cover
/// at minimum the given zatoshis that is conformed by the sum of spendable notes.
///
///
/// Discussion: why not just use ``Zatoshis``?
///
/// the `Zatoshis` value isn't enough to explain intent when seeking to match a
/// given a given amount. Is the value expressed in `Zatoshis` the ceiling value
/// or the minimum value of a given spend intent? How would you express that the
/// value spend intent is "as much as possible" without knowing the value upfront?
#[derive(Debug, Clone, Copy)]
pub enum TargetValue {
    AtLeast(Zatoshis),
    AllFunds(MaxSpendMode),
}

/// Specifies how an TargetValue::AllFunds should be evaluated
#[derive(Debug, Clone, Copy)]
pub enum MaxSpendMode {
    /// `MaxSpendable` will target to spend all _currently_ spendable funds where it
    /// could be the case that the wallet has received other funds that are not
    /// confirmed and therefore not spendable yet and the caller evaluates that as
    /// an acceptable scenario.
    MaxSpendable,
    /// `Everything` will target to spend **all funds** and will fail if there are
    /// unspendable funds in the wallet or if the wallet is not yet synced.
    Everything,
}
/// Balance information for a value within a single pool in an account.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Balance {
    spendable_value: Zatoshis,
    locked_value: Zatoshis,
    change_pending_confirmation: Zatoshis,
    value_pending_spendability: Zatoshis,
    uneconomic_value: Zatoshis,
}

impl Balance {
    /// The [`Balance`] value having zero values for all its fields.
    pub const ZERO: Self = Self {
        spendable_value: Zatoshis::ZERO,
        locked_value: Zatoshis::ZERO,
        change_pending_confirmation: Zatoshis::ZERO,
        value_pending_spendability: Zatoshis::ZERO,
        uneconomic_value: Zatoshis::ZERO,
    };

    fn check_total_adding(&self, value: Zatoshis) -> Result<Zatoshis, BalanceError> {
        (self.spendable_value
            + self.locked_value
            + self.change_pending_confirmation
            + self.value_pending_spendability
            + value)
            .ok_or(BalanceError::Overflow)
    }

    /// Returns the value in the account that may currently be spent; it is possible to compute
    /// witnesses for all the notes that comprise this value, and all of this value is confirmed to
    /// the required confirmation depth.
    pub fn spendable_value(&self) -> Zatoshis {
        self.spendable_value
    }

    /// Returns the value in the account that is currently "locked".
    ///
    /// The outputs that comprise this balance are seen by the wallet as being committed to be
    /// spent by a transaction proposal or PCZT.
    pub fn locked_value(&self) -> Zatoshis {
        self.locked_value
    }

    /// Adds the specified value to the spendable total, checking for overflow.
    pub fn add_spendable_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
        self.check_total_adding(value)?;
        self.spendable_value = (self.spendable_value + value).unwrap();
        Ok(())
    }

    /// Adds the specified value to the locked total, checking for overflow.
    pub fn add_locked_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
        self.check_total_adding(value)?;
        self.locked_value = (self.locked_value + value).unwrap();
        Ok(())
    }

    /// Returns the value in the account of shielded change notes that do not yet have sufficient
    /// confirmations to be spendable.
    pub fn change_pending_confirmation(&self) -> Zatoshis {
        self.change_pending_confirmation
    }

    /// Adds the specified value to the pending change total, checking for overflow.
    pub fn add_pending_change_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
        self.check_total_adding(value)?;
        self.change_pending_confirmation = (self.change_pending_confirmation + value).unwrap();
        Ok(())
    }

    /// Returns the value in the account of all remaining received notes that either do not have
    /// sufficient confirmations to be spendable, or for which witnesses cannot yet be constructed
    /// without additional scanning.
    pub fn value_pending_spendability(&self) -> Zatoshis {
        self.value_pending_spendability
    }

    /// Adds the specified value to the pending spendable total, checking for overflow.
    pub fn add_pending_spendable_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
        self.check_total_adding(value)?;
        self.value_pending_spendability = (self.value_pending_spendability + value).unwrap();
        Ok(())
    }

    /// Returns the value in the account of notes that have value less than or equal to the marginal
    /// fee, and consequently cannot be spent except as a grace input.
    pub fn uneconomic_value(&self) -> Zatoshis {
        self.uneconomic_value
    }

    /// Adds the specified value to the uneconomic value total, checking for overflow.
    pub fn add_uneconomic_value(&mut self, value: Zatoshis) -> Result<(), BalanceError> {
        self.uneconomic_value = (self.uneconomic_value + value).ok_or(BalanceError::Overflow)?;
        Ok(())
    }

    /// Returns the total value of funds represented by this [`Balance`].
    pub fn total(&self) -> Zatoshis {
        (self.spendable_value
            + self.locked_value
            + self.change_pending_confirmation
            + self.value_pending_spendability)
            .expect("Balance cannot overflow MAX_MONEY")
    }
}

impl core::ops::Add<Balance> for Balance {
    type Output = Result<Balance, BalanceError>;

    fn add(self, rhs: Balance) -> Self::Output {
        let result = Balance {
            spendable_value: (self.spendable_value + rhs.spendable_value)
                .ok_or(BalanceError::Overflow)?,
            locked_value: (self.locked_value + rhs.locked_value).ok_or(BalanceError::Overflow)?,
            change_pending_confirmation: (self.change_pending_confirmation
                + rhs.change_pending_confirmation)
                .ok_or(BalanceError::Overflow)?,
            value_pending_spendability: (self.value_pending_spendability
                + rhs.value_pending_spendability)
                .ok_or(BalanceError::Overflow)?,
            uneconomic_value: (self.uneconomic_value + rhs.uneconomic_value)
                .ok_or(BalanceError::Overflow)?,
        };

        result.check_total_adding(Zatoshis::ZERO)?;

        Ok(result)
    }
}

/// Balance information for a single account. The sum of this struct's fields is the total balance
/// of the wallet.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AccountBalance {
    sapling_balance: Balance,
    orchard_balance: Balance,
    ironwood_balance: Balance,
    unshielded_regular_balance: Balance,
    unshielded_coinbase_balance: Balance,
}

impl AccountBalance {
    /// The [`Balance`] value having zero values for all its fields.
    pub const ZERO: Self = Self {
        sapling_balance: Balance::ZERO,
        orchard_balance: Balance::ZERO,
        ironwood_balance: Balance::ZERO,
        unshielded_regular_balance: Balance::ZERO,
        unshielded_coinbase_balance: Balance::ZERO,
    };

    fn check_total(&self) -> Result<Zatoshis, BalanceError> {
        (self.sapling_balance.total()
            + self.orchard_balance.total()
            + self.ironwood_balance.total()
            + self.unshielded_regular_balance.total()
            + self.unshielded_coinbase_balance.total())
        .ok_or(BalanceError::Overflow)
    }

    /// Returns the [`Balance`] of Sapling funds in the account.
    pub fn sapling_balance(&self) -> &Balance {
        &self.sapling_balance
    }

    /// Provides a mutable reference to the [`Balance`] of Sapling funds in the account
    /// to the specified callback, checking invariants after the callback's action has been
    /// evaluated.
    pub fn with_sapling_balance_mut<A, E: From<BalanceError>>(
        &mut self,
        f: impl FnOnce(&mut Balance) -> Result<A, E>,
    ) -> Result<A, E> {
        let result = f(&mut self.sapling_balance)?;
        self.check_total()?;
        Ok(result)
    }

    /// Returns the [`Balance`] of Orchard funds in the account.
    pub fn orchard_balance(&self) -> &Balance {
        &self.orchard_balance
    }

    /// Provides a mutable reference to the [`Balance`] of Orchard funds in the account
    /// to the specified callback, checking invariants after the callback's action has been
    /// evaluated.
    pub fn with_orchard_balance_mut<A, E: From<BalanceError>>(
        &mut self,
        f: impl FnOnce(&mut Balance) -> Result<A, E>,
    ) -> Result<A, E> {
        let result = f(&mut self.orchard_balance)?;
        self.check_total()?;
        Ok(result)
    }

    /// Returns the [`Balance`] of Ironwood funds in the account.
    pub fn ironwood_balance(&self) -> &Balance {
        &self.ironwood_balance
    }

    /// Provides a mutable reference to the [`Balance`] of Ironwood funds in the account
    /// to the specified callback, checking invariants after the callback's action has been
    /// evaluated.
    pub fn with_ironwood_balance_mut<A, E: From<BalanceError>>(
        &mut self,
        f: impl FnOnce(&mut Balance) -> Result<A, E>,
    ) -> Result<A, E> {
        let result = f(&mut self.ironwood_balance)?;
        self.check_total()?;
        Ok(result)
    }

    /// Returns the total value of unspent transparent transaction outputs belonging to the wallet.
    #[deprecated(
        note = "this function is deprecated. Please use [`AccountBalance::unshielded_regular_balance`] and [`AccountBalance::unshielded_coinbase_balance`] instead."
    )]
    pub fn unshielded(&self) -> Zatoshis {
        (self.unshielded_regular_balance.total() + self.unshielded_coinbase_balance.total())
            .expect("Account balance cannot overflow MAX_MONEY")
    }

    /// Returns the combined [`Balance`] of unshielded funds in the account, computed as the sum
    /// of the [`unshielded_regular_balance`] and the [`unshielded_coinbase_balance`].
    ///
    /// The [`spendable_value`] field of the returned [`Balance`] contains funds that may be spent
    /// in a shielding transaction: transparent funds that satisfy the wallet's confirmation
    /// policy, including coinbase funds that have reached maturity. The
    /// [`value_pending_spendability`] field contains transparent funds that are not yet
    /// spendable: funds that do not yet have the number of confirmations required by the
    /// wallet's confirmation policy, and coinbase funds that have not yet reached maturity. The
    /// [`change_pending_confirmation`] field is currently always zero, because this crate does
    /// not yet distinguish transparent change from other transparent value awaiting
    /// confirmation.
    ///
    /// [`unshielded_regular_balance`]: AccountBalance::unshielded_regular_balance
    /// [`unshielded_coinbase_balance`]: AccountBalance::unshielded_coinbase_balance
    /// [`spendable_value`]: Balance::spendable_value
    /// [`change_pending_confirmation`]: Balance::change_pending_confirmation
    /// [`value_pending_spendability`]: Balance::value_pending_spendability
    pub fn unshielded_balance(&self) -> Balance {
        (self.unshielded_regular_balance + self.unshielded_coinbase_balance)
            .expect("Account balance cannot overflow MAX_MONEY")
    }

    /// Returns the [`Balance`] of regular (non-coinbase) transparent funds in the account.
    ///
    /// Transparent outputs whose containing transaction's index within its block is unknown are
    /// classified as regular (non-coinbase) funds, consistent with the treatment described for
    /// `CoinbaseFilter`.
    pub fn unshielded_regular_balance(&self) -> &Balance {
        &self.unshielded_regular_balance
    }

    /// Provides a mutable reference to the [`Balance`] of regular (non-coinbase) transparent
    /// funds in the account to the specified callback, checking invariants after the callback's
    /// action has been evaluated.
    pub fn with_unshielded_regular_balance_mut<A, E: From<BalanceError>>(
        &mut self,
        f: impl FnOnce(&mut Balance) -> Result<A, E>,
    ) -> Result<A, E> {
        let result = f(&mut self.unshielded_regular_balance)?;
        self.check_total()?;
        Ok(result)
    }

    /// Returns the [`Balance`] of funds in coinbase transparent outputs belonging to the
    /// account.
    ///
    /// Coinbase outputs may only be spent by shielding them, and only once they have reached
    /// coinbase maturity; immature coinbase funds are reported in the
    /// [`value_pending_spendability`] field of the returned [`Balance`]. Outputs whose
    /// containing transaction's index within its block is unknown are conservatively classified
    /// as regular (non-coinbase) funds and do not contribute to this balance; see
    /// `CoinbaseFilter`.
    ///
    /// [`value_pending_spendability`]: Balance::value_pending_spendability
    pub fn unshielded_coinbase_balance(&self) -> &Balance {
        &self.unshielded_coinbase_balance
    }

    /// Provides a mutable reference to the [`Balance`] of transparent coinbase funds in the
    /// account to the specified callback, checking invariants after the callback's action has
    /// been evaluated.
    pub fn with_unshielded_coinbase_balance_mut<A, E: From<BalanceError>>(
        &mut self,
        f: impl FnOnce(&mut Balance) -> Result<A, E>,
    ) -> Result<A, E> {
        let result = f(&mut self.unshielded_coinbase_balance)?;
        self.check_total()?;
        Ok(result)
    }

    /// Returns the total value of economically relevant notes and UTXOs belonging to the account.
    pub fn total(&self) -> Zatoshis {
        (self.sapling_balance.total()
            + self.orchard_balance.total()
            + self.ironwood_balance.total()
            + self.unshielded_regular_balance.total()
            + self.unshielded_coinbase_balance.total())
        .expect("Account balance cannot overflow MAX_MONEY")
    }

    /// Returns the total value of shielded (Sapling, Orchard, and Ironwood) funds that may
    /// immediately be spent.
    pub fn spendable_value(&self) -> Zatoshis {
        (self.sapling_balance.spendable_value
            + self.orchard_balance.spendable_value
            + self.ironwood_balance.spendable_value)
            .expect("Account balance cannot overflow MAX_MONEY")
    }

    /// Returns the total value of notes and UTXOs that are locked, having been committed to
    /// an in-flight transaction proposal or PCZT.
    pub fn locked_value(&self) -> Zatoshis {
        (self.sapling_balance.locked_value()
            + self.orchard_balance.locked_value()
            + self.ironwood_balance.locked_value()
            + self.unshielded_regular_balance.locked_value()
            + self.unshielded_coinbase_balance.locked_value())
        .expect("Account balance cannot overflow MAX_MONEY")
    }

    /// Returns the total value of change and/or shielding transaction outputs that are awaiting
    /// sufficient confirmations for spendability.
    pub fn change_pending_confirmation(&self) -> Zatoshis {
        (self.sapling_balance.change_pending_confirmation
            + self.orchard_balance.change_pending_confirmation
            + self.ironwood_balance.change_pending_confirmation)
            .expect("Account balance cannot overflow MAX_MONEY")
    }

    /// Returns the value of shielded funds that are not yet spendable because additional scanning
    /// is required before it will be possible to derive witnesses for the associated notes.
    pub fn value_pending_spendability(&self) -> Zatoshis {
        (self.sapling_balance.value_pending_spendability
            + self.orchard_balance.value_pending_spendability
            + self.ironwood_balance.value_pending_spendability)
            .expect("Account balance cannot overflow MAX_MONEY")
    }

    /// Returns the value in the account of notes and transparent UTXOs that have value less than
    /// the marginal fee, and consequently cannot be spent except as a grace input.
    pub fn uneconomic_value(&self) -> Zatoshis {
        (self.sapling_balance.uneconomic_value
            + self.orchard_balance.uneconomic_value
            + self.ironwood_balance.uneconomic_value
            + self.unshielded_regular_balance.uneconomic_value
            + self.unshielded_coinbase_balance.uneconomic_value)
            .expect("Account balance cannot overflow MAX_MONEY")
    }
}

/// Source metadata for a ZIP 32-derived key.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Zip32Derivation {
    seed_fingerprint: SeedFingerprint,
    account_index: zip32::AccountId,
    #[cfg(feature = "zcashd-compat")]
    legacy_address_index: Option<zcashd::LegacyAddressIndex>,
}

impl Zip32Derivation {
    /// Constructs new derivation metadata from its constituent parts.
    pub fn new(
        seed_fingerprint: SeedFingerprint,
        account_index: zip32::AccountId,
        #[cfg(feature = "zcashd-compat")] legacy_address_index: Option<zcashd::LegacyAddressIndex>,
    ) -> Self {
        Self {
            seed_fingerprint,
            account_index,
            #[cfg(feature = "zcashd-compat")]
            legacy_address_index,
        }
    }

    /// Returns the seed fingerprint.
    pub fn seed_fingerprint(&self) -> &SeedFingerprint {
        &self.seed_fingerprint
    }

    /// Returns the account-level index in the ZIP 32 derivation path.
    pub fn account_index(&self) -> zip32::AccountId {
        self.account_index
    }

    #[cfg(feature = "zcashd-compat")]
    pub fn legacy_address_index(&self) -> Option<zcashd::LegacyAddressIndex> {
        self.legacy_address_index
    }
}

/// An enumeration used to control what information is tracked by the wallet for
/// notes received by a given account.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum AccountPurpose {
    /// For spending accounts, the wallet will track information needed to spend
    /// received notes.
    Spending { derivation: Option<Zip32Derivation> },
    /// For view-only accounts, the wallet will not track spend information.
    ViewOnly,
}

/// The kinds of accounts supported by `zcash_client_backend`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum AccountSource {
    /// An account derived from a known seed.
    Derived {
        derivation: Zip32Derivation,
        key_source: Option<String>,
    },

    /// An account imported from a viewing key.
    Imported {
        purpose: AccountPurpose,
        key_source: Option<String>,
    },
}

impl AccountSource {
    /// Returns the key derivation metadata for the account source, if any is available.
    pub fn key_derivation(&self) -> Option<&Zip32Derivation> {
        match self {
            AccountSource::Derived { derivation, .. } => Some(derivation),
            AccountSource::Imported {
                purpose: AccountPurpose::Spending { derivation },
                ..
            } => derivation.as_ref(),
            _ => None,
        }
    }

    /// Returns the application-level key source identifier.
    pub fn key_source(&self) -> Option<&str> {
        match self {
            AccountSource::Derived { key_source, .. } => key_source.as_ref().map(|s| s.as_str()),
            AccountSource::Imported { key_source, .. } => key_source.as_ref().map(|s| s.as_str()),
        }
    }
}

/// A set of capabilities that a client account must provide.
///
/// An account represents a distinct set of viewing keys within the wallet; the keys for an account
/// must not be shared with any other account in the wallet, and an application managing wallet
/// accounts must ensure that it either maintains spending keys that can be used for spending _all_
/// outputs detectable by the viewing keys of the account, or for none of them (i.e. the account is
/// view-only.)
///
/// Balance information is available for any full-viewing-key based account; for an
/// incoming-viewing-key only account balance cannot be determined because spends cannot be
/// detected, and so balance-related APIs and APIs that rely upon spentness checks MUST be
/// implemented to return errors if invoked for an IVK-only account.
///
/// For spending accounts in implementations that support the `transparent-key-import` feature,
/// care must be taken to ensure that spending keys corresponding to every imported transparent
/// address in an account are maintained by the application.
pub trait Account {
    type AccountId: Copy;

    /// Returns the unique identifier for the account.
    fn id(&self) -> Self::AccountId;

    /// Returns the human-readable name for the account, if any has been configured.
    fn name(&self) -> Option<&str>;

    /// Returns the birthday height for the account.
    fn birthday_height(&self) -> BlockHeight;

    /// Returns whether this account is derived or imported, and the derivation parameters
    /// if applicable.
    fn source(&self) -> &AccountSource;

    /// Returns whether the account is a spending account or a view-only account.
    fn purpose(&self) -> AccountPurpose {
        match self.source() {
            AccountSource::Derived { derivation, .. } => AccountPurpose::Spending {
                derivation: Some(derivation.clone()),
            },
            AccountSource::Imported { purpose, .. } => purpose.clone(),
        }
    }

    /// Returns the UFVK that the wallet backend has stored for the account, if any.
    ///
    /// Accounts for which this returns `None` cannot be used in wallet contexts, because
    /// they are unable to maintain an accurate balance.
    fn ufvk(&self) -> Option<&UnifiedFullViewingKey>;

    /// Returns the UIVK that the wallet backend has stored for the account.
    ///
    /// All accounts are required to have at least an incoming viewing key. This gives no
    /// indication about whether an account can be used in a wallet context; for that, use
    /// [`Account::ufvk`].
    fn uivk(&self) -> UnifiedIncomingViewingKey;
}

#[cfg(any(test, feature = "test-dependencies"))]
impl<A: Copy> Account for (A, UnifiedFullViewingKey, BlockHeight) {
    type AccountId = A;

    fn id(&self) -> A {
        self.0
    }

    fn name(&self) -> Option<&str> {
        None
    }

    fn birthday_height(&self) -> BlockHeight {
        self.2
    }

    fn source(&self) -> &AccountSource {
        &AccountSource::Imported {
            purpose: AccountPurpose::ViewOnly,
            key_source: None,
        }
    }

    fn ufvk(&self) -> Option<&UnifiedFullViewingKey> {
        Some(&self.1)
    }

    fn uivk(&self) -> UnifiedIncomingViewingKey {
        self.1.to_unified_incoming_viewing_key()
    }
}

#[cfg(any(test, feature = "test-dependencies"))]
impl<A: Copy> Account for (A, UnifiedIncomingViewingKey, BlockHeight) {
    type AccountId = A;

    fn id(&self) -> A {
        self.0
    }

    fn name(&self) -> Option<&str> {
        None
    }

    fn birthday_height(&self) -> BlockHeight {
        self.2
    }

    fn source(&self) -> &AccountSource {
        &AccountSource::Imported {
            purpose: AccountPurpose::ViewOnly,
            key_source: None,
        }
    }

    fn ufvk(&self) -> Option<&UnifiedFullViewingKey> {
        None
    }

    fn uivk(&self) -> UnifiedIncomingViewingKey {
        self.1.clone()
    }
}

/// Source metadata for an address in the wallet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AddressSource {
    /// The address was produced by HD derivation via a known path, with the given diversifier
    /// index.
    Derived {
        diversifier_index: DiversifierIndex,
        #[cfg(feature = "transparent-inputs")]
        transparent_key_scope: Option<TransparentKeyScope>,
    },
    /// No derivation information is available; this is common for imported addresses.
    #[cfg(feature = "transparent-key-import")]
    Standalone,
}

impl AddressSource {
    /// Returns the transparent key scope at which the address was derived, if this source metadata
    /// is for a transparent address derived from a UIVK in the wallet.
    #[cfg(feature = "transparent-inputs")]
    pub fn transparent_key_scope(&self) -> Option<&TransparentKeyScope> {
        match self {
            AddressSource::Derived {
                transparent_key_scope,
                ..
            } => transparent_key_scope.as_ref(),
            #[cfg(feature = "transparent-key-import")]
            AddressSource::Standalone => None,
        }
    }
}

/// Information about an address in the wallet.
#[derive(Clone)]
pub struct AddressInfo {
    address: Address,
    source: AddressSource,
}

impl AddressInfo {
    /// Constructs an `AddressInfo` from its constituent parts.
    pub fn from_parts(address: Address, source: AddressSource) -> Option<Self> {
        // Only allow `transparent_key_scope` to be set for transparent addresses.
        #[cfg(feature = "transparent-inputs")]
        let valid = source.transparent_key_scope().is_none()
            || matches!(address, Address::Transparent(_) | Address::Tex(_));
        #[cfg(not(feature = "transparent-inputs"))]
        let valid = true;

        valid.then_some(Self { address, source })
    }

    /// Returns the address itself.
    pub fn address(&self) -> &Address {
        &self.address
    }

    /// Returns the source metadata for the address.
    pub fn source(&self) -> AddressSource {
        self.source
    }

    /// Returns the key scope if this is a transparent address.
    #[cfg(feature = "transparent-inputs")]
    #[deprecated(
        since = "0.20.0",
        note = "use AddressSource::transparent_key_scope instead"
    )]
    pub fn transparent_key_scope(&self) -> Option<&TransparentKeyScope> {
        self.source.transparent_key_scope()
    }
}

/// A polymorphic ratio type, usually used for rational numbers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Ratio<T> {
    numerator: T,
    denominator: T,
}

impl<T> Ratio<T> {
    /// Constructs a new Ratio from a numerator and a denominator.
    pub fn new(numerator: T, denominator: T) -> Self {
        Self {
            numerator,
            denominator,
        }
    }

    /// Returns the numerator of the ratio.
    pub fn numerator(&self) -> &T {
        &self.numerator
    }

    /// Returns the denominator of the ratio.
    pub fn denominator(&self) -> &T {
        &self.denominator
    }
}

/// A type representing the progress the wallet has made toward detecting all of the funds
/// belonging to the wallet.
///
/// The window over which progress is computed spans from the wallet's birthday to the current
/// chain tip. It is divided into two regions, the "Scan Window" which covers the region from the
/// wallet recovery height to the current chain tip, and the "Recovery Window" which covers the
/// range from the wallet birthday to the wallet recovery height. If no wallet recovery height is
/// available, the scan window will cover the entire range from the wallet birthday to the chain
/// tip.
///
/// Progress for both scanning and recovery is represented in terms of the ratio between notes
/// scanned and the total number of notes added to the chain in the relevant window. This ratio
/// should only be used to compute progress percentages for display, and the numerator and
/// denominator should not be treated as authoritative note counts. In the case that there are no
/// notes in a given block range, the denominator of these values will be zero, so callers should always
/// use checked division when converting the resulting values to percentages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Progress {
    scan: Ratio<u64>,
    recovery: Option<Ratio<u64>>,
}

impl Progress {
    /// Constructs a new progress value from its constituent parts.
    pub fn new(scan: Ratio<u64>, recovery: Option<Ratio<u64>>) -> Self {
        Self { scan, recovery }
    }

    /// Returns the progress the wallet has made in scanning blocks for shielded notes belonging to
    /// the wallet between the wallet recovery height (or the wallet birthday if no recovery height
    /// is set) and the chain tip.
    pub fn scan(&self) -> Ratio<u64> {
        self.scan
    }

    /// Returns the progress the wallet has made in scanning blocks for shielded notes belonging to
    /// the wallet between the wallet birthday and the block height at which recovery from seed was
    /// initiated.
    ///
    /// Returns `None` if no recovery height is set for the wallet.
    pub fn recovery(&self) -> Option<Ratio<u64>> {
        self.recovery
    }
}

/// A type representing the potentially-spendable value of unspent outputs in the wallet.
///
/// The balances reported using this data structure may overestimate the total spendable value of
/// the wallet, in the case that the spend of a previously received shielded note has not yet been
/// detected by the process of scanning the chain. The balances reported using this data structure
/// can only be certain to be unspent in the case that [`Self::is_synced`] is true, and even in
/// this circumstance it is possible that a newly created transaction could conflict with a
/// not-yet-mined transaction in the mempool.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletSummary<AccountId: Eq + Hash> {
    account_balances: HashMap<AccountId, AccountBalance>,
    chain_tip_height: BlockHeight,
    fully_scanned_height: BlockHeight,
    progress: Progress,
    next_sapling_subtree_index: u64,
    #[cfg(feature = "orchard")]
    next_orchard_subtree_index: u64,
    #[cfg(feature = "orchard")]
    next_ironwood_subtree_index: u64,
}

impl<AccountId: Eq + Hash> WalletSummary<AccountId> {
    /// Constructs a new [`WalletSummary`] from its constituent parts.
    pub fn new(
        account_balances: HashMap<AccountId, AccountBalance>,
        chain_tip_height: BlockHeight,
        fully_scanned_height: BlockHeight,
        progress: Progress,
        next_sapling_subtree_index: u64,
        #[cfg(feature = "orchard")] next_orchard_subtree_index: u64,
        #[cfg(feature = "orchard")] next_ironwood_subtree_index: u64,
    ) -> Self {
        Self {
            account_balances,
            chain_tip_height,
            fully_scanned_height,
            progress,
            next_sapling_subtree_index,
            #[cfg(feature = "orchard")]
            next_orchard_subtree_index,
            #[cfg(feature = "orchard")]
            next_ironwood_subtree_index,
        }
    }

    /// Returns the balances of accounts in the wallet, keyed by account ID.
    pub fn account_balances(&self) -> &HashMap<AccountId, AccountBalance> {
        &self.account_balances
    }

    /// Returns the height of the current chain tip.
    pub fn chain_tip_height(&self) -> BlockHeight {
        self.chain_tip_height
    }

    /// Returns the height below which all blocks have been scanned by the wallet, ignoring blocks
    /// below the wallet birthday.
    pub fn fully_scanned_height(&self) -> BlockHeight {
        self.fully_scanned_height
    }

    /// Returns the progress of scanning the chain to bring the wallet up to date.
    ///
    /// This progress metric is intended as an indicator of how close the wallet is to
    /// general usability, including the ability to spend existing funds that were
    /// previously spendable.
    ///
    /// The window over which progress is computed spans from the wallet's birthday to the current
    /// chain tip. It is divided into two segments: a "recovery" segment, between the wallet
    /// birthday and the recovery height (currently the height at which recovery from seed was
    /// initiated, but how this boundary is computed may change in the future), and a "scan"
    /// segment, between the recovery height and the current chain tip.
    ///
    /// When converting the ratios returned here to percentages, checked division must be used in
    /// order to avoid divide-by-zero errors. A zero denominator in a returned ratio indicates that
    /// there are no shielded notes to be scanned in the associated block range.
    pub fn progress(&self) -> Progress {
        self.progress
    }

    /// Returns the Sapling subtree index that should start the next range of subtree
    /// roots passed to [`WalletCommitmentTrees::put_sapling_subtree_roots`].
    pub fn next_sapling_subtree_index(&self) -> u64 {
        self.next_sapling_subtree_index
    }

    /// Returns the Orchard subtree index that should start the next range of subtree
    /// roots passed to [`WalletCommitmentTrees::put_orchard_subtree_roots`].
    #[cfg(feature = "orchard")]
    pub fn next_orchard_subtree_index(&self) -> u64 {
        self.next_orchard_subtree_index
    }

    /// Returns the Ironwood subtree index that should start the next range of subtree
    /// roots passed to [`WalletCommitmentTrees::put_ironwood_subtree_roots`].
    #[cfg(feature = "orchard")]
    pub fn next_ironwood_subtree_index(&self) -> u64 {
        self.next_ironwood_subtree_index
    }

    /// Returns whether or not wallet scanning is complete.
    pub fn is_synced(&self) -> bool {
        self.chain_tip_height == self.fully_scanned_height
    }
}

/// A predicate that can be used to choose whether or not a particular note is retained in note
/// selection.
pub trait NoteRetention<NoteRef> {
    /// Returns whether the specified Sapling note should be retained.
    fn should_retain_sapling(&self, note: &ReceivedNote<NoteRef, sapling::Note>) -> bool;
    /// Returns whether the specified Orchard note should be retained.
    #[cfg(feature = "orchard")]
    fn should_retain_orchard(&self, note: &ReceivedNote<NoteRef, orchard::note::Note>) -> bool;
    /// Returns whether the specified Ironwood note should be retained. Ironwood notes are
    /// Orchard-shaped, so this uses the same note type as Orchard.
    #[cfg(feature = "orchard")]
    fn should_retain_ironwood(&self, note: &ReceivedNote<NoteRef, orchard::note::Note>) -> bool;
}

pub(crate) struct SimpleNoteRetention {
    pub(crate) sapling: bool,
    #[cfg(feature = "orchard")]
    pub(crate) orchard: bool,
    #[cfg(feature = "orchard")]
    pub(crate) ironwood: bool,
}

impl<NoteRef> NoteRetention<NoteRef> for SimpleNoteRetention {
    fn should_retain_sapling(&self, _: &ReceivedNote<NoteRef, sapling::Note>) -> bool {
        self.sapling
    }

    #[cfg(feature = "orchard")]
    fn should_retain_orchard(&self, _: &ReceivedNote<NoteRef, orchard::note::Note>) -> bool {
        self.orchard
    }

    #[cfg(feature = "orchard")]
    fn should_retain_ironwood(&self, _: &ReceivedNote<NoteRef, orchard::note::Note>) -> bool {
        self.ironwood
    }
}

/// Shielded outputs that were received by the wallet.
#[derive(Debug)]
pub struct ReceivedNotes<NoteRef> {
    sapling: Vec<ReceivedNote<NoteRef, sapling::Note>>,
    #[cfg(feature = "orchard")]
    orchard: Vec<ReceivedNote<NoteRef, orchard::note::Note>>,
    // Ironwood notes are Orchard-shaped `orchard::note::Note` values (note plaintext version 3),
    // but are tracked as a distinct pool so that Orchard and Ironwood value and bundle action
    // counts are accounted for separately.
    #[cfg(feature = "orchard")]
    ironwood: Vec<ReceivedNote<NoteRef, orchard::note::Note>>,
}

/// The necessary and optional notes returned for consolidation-aware input selection.
///
/// `funding` contains the notes selected to fund the requested value. `additional` contains
/// disjoint, ordinarily spendable notes that the input selector may add when doing so does not
/// change the transaction's fee or observable shape.
#[derive(Debug)]
pub struct ConsolidationNotes<NoteRef> {
    funding: ReceivedNotes<NoteRef>,
    additional: ReceivedNotes<NoteRef>,
}

impl<NoteRef> ConsolidationNotes<NoteRef> {
    /// Constructs a consolidation selection from its necessary and optional notes.
    ///
    /// `funding` and `additional` must be disjoint and contain notes only from the requested
    /// source pool. `additional` must also obey the caller's candidate limit and use the same
    /// preferred lock tier as `funding`.
    pub fn from_parts(funding: ReceivedNotes<NoteRef>, additional: ReceivedNotes<NoteRef>) -> Self {
        Self {
            funding,
            additional,
        }
    }

    /// Consumes this selection and returns its necessary and optional notes.
    pub fn into_parts(self) -> (ReceivedNotes<NoteRef>, ReceivedNotes<NoteRef>) {
        (self.funding, self.additional)
    }
}

impl<NoteRef> ReceivedNotes<NoteRef> {
    /// Construct a new empty [`ReceivedNotes`].
    pub fn empty() -> Self {
        Self::new(
            vec![],
            #[cfg(feature = "orchard")]
            vec![],
            #[cfg(feature = "orchard")]
            vec![],
        )
    }

    /// Construct a new [`ReceivedNotes`] from its constituent parts.
    pub fn new(
        sapling: Vec<ReceivedNote<NoteRef, sapling::Note>>,
        #[cfg(feature = "orchard")] orchard: Vec<ReceivedNote<NoteRef, orchard::note::Note>>,
        #[cfg(feature = "orchard")] ironwood: Vec<ReceivedNote<NoteRef, orchard::note::Note>>,
    ) -> Self {
        Self {
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
            #[cfg(feature = "orchard")]
            ironwood,
        }
    }

    /// Returns the set of spendable Sapling notes.
    pub fn sapling(&self) -> &[ReceivedNote<NoteRef, sapling::Note>] {
        self.sapling.as_ref()
    }

    /// Consumes this value and returns the Sapling notes contained within it.
    pub fn take_sapling(self) -> Vec<ReceivedNote<NoteRef, sapling::Note>> {
        self.sapling
    }

    /// Returns the set of spendable Orchard notes.
    #[cfg(feature = "orchard")]
    pub fn orchard(&self) -> &[ReceivedNote<NoteRef, orchard::note::Note>] {
        self.orchard.as_ref()
    }

    /// Consumes this value and returns the Orchard notes contained within it.
    #[cfg(feature = "orchard")]
    pub fn take_orchard(self) -> Vec<ReceivedNote<NoteRef, orchard::note::Note>> {
        self.orchard
    }

    /// Returns the set of spendable Ironwood notes.
    #[cfg(feature = "orchard")]
    pub fn ironwood(&self) -> &[ReceivedNote<NoteRef, orchard::note::Note>] {
        self.ironwood.as_ref()
    }

    /// Consumes this value and returns the Ironwood notes contained within it.
    #[cfg(feature = "orchard")]
    pub fn take_ironwood(self) -> Vec<ReceivedNote<NoteRef, orchard::note::Note>> {
        self.ironwood
    }

    /// Computes the total value of Sapling notes.
    pub fn sapling_value(&self) -> Result<Zatoshis, BalanceError> {
        self.sapling.iter().try_fold(Zatoshis::ZERO, |acc, n| {
            (acc + n.note_value()?).ok_or(BalanceError::Overflow)
        })
    }

    /// Computes the total value of Orchard notes.
    #[cfg(feature = "orchard")]
    pub fn orchard_value(&self) -> Result<Zatoshis, BalanceError> {
        self.orchard.iter().try_fold(Zatoshis::ZERO, |acc, n| {
            (acc + n.note_value()?).ok_or(BalanceError::Overflow)
        })
    }

    /// Computes the total value of Ironwood notes.
    #[cfg(feature = "orchard")]
    pub fn ironwood_value(&self) -> Result<Zatoshis, BalanceError> {
        self.ironwood.iter().try_fold(Zatoshis::ZERO, |acc, n| {
            (acc + n.note_value()?).ok_or(BalanceError::Overflow)
        })
    }

    /// Computes the total value of spendable inputs
    pub fn total_value(&self) -> Result<Zatoshis, BalanceError> {
        #[cfg(not(feature = "orchard"))]
        return self.sapling_value();

        #[cfg(feature = "orchard")]
        return (self.sapling_value()? + self.orchard_value()? + self.ironwood_value()?)
            .ok_or(BalanceError::Overflow);
    }

    /// Returns whether the collection contains no notes in any pool.
    pub fn is_empty(&self) -> bool {
        #[cfg(not(feature = "orchard"))]
        return self.sapling.is_empty();

        #[cfg(feature = "orchard")]
        return self.sapling.is_empty() && self.orchard.is_empty() && self.ironwood.is_empty();
    }

    /// Appends each pool's notes from `other` to this collection.
    pub(crate) fn append(&mut self, mut other: Self) {
        self.sapling.append(&mut other.sapling);
        #[cfg(feature = "orchard")]
        {
            self.orchard.append(&mut other.orchard);
            self.ironwood.append(&mut other.ironwood);
        }
    }

    /// Consumes this collection, returning one holding only the OLDEST single note whose value
    /// alone is at least `value`, drawn from the first pool in `sources` that holds one; the
    /// result is empty when no single note qualifies. Age is the note's commitment tree
    /// position, which is assigned in strict chain order.
    ///
    /// This is the best-effort reduction behind the default implementation of
    /// [`InputSource::select_single_spendable_note`]: it can only choose among the notes it
    /// holds, so a covering note the producing selection did not surface cannot be found here.
    pub fn into_single_covering(mut self, value: Zatoshis, sources: &[ShieldedPool]) -> Self {
        fn take_oldest_covering<NoteRef, N>(
            notes: &mut Vec<ReceivedNote<NoteRef, N>>,
            covers: impl Fn(&ReceivedNote<NoteRef, N>) -> bool,
        ) -> Option<ReceivedNote<NoteRef, N>> {
            let idx = notes
                .iter()
                .enumerate()
                .filter(|(_, n)| covers(n))
                .min_by_key(|(_, n)| n.note_commitment_tree_position())
                .map(|(idx, _)| idx)?;
            Some(notes.swap_remove(idx))
        }

        for pool in sources {
            match pool {
                ShieldedPool::Sapling => {
                    if let Some(note) = take_oldest_covering(&mut self.sapling, |n| {
                        n.note_value().is_ok_and(|v| v >= value)
                    }) {
                        return Self::new(
                            vec![note],
                            #[cfg(feature = "orchard")]
                            vec![],
                            #[cfg(feature = "orchard")]
                            vec![],
                        );
                    }
                }
                #[cfg(feature = "orchard")]
                ShieldedPool::Orchard => {
                    if let Some(note) = take_oldest_covering(&mut self.orchard, |n| {
                        n.note_value().is_ok_and(|v| v >= value)
                    }) {
                        return Self::new(vec![], vec![note], vec![]);
                    }
                }
                #[cfg(feature = "orchard")]
                ShieldedPool::Ironwood => {
                    if let Some(note) = take_oldest_covering(&mut self.ironwood, |n| {
                        n.note_value().is_ok_and(|v| v >= value)
                    }) {
                        return Self::new(vec![], vec![], vec![note]);
                    }
                }
                #[cfg(not(feature = "orchard"))]
                ShieldedPool::Orchard | ShieldedPool::Ironwood => {}
            }
        }
        Self::empty()
    }

    /// Consumes this [`ReceivedNotes`] value and produces a vector of
    /// [`ReceivedNote<NoteRef, Note>`] values.
    pub fn into_vec(
        self,
        retention: &impl NoteRetention<NoteRef>,
    ) -> Vec<ReceivedNote<NoteRef, Note>> {
        let iter = self.sapling.into_iter().filter_map(|n| {
            retention
                .should_retain_sapling(&n)
                .then(|| n.map_note(Note::Sapling))
        });

        #[cfg(feature = "orchard")]
        let iter = iter.chain(self.orchard.into_iter().filter_map(|n| {
            retention.should_retain_orchard(&n).then(|| {
                n.map_note(|note| Note::Orchard {
                    note,
                    pool: orchard::ValuePool::Orchard,
                })
            })
        }));

        // Ironwood notes are `orchard::note::Note` values, so they are emitted as `Note::Orchard`;
        // the transaction builder routes them to the Ironwood bundle by their version 3 plaintext.
        #[cfg(feature = "orchard")]
        let iter = iter.chain(self.ironwood.into_iter().filter_map(|n| {
            retention.should_retain_ironwood(&n).then(|| {
                n.map_note(|note| Note::Orchard {
                    note,
                    pool: orchard::ValuePool::Ironwood,
                })
            })
        }));

        iter.collect()
    }
}

/// A type describing the mined-ness of transactions that should be returned in response to a
/// [`TransactionDataRequest`].
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg(feature = "transparent-inputs")]
pub enum TransactionStatusFilter {
    /// Only mined transactions should be returned.
    Mined,
    /// Only mempool transactions should be returned.
    Mempool,
    /// Both mined transactions and transactions in the mempool should be returned.
    All,
}

/// A type used to filter transactions to be returned in response to a [`TransactionDataRequest`],
/// in terms of the spentness of the transaction's transparent outputs.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg(feature = "transparent-inputs")]
pub enum OutputStatusFilter {
    /// Only transactions that have currently-unspent transparent outputs should be returned.
    Unspent,
    /// All transactions corresponding to the data request should be returned, irrespective of
    /// whether or not those transactions produce transparent outputs that are currently unspent.
    All,
}

/// Payload data for [`TransactionDataRequest::TransactionsInvolvingAddress`].
///
/// Values of this type are not constructed directly, but are instead constructed using
/// [`TransactionDataRequest::transactions_involving_address`].
#[cfg(feature = "transparent-inputs")]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Getters, CopyGetters)]
pub struct TransactionsInvolvingAddress {
    /// The address to request transactions and/or UTXOs for.
    #[getset(get_copy = "pub")]
    address: TransparentAddress,
    /// Only transactions mined at heights greater than or equal to this height should be
    /// returned.
    #[getset(get_copy = "pub")]
    block_range_start: BlockHeight,
    /// If set, only transactions mined at heights less than this height should be returned.
    #[getset(get_copy = "pub")]
    block_range_end: Option<BlockHeight>,
    /// If a `request_at` time is set, the caller evaluating this request should attempt to
    /// retrieve transaction data related to the specified address at a time that is as close
    /// as practical to the specified instant, and in a fashion that decorrelates this request
    /// to a light wallet server from other requests made by the same caller.
    ///
    /// This may be ignored by callers that are able to satisfy the request without exposing
    /// correlations between addresses to untrusted parties; for example, a wallet application
    /// that uses a private, trusted-for-privacy supplier of chain data can safely ignore this
    /// field.
    #[getset(get_copy = "pub")]
    request_at: Option<SystemTime>,
    /// The caller should respond to this request only with transactions that conform to the
    /// specified transaction status filter.
    #[getset(get = "pub")]
    tx_status_filter: TransactionStatusFilter,
    /// The caller should respond to this request only with transactions containing outputs
    /// that conform to the specified output status filter.
    #[getset(get = "pub")]
    output_status_filter: OutputStatusFilter,
}

/// A request for transaction data enhancement, spentness check, or discovery
/// of spends from a given transparent address within a specific block range.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TransactionDataRequest {
    /// Information about the chain's view of a transaction is requested.
    ///
    /// The caller evaluating this request on behalf of the wallet backend should respond to this
    /// request by determining the status of the specified transaction with respect to the main
    /// chain; if using `lightwalletd` for access to chain data, this may be obtained by
    /// interpreting the results of the `GetTransaction` RPC method. It should then call
    /// [`WalletWrite::set_transaction_status`] to provide the resulting transaction status
    /// information to the wallet backend.
    GetStatus(TxId),
    /// Transaction enhancement (download of complete raw transaction data) is requested.
    ///
    /// The caller evaluating this request on behalf of the wallet backend should respond to this
    /// request by providing complete data for the specified transaction to
    /// [`wallet::decrypt_and_store_transaction`]; if using `lightwalletd` for access to chain
    /// state, this may be obtained via the `GetTransaction` RPC method. If no data is available
    /// for the specified transaction, this should be reported to the backend using
    /// [`WalletWrite::set_transaction_status`]. A [`TransactionDataRequest::Enhancement`] request
    /// subsumes any previously existing [`TransactionDataRequest::GetStatus`] request.
    Enhancement(TxId),
    /// Information about transactions that receive or spend funds belonging to the specified
    /// transparent address is requested.
    ///
    /// Fully transparent transactions, and transactions that do not contain either shielded inputs
    /// or shielded outputs belonging to the wallet, may not be discovered by the process of
    /// out-of-order chain scanning due to race conditions related to advancing the transparent
    /// address gap limit; as a consequence, the wallet must actively query to find transactions
    /// that spend such funds. Ideally we'd be able to query by [`OutPoint`] but this is not
    /// currently functionality that is supported by the light wallet server; for full-node wallets
    /// or other arrangements that allow privacy-preserving retrieval of individually identifying
    /// information such as backends that support private information retrieval (PIR) consider
    /// enabling the `spend-index` feature.
    ///
    /// The caller evaluating this request on behalf of the wallet backend should respond to this
    /// request by detecting transactions involving the specified address within the provided block
    /// range; if using `lightwalletd` for access to chain data, this may be performed using the
    /// `GetTaddressTxids` RPC method. It should then call [`wallet::decrypt_and_store_transaction`]
    /// for each transaction so detected. If no transactions are detected within the given range,
    /// the caller should instead invoke [`WalletWrite::notify_address_checked`] with
    /// `block_end_height - 1` as the `as_of_height` argument.
    #[cfg(feature = "transparent-inputs")]
    TransactionsInvolvingAddress(TransactionsInvolvingAddress),
    /// The main-chain transaction that spends of a specific transparent output, or confirmation
    /// that the output remains unspent, is requested.
    ///
    /// When the `spend-index` feature is enabled, `GetSpendingTx` requests will be emitted by the
    /// backend instead of [`TransactionDataRequest::TransactionsInvolvingAddress`], in
    /// circumstances when spentness determination is needed. This feature should only be enabled
    /// for wallets whose chain-data source can resolve the spend of an individual outpoint
    /// directly — for example a full node that maintains a spent-outpoint index. It avoids needing
    /// to retrieve potentially large amounts of transaction history (in the cas of a
    /// heavily-reused address) just to discover whether one output was spent.
    ///
    /// The caller evaluating this request on behalf of the wallet backend should determine whether
    /// `outpoint` has been spent on the main chain. Spentness should be taken from an
    /// authoritative source (e.g. the node's UTXO set); the spend index is used only to identify
    /// the spending transaction. If the output is spent, the caller should provide the spending
    /// transaction to [`wallet::decrypt_and_store_transaction`]. If the output is confirmed
    /// unspent as of some height, the caller should invoke
    /// [`WalletWrite::notify_output_verified_unspent`] with that height. If the output is known to
    /// be spent but the spending transaction cannot yet be resolved (e.g. an index is still being
    /// built — see ZcashFoundation/zebra#10806), the caller should do nothing, so that the request
    /// is re-issued and retried later.
    #[cfg(feature = "spend-index")]
    GetSpendingTx(OutPoint),
}

impl TransactionDataRequest {
    /// Constructs a request for Information about transactions that receive or spend funds
    /// belonging to the specified transparent address.
    ///
    /// # Parameters:
    /// - `address`: The address to request transactions and/or UTXOs for.
    /// - `block_range_start`: Only transactions mined at heights greater than or equal to this
    ///   height should be returned.
    /// - `block_range_end`: Only transactions mined at heights less than this height should be
    ///   returned.
    /// - `request_at`: If a `request_at` time is set, the caller evaluating this request should attempt to
    ///   retrieve transaction data related to the specified address at a time that is as close
    ///   as practical to the specified instant, and in a fashion that decorrelates this request
    ///   to a light wallet server from other requests made by the same caller. This may be ignored
    ///   by callers that are able to satisfy the request without exposing correlations between
    ///   addresses to untrusted parties; for example, a wallet application that uses a private,
    ///   trusted-for-privacy supplier of chain data can safely ignore this field.
    /// - `tx_status_filter`: The caller should respond to this request only with transactions that
    ///   conform to the specified transaction status filter.
    /// - `output_status_filter: The caller should respond to this request only with transactions
    ///   containing outputs that conform to the specified output status filter.
    ///
    /// See [`TransactionDataRequest::TransactionsInvolvingAddress`] for more information.
    #[cfg(feature = "transparent-inputs")]
    pub fn transactions_involving_address(
        address: TransparentAddress,
        block_range_start: BlockHeight,
        block_range_end: Option<BlockHeight>,
        request_at: Option<SystemTime>,
        tx_status_filter: TransactionStatusFilter,
        output_status_filter: OutputStatusFilter,
    ) -> Self {
        TransactionDataRequest::TransactionsInvolvingAddress(TransactionsInvolvingAddress {
            address,
            block_range_start,
            block_range_end,
            request_at,
            tx_status_filter,
            output_status_filter,
        })
    }
}

/// Metadata about the status of a transaction obtained by inspecting the chain state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TransactionStatus {
    /// The requested transaction ID was not recognized by the node.
    TxidNotRecognized,
    /// The requested transaction ID corresponds to a transaction that is recognized by the node,
    /// but is in the mempool or is otherwise not mined in the main chain (but may have been mined
    /// on a fork that was reorged away).
    NotInMainChain,
    /// The requested transaction ID corresponds to a transaction that has been included in the
    /// block at the provided height.
    Mined(BlockHeight),
}

/// Metadata about the structure of unspent outputs in a single pool within a wallet account.
///
/// This type is often used to represent a filtered view of outputs in the account that were
/// selected according to the conditions imposed by a [`NoteFilter`].
#[derive(Debug, Clone)]
pub struct PoolMeta {
    note_count: usize,
    value: Zatoshis,
}

impl PoolMeta {
    /// Constructs a new [`PoolMeta`] value from its constituent parts.
    pub fn new(note_count: usize, value: Zatoshis) -> Self {
        Self { note_count, value }
    }

    /// Returns the number of unspent outputs in the account, potentially selected in accordance
    /// with some [`NoteFilter`].
    pub fn note_count(&self) -> usize {
        self.note_count
    }

    /// Returns the total value of unspent outputs in the account that are accounted for in
    /// [`Self::note_count`].
    pub fn value(&self) -> Zatoshis {
        self.value
    }
}

/// Metadata about the structure of the wallet for a particular account.
///
/// At present this just contains counts of unspent outputs in each pool, but it may be extended in
/// the future to contain note values or other more detailed information about wallet structure.
///
/// Values of this type are intended to be used in selection of change output values. A value of
/// this type may represent filtered data, and may therefore not count all of the unspent notes in
/// the wallet.
///
/// A [`AccountMeta`] value is normally produced by querying the wallet database via passing a
/// [`NoteFilter`] to [`InputSource::get_account_metadata`].
#[derive(Debug, Clone)]
pub struct AccountMeta {
    sapling: Option<PoolMeta>,
    orchard: Option<PoolMeta>,
    ironwood: Option<PoolMeta>,
}

impl AccountMeta {
    /// Constructs a new [`AccountMeta`] value from its constituent parts.
    ///
    /// Ironwood metadata is tracked separately from Orchard, as Ironwood is a distinct pool.
    pub fn new(
        sapling: Option<PoolMeta>,
        orchard: Option<PoolMeta>,
        ironwood: Option<PoolMeta>,
    ) -> Self {
        Self {
            sapling,
            orchard,
            ironwood,
        }
    }

    /// Returns metadata about Sapling notes belonging to the account for which this was generated.
    ///
    /// Returns [`None`] if no metadata is available or it was not possible to evaluate the query
    /// described by a [`NoteFilter`] given the available wallet data.
    pub fn sapling(&self) -> Option<&PoolMeta> {
        self.sapling.as_ref()
    }

    /// Returns metadata about Orchard notes belonging to the account for which this was generated.
    ///
    /// Returns [`None`] if no metadata is available or it was not possible to evaluate the query
    /// described by a [`NoteFilter`] given the available wallet data.
    pub fn orchard(&self) -> Option<&PoolMeta> {
        self.orchard.as_ref()
    }

    /// Returns metadata about Ironwood notes belonging to the account for which this was generated.
    ///
    /// Ironwood notes are Orchard-shaped but belong to a pool distinct from Orchard. Returns
    /// [`None`] if no metadata is available or it was not possible to evaluate the query described
    /// by a [`NoteFilter`] given the available wallet data.
    pub fn ironwood(&self) -> Option<&PoolMeta> {
        self.ironwood.as_ref()
    }

    fn sapling_note_count(&self) -> Option<usize> {
        self.sapling.as_ref().map(|m| m.note_count)
    }

    fn orchard_note_count(&self) -> Option<usize> {
        self.orchard.as_ref().map(|m| m.note_count)
    }

    fn ironwood_note_count(&self) -> Option<usize> {
        self.ironwood.as_ref().map(|m| m.note_count)
    }

    /// Returns the number of unspent notes in the wallet for the given shielded pool.
    pub fn note_count(&self, protocol: ShieldedPool) -> Option<usize> {
        match protocol {
            ShieldedPool::Sapling => self.sapling_note_count(),
            ShieldedPool::Orchard => self.orchard_note_count(),
            ShieldedPool::Ironwood => self.ironwood_note_count(),
        }
    }

    /// Returns the total number of unspent shielded notes belonging to the account for which this
    /// was generated.
    ///
    /// Returns [`None`] if no metadata is available or it was not possible to evaluate the query
    /// described by a [`NoteFilter`] given the available wallet data. If metadata is available
    /// only for a single pool, the metadata for that pool will be returned.
    pub fn total_note_count(&self) -> Option<usize> {
        [
            self.sapling_note_count(),
            self.orchard_note_count(),
            self.ironwood_note_count(),
        ]
        .into_iter()
        .flatten()
        .reduce(|a, b| a + b)
    }

    fn sapling_value(&self) -> Option<Zatoshis> {
        self.sapling.as_ref().map(|m| m.value)
    }

    fn orchard_value(&self) -> Option<Zatoshis> {
        self.orchard.as_ref().map(|m| m.value)
    }

    fn ironwood_value(&self) -> Option<Zatoshis> {
        self.ironwood.as_ref().map(|m| m.value)
    }

    /// Returns the total value of shielded notes represented by [`Self::total_note_count`]
    ///
    /// Returns [`None`] if no metadata is available or it was not possible to evaluate the query
    /// described by a [`NoteFilter`] given the available wallet data. If metadata is available
    /// only for a single pool, the metadata for that pool will be returned.
    pub fn total_value(&self) -> Option<Zatoshis> {
        [
            self.sapling_value(),
            self.orchard_value(),
            self.ironwood_value(),
        ]
        .into_iter()
        .flatten()
        .reduce(|a, b| (a + b).expect("Does not overflow Zcash maximum value."))
    }
}

/// A `u8` value in the range 0..=MAX
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct BoundedU8<const MAX: u8>(u8);

impl<const MAX: u8> BoundedU8<MAX> {
    /// Creates a constant `BoundedU8` from a [`u8`] value.
    ///
    /// Panics: if the value is outside the range `0..=MAX`.
    pub const fn new_const(value: u8) -> Self {
        assert!(value <= MAX);
        Self(value)
    }

    /// Creates a `BoundedU8` from a [`u8`] value.
    ///
    /// Returns `None` if the provided value is outside the range `0..=MAX`.
    pub fn new(value: u8) -> Option<Self> {
        if value <= MAX {
            Some(Self(value))
        } else {
            None
        }
    }

    /// Returns the wrapped [`u8`] value.
    pub fn value(&self) -> u8 {
        self.0
    }
}

impl<const MAX: u8> From<BoundedU8<MAX>> for u8 {
    fn from(value: BoundedU8<MAX>) -> Self {
        value.0
    }
}

impl<const MAX: u8> From<BoundedU8<MAX>> for usize {
    fn from(value: BoundedU8<MAX>) -> Self {
        usize::from(value.0)
    }
}

/// A small query language for filtering notes belonging to an account.
///
/// A filter described using this language is applied to notes individually. It is primarily
/// intended for retrieval of account metadata in service of making determinations for how to
/// allocate change notes, and is not currently intended for use in broader note selection
/// contexts.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NoteFilter {
    /// Selects notes having value strictly greater than the provided value.
    ExceedsMinValue(Zatoshis),
    /// Selects notes having value greater than or equal to approximately the n'th percentile of
    /// previously sent notes in the account, irrespective of pool. The wrapped value must be in
    /// the range `1..=99`. The value `n` is respected in a best-effort fashion; results are likely
    /// to be inaccurate if the account has not yet completed scanning or if insufficient send data
    /// is available to establish a distribution.
    // TODO: it might be worthwhile to add an optional parameter here that can be used to ignore
    // low-valued (test/memo-only) sends when constructing the distribution to be drawn from.
    ExceedsPriorSendPercentile(BoundedU8<99>),
    /// Selects notes having value greater than or equal to the specified percentage of the account
    /// balance across all shielded pools. The wrapped value must be in the range `1..=99`
    ExceedsBalancePercentage(BoundedU8<99>),
    /// A note will be selected if it satisfies both of the specified conditions.
    ///
    /// If it is not possible to evaluate one of the conditions (for example,
    /// [`NoteFilter::ExceedsPriorSendPercentile`] cannot be evaluated if no sends have been
    /// performed) then that condition will be ignored. If neither condition can be evaluated,
    /// then the entire condition cannot be evaluated.
    Combine(Box<NoteFilter>, Box<NoteFilter>),
    /// A note will be selected if it satisfies the first condition; if it is not possible to
    /// evaluate that condition (for example, [`NoteFilter::ExceedsPriorSendPercentile`] cannot
    /// be evaluated if no sends have been performed) then the second condition will be used for
    /// evaluation.
    Attempt {
        condition: Box<NoteFilter>,
        fallback: Box<NoteFilter>,
    },
}

impl NoteFilter {
    /// Constructs a [`NoteFilter::Combine`] query node.
    pub fn combine(l: NoteFilter, r: NoteFilter) -> Self {
        Self::Combine(Box::new(l), Box::new(r))
    }

    /// Constructs a [`NoteFilter::Attempt`] query node.
    pub fn attempt(condition: NoteFilter, fallback: NoteFilter) -> Self {
        Self::Attempt {
            condition: Box::new(condition),
            fallback: Box::new(fallback),
        }
    }
}

/// Controls which transparent outputs are eligible for selection. This is an
/// input-selection control only; it does not encode any consensus rule.
#[cfg(feature = "transparent-inputs")]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CoinbaseFilter {
    /// Select all spendable transparent outputs.
    #[default]
    AllTransparentOutputs,
    /// Select only coinbase transparent outputs.
    ///
    /// Coinbase transactions are identified by having `tx_index == 0` within
    /// their containing block. Outputs for which the transaction index is
    /// unknown are conservatively treated as non-coinbase and will be excluded
    /// when this filter is active.
    CoinbaseOnly,
    /// Select only non-coinbase transparent outputs.
    ///
    /// Used for general (non-shielding) transfers, which may produce transparent
    /// change; coinbase funds must instead be shielded via
    /// [`propose_shielding_coinbase`](crate::data_api::wallet::propose_shielding_coinbase).
    /// Outputs whose transaction index is unknown are treated as non-coinbase
    /// and are included.
    NonCoinbaseOnly,
}

/// A trait representing the capability to query a data store for unspent transaction outputs
/// belonging to a account.
#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
pub trait InputSource {
    /// The type of errors produced by a wallet backend.
    type Error: Debug;

    /// Backend-specific account identifier.
    ///
    /// An account identifier corresponds to at most a single unified spending key's worth of spend
    /// authority, such that both received notes and change spendable by that spending authority
    /// will be interpreted as belonging to that account. This might be a database identifier type
    /// or a UUID.
    type AccountId: Copy + Debug + Eq + Hash;

    /// Backend-specific note identifier.
    ///
    /// For example, this might be a database identifier type or a UUID.
    type NoteRef: Copy + Debug + Eq + Ord;

    /// Fetches a spendable note by indexing into a transaction's shielded outputs for the
    /// specified shielded protocol.
    ///
    /// Returns `Ok(None)` if the note is not known to belong to the wallet or if the note
    /// is not spendable as of the given height. Locked outputs are selected according to
    /// `lock_filter` (see [`LockFilter`]; a [`LockFilter::Policy`] carrying the default
    /// [`LockedInputPolicy::Exclude`] selects none).
    ///
    /// [`LockedInputPolicy::Exclude`]: crate::data_api::wallet::input_selection::LockedInputPolicy::Exclude
    fn get_spendable_note(
        &self,
        txid: &TxId,
        protocol: ShieldedPool,
        index: u32,
        target_height: TargetHeight,
        lock_filter: LockFilter<'_>,
    ) -> Result<Option<ReceivedNote<Self::NoteRef, Note>>, Self::Error>;

    /// Returns whether an anchor is COMPUTABLE at `height` for spends from the given pool: whether
    /// this data source can produce the note commitment tree root, and witnesses to it, as of the
    /// end of that block.
    ///
    /// A height inside the wallet's scanned range need not qualify: tree states are only
    /// materialized at the heights the wallet chose to retain, and a wallet that scanned past
    /// NU6.3 activation before boundary checkpointing was repaired is permanently missing the
    /// anchor-retention boundaries whose blocks carried no shielded outputs. Such a hole cannot be
    /// backfilled from local state, so a caller deciding whether to anchor at a retained boundary
    /// should consult this before committing to it, and fall back rather than propose a
    /// transaction that cannot be built.
    fn anchor_computable(
        &self,
        protocol: ShieldedPool,
        height: BlockHeight,
    ) -> Result<bool, Self::Error>;

    /// Returns a list of spendable notes sufficient to cover the specified target value, if
    /// possible. Only spendable notes corresponding to the specified shielded protocol will
    /// be included. Locked outputs are selected according to `lock_filter` (see [`LockFilter`];
    /// a [`LockFilter::Policy`] carrying the default `Exclude` selects none).
    #[allow(clippy::too_many_arguments)]
    fn select_spendable_notes(
        &self,
        account: Self::AccountId,
        target_value: TargetValue,
        sources: &[ShieldedPool],
        target_height: TargetHeight,
        confirmations_policy: ConfirmationsPolicy,
        exclude: &[Self::NoteRef],
        lock_filter: LockFilter<'_>,
    ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error>;

    /// Returns notes for consolidation-aware selection from `source`.
    ///
    /// The `funding` part of the result contains notes selected toward `value`. The `additional`
    /// part contains at most `max_additional_notes` disjoint notes that may be added
    /// opportunistically. The input selector validates that the funding covers the target and
    /// that adding any optional notes stays within its bounded consolidation envelope while
    /// preserving the transaction's fee and observable shape.
    ///
    /// Implementations backed by a queryable store should minimize the funding-note count within
    /// lock-tier preference, and return the smallest eligible notes from the funding tier as
    /// additional candidates. The default implementation preserves the data source's ordinary
    /// funding behavior and returns no additional candidates.
    #[allow(clippy::too_many_arguments)]
    fn select_spendable_notes_for_consolidation(
        &self,
        account: Self::AccountId,
        value: Zatoshis,
        source: ShieldedPool,
        target_height: TargetHeight,
        confirmations_policy: ConfirmationsPolicy,
        exclude: &[Self::NoteRef],
        lock_filter: LockFilter<'_>,
        _max_additional_notes: usize,
    ) -> Result<ConsolidationNotes<Self::NoteRef>, Self::Error> {
        self.select_spendable_notes(
            account,
            TargetValue::AtLeast(value),
            &[source],
            target_height,
            confirmations_policy,
            exclude,
            lock_filter,
        )
        .map(|funding| ConsolidationNotes::from_parts(funding, ReceivedNotes::empty()))
    }

    /// Returns the OLDEST single spendable note whose value alone is at least `value`, drawn
    /// from the first pool in `sources` (in the given preference order) that holds one. The
    /// returned collection contains at most one note; it is empty when no single eligible note
    /// covers the value.
    ///
    /// This is the selection primitive behind
    /// [`NoteSelection::PreferSingle`](crate::data_api::wallet::input_selection::NoteSelection):
    /// a ZIP 318 migration transfer spends exactly one note, so a canonical pool crossing must
    /// be funded from one.
    ///
    /// The default implementation is BEST-EFFORT: it reports a note only when
    /// [`Self::select_spendable_notes`] happens to surface one that covers the value on its
    /// own. An implementation backed by a queryable store should override it with a direct
    /// query, so that a covering note is found whenever one exists.
    #[allow(clippy::too_many_arguments)]
    fn select_single_spendable_note(
        &self,
        account: Self::AccountId,
        value: Zatoshis,
        sources: &[ShieldedPool],
        target_height: TargetHeight,
        confirmations_policy: ConfirmationsPolicy,
        exclude: &[Self::NoteRef],
        lock_filter: LockFilter<'_>,
    ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error> {
        self.select_spendable_notes(
            account,
            TargetValue::AtLeast(value),
            sources,
            target_height,
            confirmations_policy,
            exclude,
            lock_filter,
        )
        .map(|notes| notes.into_single_covering(value, sources))
    }

    /// Returns the list of notes belonging to the wallet that are unspent as of the specified
    /// target height. Locked outputs are selected according to `lock_filter` (see [`LockFilter`];
    /// a [`LockFilter::Policy`] carrying the default `Exclude` selects none).
    fn select_unspent_notes(
        &self,
        account: Self::AccountId,
        sources: &[ShieldedPool],
        target_height: TargetHeight,
        exclude: &[Self::NoteRef],
        lock_filter: LockFilter<'_>,
    ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error>;

    /// Returns metadata describing the structure of the wallet for the specified account.
    ///
    /// The returned metadata value must exclude:
    /// - notes that are not considered spendable as of the given `target_height`
    /// - unspent notes excluded by the provided selector;
    /// - unspent notes identified in the given `exclude` list.
    /// - locked notes not admitted by `lock_filter` (see [`LockFilter`]; a [`LockFilter::Policy`]
    ///   carrying the default `Exclude` admits none).
    ///
    /// Implementations of this method may limit the complexity of supported queries. Such
    /// limitations should be clearly documented for the implementing type.
    fn get_account_metadata(
        &self,
        account: Self::AccountId,
        selector: &NoteFilter,
        target_height: TargetHeight,
        exclude: &[Self::NoteRef],
        lock_filter: LockFilter<'_>,
    ) -> Result<AccountMeta, Self::Error>;

    /// Fetches the transparent output corresponding to the provided `outpoint` if it is considered
    /// spendable as of the provided `target_height`.
    ///
    /// Returns `Ok(None)` if the UTXO is not known to belong to the wallet or would not be
    /// spendable in a transaction mined in the block at the target height.
    #[cfg(feature = "transparent-inputs")]
    fn get_unspent_transparent_output(
        &self,
        _outpoint: &OutPoint,
        _target_height: TargetHeight,
    ) -> Result<Option<WalletTransparentOutput<Self::AccountId>>, Self::Error> {
        unimplemented!(
            "InputSource::get_spendable_transparent_output must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Returns the list of unspent transparent outputs received by this wallet at `address`
    /// such that, at height `target_height`:
    /// * the transaction that produced the output had or will have at least the required number of
    ///   confirmations according to the provided [`ConfirmationsPolicy`]; and
    /// * the output can potentially be spent in a transaction mined in a block at the given
    ///   `target_height` (also taking into consideration the coinbase maturity rule).
    ///
    /// The `output_filter` parameter controls which transparent outputs are eligible. When set
    /// to [`CoinbaseFilter::CoinbaseOnly`], only outputs from coinbase transactions
    /// should be returned.
    ///
    /// Any output that is potentially spent by an unmined transaction in the mempool should be
    /// excluded unless the spending transaction will be expired at `target_height`.
    /// Locked outputs are selected according to `lock_filter` (see [`LockFilter`]; a
    /// [`LockFilter::Policy`] carrying the default `Exclude` selects none).
    #[cfg(feature = "transparent-inputs")]
    fn get_spendable_transparent_outputs(
        &self,
        _address: &TransparentAddress,
        _target_height: TargetHeight,
        _confirmations_policy: ConfirmationsPolicy,
        _output_filter: CoinbaseFilter,
        _lock_filter: LockFilter<'_>,
    ) -> Result<Vec<WalletTransparentOutput<Self::AccountId>>, Self::Error> {
        unimplemented!(
            "InputSource::get_spendable_transparent_outputs must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Returns the list of spendable transparent outputs received by this wallet at any of the
    /// given `addresses`, subject to the same spendability conditions as
    /// [`InputSource::get_spendable_transparent_outputs`].
    ///
    /// This is the batched equivalent of calling
    /// [`InputSource::get_spendable_transparent_outputs`] once per address. It exists so that data
    /// stores can satisfy a multi-address request with a single query rather than one query per
    /// address, which is prohibitively expensive for wallets that hold large numbers of transparent
    /// addresses (as occurs when shielding). The default implementation simply iterates over
    /// `addresses`; data stores should override it with a batched query where possible.
    ///
    /// Each returned output identifies its receiving address via
    /// [`WalletTransparentOutput::recipient_address`].
    #[cfg(feature = "transparent-inputs")]
    fn get_spendable_transparent_outputs_for_addresses(
        &self,
        addresses: &[TransparentAddress],
        target_height: TargetHeight,
        confirmations_policy: ConfirmationsPolicy,
        output_filter: CoinbaseFilter,
        lock_filter: LockFilter<'_>,
    ) -> Result<Vec<WalletTransparentOutput<Self::AccountId>>, Self::Error> {
        let mut outputs = Vec::new();
        for address in addresses {
            outputs.extend(self.get_spendable_transparent_outputs(
                address,
                target_height,
                confirmations_policy,
                output_filter,
                lock_filter,
            )?);
        }
        Ok(outputs)
    }

    /// Returns the spendable transparent outputs received by `account` whose total post-fee
    /// value (sum of values minus the cumulative marginal fee cost of the gathered inputs
    /// themselves, per `fee_rule`) is at least `target_value`, or `max_inputs` outputs
    /// (whichever is reached first).
    ///
    /// The gather is intended to scale to wallets with large numbers of transparent addresses and
    /// UTXOs: it returns a value-bounded subset rather than every spendable output, so the
    /// selector does not need to materialize the wallet's full UTXO set. Data stores should
    /// implement this with a single query that orders eligible UTXOs by descending value and
    /// accumulates them, recomputing the cumulative fee via `fee_rule` at each step, stopping
    /// once the post-fee cumulative value meets the bound. This produces a tighter result than a
    /// static value bound, without requiring a separate round trip to correct an under-estimated
    /// headroom.
    ///
    /// `max_inputs` bounds the number of transparent inputs a single transaction may consume,
    /// independent of `target_value`: even a small requested value could otherwise require an
    /// unbounded number of inputs for a wallet holding a very large number of small (e.g. dust)
    /// UTXOs. When the cap is reached before the value target, the returned set's post-fee value
    /// may be less than `target_value`; the caller's input-selection loop is expected to surface
    /// this as an `InsufficientFunds` error, the same as for any other value shortfall.
    ///
    /// `fee_rule` is fixed to [`StandardFeeRule`] (rather than being generic over the caller's
    /// actual [`ChangeStrategy`]) so that implementations of this method do not need to be
    /// generic over an arbitrary fee rule type. This is a heuristic bound only: the transaction's
    /// real fee is still computed by the caller's actual change strategy, and if this gather's
    /// estimate turns out to be insufficient, the caller's input-selection loop will surface an
    /// `InsufficientFunds` error and can re-invoke this method with a corrected `target_value`.
    ///
    /// For `TargetValue::AllFunds`, no value bound is applied and the gather returns every
    /// eligible output up to `max_inputs`.
    ///
    /// When `address_allow_list` is `Some`, only outputs received at one of the listed
    /// transparent addresses are eligible; when `None`, outputs received at any of the
    /// account's transparent addresses are eligible. The restriction must be applied
    /// *within* the gather (not to its results), so that outputs excluded by the allow list
    /// do not consume the value bound.
    ///
    /// This is the value-bounded counterpart to [`InputSource::get_spendable_transparent_outputs`]
    /// and [`InputSource::get_spendable_transparent_outputs_for_addresses`], intended for use by
    /// general (non-shielding) input selection in `propose_transaction`.
    ///
    /// [`ChangeStrategy`]: crate::fees::ChangeStrategy
    #[cfg(feature = "transparent-inputs")]
    #[allow(clippy::too_many_arguments)]
    fn select_spendable_transparent_outputs(
        &self,
        account: Self::AccountId,
        target_height: TargetHeight,
        confirmations_policy: ConfirmationsPolicy,
        output_filter: CoinbaseFilter,
        address_allow_list: Option<&[TransparentAddress]>,
        target_value: TargetValue,
        max_inputs: usize,
        fee_rule: &StandardFeeRule,
        lock_filter: LockFilter<'_>,
    ) -> Result<Vec<WalletTransparentOutput<Self::AccountId>>, Self::Error> {
        let _ = (
            account,
            target_height,
            confirmations_policy,
            output_filter,
            address_allow_list,
            target_value,
            max_inputs,
            fee_rule,
            lock_filter,
        );
        unimplemented!(
            "InputSource::select_spendable_transparent_outputs must be overridden for \
             wallets to use the value-bounded transparent input gather in propose_transaction"
        )
    }
}

/// Read-only operations required for light wallet functions.
///
/// This trait defines the read-only portion of the storage interface atop which
/// higher-level wallet operations are implemented. It serves to allow wallet functions to
/// be abstracted away from any particular data storage substrate.
#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
pub trait WalletRead {
    /// The type of errors that may be generated when querying a wallet data store.
    type Error: Debug;

    /// The type of the account identifier.
    ///
    /// An account identifier corresponds to at most a single unified spending key's worth of spend
    /// authority, such that both received notes and change spendable by that spending authority
    /// will be interpreted as belonging to that account.
    type AccountId: Copy + Debug + Eq + Hash;

    /// The concrete account type used by this wallet backend.
    type Account: Account<AccountId = Self::AccountId>;

    /// Returns a vector with the IDs of all accounts known to this wallet.
    fn get_account_ids(&self) -> Result<Vec<Self::AccountId>, Self::Error>;

    /// Returns the account corresponding to the given ID, if any.
    fn get_account(
        &self,
        account_id: Self::AccountId,
    ) -> Result<Option<Self::Account>, Self::Error>;

    /// Returns the account corresponding to a given [`SeedFingerprint`] and
    /// [`zip32::AccountId`], if any.
    fn get_derived_account(
        &self,
        derivation: &Zip32Derivation,
    ) -> Result<Option<Self::Account>, Self::Error>;

    /// Verifies that the given seed corresponds to the viewing key for the specified account.
    ///
    /// Returns:
    /// - `Ok(true)` if the viewing key for the specified account can be derived from the
    ///   provided seed.
    /// - `Ok(false)` if the derived viewing key does not match, or the specified account is not
    ///   present in the database.
    /// - `Err(_)` if a Unified Spending Key cannot be derived from the seed for the
    ///   specified account or the account has no known ZIP-32 derivation.
    fn validate_seed(
        &self,
        account_id: Self::AccountId,
        seed: &SecretVec<u8>,
    ) -> Result<bool, Self::Error>;

    /// Checks whether the given seed is relevant to any of the derived accounts (where
    /// [`Account::source`] is [`AccountSource::Derived`]) in the wallet.
    ///
    /// This API does not check whether the seed is relevant to any imported account,
    /// because that would require brute-forcing the ZIP 32 account index space.
    fn seed_relevance_to_derived_accounts(
        &self,
        seed: &SecretVec<u8>,
    ) -> Result<SeedRelevance<Self::AccountId>, Self::Error>;

    /// Returns the account corresponding to a given [`UnifiedFullViewingKey`], if any.
    fn get_account_for_ufvk(
        &self,
        ufvk: &UnifiedFullViewingKey,
    ) -> Result<Option<Self::Account>, Self::Error>;

    /// Returns information about every address tracked for this account.
    fn list_addresses(&self, account: Self::AccountId) -> Result<Vec<AddressInfo>, Self::Error>;

    /// Returns the wallet account that controls the given address, if any.
    ///
    /// Backends that can answer this query from an indexed lookup should implement it
    /// directly. Backends without such an index can delegate to
    /// [`defaults::find_account_for_address`], which implements the semantics described below
    /// using [`UnifiedIncomingViewingKey::decrypt_diversifiers`] and a linear scan over
    /// [`Self::get_account_ids`] / [`Self::list_addresses`].
    ///
    /// # Unified Addresses
    ///
    /// For a Unified Address each account's [`UnifiedIncomingViewingKey`] is asked, via
    /// [`UnifiedIncomingViewingKey::decrypt_diversifiers`], whether it could have derived any
    /// shielded receiver of the UA. An account matches if at least one shielded receiver is
    /// attributable to it — including receivers that have never been previously exposed by
    /// the wallet. If the shielded receivers of the UA are attributable to more than one
    /// account, this is treated as an inconsistent ("frankenstein") address and
    /// [`FindAccountForAddressError::UnifiedAddressConflict`] is returned rather than
    /// arbitrarily selecting one account.
    ///
    /// Backends are permitted to additionally resolve UAs by exact match against their
    /// tracked-address index before (or instead of) running the UIVK-algebra step, provided
    /// the exact-match result is consistent with at least one account identified by the
    /// algebraic step.
    ///
    /// # Non-Unified Addresses
    ///
    /// Backends should resolve bare shielded addresses (Sapling) via the same UIVK-algebraic
    /// path where feasible, so that an address derivable from an account's UIVK is resolved
    /// whether or not it has been previously exposed. Backends that do not can treat a bare
    /// shielded address as an exact-match lookup over their tracked-address index.
    ///
    /// Transparent and TEX addresses are resolved by exact match against tracked addresses
    /// only, since a diversifier index cannot be recovered from a transparent receiver alone.
    ///
    /// # Returns
    ///
    /// - `Ok(Some(account_id))` if the address is controlled by a single account known to
    ///   this wallet.
    /// - `Ok(None)` if no receiver of the address is recognized as belonging to any account.
    /// - `Err(FindAccountForAddressError::Backend(_))` if the lookup fails due to a
    ///   backend error.
    /// - `Err(FindAccountForAddressError::UnifiedAddressConflict)` if the provided address
    ///   is a Unified Address whose receiver components map to different accounts.
    ///
    /// [`UnifiedIncomingViewingKey`]: zcash_keys::keys::UnifiedIncomingViewingKey
    /// [`UnifiedIncomingViewingKey::decrypt_diversifiers`]: zcash_keys::keys::UnifiedIncomingViewingKey::decrypt_diversifiers
    /// [`FindAccountForAddressError::UnifiedAddressConflict`]: error::FindAccountForAddressError::UnifiedAddressConflict
    fn find_account_for_address<P: consensus::Parameters>(
        &self,
        params: &P,
        address: &zcash_keys::address::Address,
    ) -> Result<Option<Self::AccountId>, error::FindAccountForAddressError<Self::Error>>;

    /// Returns the most recently generated unified address for the specified account that conforms
    /// to the specified address filter, if the account identifier specified refers to a valid
    /// account for this wallet.
    ///
    /// This will return `Ok(None)` if no previously generated address conforms to the specified
    /// request.
    fn get_last_generated_address_matching(
        &self,
        account: Self::AccountId,
        address_filter: UnifiedAddressRequest,
    ) -> Result<Option<UnifiedAddress>, Self::Error>;

    /// Returns the birthday height for the given account, or an error if the account is not known
    /// to the wallet.
    fn get_account_birthday(&self, account: Self::AccountId) -> Result<BlockHeight, Self::Error>;

    /// Returns the birthday height for the wallet.
    ///
    /// This returns the earliest birthday height among accounts maintained by this wallet,
    /// or `Ok(None)` if the wallet has no initialized accounts.
    fn get_wallet_birthday(&self) -> Result<Option<BlockHeight>, Self::Error>;

    /// Returns the height at which the wallet as a whole will have exited recovery mode.
    ///
    /// This returns the latest `recover_until` height among accounts maintained by this
    /// wallet (see [`AccountBirthday::recover_until`]), or `Ok(None)` if no account has a
    /// recovery horizon set (for example, in a wallet whose accounts were all created at
    /// the chain tip rather than restored from backup). Heights below the returned value,
    /// exclusive, are in scope for wallet recovery for at least one account.
    fn get_wallet_recover_until(&self) -> Result<Option<BlockHeight>, Self::Error>;

    /// Returns a [`WalletSummary`] that represents the sync status and the wallet balances as of
    /// the chain tip given the specified confirmation policy for all accounts known to the wallet,
    /// or `Ok(None)` if the wallet has no summary data available.
    fn get_wallet_summary(
        &self,
        confirmations_policy: ConfirmationsPolicy,
    ) -> Result<Option<WalletSummary<Self::AccountId>>, Self::Error>;

    /// Returns the height of the chain as known to the wallet as of the most recent call to
    /// [`WalletWrite::update_chain_tip`].
    ///
    /// This will return `Ok(None)` if the height of the current consensus chain tip is unknown.
    fn chain_height(&self) -> Result<Option<BlockHeight>, Self::Error>;

    /// Returns the interval on which this wallet retains note commitment tree checkpoints as
    /// durable anchors.
    ///
    /// A ZIP 318 pool migration anchors each of its pool-crossing transfers to a boundary of this
    /// interval, and proves the transfer long after that boundary has passed; the proof can only be
    /// constructed if the wallet kept the boundary's checkpoint. Reading the grid back off the
    /// wallet that maintains it — rather than configuring the migration separately — is what
    /// guarantees the two agree.
    ///
    /// The default implementation returns [`AnchorRetentionInterval::ZIP_318`], which matches the
    /// retention a backend performs if it does not configure the interval. A backend that DOES make
    /// retention configurable must override this to report the interval it actually retains, or
    /// migrations over it will draw anchors it has pruned.
    ///
    /// [`AnchorRetentionInterval::ZIP_318`]: anchor_retention::AnchorRetentionInterval::ZIP_318
    fn anchor_retention_interval(&self) -> anchor_retention::AnchorRetentionInterval {
        anchor_retention::AnchorRetentionInterval::ZIP_318
    }

    /// Returns the ZIP 318 pool-migration parameters in force for this wallet: the specified
    /// values, with the anchor bucket grid taken from [`Self::anchor_retention_interval`].
    ///
    /// Every decision that depends on the grid must consult this rather than the network defaults,
    /// so that a wallet retaining a non-standard interval is treated consistently: bucketing an
    /// anchor and judging the resulting transaction a canonical crossing are the same question
    /// asked twice, and they must be asked of the same grid. Overriding
    /// [`Self::anchor_retention_interval`] is sufficient; this composes it.
    fn pool_migration_params(&self) -> anchor_retention::PoolMigrationParams {
        anchor_retention::PoolMigrationParams::new(self.anchor_retention_interval())
    }

    /// Returns the block hash for the block at the given height, if the
    /// associated block data is available. Returns `Ok(None)` if the hash
    /// is not found in the database.
    fn get_block_hash(&self, block_height: BlockHeight) -> Result<Option<BlockHash>, Self::Error>;

    /// Returns the available block metadata for the block at the specified height, if any.
    fn block_metadata(&self, height: BlockHeight) -> Result<Option<BlockMetadata>, Self::Error>;

    /// Returns the metadata for the block at the height to which the wallet has been fully
    /// scanned.
    ///
    /// This is the height for which the wallet has fully trial-decrypted this and all preceding
    /// blocks above the wallet's birthday height. Along with this height, this method returns
    /// metadata describing the state of the wallet's note commitment trees as of the end of that
    /// block.
    fn block_fully_scanned(&self) -> Result<Option<BlockMetadata>, Self::Error>;

    /// Returns the block height and hash for the block at the maximum scanned block height.
    ///
    /// This will return `Ok(None)` if no blocks have been scanned.
    fn get_max_height_hash(&self) -> Result<Option<(BlockHeight, BlockHash)>, Self::Error>;

    /// Returns block metadata for the maximum height that the wallet has scanned.
    ///
    /// If the wallet is fully synced, this will be equivalent to `block_fully_scanned`;
    /// otherwise the maximal scanned height is likely to be greater than the fully scanned height
    /// due to the fact that out-of-order scanning can leave gaps.
    fn block_max_scanned(&self) -> Result<Option<BlockMetadata>, Self::Error>;

    /// Returns a vector of suggested scan ranges based upon the current wallet state.
    ///
    /// This method should only be used in cases where the [`CompactBlock`] data that will be made
    /// available to `scan_cached_blocks` for the requested block ranges includes note commitment
    /// tree size information for each block; or else the scan is likely to fail if notes belonging
    /// to the wallet are detected.
    ///
    /// The returned range(s) may include block heights beyond the current chain tip. Ranges are
    /// returned in order of descending priority, and higher-priority ranges should always be
    /// scanned before lower-priority ranges; in particular, ranges with [`ScanPriority::Verify`]
    /// priority must always be scanned first in order to avoid blockchain continuity errors in the
    /// case of a reorg.
    ///
    /// [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
    /// [`ScanPriority::Verify`]: crate::data_api::scanning::ScanPriority
    fn suggest_scan_ranges(&self) -> Result<Vec<ScanRange>, Self::Error>;

    /// Returns the default target height (for the block in which a new
    /// transaction would be mined) and anchor height (to use for a new
    /// transaction), given the range of block heights that the backend
    /// knows about.
    ///
    /// This will return `Ok(None)` if no block data is present in the database.
    fn get_target_and_anchor_heights(
        &self,
        min_confirmations: NonZeroU32,
    ) -> Result<Option<(TargetHeight, BlockHeight)>, Self::Error>;

    /// Returns the block height in which the specified transaction was mined, or `Ok(None)` if the
    /// transaction is not known to the wallet or not in the main chain.
    fn get_tx_height(&self, txid: TxId) -> Result<Option<BlockHeight>, Self::Error>;

    /// Returns all unified full viewing keys known to this wallet.
    fn get_unified_full_viewing_keys(
        &self,
    ) -> Result<HashMap<Self::AccountId, UnifiedFullViewingKey>, Self::Error>;

    /// Returns the memo for a note.
    ///
    /// Returns `Ok(None)` if the note is known to the wallet but memo data has not yet been
    /// populated for that note, or if the note identifier does not correspond to a note
    /// that is known to the wallet.
    fn get_memo(&self, note_id: NoteId) -> Result<Option<Memo>, Self::Error>;

    /// Returns the transaction with the given txid, if known to the wallet.
    ///
    /// Returns `None` if the txid is not known to the wallet or if the raw transaction data is not
    /// available.
    fn get_transaction(&self, txid: TxId) -> Result<Option<Transaction>, Self::Error>;

    /// Returns the nullifiers for Sapling notes that the wallet is tracking, along with their
    /// associated account IDs, that are either unspent or have not yet been confirmed as spent (in
    /// that a spending transaction known to the wallet has not yet been included in a block).
    fn get_sapling_nullifiers(
        &self,
        query: NullifierQuery,
    ) -> Result<Vec<(Self::AccountId, sapling::Nullifier)>, Self::Error>;

    /// Returns the nullifiers for Orchard notes that the wallet is tracking, along with their
    /// associated account IDs, that are either unspent or have not yet been confirmed as spent (in
    /// that a spending transaction known to the wallet has not yet been included in a block).
    #[cfg(feature = "orchard")]
    fn get_orchard_nullifiers(
        &self,
        _query: NullifierQuery,
    ) -> Result<Vec<(Self::AccountId, orchard::note::Nullifier)>, Self::Error> {
        unimplemented!(
            "WalletRead::get_orchard_nullifiers must be overridden for wallets to use the `orchard` feature"
        )
    }

    /// Returns the nullifiers for Ironwood notes that the wallet is tracking, along with their
    /// associated account IDs, that are either unspent or have not yet been confirmed as spent.
    /// Ironwood nullifiers are Orchard-shaped but are tracked as a separate pool.
    ///
    /// This is a required method (like [`WalletRead::get_sapling_nullifiers`]) rather than
    /// defaulting to a panic: it is called on the scan path, so a backend that does not override it
    /// would abort the process on the first scan. Requiring it surfaces the omission at compile
    /// time instead.
    #[cfg(feature = "orchard")]
    fn get_ironwood_nullifiers(
        &self,
        query: NullifierQuery,
    ) -> Result<Vec<(Self::AccountId, orchard::note::Nullifier)>, Self::Error>;

    /// Returns the set of non-ephemeral transparent receivers associated with the given
    /// account controlled by this wallet.
    ///
    /// The set contains all non-ephemeral transparent receivers that are known to have
    /// been derived under this account. Wallets should scan the chain for UTXOs sent to
    /// these receivers.
    ///
    /// # Parameters
    /// - `account`: The identifier for the account from which transparent receivers should be
    ///   returned.
    /// - `include_change`: A flag indicating whether transparent change addresses should be
    ///   returned.
    /// - `include_standalone`: A flag indicating whether imported standalone addresses associated
    ///   with the account should be returned. The value of this flag is ignored unless the
    ///   `transparent-key-import` feature is enabled.
    ///
    /// Use [`Self::get_ephemeral_transparent_receivers`] to obtain the ephemeral transparent
    /// receivers.
    #[cfg(feature = "transparent-inputs")]
    fn get_transparent_receivers(
        &self,
        _account: Self::AccountId,
        _include_change: bool,
        _include_standalone: bool,
    ) -> Result<HashMap<TransparentAddress, TransparentAddressMetadata>, Self::Error> {
        unimplemented!(
            "WalletRead::get_transparent_receivers must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Returns the set of previously-exposed ephemeral transparent receivers generated by the given
    /// account controlled by this wallet.
    ///
    /// The set contains all ephemeral transparent receivers that are known to have been derived
    /// under this account within `exposure_depth` blocks of the chain tip. Wallets may scan the
    /// chain for UTXOs sent to these receivers, but should do so in a fashion that does not reveal
    /// that they are controlled by the same wallet. If the [`next_check_time`] field is set for a
    /// returned [`TransparentAddressMetadata`], the wallet application should defer any query to
    /// any public light wallet server for this address until [`next_check_time`] has passed; when
    /// using a light wallet server that is trusted for privacy, this delay may be omitted.
    ///
    /// # Parameters
    /// - `account`: The identifier for the account from which transparent receivers should be
    ///   returned.
    /// - `exposure_depth`: Implementations of this method should return only addresses exposed at
    ///   heights greater than `chain_tip_height - exposure_depth`.
    /// - `exclude_used`: When set to `true`, do not return addresses that are known to have
    ///   already received funds in a transaction.
    ///
    /// [`next_check_time`]: TransparentAddressMetadata::next_check_time
    #[cfg(feature = "transparent-inputs")]
    fn get_ephemeral_transparent_receivers(
        &self,
        _account: Self::AccountId,
        _exposure_depth: u32,
        _exclude_used: bool,
    ) -> Result<HashMap<TransparentAddress, TransparentAddressMetadata>, Self::Error> {
        unimplemented!(
            "WalletRead::get_ephemeral_transparent_receivers must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Returns a mapping from each transparent receiver associated with the specified account
    /// to the key scope for that address and the balance of funds given the specified target
    /// height and confirmations policy.
    #[cfg(feature = "transparent-inputs")]
    fn get_transparent_balances(
        &self,
        _account: Self::AccountId,
        _target_height: TargetHeight,
        _confirmations_policy: ConfirmationsPolicy,
    ) -> Result<TransparentBalances, Self::Error> {
        unimplemented!(
            "WalletRead::get_transparent_balances must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Returns the metadata associated with a given transparent receiver in an account
    /// controlled by this wallet, if available.
    ///
    /// This is equivalent to (but may be implemented more efficiently than):
    /// ```compile_fail
    /// Ok(
    ///     if let Some(result) = self.get_transparent_receivers(account, true)?.get(address) {
    ///         Some(result.clone())
    ///     } else {
    ///         self.get_ephemeral_transparent_receivers(account, u32::MAX, false)?
    ///             .get(address)
    ///             .cloned()
    ///     },
    /// )
    /// ```
    ///
    /// Returns `Ok(None)` if the address is not recognized, or we do not have metadata for it.
    /// Returns `Ok(Some(metadata))` if we have the metadata.
    #[cfg(feature = "transparent-inputs")]
    fn get_transparent_address_metadata(
        &self,
        _account: Self::AccountId,
        _address: &TransparentAddress,
    ) -> Result<Option<TransparentAddressMetadata>, Self::Error> {
        unimplemented!(
            "WalletRead::get_transparent_address_metadata must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Returns the maximum block height at which a transparent output belonging to the wallet has
    /// been observed.
    ///
    /// We must start looking for UTXOs for addresses within the current gap limit as of the block
    /// height at which they might have first been revealed. This would have occurred when the gap
    /// advanced as a consequence of a transaction being mined. The address at the start of the current
    /// gap was potentially first revealed after the address at index `gap_start - (gap_limit + 1)`
    /// received an output in a mined transaction; therefore, we take that height to be where we
    /// should start searching for UTXOs.
    #[cfg(feature = "transparent-inputs")]
    fn utxo_query_height(&self, _account: Self::AccountId) -> Result<BlockHeight, Self::Error> {
        unimplemented!(
            "WalletRead::utxo_query_height must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Returns a vector of [`TransactionDataRequest`] values that describe information needed by
    /// the wallet to complete its view of transaction history.
    ///
    /// Requests for the same transaction data may be returned repeatedly by successive data
    /// requests. The caller of this method should consider the latest set of requests returned
    /// by this method to be authoritative and to subsume that returned by previous calls.
    ///
    /// Callers should poll this method on a regular interval, not as part of ordinary chain
    /// scanning, which already produces requests for transaction data enhancement. Note that
    /// responding to a set of transaction data requests may result in the creation of new
    /// transaction data requests, such as when it is necessary to fill in purely-transparent
    /// transaction history by walking the chain backwards via transparent inputs.
    fn transaction_data_requests(&self) -> Result<Vec<TransactionDataRequest>, Self::Error>;

    /// Returns a vector of [`ReceivedTransactionOutput`] values describing the outputs of the
    /// specified transaction that were received by the wallet. The number of confirmations until
    /// each received output will be considered spendable is determined based upon the specified
    /// target height and confirmations policy.
    fn get_received_outputs(
        &self,
        txid: TxId,
        target_height: TargetHeight,
        confirmations_policy: ConfirmationsPolicy,
    ) -> Result<Vec<ReceivedTransactionOutput>, Self::Error>;
}

/// Read-only operations required for testing light wallet functions.
///
/// These methods expose internal details or unstable interfaces, primarily to enable use
/// of the [`testing`] framework. They should not be used in production software.
#[cfg(any(test, feature = "test-dependencies"))]
#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
pub trait WalletTest: InputSource + WalletRead {
    /// Returns a vector of transaction summaries.
    ///
    /// Currently test-only, as production use could return a very large number of results; either
    /// pagination or a streaming design will be necessary to stabilize this feature for production
    /// use.
    fn get_tx_history(
        &self,
    ) -> Result<
        Vec<testing::TransactionSummary<<Self as WalletRead>::AccountId>>,
        <Self as WalletRead>::Error,
    >;

    /// Returns the note IDs for shielded notes sent by the wallet in a particular
    /// transaction.
    fn get_sent_note_ids(
        &self,
        _txid: &TxId,
        _protocol: ShieldedPool,
    ) -> Result<Vec<NoteId>, <Self as WalletRead>::Error>;

    /// Returns the outputs for a transaction sent by the wallet.
    #[allow(clippy::type_complexity)]
    fn get_sent_outputs(
        &self,
        txid: &TxId,
    ) -> Result<Vec<OutputOfSentTx>, <Self as WalletRead>::Error>;

    #[allow(clippy::type_complexity)]
    fn get_checkpoint_history(
        &self,
        protocol: &ShieldedPool,
    ) -> Result<
        Vec<(BlockHeight, Option<incrementalmerkletree::Position>)>,
        <Self as WalletRead>::Error,
    >;

    /// Fetches the transparent output corresponding to the provided `outpoint`.
    /// Allows selecting unspendable outputs for testing purposes.
    ///
    /// # Parameters
    /// - `outpoint`: The identifier for the output to be retrieved.
    /// - `spendable_as_of`: The target height of a transaction under construction that will spend the
    ///   returned output. If this is `None`, no spendability checks are performed.
    ///
    /// Returns `Ok(None)` if the UTXO is not known to belong to the wallet or if `spendable_as_of`
    /// is set and the output is available to be spent by the wallet in a transaction that is
    /// intended to be mined at the target height.
    #[cfg(feature = "transparent-inputs")]
    fn get_transparent_output(
        &self,
        _outpoint: &OutPoint,
        _spendable_as_of: Option<TargetHeight>,
    ) -> Result<
        Option<WalletTransparentOutput<<Self as WalletRead>::AccountId>>,
        <Self as InputSource>::Error,
    > {
        unimplemented!(
            "WalletTest::get_transparent_output must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Returns all the notes that have been received by the wallet.
    fn get_notes(
        &self,
        protocol: ShieldedPool,
    ) -> Result<Vec<ReceivedNote<Self::NoteRef, Note>>, <Self as InputSource>::Error>;

    /// Returns a vector of ephemeral transparent addresses associated with the given
    /// account controlled by this wallet, along with their metadata. The result includes
    /// reserved addresses, and addresses for the backend's configured gap limit worth
    /// of additional indices (capped to the maximum index).
    ///
    /// If `index_range` is some `Range`, it limits the result to addresses with indices
    /// in that range. An `index_range` of `None` is defined to be equivalent to
    /// `0..(1u32 << 31)`.
    ///
    /// Wallets should scan the chain for UTXOs sent to these ephemeral transparent
    /// receivers, but do not need to do so regularly. Under expected usage, outputs
    /// would only be detected with these receivers in the following situations:
    ///
    /// - This wallet created a payment to a ZIP 320 (TEX) address, but the second
    ///   transaction (that spent the output sent to the ephemeral address) did not get
    ///   mined before it expired.
    ///   - In this case the output will already be known to the wallet (because it
    ///     stores the transactions that it creates).
    ///
    /// - Another wallet app using the same seed phrase created a payment to a ZIP 320
    ///   address, and this wallet queried for the ephemeral UTXOs after the first
    ///   transaction was mined but before the second transaction was mined.
    ///   - In this case, the output should not be considered unspent until the expiry
    ///     height of the transaction it was received in has passed. Wallets creating
    ///     payments to TEX addresses generally set the same expiry height for the first
    ///     and second transactions, meaning that this wallet does not need to observe
    ///     the second transaction to determine when it would have expired.
    ///
    /// - A TEX address recipient decided to return funds that the wallet had sent to
    ///   them.
    ///
    /// In all cases, the wallet should re-shield the unspent outputs, in a separate
    /// transaction per ephemeral address, before re-spending the funds.
    #[cfg(feature = "transparent-inputs")]
    fn get_known_ephemeral_addresses(
        &self,
        _account: <Self as WalletRead>::AccountId,
        _index_range: Option<Range<NonHardenedChildIndex>>,
    ) -> Result<Vec<(TransparentAddress, TransparentAddressMetadata)>, <Self as WalletRead>::Error>
    {
        unimplemented!(
            "WalletRead::get_known_ephemeral_addresses must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// If a given ephemeral address might have been reserved, i.e. would be included in
    /// the result of `get_known_ephemeral_addresses(account_id, None)` for any of the
    /// wallet's accounts, then return `Ok(Some(account_id))`. Otherwise return `Ok(None)`.
    ///
    /// This is equivalent to (but may be implemented more efficiently than):
    /// ```compile_fail
    /// for account_id in self.get_account_ids()? {
    ///     if self
    ///         .get_known_ephemeral_addresses(account_id, None)?
    ///         .into_iter()
    ///         .any(|(known_addr, _)| &known_addr == address)
    ///     {
    ///         return Ok(Some(account_id));
    ///     }
    /// }
    /// Ok(None)
    /// ```
    #[cfg(feature = "transparent-inputs")]
    fn find_account_for_ephemeral_address(
        &self,
        address: &TransparentAddress,
    ) -> Result<Option<<Self as WalletRead>::AccountId>, <Self as WalletRead>::Error> {
        for account_id in self.get_account_ids()? {
            if self
                .get_known_ephemeral_addresses(account_id, None)?
                .into_iter()
                .any(|(known_addr, _)| &known_addr == address)
            {
                return Ok(Some(account_id));
            }
        }
        Ok(None)
    }

    /// Performs final checks at the conclusion of each test.
    ///
    /// This method allows wallet backend developers to perform any necessary consistency
    /// checks or cleanup. By default it does nothing.
    fn finally(&self) {}
}

/// The output of a transaction sent by the wallet.
///
/// This type is opaque, and exists for use by tests defined in this crate.
#[cfg(any(test, feature = "test-dependencies"))]
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct OutputOfSentTx {
    value: Zatoshis,
    external_recipient: Option<Address>,
    #[cfg(feature = "transparent-inputs")]
    ephemeral_address: Option<(Address, NonHardenedChildIndex)>,
}

#[cfg(any(test, feature = "test-dependencies"))]
impl OutputOfSentTx {
    /// Constructs an output from its test-relevant parts.
    ///
    /// If the output is to an ephemeral address, `ephemeral_address` should contain the
    /// address along with the `address_index` it was derived from under the BIP 32 path
    /// `m/44'/<coin_type>'/<account>'/2/<address_index>`.
    pub fn from_parts(
        value: Zatoshis,
        external_recipient: Option<Address>,
        #[cfg(feature = "transparent-inputs")] ephemeral_address: Option<(
            Address,
            NonHardenedChildIndex,
        )>,
    ) -> Self {
        Self {
            value,
            external_recipient,
            #[cfg(feature = "transparent-inputs")]
            ephemeral_address,
        }
    }

    /// Returns the value of the output.
    pub fn value(&self) -> Zatoshis {
        self.value
    }

    /// Returns the recipient of the sent output.
    pub fn external_recipient(&self) -> Option<&Address> {
        self.external_recipient.as_ref()
    }

    /// Returns the ephemeral address to which the output was sent, along with the non-hardened
    /// transparent child index at which that address was derived.
    #[cfg(feature = "transparent-inputs")]
    pub fn ephemeral_address(&self) -> Option<&(Address, NonHardenedChildIndex)> {
        self.ephemeral_address.as_ref()
    }
}

/// The relevance of a seed to a given wallet.
///
/// This is the return type for [`WalletRead::seed_relevance_to_derived_accounts`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SeedRelevance<A: Copy> {
    /// The seed is relevant to at least one derived account within the wallet.
    Relevant { account_ids: NonEmpty<A> },
    /// The seed is not relevant to any of the derived accounts within the wallet.
    NotRelevant,
    /// The wallet contains no derived accounts.
    NoDerivedAccounts,
    /// The wallet contains no accounts.
    NoAccounts,
}

/// Metadata describing the sizes of the zcash note commitment trees as of a particular block.
#[derive(Debug, Clone, Copy)]
pub struct BlockMetadata {
    block_height: BlockHeight,
    block_hash: BlockHash,
    sapling_tree_size: Option<u32>,
    #[cfg(feature = "orchard")]
    orchard_tree_size: Option<u32>,
    #[cfg(feature = "orchard")]
    ironwood_tree_size: Option<u32>,
}

impl BlockMetadata {
    /// Constructs a new [`BlockMetadata`] value from its constituent parts.
    pub fn from_parts(
        block_height: BlockHeight,
        block_hash: BlockHash,
        sapling_tree_size: Option<u32>,
        #[cfg(feature = "orchard")] orchard_tree_size: Option<u32>,
        #[cfg(feature = "orchard")] ironwood_tree_size: Option<u32>,
    ) -> Self {
        Self {
            block_height,
            block_hash,
            sapling_tree_size,
            #[cfg(feature = "orchard")]
            orchard_tree_size,
            #[cfg(feature = "orchard")]
            ironwood_tree_size,
        }
    }

    /// Returns the block height.
    pub fn block_height(&self) -> BlockHeight {
        self.block_height
    }

    /// Returns the hash of the block
    pub fn block_hash(&self) -> BlockHash {
        self.block_hash
    }

    /// Returns the size of the Sapling note commitment tree for the final treestate of the block
    /// that this [`BlockMetadata`] describes, if available.
    pub fn sapling_tree_size(&self) -> Option<u32> {
        self.sapling_tree_size
    }

    /// Returns the size of the Orchard note commitment tree for the final treestate of the block
    /// that this [`BlockMetadata`] describes, if available.
    #[cfg(feature = "orchard")]
    pub fn orchard_tree_size(&self) -> Option<u32> {
        self.orchard_tree_size
    }

    /// Returns the size of the Ironwood note commitment tree for the final treestate of the block
    /// that this [`BlockMetadata`] describes, if available.
    #[cfg(feature = "orchard")]
    pub fn ironwood_tree_size(&self) -> Option<u32> {
        self.ironwood_tree_size
    }
}

/// The protocol-specific note commitment and nullifier data extracted from the per-transaction
/// shielded bundles in [`CompactBlock`], used by the wallet for note commitment tree maintenance
/// and spend detection.
///
/// [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
pub struct ScannedBundles<NoteCommitment, NF> {
    final_tree_size: u32,
    commitments: Vec<(NoteCommitment, Retention<BlockHeight>)>,
    nullifier_map: Vec<(TxIndex, TxId, Vec<NF>)>,
}

impl<NoteCommitment, NF> ScannedBundles<NoteCommitment, NF> {
    pub(crate) fn new(
        final_tree_size: u32,
        commitments: Vec<(NoteCommitment, Retention<BlockHeight>)>,
        nullifier_map: Vec<(TxIndex, TxId, Vec<NF>)>,
    ) -> Self {
        Self {
            final_tree_size,
            nullifier_map,
            commitments,
        }
    }

    /// Returns the size of the note commitment tree as of the end of the scanned block.
    pub fn final_tree_size(&self) -> u32 {
        self.final_tree_size
    }

    /// Returns the vector of nullifiers for each transaction in the block.
    ///
    /// The returned tuple is keyed by both transaction ID and the index of the transaction within
    /// the block, so that either the txid or the combination of the block hash available from
    /// [`ScannedBlock::block_hash`] and returned transaction index may be used to uniquely
    /// identify the transaction, depending upon the needs of the caller.
    pub fn nullifier_map(&self) -> &[(TxIndex, TxId, Vec<NF>)] {
        &self.nullifier_map
    }

    /// Returns the ordered list of note commitments to be added to the note commitment
    /// tree.
    pub fn commitments(&self) -> &[(NoteCommitment, Retention<BlockHeight>)] {
        &self.commitments
    }
}

/// A struct used to return the vectors of note commitments for a [`ScannedBlock`]
/// as owned values.
pub struct ScannedBlockCommitments {
    /// The ordered vector of note commitments for Sapling outputs of the block.
    pub sapling: Vec<(sapling::Node, Retention<BlockHeight>)>,
    /// The ordered vector of note commitments for Orchard outputs of the block.
    /// Present only when the `orchard` feature is enabled.
    #[cfg(feature = "orchard")]
    pub orchard: Vec<(orchard::tree::MerkleHashOrchard, Retention<BlockHeight>)>,
    /// The ordered vector of note commitments for Ironwood outputs of the block.
    /// Present only when the `orchard` feature is enabled.
    #[cfg(feature = "orchard")]
    pub ironwood: Vec<(orchard::tree::MerkleHashOrchard, Retention<BlockHeight>)>,
}

/// The subset of information that is relevant to this wallet that has been
/// decrypted and extracted from a [`CompactBlock`].
///
/// [`CompactBlock`]: crate::proto::compact_formats::CompactBlock
pub struct ScannedBlock<AccountId> {
    block_height: BlockHeight,
    block_hash: BlockHash,
    block_time: u32,
    transactions: Vec<WalletTx<AccountId>>,
    sapling: ScannedBundles<sapling::Node, sapling::Nullifier>,
    #[cfg(feature = "orchard")]
    orchard: ScannedBundles<orchard::tree::MerkleHashOrchard, orchard::note::Nullifier>,
    #[cfg(feature = "orchard")]
    ironwood: ScannedBundles<orchard::tree::MerkleHashOrchard, orchard::note::Nullifier>,
}

impl<AccountId> ScannedBlock<AccountId> {
    /// Constructs a new `ScannedBlock`
    pub(crate) fn from_parts(
        block_height: BlockHeight,
        block_hash: BlockHash,
        block_time: u32,
        transactions: Vec<WalletTx<AccountId>>,
        sapling: ScannedBundles<sapling::Node, sapling::Nullifier>,
        #[cfg(feature = "orchard")] orchard: ScannedBundles<
            orchard::tree::MerkleHashOrchard,
            orchard::note::Nullifier,
        >,
        #[cfg(feature = "orchard")] ironwood: ScannedBundles<
            orchard::tree::MerkleHashOrchard,
            orchard::note::Nullifier,
        >,
    ) -> Self {
        Self {
            block_height,
            block_hash,
            block_time,
            transactions,
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
            #[cfg(feature = "orchard")]
            ironwood,
        }
    }

    /// Returns the height of the block that was scanned.
    pub fn height(&self) -> BlockHeight {
        self.block_height
    }

    /// Returns the block hash of the block that was scanned.
    pub fn block_hash(&self) -> BlockHash {
        self.block_hash
    }

    /// Returns the block time of the block that was scanned, as a Unix timestamp in seconds.
    pub fn block_time(&self) -> u32 {
        self.block_time
    }

    /// Returns the list of transactions from this block that are relevant to the wallet.
    pub fn transactions(&self) -> &[WalletTx<AccountId>] {
        &self.transactions
    }

    /// Returns the Sapling note commitment tree and nullifier data for the block.
    pub fn sapling(&self) -> &ScannedBundles<sapling::Node, sapling::Nullifier> {
        &self.sapling
    }

    /// Returns the Orchard note commitment tree and nullifier data for the block.
    #[cfg(feature = "orchard")]
    pub fn orchard(
        &self,
    ) -> &ScannedBundles<orchard::tree::MerkleHashOrchard, orchard::note::Nullifier> {
        &self.orchard
    }

    /// Returns the Ironwood note commitment tree and nullifier data for the block.
    #[cfg(feature = "orchard")]
    pub fn ironwood(
        &self,
    ) -> &ScannedBundles<orchard::tree::MerkleHashOrchard, orchard::note::Nullifier> {
        &self.ironwood
    }

    /// Consumes `self` and returns the lists of Sapling, Orchard, and Ironwood note commitments
    /// associated with the scanned block as an owned value.
    pub fn into_commitments(self) -> ScannedBlockCommitments {
        ScannedBlockCommitments {
            sapling: self.sapling.commitments,
            #[cfg(feature = "orchard")]
            orchard: self.orchard.commitments,
            #[cfg(feature = "orchard")]
            ironwood: self.ironwood.commitments,
        }
    }

    /// Returns the [`BlockMetadata`] corresponding to the scanned block.
    pub fn to_block_metadata(&self) -> BlockMetadata {
        BlockMetadata {
            block_height: self.block_height,
            block_hash: self.block_hash,
            sapling_tree_size: Some(self.sapling.final_tree_size),
            #[cfg(feature = "orchard")]
            orchard_tree_size: Some(self.orchard.final_tree_size),
            #[cfg(feature = "orchard")]
            ironwood_tree_size: Some(self.ironwood.final_tree_size),
        }
    }
}

/// A trait representing a decryptable transaction.
pub trait DecryptableTransaction<AccountId> {
    type DecryptedSaplingOutput;
    #[cfg(feature = "orchard")]
    type DecryptedOrchardOutput;
}

impl<AccountId> DecryptableTransaction<AccountId> for Transaction {
    type DecryptedSaplingOutput = DecryptedOutput<sapling::Note, AccountId>;
    #[cfg(feature = "orchard")]
    type DecryptedOrchardOutput = DecryptedOutput<(orchard::Note, orchard::ValuePool), AccountId>;
}

/// A transaction that was detected during scanning of the blockchain,
/// including its decrypted Sapling and/or Orchard outputs.
///
/// The purpose of this struct is to permit atomic updates of the
/// wallet database when transactions are successfully decrypted.
pub struct DecryptedTransaction<'a, Tx: DecryptableTransaction<AccountId>, AccountId> {
    mined_height: Option<BlockHeight>,
    tx: &'a Tx,
    sapling_outputs: Vec<Tx::DecryptedSaplingOutput>,
    #[cfg(feature = "orchard")]
    orchard_outputs: Vec<Tx::DecryptedOrchardOutput>,
    #[cfg(feature = "orchard")]
    ironwood_outputs: Vec<Tx::DecryptedOrchardOutput>,
}

impl<'a, Tx: DecryptableTransaction<AccountId>, AccountId> DecryptedTransaction<'a, Tx, AccountId> {
    /// Constructs a new [`DecryptedTransaction`] from its constituent parts.
    ///
    /// Ironwood outputs are Orchard-shaped but belong to a distinct pool, and are passed and
    /// tracked separately from Orchard outputs.
    pub fn new(
        mined_height: Option<BlockHeight>,
        tx: &'a Tx,
        sapling_outputs: Vec<Tx::DecryptedSaplingOutput>,
        #[cfg(feature = "orchard")] orchard_outputs: Vec<Tx::DecryptedOrchardOutput>,
        #[cfg(feature = "orchard")] ironwood_outputs: Vec<Tx::DecryptedOrchardOutput>,
    ) -> Self {
        Self {
            mined_height,
            tx,
            sapling_outputs,
            #[cfg(feature = "orchard")]
            orchard_outputs,
            #[cfg(feature = "orchard")]
            ironwood_outputs,
        }
    }

    /// Returns the height at which the transaction was mined, if known.
    pub fn mined_height(&self) -> Option<BlockHeight> {
        self.mined_height
    }
    /// Returns the raw transaction data.
    pub fn tx(&self) -> &Tx {
        self.tx
    }
    /// Returns the Sapling outputs that were decrypted from the transaction.
    pub fn sapling_outputs(&self) -> &[Tx::DecryptedSaplingOutput] {
        &self.sapling_outputs
    }
    /// Returns the Orchard outputs that were decrypted from the transaction.
    #[cfg(feature = "orchard")]
    pub fn orchard_outputs(&self) -> &[Tx::DecryptedOrchardOutput] {
        &self.orchard_outputs
    }

    /// Returns the Ironwood outputs that were decrypted from the transaction.
    ///
    /// Ironwood outputs are Orchard-shaped but belong to a pool distinct from Orchard.
    #[cfg(feature = "orchard")]
    pub fn ironwood_outputs(&self) -> &[Tx::DecryptedOrchardOutput] {
        &self.ironwood_outputs
    }

    /// Returns whether the transaction has decrypted outputs
    pub fn has_decrypted_outputs(&self) -> bool {
        let has_sapling = !self.sapling_outputs.is_empty();
        #[cfg(feature = "orchard")]
        let has_orchard = !self.orchard_outputs.is_empty() || !self.ironwood_outputs.is_empty();
        #[cfg(not(feature = "orchard"))]
        let has_orchard = false;

        has_sapling || has_orchard
    }
}

/// A transaction that was constructed and sent by the wallet.
///
/// The purpose of this struct is to permit atomic updates of the
/// wallet database when transactions are created and submitted
/// to the network.
pub struct SentTransaction<'a, AccountId> {
    tx: &'a Transaction,
    created: time::OffsetDateTime,
    target_height: TargetHeight,
    funding_account: AccountId,
    outputs: &'a [SentTransactionOutput<AccountId>],
    fee_amount: Zatoshis,
    #[cfg(feature = "transparent-inputs")]
    utxos_spent: &'a [OutPoint],
}

impl<'a, AccountId> SentTransaction<'a, AccountId> {
    /// Constructs a new [`SentTransaction`] from its constituent parts.
    ///
    /// ### Parameters
    /// - `tx`: the raw transaction data
    /// - `created`: the system time at which the transaction was created
    /// - `target_height`: the target height that was used in the construction of the transaction
    /// - `funding_account`: the account that spent funds in creation of the transaction
    /// - `outputs`: the outputs created by the transaction, including those sent to external
    ///   recipients which may not otherwise be recoverable
    /// - `fee_amount`: the fee value paid by the transaction
    /// - `utxos_spent`: the UTXOs controlled by the wallet that were spent in this transaction
    pub fn new(
        tx: &'a Transaction,
        created: time::OffsetDateTime,
        target_height: TargetHeight,
        funding_account: AccountId,
        outputs: &'a [SentTransactionOutput<AccountId>],
        fee_amount: Zatoshis,
        #[cfg(feature = "transparent-inputs")] utxos_spent: &'a [OutPoint],
    ) -> Self {
        Self {
            tx,
            created,
            target_height,
            funding_account,
            outputs,
            fee_amount,
            #[cfg(feature = "transparent-inputs")]
            utxos_spent,
        }
    }

    /// Returns the transaction that was sent.
    pub fn tx(&self) -> &Transaction {
        self.tx
    }
    /// Returns the timestamp of the transaction's creation.
    pub fn created(&self) -> time::OffsetDateTime {
        self.created
    }
    /// Returns the id for the account that created the outputs.
    pub fn funding_account(&self) -> &AccountId {
        &self.funding_account
    }
    /// Returns the outputs of the transaction.
    pub fn outputs(&self) -> &[SentTransactionOutput<AccountId>] {
        self.outputs
    }
    /// Returns the fee paid by the transaction.
    pub fn fee_amount(&self) -> Zatoshis {
        self.fee_amount
    }
    /// Returns the list of UTXOs spent in the created transaction.
    #[cfg(feature = "transparent-inputs")]
    pub fn utxos_spent(&self) -> &[OutPoint] {
        self.utxos_spent
    }

    /// Returns the block height that this transaction was created to target.
    pub fn target_height(&self) -> TargetHeight {
        self.target_height
    }
}

/// High-level information about the output of a transaction received by the wallet.
///
/// This type is capable of representing both shielded and transparent outputs. It does not
/// internally store the transaction ID, so it must be interpreted in the context of a caller
/// having requested output information for a specific transaction.
pub struct ReceivedTransactionOutput {
    pool_type: PoolType,
    output_index: usize,
    value: Zatoshis,
    confirmations_until_spendable: u32,
}

impl ReceivedTransactionOutput {
    /// Constructs a [`ReceivedTransactionOutput`] from its constituent parts.
    pub fn from_parts(
        pool_type: PoolType,
        output_index: usize,
        value: Zatoshis,
        confirmations_until_spendable: u32,
    ) -> Self {
        Self {
            pool_type,
            output_index,
            value,
            confirmations_until_spendable,
        }
    }

    /// Returns the pool in which the output value was received.
    pub fn pool_type(&self) -> PoolType {
        self.pool_type
    }

    /// Returns the index of the output among the transaction's outputs to the associated pool.
    pub fn output_index(&self) -> usize {
        self.output_index
    }

    /// Returns the value of the output.
    pub fn value(&self) -> Zatoshis {
        self.value
    }

    /// Returns the number of confirmations required for the output to be treated as spendable,
    /// given a [`ConfirmationsPolicy`] that was specified at the time of the request for this
    /// data.
    pub fn confirmations_until_spendable(&self) -> u32 {
        self.confirmations_until_spendable
    }
}

/// Identifies one of the wallet-maintained note commitment trees.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NoteCommitmentTree {
    /// The Sapling note commitment tree.
    Sapling,
    /// The Orchard note commitment tree.
    #[cfg(feature = "orchard")]
    Orchard,
    /// The Ironwood note commitment tree.
    #[cfg(feature = "orchard")]
    Ironwood,
}

/// An output of a transaction generated by the wallet.
///
/// This type is capable of representing both shielded and transparent outputs.
pub struct SentTransactionOutput<AccountId> {
    output_index: usize,
    note_commitment_tree: Option<NoteCommitmentTree>,
    recipient: Recipient<AccountId>,
    value: Zatoshis,
    memo: Option<MemoBytes>,
}

impl<AccountId> SentTransactionOutput<AccountId> {
    /// Constructs a new [`SentTransactionOutput`] from its constituent parts.
    ///
    /// ### Fields:
    /// * `output_index` - the index of the output or action in the sent transaction
    /// * `recipient` - the recipient of the output, either a Zcash address or a
    ///   wallet-internal account and the note belonging to the wallet created by
    ///   the output
    /// * `value` - the value of the output, in zatoshis
    /// * `memo` - the memo that was sent with this output
    pub fn from_parts(
        output_index: usize,
        recipient: Recipient<AccountId>,
        value: Zatoshis,
        memo: Option<MemoBytes>,
    ) -> Self {
        Self {
            output_index,
            note_commitment_tree: None,
            recipient,
            value,
            memo,
        }
    }

    /// Constructs a new [`SentTransactionOutput`] with explicit note commitment tree metadata.
    pub(crate) fn from_parts_in_tree(
        note_commitment_tree: Option<NoteCommitmentTree>,
        output_index: usize,
        recipient: Recipient<AccountId>,
        value: Zatoshis,
        memo: Option<MemoBytes>,
    ) -> Self {
        Self {
            output_index,
            note_commitment_tree,
            recipient,
            value,
            memo,
        }
    }

    /// Returns the index within the transaction that contains the recipient output.
    ///
    /// - If `recipient_address` is a Sapling address, this is an index into the Sapling
    ///   outputs of the transaction.
    /// - If `recipient_address` is a transparent address, this is an index into the
    ///   transparent outputs of the transaction.
    pub fn output_index(&self) -> usize {
        self.output_index
    }
    /// Returns the note commitment tree for this output, if known.
    pub fn note_commitment_tree(&self) -> Option<NoteCommitmentTree> {
        self.note_commitment_tree
    }
    /// Returns the recipient address of the transaction, or the account id and
    /// resulting note/outpoint for wallet-internal outputs.
    pub fn recipient(&self) -> &Recipient<AccountId> {
        &self.recipient
    }
    /// Returns the value of the newly created output.
    pub fn value(&self) -> Zatoshis {
        self.value
    }
    /// Returns the memo that was attached to the output, if any. This will only be `None`
    /// for transparent outputs.
    pub fn memo(&self) -> Option<&MemoBytes> {
        self.memo.as_ref()
    }
}

/// A data structure used to set the birthday height for an account, and ensure that the initial
/// note commitment tree state is recorded at that height.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccountBirthday {
    prior_chain_state: ChainState,
    recover_until: Option<BlockHeight>,
}

/// Errors that can occur in the construction of an [`AccountBirthday`] from a [`TreeState`].
#[derive(Debug)]
#[non_exhaustive]
pub enum BirthdayError {
    /// The block height of the [`TreeState`] was out of range for a [`BlockHeight`].
    HeightInvalid(TryFromIntError),
    /// The note commitment tree frontiers of the [`TreeState`] could not be decoded.
    Decode(io::Error),
}

impl fmt::Display for BirthdayError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BirthdayError::HeightInvalid(e) => {
                write!(f, "Invalid block height for account birthday: {e}")
            }
            BirthdayError::Decode(e) => write!(
                f,
                "Failed to decode the note commitment tree state for the account birthday: {e}"
            ),
        }
    }
}

impl std::error::Error for BirthdayError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            BirthdayError::HeightInvalid(e) => Some(e),
            BirthdayError::Decode(e) => Some(e),
        }
    }
}

impl From<TryFromIntError> for BirthdayError {
    fn from(value: TryFromIntError) -> Self {
        Self::HeightInvalid(value)
    }
}

impl From<io::Error> for BirthdayError {
    fn from(value: io::Error) -> Self {
        Self::Decode(value)
    }
}

impl AccountBirthday {
    /// Constructs a new [`AccountBirthday`] from its constituent parts.
    ///
    /// * `prior_chain_state`: The chain state prior to the birthday height of the account. The
    ///   birthday height is defined as the height of the first block to be scanned in wallet
    ///   recovery.
    /// * `recover_until`: An optional height at which the wallet should exit "recovery mode". In
    ///   order to avoid confusing shifts in wallet balance and spendability that may temporarily be
    ///   visible to a user during the process of recovering from seed, wallets may optionally set a
    ///   "recover until" height. The wallet is considered to be in "recovery mode" until there
    ///   exist no unscanned ranges between the wallet's birthday height and the provided
    ///   `recover_until` height, exclusive.
    pub fn from_parts(prior_chain_state: ChainState, recover_until: Option<BlockHeight>) -> Self {
        Self {
            prior_chain_state,
            recover_until,
        }
    }

    /// Constructs a new [`AccountBirthday`] from a [`TreeState`] returned from `lightwalletd`.
    ///
    /// * `treestate`: The tree state corresponding to the last block prior to the wallet's
    ///   birthday height.
    /// * `recover_until`: An optional height at which the wallet should exit "recovery mode". In
    ///   order to avoid confusing shifts in wallet balance and spendability that may temporarily be
    ///   visible to a user during the process of recovering from seed, wallets may optionally set a
    ///   "recover until" height. The wallet is considered to be in "recovery mode" until there
    ///   exist no unscanned ranges between the wallet's birthday height and the provided
    ///   `recover_until` height, exclusive.
    pub fn from_treestate(
        treestate: TreeState,
        recover_until: Option<BlockHeight>,
    ) -> Result<Self, BirthdayError> {
        Ok(Self {
            prior_chain_state: treestate.to_chain_state()?,
            recover_until,
        })
    }

    /// Returns the Sapling note commitment tree frontier as of the end of the block at
    /// [`Self::height`].
    pub fn sapling_frontier(
        &self,
    ) -> &Frontier<sapling::Node, { sapling::NOTE_COMMITMENT_TREE_DEPTH }> {
        self.prior_chain_state.final_sapling_tree()
    }

    /// Returns the Orchard note commitment tree frontier as of the end of the block at
    /// [`Self::height`].
    #[cfg(feature = "orchard")]
    pub fn orchard_frontier(
        &self,
    ) -> &Frontier<orchard::tree::MerkleHashOrchard, { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 }>
    {
        self.prior_chain_state.final_orchard_tree()
    }

    /// Returns the birthday height of the account.
    pub fn height(&self) -> BlockHeight {
        self.prior_chain_state.block_height() + 1
    }

    /// Returns the height at which the wallet should exit "recovery mode".
    pub fn recover_until(&self) -> Option<BlockHeight> {
        self.recover_until
    }

    /// Returns the [`ChainState`] corresponding to the last block prior to the wallet's birthday
    pub fn prior_chain_state(&self) -> &ChainState {
        &self.prior_chain_state
    }

    #[cfg(any(test, feature = "test-dependencies"))]
    /// Constructs a new [`AccountBirthday`] at the given network upgrade's activation,
    /// with no "recover until" height.
    ///
    /// # Panics
    ///
    /// Panics if the activation height for the given network upgrade is not set.
    pub fn from_activation<P: zcash_protocol::consensus::Parameters>(
        params: &P,
        network_upgrade: NetworkUpgrade,
        prior_block_hash: BlockHash,
    ) -> AccountBirthday {
        AccountBirthday::from_parts(
            ChainState::empty(
                params.activation_height(network_upgrade).unwrap() - 1,
                prior_block_hash,
            ),
            None,
        )
    }

    #[cfg(any(test, feature = "test-dependencies"))]
    /// Constructs a new [`AccountBirthday`] at Sapling activation, with no
    /// "recover until" height.
    ///
    /// # Panics
    ///
    /// Panics if the Sapling activation height is not set.
    pub fn from_sapling_activation<P: zcash_protocol::consensus::Parameters>(
        params: &P,
        prior_block_hash: BlockHash,
    ) -> AccountBirthday {
        Self::from_activation(params, NetworkUpgrade::Sapling, prior_block_hash)
    }
}

/// This trait encapsulates the write capabilities required to update stored wallet data.
///
/// # Adding accounts
///
/// This trait provides several methods for adding accounts to the wallet data:
/// - [`WalletWrite::create_account`]
/// - [`WalletWrite::import_account_hd`]
/// - [`WalletWrite::import_account_ufvk`]
///
/// All of these methods take an [`AccountBirthday`]. The birthday height is defined as
/// the minimum block height that will be scanned for funds belonging to the wallet. If
/// `birthday.height()` is below the current chain tip, the account addition operation
/// will trigger a re-scan of the blocks at and above the provided height.
///
/// The order in which you call these methods will affect the resulting wallet structure:
/// - If only [`WalletWrite::create_account`] is used, the resulting accounts will have
///   sequential [ZIP 32] account indices within each given seed.
/// - If [`WalletWrite::import_account_hd`] is used to import accounts with non-sequential
///   ZIP 32 account indices from the same seed, a call to [`WalletWrite::create_account`]
///   will use the ZIP 32 account index just after the highest-numbered existing account.
/// - If an account is added to the wallet, and then a later call to one of the methods
///   would produce a UFVK that collides with that account on any FVK component (i.e.
///   Sapling, Orchard, or transparent), an error will be returned. This can occur in the
///   following cases:
///   - An account is created via [`WalletWrite::create_account`] with an auto-selected
///     ZIP 32 account index, and that index is later imported explicitly via either
///     [`WalletWrite::import_account_ufvk`] or [`WalletWrite::import_account_hd`].
///   - An account is imported via [`WalletWrite::import_account_ufvk`] or
///     [`WalletWrite::import_account_hd`], and then the ZIP 32 account index
///     corresponding to that account's UFVK is later imported either implicitly
///     via [`WalletWrite::create_account`], or explicitly via a call to
///     [`WalletWrite::import_account_ufvk`] or [`WalletWrite::import_account_hd`].
///
/// Note that an error will be returned on an FVK collision even if the UFVKs do not
/// match exactly, e.g. if they have different subsets of components.
///
/// An account is treated as having a single root of spending authority that spans the shielded and
/// transparent rules for the purpose of balance, transaction listing, and so forth. However,
/// transparent keys imported via `WalletWrite::import_standalone_transparent_pubkey` or
/// `WalletWrite::import_standalone_transparent_script` (available with the
/// `transparent-key-import` feature) break this abstraction slightly, so wallets using this API
/// need to be cautious to enforce the invariant that the wallet either maintains access to the
/// keys required to spend **ALL** outputs received by the account, or that it **DOES NOT** offer
/// any spending capability for the account, i.e. the account is treated as view-only for all
/// user-facing operations.
///
/// A future change to this trait might introduce a method to "upgrade" an imported
/// account with derivation information. See [zcash/librustzcash#1284] for details.
///
/// Users of the `WalletWrite` trait should generally distinguish in their APIs and wallet UIs
/// between creating a new account, and importing an account that previously existed. By
/// convention, wallets should only allow a new account to be generated for a seed after confirmed
/// funds have been received by the newest existing account for that seed; this allows automated
/// account recovery to discover and recover all funds within a particular seed.
///
/// # Creating a new wallet
///
/// To create a new wallet:
/// - Generate a new [BIP 39] mnemonic phrase, using a crate like [`bip0039`].
/// - Derive the corresponding seed from the mnemonic phrase.
/// - Use [`WalletWrite::create_account`] with the resulting seed.
///
/// Callers should construct the [`AccountBirthday`] using [`AccountBirthday::from_treestate`] for
/// the block at height `chain_tip_height - 100`. Setting the birthday height to a tree state below
/// the pruning depth ensures that reorgs cannot cause funds intended for the wallet to be missed;
/// otherwise, if the chain tip height were used for the wallet birthday, a transaction targeted at
/// a height greater than the chain tip could be mined at a height below that tip as part of a
/// reorg.
///
/// # Restoring a wallet from backup
///
/// To restore a backed-up wallet:
/// - Derive the seed from its BIP 39 mnemonic phrase.
/// - Use [`WalletWrite::import_account_hd`] once for each ZIP 32 account index that the
///   user wants to restore.
/// - If the highest previously-used ZIP 32 account index was _not_ restored by the user,
///   remember this index separately as `index_max`. The first time the user wants to
///   generate a new account, use [`WalletWrite::import_account_hd`] to create the account
///   `index_max + 1`.
/// - [`WalletWrite::create_account`] can be used to generate subsequent new accounts in
///   the restored wallet.
///
/// Automated account recovery has not yet been implemented by this crate. A wallet app
/// that supports multiple accounts can implement it manually by tracking account balances
/// relative to [`WalletSummary::fully_scanned_height`], and creating new accounts as
/// funds appear in existing accounts.
///
/// If the number of accounts is known in advance, the wallet should create all accounts before
/// scanning the chain so that the scan can be done in a single pass for all accounts.
///
/// [ZIP 32]: https://zips.z.cash/zip-0032
/// [zcash/librustzcash#1284]: https://github.com/zcash/librustzcash/issues/1284
/// [BIP 39]: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
/// [`bip0039`]: https://crates.io/crates/bip0039
#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
pub trait WalletWrite:
    WalletRead
    + OutputLockStore<
        AccountId = <Self as WalletRead>::AccountId,
        Error = <Self as WalletRead>::Error,
    >
{
    /// The type of identifiers used to look up transparent UTXOs.
    type UtxoRef;

    /// Tells the wallet to track the next available account-level spend authority for the provided
    /// seed value, given the current set of [ZIP 316] account identifiers known to the wallet database.
    ///
    /// The "next available account" is defined as the ZIP-32 account index immediately following
    /// the highest existing account index among all accounts in the wallet that share the given
    /// seed. Users of the [`WalletWrite`] trait that only call this method are guaranteed to have
    /// accounts with sequential indices.
    ///
    /// Returns the account identifier for the newly-created wallet database entry, along with the
    /// associated [`UnifiedSpendingKey`]. Note that the unique account identifier should *not* be
    /// assumed equivalent to the ZIP 32 account index. It is an opaque identifier for a pool of
    /// funds or set of outputs controlled by a single spending authority.
    ///
    /// The ZIP-32 account index may be obtained by calling [`WalletRead::get_account`]
    /// with the returned account identifier.
    ///
    /// The [`WalletWrite`] trait documentation has more details about account creation and import.
    ///
    /// # Arguments
    /// - `account_name`: A human-readable name for the account.
    /// - `seed`: The 256-byte (at least) HD seed from which to derive the account UFVK.
    /// - `birthday`: Metadata about where to start scanning blocks to find transactions intended
    ///   for the account.
    /// - `key_source`: A string identifier or other metadata describing the source of the seed.
    ///   This is treated as opaque metadata by the wallet backend; it is provided for use by
    ///   applications which need to track additional identifying information for an account.
    ///
    /// # Implementation notes
    ///
    /// Implementations of this method **MUST NOT** "fill in gaps" by selecting an account index
    /// that is lower than any existing account index among all accounts in the wallet that share
    /// the given seed.
    ///
    /// # Panics
    ///
    /// Panics if the length of the seed is not between 32 and 252 bytes inclusive.
    ///
    /// [ZIP 316]: https://zips.z.cash/zip-0316
    fn create_account(
        &mut self,
        account_name: &str,
        seed: &SecretVec<u8>,
        birthday: &AccountBirthday,
        key_source: Option<&str>,
    ) -> Result<(<Self as WalletRead>::AccountId, UnifiedSpendingKey), <Self as WalletRead>::Error>;

    /// Tells the wallet to track a specific account index for a given seed.
    ///
    /// Returns details about the imported account, including the unique account identifier for
    /// the newly-created wallet database entry, along with the associated [`UnifiedSpendingKey`].
    /// Note that the unique account identifier should *not* be assumed equivalent to the ZIP 32
    /// account index. It is an opaque identifier for a pool of funds or set of outputs controlled
    /// by a single spending authority.
    ///
    /// Import accounts with indices that are exactly one greater than the highest existing account
    /// index to ensure account indices are contiguous, thereby facilitating automated account
    /// recovery.
    ///
    /// The [`WalletWrite`] trait documentation has more details about account creation and import.
    ///
    /// # Arguments
    /// - `account_name`: A human-readable name for the account.
    /// - `seed`: The 256-byte (at least) HD seed from which to derive the account UFVK.
    /// - `account_index`: The ZIP 32 account-level component of the HD derivation path at
    ///   which to derive the account's UFVK.
    /// - `birthday`: Metadata about where to start scanning blocks to find transactions intended
    ///   for the account.
    /// - `key_source`: A string identifier or other metadata describing the source of the seed.
    ///   This is treated as opaque metadata by the wallet backend; it is provided for use by
    ///   applications which need to track additional identifying information for an account.
    ///
    /// # Panics
    ///
    /// Panics if the length of the seed is not between 32 and 252 bytes inclusive.
    ///
    /// [ZIP 316]: https://zips.z.cash/zip-0316
    fn import_account_hd(
        &mut self,
        account_name: &str,
        seed: &SecretVec<u8>,
        account_index: zip32::AccountId,
        birthday: &AccountBirthday,
        key_source: Option<&str>,
    ) -> Result<(Self::Account, UnifiedSpendingKey), <Self as WalletRead>::Error>;

    /// Tells the wallet to track an account using a unified full viewing key.
    ///
    /// Returns details about the imported account, including the unique account identifier for
    /// the newly-created wallet database entry. Unlike the other account creation APIs
    /// ([`Self::create_account`] and [`Self::import_account_hd`]), no spending key is returned
    /// because the wallet has no information about how the UFVK was derived.
    ///
    /// Certain optimizations are possible for accounts which will never be used to spend funds. If
    /// `spending_key_available` is `false`, the wallet may choose to optimize for this case, in
    /// which case any attempt to spend funds from the account will result in an error.
    ///
    /// The [`WalletWrite`] trait documentation has more details about account creation and import.
    ///
    /// # Arguments
    /// - `account_name`: A human-readable name for the account.
    /// - `unified_key`: The UFVK used to detect transactions involving the account.
    /// - `birthday`: Metadata about where to start scanning blocks to find transactions intended
    ///   for the account.
    /// - `purpose`: Metadata describing whether or not data required for spending should be
    ///   tracked by the wallet.
    /// - `key_source`: A string identifier or other metadata describing the source of the seed.
    ///   This is treated as opaque metadata by the wallet backend; it is provided for use by
    ///   applications which need to track additional identifying information for an account.
    fn import_account_ufvk(
        &mut self,
        account_name: &str,
        unified_key: &UnifiedFullViewingKey,
        birthday: &AccountBirthday,
        purpose: AccountPurpose,
        key_source: Option<&str>,
    ) -> Result<Self::Account, <Self as WalletRead>::Error>;

    /// Deletes the specified account, and all transactions that exclusively involve it, from the
    /// wallet database.
    ///
    /// WARNING: This is a destructive operation and may result in the permanent loss of
    /// potentially important information that is not recoverable from chain data, including:
    /// * Data about transactions sent by the account for which [`OvkPolicy::Discard`] (or
    ///   [`OvkPolicy::Custom`] with random OVKs) was used;
    /// * Data related to transactions that the account attempted to send that expired or were
    ///   otherwise invalidated without having been mined in the main chain;
    /// * Data related to transactions that were observed in the mempool as having inputs or
    ///   outputs that involved the account, but that were never mined in the main chain;
    /// * Data related to transactions that were received by the wallet in a mined block, where
    ///   that block was later un-mined in a chain reorg and the transaction was either invalidated
    ///   or was never re-mined.
    ///
    /// [`OvkPolicy::Discard`]: crate::wallet::OvkPolicy::Discard
    /// [`OvkPolicy::Custom`]: crate::wallet::OvkPolicy::Custom
    fn delete_account(
        &mut self,
        account: <Self as WalletRead>::AccountId,
    ) -> Result<(), <Self as WalletRead>::Error>;

    /// Imports the given pubkey into the account without key derivation information, and adds the
    /// associated transparent p2pkh address.
    ///
    /// The imported address will contribute to the balance of the account (for UFVK-based
    /// accounts), but spending funds held by this address requires the associated spending keys to
    /// be provided explicitly when calling [`create_proposed_transactions`]. By extension, calls
    /// to [`propose_shielding`] must only include addresses for which the spending application
    /// holds or can obtain the spending keys.
    ///
    /// [`create_proposed_transactions`]: crate::data_api::wallet::create_proposed_transactions
    /// [`propose_shielding`]: crate::data_api::wallet::propose_shielding
    #[cfg(feature = "transparent-key-import")]
    fn import_standalone_transparent_pubkey(
        &mut self,
        _account: <Self as WalletRead>::AccountId,
        _pubkey: secp256k1::PublicKey,
    ) -> Result<(), <Self as WalletRead>::Error> {
        unimplemented!(
            "WalletWrite::import_standalone_transparent_pubkey must be overridden for wallets to use the `transparent-key-import` feature"
        )
    }

    /// Imports a batch of standalone transparent pubkeys into the account, adding the associated
    /// transparent p2pkh addresses. See [`import_standalone_transparent_pubkey`] for the semantics
    /// and spending limitations that apply to each imported pubkey.
    ///
    /// This is equivalent to calling [`import_standalone_transparent_pubkey`] once per pubkey, but
    /// implementations may validate the target account a single time for the whole batch. The
    /// default implementation calls [`import_standalone_transparent_pubkey`] for each pubkey; a
    /// pubkey whose receiver address is already known to the wallet is skipped.
    ///
    /// [`import_standalone_transparent_pubkey`]: Self::import_standalone_transparent_pubkey
    #[cfg(feature = "transparent-key-import")]
    fn import_standalone_transparent_pubkeys(
        &mut self,
        account: <Self as WalletRead>::AccountId,
        pubkeys: &[secp256k1::PublicKey],
    ) -> Result<(), <Self as WalletRead>::Error> {
        for pubkey in pubkeys {
            self.import_standalone_transparent_pubkey(account, *pubkey)?;
        }
        Ok(())
    }

    /// Imports the given redeem script into the account without key derivation information, and
    /// adds the associated transparent p2sh address.
    ///
    /// The imported address will contribute to the balance of the account (for UFVK-based
    /// accounts), but spending funds held by this address requires the associated spending keys to
    /// be provided explicitly when calling [`create_proposed_transactions`]. By extension, calls
    /// to [`propose_shielding`] must only include addresses for which the spending application
    /// holds or can obtain the spending keys.
    ///
    /// [`create_proposed_transactions`]: crate::data_api::wallet::create_proposed_transactions
    /// [`propose_shielding`]: crate::data_api::wallet::propose_shielding
    ///
    /// # Spending limitations
    ///
    /// P2PKH-in-P2SH scripts are unsupported by PCZT at this time, so the only way to spend
    /// from such an address is to use the [`create_proposed_transactions`] signing path.
    #[cfg(feature = "transparent-key-import")]
    fn import_standalone_transparent_script(
        &mut self,
        _account: <Self as WalletRead>::AccountId,
        _script: zcash_script::script::Redeem,
    ) -> Result<(), <Self as WalletRead>::Error> {
        unimplemented!(
            "WalletWrite::import_standalone_transparent_script must be overridden for wallets to use the `transparent-key-import` feature"
        )
    }

    /// Generates, persists, and marks as exposed the next available diversified address for the
    /// specified account, given the current addresses known to the wallet.
    ///
    /// Returns `Ok(None)` if the account identifier does not correspond to a known
    /// account.
    fn get_next_available_address(
        &mut self,
        account: <Self as WalletRead>::AccountId,
        request: UnifiedAddressRequest,
    ) -> Result<Option<(UnifiedAddress, DiversifierIndex)>, <Self as WalletRead>::Error>;

    /// Generates, persists, and marks as exposed a diversified address for the specified account
    /// at the provided diversifier index.
    ///
    /// Returns `Ok(None)` in the case that it is not possible to generate an address conforming
    /// to the provided request at the specified diversifier index. Such a result might arise from
    /// the diversifier index not being valid for a [`ReceiverRequirement::Require`]'ed receiver.
    /// Some implementations of this trait may return `Err(_)` in some cases to expose more
    /// information, which is only accessible in a backend-specific context.
    ///
    /// Address generation should fail if an address has already been exposed for the given
    /// diversifier index and the given request produced an address having different receivers than
    /// what was originally exposed.
    ///
    /// # WARNINGS
    /// If an address generated using this method has a transparent receiver and the
    /// chosen diversifier index would be outside the wallet's internally-configured gap limit,
    /// funds sent to these address are **likely to not be discovered on recovery from seed**. It
    /// up to the caller of this method to either ensure that they only request transparent
    /// receivers with indices within the range of a reasonable gap limit, or that they ensure that
    /// their wallet provides backup facilities that can be used to ensure that funds sent to such
    /// addresses are recoverable after a loss of wallet data.
    ///
    /// [`ReceiverRequirement::Require`]: zcash_keys::keys::ReceiverRequirement::Require
    fn get_address_for_index(
        &mut self,
        account: <Self as WalletRead>::AccountId,
        diversifier_index: DiversifierIndex,
        request: UnifiedAddressRequest,
    ) -> Result<Option<UnifiedAddress>, <Self as WalletRead>::Error>;

    /// Updates the wallet's view of the blockchain.
    ///
    /// This method is used to provide the wallet with information about the state of the
    /// blockchain, and detect any previously scanned data that needs to be re-validated
    /// before proceeding with scanning. It should be called at wallet startup prior to calling
    /// [`WalletRead::suggest_scan_ranges`] in order to provide the wallet with the information it
    /// needs to correctly prioritize scanning operations.
    fn update_chain_tip(
        &mut self,
        tip_height: BlockHeight,
    ) -> Result<(), <Self as WalletRead>::Error>;

    /// Drops the scan work queued below `height`, except where retained by
    /// `retain_with_priority`. Returns the number of queue entries removed or altered.
    ///
    /// If `retain_with_priority` is `None`, no entries below `height` are retained,
    /// irrespective of their priority. If it is `Some(priority)`, entries with that
    /// priority and greater are retained (left untouched, even where they straddle
    /// `height`), as are entries with the bookkeeping priorities
    /// [`ScanPriority::Scanned`] and [`ScanPriority::Ignored`] — those record which
    /// regions of the chain the backend has already covered or deliberately skips, and
    /// removing them would cause the backend to forget coverage state it maintains
    /// itself (use the `None` form when that full reset is the intent). Entries with
    /// priorities between the bookkeeping ones and the retained threshold are pruned.
    ///
    /// Pruning must not leave a gap in the queue's coverage: implementations are required
    /// to preserve contiguity across whatever remains below `height`, which in general
    /// means demoting pruned ranges to [`ScanPriority::Ignored`] rather than deleting them
    /// outright. Only coverage below the lowest retained entry may be deleted, since that
    /// merely raises the floor of the queue. A caller may therefore observe that the total
    /// span of the queue is unchanged and that the pruned region is now `Ignored`.
    ///
    /// This is a queue-hygiene operation. The primary use case is discarding historic scan
    /// ranges that no remaining account justifies: [`WalletWrite::delete_account`] does not
    /// modify the scan queue, so the deep ranges queued for a since-deleted account's
    /// birthday would otherwise still be scanned even though no remaining account can have
    /// notes below its own birthday. In that case, pass the wallet birthday
    /// ([`WalletRead::get_wallet_birthday`]) as `height` and retain
    /// [`ScanPriority::OpenAdjacent`] and greater — the priorities that may legitimately
    /// reach below the wallet birthday in service of note witnesses.
    fn prune_scan_queue_below(
        &mut self,
        height: BlockHeight,
        retain_with_priority: Option<ScanPriority>,
    ) -> Result<u64, <Self as WalletRead>::Error>;

    /// Updates the state of the wallet database by persisting the provided block information,
    /// along with the note commitments that were detected when scanning the block for transactions
    /// pertaining to this wallet.
    ///
    /// ### Arguments
    /// - `from_state` must be the chain state for the block height prior to the first
    ///   block in `blocks`.
    /// - `blocks` must be sequential, in order of increasing block height.
    fn put_blocks(
        &mut self,
        from_state: &ChainState,
        blocks: Vec<ScannedBlock<<Self as WalletRead>::AccountId>>,
    ) -> Result<(), <Self as WalletRead>::Error>;

    /// Adds a transparent UTXO received by the wallet to the data store.
    fn put_received_transparent_utxo(
        &mut self,
        output: &WalletTransparentOutput<<Self as WalletRead>::AccountId>,
    ) -> Result<Self::UtxoRef, <Self as WalletRead>::Error>;

    /// Caches a decrypted transaction in the persistent wallet store.
    fn store_decrypted_tx(
        &mut self,
        received_tx: DecryptedTransaction<Transaction, <Self as WalletRead>::AccountId>,
    ) -> Result<(), <Self as WalletRead>::Error>;

    /// Sets the trust status of the given transaction to either trusted or untrusted.
    ///
    /// The outputs of a trusted transaction will be available for spending with
    /// [`ConfirmationsPolicy::trusted`] confirmations even if the output is not wallet-internal.
    fn set_tx_trust(
        &mut self,
        txid: TxId,
        trusted: bool,
    ) -> Result<(), <Self as WalletRead>::Error>;

    /// Saves information about transactions constructed by the wallet to the persistent
    /// wallet store.
    ///
    /// This must be called before the transactions are sent to the network.
    ///
    /// Transactions that have been stored by this method should be retransmitted while it
    /// is still possible that they could be mined.
    ///
    /// Implementations must unlock any locked outputs that are recorded as spent by the
    /// stored transactions. Once spend records exist, the outputs are protected from
    /// double-selection by the spend tracking mechanism, so the explicit locks are no
    /// longer needed.
    fn store_transactions_to_be_sent(
        &mut self,
        transactions: &[SentTransaction<<Self as WalletRead>::AccountId>],
    ) -> Result<(), <Self as WalletRead>::Error>;

    /// Truncates the wallet database to at most the specified height.
    ///
    /// Implementations of this method may choose a lower block height to which the data store will
    /// be truncated if it is not possible to truncate exactly to the specified height. Upon
    /// successful truncation, this method returns the height to which the data store was actually
    /// truncated.
    ///
    /// This method assumes that the state of the underlying data store is consistent up to a
    /// particular block height. Since it is possible that a chain reorg might invalidate some
    /// stored state, this method must be implemented in order to allow users of this API to
    /// "reset" the data store to correctly represent chainstate as of at most the requested block
    /// height.
    ///
    /// After calling this method, the block at the returned height will be the most recent block
    /// and all other operations will treat this block as the chain tip for balance determination
    /// purposes.
    ///
    /// There may be restrictions on heights to which it is possible to truncate. Specifically, it
    /// will only be possible to truncate to heights at which is is possible to create a witness
    /// given the current state of the wallet's note commitment tree.
    fn truncate_to_height(
        &mut self,
        max_height: BlockHeight,
    ) -> Result<BlockHeight, <Self as WalletRead>::Error>;

    /// Truncates the wallet database to the specified chain state.
    ///
    /// In contrast to [`truncate_to_height`], this method allows the caller to truncate the wallet
    /// database to a precise height by providing additional chain state information needed for
    /// note commitment tree maintenance after the truncation.
    ///
    /// [`truncate_to_height`]: WalletWrite::truncate_to_height
    fn truncate_to_chain_state(
        &mut self,
        chain_state: ChainState,
    ) -> Result<(), <Self as WalletRead>::Error>;

    /// Rewinds the wallet to the specified chain state, preserving wallet data which has been
    /// confirmed beyond the pruning depth, and lowering the birthday height of selected accounts
    /// to the block following the chain state.
    ///
    /// In contrast to [`truncate_to_chain_state`], which unconditionally removes wallet state
    /// above `chain_state.block_height()`, this rewinds the scan queue to the target height but
    /// only rewinds blocks, note commitment trees, transactions, transparent UTXO observations,
    /// and nullifier-map entries as far back as the implementation's pruning floor; data at or
    /// below that floor is preserved.
    ///
    /// `reset_account_birthdays` selects which accounts (if any) may have their birthday
    /// metadata lowered as a result of this rewind. The semantics are:
    ///
    /// - Every account in `reset_account_birthdays` has its birthday metadata updated to
    ///   `chain_state.block_height() + 1` (with corresponding tree sizes taken from
    ///   `chain_state`) if and only if the new birthday is less than the account's existing
    ///   birthday. Existing birthdays are never raised by this method.
    /// - Accounts that are *not* in `reset_account_birthdays` are never modified, regardless of
    ///   the rewind target. Note that this only governs per-account birthday metadata:
    ///   rescanning of blocks that re-enter the scan queue applies to *all* accounts in the
    ///   wallet, since scanning is performed against all viewing keys.
    /// - If `reset_account_birthdays` is empty and *every* account in the wallet has a birthday
    ///   greater than `chain_state.block_height() + 1` (the value to which a reset birthday
    ///   would be lowered), this method returns [`RewindError::RewindBeyondBirthdays`] and no
    ///   other state is modified. So long as at least one account in the wallet already has a
    ///   birthday at or below `chain_state.block_height() + 1`, this error is not returned —
    ///   such an account already provides the wallet with an anchor at or below the new
    ///   birthday floor, so no reset is required. The reported map contains every account in
    ///   the wallet along with its existing birthday height; the caller may re-invoke the
    ///   method with any subset of those accounts included in `reset_account_birthdays`.
    ///
    /// Implementations may also return an [`Err`] (typically via [`RewindError::DataSource`])
    /// if `reset_account_birthdays` contains identifiers that do not correspond to accounts in
    /// the wallet.
    ///
    /// [`truncate_to_chain_state`]: WalletWrite::truncate_to_chain_state
    fn rewind_to_chain_state(
        &mut self,
        chain_state: ChainState,
        reset_account_birthdays: HashSet<<Self as WalletRead>::AccountId>,
    ) -> Result<(), RewindError<<Self as WalletRead>::AccountId, <Self as WalletRead>::Error>>;

    /// Reserves the next `n` available ephemeral addresses for the given account.
    /// This cannot be undone, so as far as possible, errors associated with transaction
    /// construction should have been reported before calling this method.
    ///
    /// To ensure that sufficient information is stored on-chain to allow recovering
    /// funds sent back to any of the used addresses, a "gap limit" of 20 addresses
    /// should be observed as described in [BIP 44].
    ///
    /// Returns an error if there is insufficient space within the gap limit to allocate
    /// the given number of addresses, or if the account identifier does not correspond
    /// to a known account.
    ///
    /// [BIP 44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#user-content-Address_gap_limit
    #[cfg(feature = "transparent-inputs")]
    fn reserve_next_n_ephemeral_addresses(
        &mut self,
        _account_id: <Self as WalletRead>::AccountId,
        _n: usize,
    ) -> Result<Vec<(TransparentAddress, TransparentAddressMetadata)>, <Self as WalletRead>::Error>
    {
        unimplemented!(
            "WalletWrite::reserve_next_n_ephemeral_addresses must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Reserves the next `n` available internal-scope (change) transparent addresses for
    /// the given account, as described in [BIP 44] under the `change` path level. This
    /// cannot be undone, so as far as possible, errors associated with transaction
    /// construction should have been reported before calling this method.
    ///
    /// Internal-scope transparent addresses are used to receive change for transactions
    /// having fully-transparent value flows, when the change strategy in use is configured
    /// with [`TransparentChangePolicy::TransparentChangeAllowed`].
    ///
    /// To ensure that funds sent to internal-scope addresses are recoverable, implementations
    /// of this method should observe a gap limit as described in [BIP 44]; change addresses
    /// receive funds immediately upon reservation, so a smaller gap limit than the one used
    /// for external addresses may be observed.
    ///
    /// Returns an error if there is insufficient space within the gap limit to allocate
    /// the given number of addresses, or if the account identifier does not correspond
    /// to a known account.
    ///
    /// [BIP 44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
    /// [`TransparentChangePolicy::TransparentChangeAllowed`]: crate::fees::TransparentChangePolicy::TransparentChangeAllowed
    #[cfg(feature = "transparent-inputs")]
    fn reserve_next_n_internal_addresses(
        &mut self,
        _account_id: <Self as WalletRead>::AccountId,
        _n: usize,
    ) -> Result<Vec<(TransparentAddress, TransparentAddressMetadata)>, <Self as WalletRead>::Error>
    {
        unimplemented!(
            "WalletWrite::reserve_next_n_internal_addresses must be overridden for wallets to \
             create transactions that produce transparent change"
        )
    }

    /// Updates the wallet backend with respect to the status of a specific transaction, from the
    /// perspective of the main chain.
    ///
    /// Fully transparent transactions, and transactions that do not contain either shielded inputs
    /// or shielded outputs belonging to the wallet, may not be discovered by the process of chain
    /// scanning; as a consequence, the wallet must actively query to determine whether such
    /// transactions have been mined.
    fn set_transaction_status(
        &mut self,
        _txid: TxId,
        _status: TransactionStatus,
    ) -> Result<(), <Self as WalletRead>::Error>;

    /// Schedules a UTXO check for the given address at a random time that has an expected value of
    /// `offset_seconds` from the current system time.
    ///
    /// Returns the time at which the check has been scheduled, or `None` if the address is not
    /// being tracked by the wallet.
    #[cfg(feature = "transparent-inputs")]
    fn schedule_next_check(
        &mut self,
        _address: &TransparentAddress,
        _offset_seconds: u32,
    ) -> Result<Option<SystemTime>, <Self as WalletRead>::Error> {
        unimplemented!(
            "WalletWrite::schedule_next_check must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Informs the wallet backend that the given transparent addresses are known to have been
    /// exposed externally at or before the block height paired with each address.
    ///
    /// This method is intended for use when a wallet has learned, through means outside the
    /// observation of the chain by this backend, that addresses under the wallet's control have
    /// been disclosed to an external party. Calling this method ensures that the wallet's exposure
    /// metadata accounts for the earlier disclosures.
    ///
    /// If the wallet already tracks an earlier exposure for an address, the earlier height is
    /// retained.
    ///
    /// The operation is atomic: if any address in `exposures` is not known to the wallet,
    /// implementations must roll back all updates performed during the call and return an
    /// implementation-defined error identifying the first unrecognized address.
    /// Passing an empty slice is a no-op.
    #[cfg(feature = "transparent-inputs")]
    fn mark_transparent_addresses_exposed(
        &mut self,
        _exposures: &[(TransparentAddress, BlockHeight)],
    ) -> Result<(), <Self as WalletRead>::Error> {
        unimplemented!(
            "WalletWrite::mark_transparent_addresses_exposed must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Notifies the wallet backend that the given query for transactions involving a particular
    /// address has completed evaluation.
    ///
    /// # Arguments
    /// - `request`: the [`TransactionsInvolvingAddress`] request that was executed.
    /// - `as_of_height`: The maximum height among blocks that were inspected in the process of
    ///   performing the requested check.
    #[cfg(feature = "transparent-inputs")]
    fn notify_address_checked(
        &mut self,
        _request: TransactionsInvolvingAddress,
        _as_of_height: BlockHeight,
    ) -> Result<(), <Self as WalletRead>::Error> {
        unimplemented!(
            "WalletWrite::notify_address_checked must be overridden for wallets to use the `transparent-inputs` feature"
        )
    }

    /// Notifies the wallet backend that a specific transparent output was confirmed unspent as of
    /// the given height, in response to a [`TransactionDataRequest::GetSpendingTx`]
    /// request.
    ///
    /// # Arguments
    /// - `outpoint`: the transparent outpoint whose spend status was checked.
    /// - `as_of_height`: the maximum height among blocks that were inspected, and through which
    ///   the outpoint is confirmed to remain unspent.
    #[cfg(feature = "spend-index")]
    fn notify_output_verified_unspent(
        &mut self,
        _outpoint: OutPoint,
        _as_of_height: BlockHeight,
    ) -> Result<(), <Self as WalletRead>::Error> {
        unimplemented!(
            "WalletWrite::notify_output_verified_unspent must be overridden for wallets to use the `spend-index` feature"
        )
    }
}

/// Applies a batch of note commitment tree changes — shards, an optional replacement tree
/// cap, and a checkpoint delta — directly to the given tree's backing [`ShardStore`].
///
/// `shards` must be in ascending shard-index order; stores may reject sequences that would
/// leave gaps in the tree. Checkpoint removals are applied before additions, so that a
/// checkpoint whose data has changed may appear in both lists.
///
/// This is the shared implementation of the [`WalletCommitmentTrees`] `put_*_shards`
/// provided methods.
///
/// NOTE: This procedure must be called only within a the context of a transaction, such as
/// in the scope of a `with_*_tree_mut` call; otherwise, failure of an intermediate step could
/// lead to data corruption.
fn apply_tree_changes<H, S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
    tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
    shards: &[shardtree::LocatedPrunableTree<H>],
    cap: Option<&shardtree::PrunableTree<H>>,
    checkpoints_remove: &[BlockHeight],
    checkpoints_add: &[(BlockHeight, shardtree::store::Checkpoint)],
) -> Result<(), ShardTreeError<S::Error>>
where
    H: incrementalmerkletree::Hashable + Clone + PartialEq,
    S: ShardStore<H = H, CheckpointId = BlockHeight>,
{
    for shard in shards {
        tree.store_mut()
            .put_shard(shard.clone())
            .map_err(ShardTreeError::Storage)?;
    }
    if let Some(cap) = cap {
        tree.store_mut()
            .put_cap(cap.clone())
            .map_err(ShardTreeError::Storage)?;
    }
    for height in checkpoints_remove {
        tree.store_mut()
            .remove_checkpoint(height)
            .map_err(ShardTreeError::Storage)?;
    }
    for (height, checkpoint) in checkpoints_add {
        tree.store_mut()
            .add_checkpoint(*height, checkpoint.clone())
            .map_err(ShardTreeError::Storage)?;
    }
    Ok(())
}

/// This trait describes a capability for manipulating wallet note commitment trees.
#[cfg_attr(feature = "test-dependencies", delegatable_trait)]
pub trait WalletCommitmentTrees {
    type Error: Debug;

    /// The type of the backing [`ShardStore`] for the Sapling note commitment tree.
    type SaplingShardStore<'a>: ShardStore<H = sapling::Node, CheckpointId = BlockHeight, Error = Self::Error>;

    /// Evaluates the given callback function with a reference to the Sapling
    /// note commitment tree maintained by the wallet.
    fn with_sapling_tree_mut<F, A, E>(&mut self, callback: F) -> Result<A, E>
    where
        for<'a> F: FnMut(
            &'a mut ShardTree<
                Self::SaplingShardStore<'a>,
                { sapling::NOTE_COMMITMENT_TREE_DEPTH },
                SAPLING_SHARD_HEIGHT,
            >,
        ) -> Result<A, E>,
        E: From<ShardTreeError<Self::Error>>;

    /// Adds a sequence of Sapling note commitment tree subtree roots to the data store.
    ///
    /// Each such value should be the Merkle root of a subtree of the Sapling note commitment tree
    /// containing 2^[`SAPLING_SHARD_HEIGHT`] note commitments.
    fn put_sapling_subtree_roots(
        &mut self,
        start_index: u64,
        roots: &[CommitmentTreeRoot<sapling::Node>],
    ) -> Result<(), ShardTreeError<Self::Error>>;

    /// Returns the stored root hash of the completed Sapling subtree with the given index,
    /// or `Ok(None)` if no root is recorded for that subtree.
    ///
    /// This is the store's record of the subtree root as most recently provided via
    /// [`WalletCommitmentTrees::put_sapling_subtree_roots`] (i.e. the chain-authoritative
    /// root obtained from a chain data provider), or as recorded when a locally-completed
    /// subtree was persisted.
    fn get_sapling_subtree_root(
        &mut self,
        index: u64,
    ) -> Result<Option<sapling::Node>, ShardTreeError<Self::Error>>;

    /// The type of the backing [`ShardStore`] for the Orchard note commitment tree.
    #[cfg(feature = "orchard")]
    type OrchardShardStore<'a>: ShardStore<
            H = orchard::tree::MerkleHashOrchard,
            CheckpointId = BlockHeight,
            Error = Self::Error,
        >;

    /// Evaluates the given callback function with a reference to the Orchard
    /// note commitment tree maintained by the wallet.
    #[cfg(feature = "orchard")]
    fn with_orchard_tree_mut<F, A, E>(&mut self, callback: F) -> Result<A, E>
    where
        for<'a> F: FnMut(
            &'a mut ShardTree<
                Self::OrchardShardStore<'a>,
                { ORCHARD_SHARD_HEIGHT * 2 },
                ORCHARD_SHARD_HEIGHT,
            >,
        ) -> Result<A, E>,
        E: From<ShardTreeError<Self::Error>>;

    /// Adds a sequence of Orchard note commitment tree subtree roots to the data store.
    ///
    /// Each such value should be the Merkle root of a subtree of the Orchard note commitment tree
    /// containing 2^[`ORCHARD_SHARD_HEIGHT`] note commitments.
    #[cfg(feature = "orchard")]
    fn put_orchard_subtree_roots(
        &mut self,
        start_index: u64,
        roots: &[CommitmentTreeRoot<orchard::tree::MerkleHashOrchard>],
    ) -> Result<(), ShardTreeError<Self::Error>>;

    /// Returns the stored root hash of the completed Orchard subtree with the given index,
    /// or `Ok(None)` if no root is recorded for that subtree.
    ///
    /// This is the store's record of the subtree root as most recently provided via
    /// [`WalletCommitmentTrees::put_orchard_subtree_roots`] (i.e. the chain-authoritative
    /// root obtained from a chain data provider), or as recorded when a locally-completed
    /// subtree was persisted.
    #[cfg(feature = "orchard")]
    fn get_orchard_subtree_root(
        &mut self,
        index: u64,
    ) -> Result<Option<orchard::tree::MerkleHashOrchard>, ShardTreeError<Self::Error>>;

    /// Evaluates the given callback with the Ironwood note commitment tree
    /// maintained by the wallet, if this backend has one.
    ///
    /// The default implementation reports that no Ironwood tree is available.
    /// Backends that track Ironwood note commitments should override this and
    /// provide their separate Ironwood tree.
    #[cfg(feature = "orchard")]
    fn with_ironwood_tree_mut<F, A, E>(&mut self, _callback: F) -> Result<Option<A>, E>
    where
        for<'a> F: FnMut(
            &'a mut ShardTree<
                Self::OrchardShardStore<'a>,
                { ORCHARD_SHARD_HEIGHT * 2 },
                ORCHARD_SHARD_HEIGHT,
            >,
        ) -> Result<A, E>,
        E: From<ShardTreeError<Self::Error>>,
    {
        Ok(None)
    }

    /// Adds a sequence of Ironwood note commitment tree subtree roots to the data store, if this
    /// backend tracks an Ironwood tree.
    ///
    /// Each such value should be the Merkle root of a subtree of the Ironwood note commitment tree
    /// containing 2^[`ORCHARD_SHARD_HEIGHT`] note commitments; Ironwood shares the Orchard note
    /// commitment tree's shape, so the same shard height applies.
    ///
    /// The default implementation is a no-op, for backends that do not track an Ironwood tree
    /// (mirroring [`WalletCommitmentTrees::with_ironwood_tree_mut`]). Backends that track Ironwood
    /// note commitments should override this.
    #[cfg(feature = "orchard")]
    fn put_ironwood_subtree_roots(
        &mut self,
        _start_index: u64,
        _roots: &[CommitmentTreeRoot<orchard::tree::MerkleHashOrchard>],
    ) -> Result<(), ShardTreeError<Self::Error>> {
        Ok(())
    }

    /// Returns the stored root hash of the completed Ironwood subtree with the given
    /// index, or `Ok(None)` if no root is recorded for that subtree (in particular, if
    /// this backend does not track an Ironwood tree — the default implementation).
    #[cfg(feature = "orchard")]
    fn get_ironwood_subtree_root(
        &mut self,
        _index: u64,
    ) -> Result<Option<orchard::tree::MerkleHashOrchard>, ShardTreeError<Self::Error>> {
        Ok(None)
    }

    /// Applies a batch of changes — shards, an optional replacement tree cap, and a
    /// checkpoint delta — to the wallet's Sapling note commitment tree.
    ///
    /// `shards` must be in ascending shard-index order; stores may reject sequences that
    /// would leave gaps in the tree. Checkpoint removals are applied before additions, so
    /// that a checkpoint whose data has changed may appear in both lists.
    ///
    /// This is intended for wallet stores that accumulate note commitment tree updates
    /// outside the backing store (for example, in an in-memory tree) and flush them in
    /// batches. The default implementation applies the changes through
    /// [`WalletCommitmentTrees::with_sapling_tree_mut`].
    fn put_sapling_shards(
        &mut self,
        shards: &[shardtree::LocatedPrunableTree<sapling::Node>],
        cap: Option<&shardtree::PrunableTree<sapling::Node>>,
        checkpoints_remove: &[BlockHeight],
        checkpoints_add: &[(BlockHeight, shardtree::store::Checkpoint)],
    ) -> Result<(), ShardTreeError<Self::Error>> {
        self.with_sapling_tree_mut(|tree| {
            apply_tree_changes(tree, shards, cap, checkpoints_remove, checkpoints_add)
        })
    }

    /// Applies a batch of changes — shards, an optional replacement tree cap, and a
    /// checkpoint delta — to the wallet's Orchard note commitment tree.
    ///
    /// `shards` must be in ascending shard-index order; stores may reject sequences that
    /// would leave gaps in the tree. Checkpoint removals are applied before additions, so
    /// that a checkpoint whose data has changed may appear in both lists.
    ///
    /// This is intended for wallet stores that accumulate note commitment tree updates
    /// outside the backing store (for example, in an in-memory tree) and flush them in
    /// batches. The default implementation applies the changes through
    /// [`WalletCommitmentTrees::with_orchard_tree_mut`].
    #[cfg(feature = "orchard")]
    fn put_orchard_shards(
        &mut self,
        shards: &[shardtree::LocatedPrunableTree<orchard::tree::MerkleHashOrchard>],
        cap: Option<&shardtree::PrunableTree<orchard::tree::MerkleHashOrchard>>,
        checkpoints_remove: &[BlockHeight],
        checkpoints_add: &[(BlockHeight, shardtree::store::Checkpoint)],
    ) -> Result<(), ShardTreeError<Self::Error>> {
        self.with_orchard_tree_mut(|tree| {
            apply_tree_changes(tree, shards, cap, checkpoints_remove, checkpoints_add)
        })
    }

    /// Applies a batch of changes — shards, an optional replacement tree cap, and a
    /// checkpoint delta — to the wallet's Ironwood note commitment tree, if this backend
    /// tracks one.
    ///
    /// `shards` must be in ascending shard-index order; stores may reject sequences that
    /// would leave gaps in the tree. Checkpoint removals are applied before additions, so
    /// that a checkpoint whose data has changed may appear in both lists.
    ///
    /// The default implementation applies the changes through
    /// [`WalletCommitmentTrees::with_ironwood_tree_mut`]; for backends that do not track an
    /// Ironwood tree (see that method's documentation), the changes are ignored.
    #[cfg(feature = "orchard")]
    fn put_ironwood_shards(
        &mut self,
        shards: &[shardtree::LocatedPrunableTree<orchard::tree::MerkleHashOrchard>],
        cap: Option<&shardtree::PrunableTree<orchard::tree::MerkleHashOrchard>>,
        checkpoints_remove: &[BlockHeight],
        checkpoints_add: &[(BlockHeight, shardtree::store::Checkpoint)],
    ) -> Result<(), ShardTreeError<Self::Error>> {
        self.with_ironwood_tree_mut(|tree| {
            apply_tree_changes(tree, shards, cap, checkpoints_remove, checkpoints_add)
        })?;
        Ok(())
    }

    /// Releases all retained ("anchor") checkpoints with height strictly less than `max_height`
    /// from the wallet's note commitment trees, allowing them to be pruned normally.
    ///
    /// Anchor checkpoints are established during scanning (and may be created directly via
    /// [`ShardTree::ensure_retained`]); they are otherwise exempt from automatic pruning of excess
    /// checkpoints. This releases the retention of those that have aged below `max_height` in the
    /// Sapling and (when the `orchard` feature is enabled) the Orchard and Ironwood trees.
    fn remove_retained_checkpoints_below(
        &mut self,
        max_height: BlockHeight,
    ) -> Result<(), ShardTreeError<Self::Error>> {
        self.with_sapling_tree_mut(|tree| {
            for height in tree
                .store()
                .retained_checkpoints()
                .map_err(ShardTreeError::Storage)?
            {
                if height < max_height {
                    tree.remove_retained_checkpoint(&height)?;
                }
            }
            Ok::<_, ShardTreeError<Self::Error>>(())
        })?;

        #[cfg(feature = "orchard")]
        self.with_orchard_tree_mut(|tree| {
            for height in tree
                .store()
                .retained_checkpoints()
                .map_err(ShardTreeError::Storage)?
            {
                if height < max_height {
                    tree.remove_retained_checkpoint(&height)?;
                }
            }
            Ok::<_, ShardTreeError<Self::Error>>(())
        })?;

        // A backend that does not track an Ironwood tree returns `None` here and is left unchanged.
        #[cfg(feature = "orchard")]
        self.with_ironwood_tree_mut(|tree| {
            for height in tree
                .store()
                .retained_checkpoints()
                .map_err(ShardTreeError::Storage)?
            {
                if height < max_height {
                    tree.remove_retained_checkpoint(&height)?;
                }
            }
            Ok::<_, ShardTreeError<Self::Error>>(())
        })?;

        Ok(())
    }
}

/// Property tests for the [`Balance`] bucket arithmetic.
///
/// These pin the accounting semantics the locked-value bucket joined: every bucket except
/// `uneconomic_value` participates in [`Balance::total`] and in the shared overflow guard,
/// while `uneconomic_value` is guarded only against its own overflow and never contributes
/// to the total.
#[cfg(test)]
mod balance_tests {
    use proptest::prelude::*;
    use zcash_protocol::value::{BalanceError, MAX_MONEY, Zatoshis};

    use super::Balance;

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum Bucket {
        Spendable = 0,
        Locked = 1,
        PendingChange = 2,
        PendingSpendable = 3,
        Uneconomic = 4,
    }
    use Bucket::*;

    const ALL_BUCKETS: [Bucket; 5] = [
        Spendable,
        Locked,
        PendingChange,
        PendingSpendable,
        Uneconomic,
    ];
    /// The buckets that participate in `Balance::total` and its overflow guard.
    const TOTAL_BUCKETS: [Bucket; 4] = [Spendable, Locked, PendingChange, PendingSpendable];

    fn apply(balance: &mut Balance, bucket: Bucket, value: Zatoshis) -> Result<(), BalanceError> {
        match bucket {
            Spendable => balance.add_spendable_value(value),
            Locked => balance.add_locked_value(value),
            PendingChange => balance.add_pending_change_value(value),
            PendingSpendable => balance.add_pending_spendable_value(value),
            Uneconomic => balance.add_uneconomic_value(value),
        }
    }

    fn get(balance: &Balance, bucket: Bucket) -> Zatoshis {
        match bucket {
            Spendable => balance.spendable_value(),
            Locked => balance.locked_value(),
            PendingChange => balance.change_pending_confirmation(),
            PendingSpendable => balance.value_pending_spendability(),
            Uneconomic => balance.uneconomic_value(),
        }
    }

    fn arb_bucket() -> impl Strategy<Value = Bucket> {
        prop_oneof![
            Just(Spendable),
            Just(Locked),
            Just(PendingChange),
            Just(PendingSpendable),
            Just(Uneconomic),
        ]
    }

    /// A bucket and a value to add to it. Values are mostly small (so most sequences stay
    /// within `MAX_MONEY`) with occasional near-cap draws to exercise the overflow guards.
    fn arb_add() -> impl Strategy<Value = (Bucket, u64)> {
        (
            arb_bucket(),
            prop_oneof![
                3 => 0u64..=1_000_000,
                1 => 0u64..=MAX_MONEY,
            ],
        )
    }

    proptest! {
        /// Bucket adds succeed exactly while their overflow guard permits, mutate only the
        /// requested bucket, and leave the balance untouched on failure. `total()` is always
        /// the sum of the four participating buckets. (In particular this establishes that
        /// the `unwrap` inside each guarded add is unreachable.)
        #[test]
        fn add_total_consistency(adds in proptest::collection::vec(arb_add(), 0..12)) {
            let mut balance = Balance::ZERO;
            // The model: per-bucket totals, indexed by bucket discriminant.
            let mut model = [0u64; 5];

            for (bucket, v) in adds {
                let value = Zatoshis::from_u64(v).unwrap();
                let before = balance;
                let result = apply(&mut balance, bucket, value);

                let total: u64 = TOTAL_BUCKETS.iter().map(|b| model[*b as usize]).sum();
                let expect_ok = match bucket {
                    Uneconomic => model[Uneconomic as usize] + v <= MAX_MONEY,
                    _ => total + v <= MAX_MONEY,
                };
                if expect_ok {
                    prop_assert!(result.is_ok());
                    model[bucket as usize] += v;
                } else {
                    prop_assert!(result.is_err());
                    prop_assert_eq!(
                        balance, before,
                        "a failed add must leave the balance unchanged"
                    );
                }

                let total: u64 = TOTAL_BUCKETS.iter().map(|b| model[*b as usize]).sum();
                prop_assert_eq!(balance.total(), Zatoshis::from_u64(total).unwrap());
                for b in ALL_BUCKETS {
                    prop_assert_eq!(
                        get(&balance, b),
                        Zatoshis::from_u64(model[b as usize]).unwrap()
                    );
                }
            }
        }

        /// `Balance + Balance` is componentwise addition: it succeeds exactly when the
        /// combined total and the combined uneconomic value each remain within `MAX_MONEY`,
        /// and on success every bucket of the sum is the sum of the corresponding buckets.
        #[test]
        fn balance_addition_is_componentwise(
            a in proptest::collection::vec(arb_add(), 0..6),
            b in proptest::collection::vec(arb_add(), 0..6),
        ) {
            let build = |adds: &[(Bucket, u64)]| {
                let mut balance = Balance::ZERO;
                for (bucket, v) in adds {
                    let _ = apply(&mut balance, *bucket, Zatoshis::from_u64(*v).unwrap());
                }
                balance
            };
            let ba = build(&a);
            let bb = build(&b);

            let combined_total = u64::from(ba.total()) + u64::from(bb.total());
            let combined_uneconomic =
                u64::from(ba.uneconomic_value()) + u64::from(bb.uneconomic_value());
            match ba + bb {
                Ok(sum) => {
                    prop_assert!(combined_total <= MAX_MONEY);
                    prop_assert!(combined_uneconomic <= MAX_MONEY);
                    for bucket in ALL_BUCKETS {
                        prop_assert_eq!(
                            u64::from(get(&sum, bucket)),
                            u64::from(get(&ba, bucket)) + u64::from(get(&bb, bucket))
                        );
                    }
                    prop_assert_eq!(u64::from(sum.total()), combined_total);
                }
                Err(_) => {
                    prop_assert!(
                        combined_total > MAX_MONEY || combined_uneconomic > MAX_MONEY,
                        "balance addition failed although no component overflows"
                    );
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use incrementalmerkletree::{
        Address as TreeAddress, Hashable, Level, Marking, Position, Retention,
    };
    use shardtree::store::{Checkpoint, memory::MemoryShardStore};
    use zcash_keys::{
        address::{Address, UnifiedAddress},
        keys::UnifiedAddressRequest,
    };

    use super::*;

    #[cfg(feature = "orchard")]
    use crate::data_api::error::FindAccountForAddressError;
    use crate::data_api::testing::{
        MockWalletDb, pool::ShieldedPoolTester, sapling::SaplingPoolTester,
    };

    use transparent::address::TransparentAddress;
    use zip32::DiversifierIndex;

    #[test]
    fn put_sapling_shards_flushes_through_the_interface() {
        let mut db = MockWalletDb::new(zcash_protocol::consensus::Network::TestNetwork);

        // Build a shard-rooted subtree the same way `put_blocks` does, with a checkpoint on
        // the final leaf.
        let leaf = <sapling::Node as Hashable>::empty_leaf();
        let checkpoint_height = BlockHeight::from(3);
        let commitments = (0u64..4).map(|i| {
            (
                leaf,
                if i == 3 {
                    Retention::Checkpoint {
                        id: checkpoint_height,
                        marking: Marking::None,
                    }
                } else {
                    Retention::Ephemeral
                },
            )
        });
        let built = shardtree::LocatedTree::from_iter(
            Position::from(0)..Position::from(4),
            Level::from(SAPLING_SHARD_HEIGHT),
            commitments,
        )
        .expect("commitments produce a subtree");
        let checkpoints_add = built
            .checkpoints
            .iter()
            .map(|(height, position)| (*height, Checkpoint::at_position(*position)))
            .collect::<Vec<_>>();

        db.put_sapling_shards(&[built.subtree], None, &[], &checkpoints_add)
            .expect("bulk flush succeeds");

        // The shard and checkpoint are visible through the standard tree access path.
        db.with_sapling_tree_mut(|tree| {
            assert!(
                tree.store()
                    .get_shard(TreeAddress::from_parts(
                        Level::from(SAPLING_SHARD_HEIGHT),
                        0
                    ))
                    .map_err(ShardTreeError::Storage)?
                    .is_some()
            );
            assert_eq!(
                tree.store()
                    .max_checkpoint_id()
                    .map_err(ShardTreeError::Storage)?,
                Some(checkpoint_height)
            );
            Ok::<_, ShardTreeError<_>>(())
        })
        .expect("tree reads succeed");

        // Removals are applied before additions, so a checkpoint set can be replaced in a
        // single call.
        let new_height = BlockHeight::from(7);
        db.put_sapling_shards(
            &[],
            None,
            &[checkpoint_height],
            &[(new_height, Checkpoint::tree_empty())],
        )
        .expect("checkpoint replacement succeeds");

        db.with_sapling_tree_mut(|tree| {
            assert_eq!(
                tree.store()
                    .max_checkpoint_id()
                    .map_err(ShardTreeError::Storage)?,
                Some(new_height)
            );
            assert_eq!(
                tree.store()
                    .checkpoint_count()
                    .map_err(ShardTreeError::Storage)?,
                1
            );
            Ok::<_, ShardTreeError<_>>(())
        })
        .expect("tree reads succeed");
    }

    /// Exercises [`apply_tree_changes`] — the shared implementation of the `put_*_shards`
    /// provided methods — directly over a [`MemoryShardStore`] of the given node type.
    ///
    /// [`MemoryShardStore`]: shardtree::store::memory::MemoryShardStore
    fn check_apply_tree_changes<H>()
    where
        H: incrementalmerkletree::Hashable + Clone + PartialEq + core::fmt::Debug,
    {
        let mut tree: ShardTree<
            MemoryShardStore<H, BlockHeight>,
            { SAPLING_SHARD_HEIGHT * 2 },
            SAPLING_SHARD_HEIGHT,
        > = ShardTree::new(MemoryShardStore::empty(), 100);

        // Build a shard-rooted subtree the same way `put_blocks` does, with a checkpoint on
        // the final leaf.
        let leaf = H::empty_leaf();
        let checkpoint_height = BlockHeight::from(3);
        let commitments = (0u64..4).map(|i| {
            (
                leaf.clone(),
                if i == 3 {
                    Retention::Checkpoint {
                        id: checkpoint_height,
                        marking: Marking::None,
                    }
                } else {
                    Retention::Ephemeral
                },
            )
        });
        let built = shardtree::LocatedTree::from_iter(
            Position::from(0)..Position::from(4),
            Level::from(SAPLING_SHARD_HEIGHT),
            commitments,
        )
        .expect("commitments produce a subtree");
        let checkpoints_add = built
            .checkpoints
            .iter()
            .map(|(height, position)| (*height, Checkpoint::at_position(*position)))
            .collect::<Vec<_>>();

        apply_tree_changes(&mut tree, &[built.subtree], None, &[], &checkpoints_add)
            .expect("bulk flush succeeds");

        assert!(
            tree.store()
                .get_shard(TreeAddress::from_parts(
                    Level::from(SAPLING_SHARD_HEIGHT),
                    0
                ))
                .expect("shard read succeeds")
                .is_some()
        );
        assert_eq!(
            tree.store()
                .max_checkpoint_id()
                .expect("checkpoint read succeeds"),
            Some(checkpoint_height)
        );

        // Removals are applied before additions, so a checkpoint set can be replaced in a
        // single call.
        let new_height = BlockHeight::from(7);
        apply_tree_changes(
            &mut tree,
            &[],
            None,
            &[checkpoint_height],
            &[(new_height, Checkpoint::tree_empty())],
        )
        .expect("checkpoint replacement succeeds");

        assert_eq!(
            tree.store()
                .max_checkpoint_id()
                .expect("checkpoint read succeeds"),
            Some(new_height)
        );
        assert_eq!(
            tree.store()
                .checkpoint_count()
                .expect("checkpoint read succeeds"),
            1
        );
    }

    #[test]
    fn apply_tree_changes_supports_every_pool_node_type() {
        check_apply_tree_changes::<sapling::Node>();
        // Orchard and Ironwood both use `MerkleHashOrchard` trees of the same shape.
        #[cfg(feature = "orchard")]
        check_apply_tree_changes::<orchard::tree::MerkleHashOrchard>();
    }

    #[cfg(feature = "orchard")]
    #[test]
    fn put_ironwood_shards_is_ignored_without_an_ironwood_tree() {
        // `MockWalletDb` does not track an Ironwood tree, so the default
        // `with_ironwood_tree_mut` reports no tree and the changes are ignored rather than
        // returning an error.
        let mut db = MockWalletDb::new(zcash_protocol::consensus::Network::TestNetwork);
        db.put_ironwood_shards(
            &[],
            None,
            &[],
            &[(BlockHeight::from(1), Checkpoint::tree_empty())],
        )
        .expect("ignored on backends without an Ironwood tree");
    }

    #[test]
    fn account_meta_totals_include_ironwood() {
        let meta = AccountMeta::new(
            Some(PoolMeta::new(2, Zatoshis::const_from_u64(200))),
            Some(PoolMeta::new(3, Zatoshis::const_from_u64(300))),
            Some(PoolMeta::new(5, Zatoshis::const_from_u64(500))),
        );
        assert_eq!(meta.note_count(ShieldedPool::Ironwood), Some(5));
        assert_eq!(meta.total_note_count(), Some(10));
        assert_eq!(meta.total_value(), Some(Zatoshis::const_from_u64(1000)));

        // With metadata for only the Ironwood pool, the totals reflect that pool alone.
        let ironwood_only = AccountMeta::new(
            None,
            None,
            Some(PoolMeta::new(4, Zatoshis::const_from_u64(400))),
        );
        assert_eq!(ironwood_only.note_count(ShieldedPool::Ironwood), Some(4));
        assert_eq!(ironwood_only.total_note_count(), Some(4));
        assert_eq!(
            ironwood_only.total_value(),
            Some(Zatoshis::const_from_u64(400))
        );
    }

    fn derived_source() -> AddressSource {
        AddressSource::Derived {
            diversifier_index: DiversifierIndex::default(),
            #[cfg(feature = "transparent-inputs")]
            transparent_key_scope: None,
        }
    }

    fn address_info_of(address: Address) -> AddressInfo {
        AddressInfo::from_parts(address, derived_source())
            .expect("test address metadata must be valid")
    }

    fn transparent_address_for_tag(tag: u8) -> TransparentAddress {
        TransparentAddress::PublicKeyHash([tag; 20])
    }

    fn sapling_address_for_tag(tag: u8) -> sapling::PaymentAddress {
        match SaplingPoolTester::sk_default_address(&SaplingPoolTester::sk(&[tag; 32])) {
            Address::Sapling(pa) => pa,
            other => panic!("expected Sapling address, got {other:?}"),
        }
    }

    fn unified_account_with(
        transparent: Option<TransparentAddress>,
        sapling: Option<sapling::PaymentAddress>,
        #[cfg(feature = "orchard")] orchard: Option<orchard::Address>,
    ) -> Address {
        UnifiedAddress::from_receivers(
            #[cfg(feature = "orchard")]
            Some(orchard).flatten(),
            Some(sapling).flatten(),
            transparent,
        )
        .expect("test UA must be valid")
        .into()
    }

    #[test]
    fn find_account_for_transparent_address_returns_matching_account() {
        let wallet = MockWalletDb::from_account_addresses(
            zcash_protocol::consensus::Network::MainNetwork,
            [
                (
                    1,
                    vec![address_info_of(Address::Transparent(
                        transparent_address_for_tag(1),
                    ))],
                ),
                (
                    2,
                    vec![address_info_of(Address::Transparent(
                        transparent_address_for_tag(2),
                    ))],
                ),
            ],
        );
        let result = wallet.find_account_for_address(
            &zcash_protocol::consensus::Network::MainNetwork,
            &Address::Transparent(transparent_address_for_tag(1)),
        );
        assert_eq!(result.unwrap(), Some(1));
    }

    #[test]
    fn find_account_for_transparent_receiver_in_unified_address_returns_matching_account() {
        let transparent = transparent_address_for_tag(1);
        let sapling_address = sapling_address_for_tag(11);

        #[cfg(feature = "orchard")]
        {
            let wallet = MockWalletDb::from_account_addresses(
                zcash_protocol::consensus::Network::MainNetwork,
                [(
                    1,
                    vec![address_info_of(unified_account_with(
                        Some(transparent),
                        Some(sapling_address),
                        None,
                    ))],
                )],
            );
            let result = wallet.find_account_for_address(
                &zcash_protocol::consensus::Network::MainNetwork,
                &Address::Transparent(transparent),
            );
            assert_eq!(result.unwrap(), Some(1));
        }
        #[cfg(not(feature = "orchard"))]
        {
            let wallet = MockWalletDb::from_account_addresses(
                zcash_protocol::consensus::Network::MainNetwork,
                [(
                    1,
                    vec![address_info_of(unified_account_with(
                        Some(transparent),
                        Some(sapling_address),
                    ))],
                )],
            );
            let result = wallet.find_account_for_address(
                &zcash_protocol::consensus::Network::MainNetwork,
                &Address::Transparent(transparent),
            );
            assert_eq!(result.unwrap(), Some(1));
        }
    }

    #[test]
    fn find_account_for_address_returns_none_when_simple_address_is_unknown() {
        let address = Address::Transparent(transparent_address_for_tag(1));
        let wallet = MockWalletDb::from_account_addresses(
            zcash_protocol::consensus::Network::MainNetwork,
            [(1, vec![address_info_of(address)])],
        );

        let other_address = Address::Transparent(transparent_address_for_tag(9));
        let result = wallet.find_account_for_address(
            &zcash_protocol::consensus::Network::MainNetwork,
            &other_address,
        );

        assert_eq!(result.unwrap(), None);
    }

    fn test_ufvk(seed_tag: u8) -> zcash_keys::keys::UnifiedFullViewingKey {
        zcash_keys::keys::UnifiedSpendingKey::from_seed(
            &zcash_protocol::consensus::Network::MainNetwork,
            &[seed_tag; 32],
            zip32::AccountId::ZERO,
        )
        .expect("valid seed")
        .to_unified_full_viewing_key()
    }

    #[test]
    fn find_account_for_unified_address_returns_account_when_receivers_map_to_same_account() {
        let ufvk = test_ufvk(1);
        let wallet = MockWalletDb::from_account_ufvks(
            zcash_protocol::consensus::Network::MainNetwork,
            [(1, ufvk.clone())],
        );

        let (ua, _) = ufvk
            .default_address(UnifiedAddressRequest::AllAvailableKeys)
            .expect("default address must be derivable");

        let result = wallet.find_account_for_address(
            &zcash_protocol::consensus::Network::MainNetwork,
            &Address::Unified(ua),
        );

        assert_eq!(result.unwrap(), Some(1));
    }

    #[test]
    fn find_account_for_unified_address_returns_none_when_no_receiver_matches() {
        let wallet = MockWalletDb::from_account_ufvks(
            zcash_protocol::consensus::Network::MainNetwork,
            [(1, test_ufvk(1))],
        );

        // A UA derived from a different seed — no account in the wallet owns any of its
        // shielded receivers.
        let (ua_from_other_seed, _) = test_ufvk(99)
            .default_address(UnifiedAddressRequest::AllAvailableKeys)
            .expect("default address must be derivable");

        let result = wallet.find_account_for_address(
            &zcash_protocol::consensus::Network::MainNetwork,
            &Address::Unified(ua_from_other_seed),
        );

        assert_eq!(result.unwrap(), None);
    }

    #[test]
    fn find_account_for_sapling_address_resolves_via_uivk_algebra_when_not_previously_exposed() {
        // A bare Sapling address derivable from an account's UIVK must resolve even when the
        // wallet has never stored (and therefore never "exposed") that address.
        let ufvk = test_ufvk(1);
        let wallet = MockWalletDb::from_account_ufvks(
            zcash_protocol::consensus::Network::MainNetwork,
            [(1, ufvk.clone())],
        );

        let (ua, _) = ufvk
            .default_address(UnifiedAddressRequest::AllAvailableKeys)
            .expect("default address must be derivable");
        let sapling_pa = *ua.sapling().expect("sapling receiver");

        // `wallet` has no stored addresses: only the account's UFVK. The list_addresses scan
        // would therefore miss this address; only the synthesized-UA algebraic path can
        // resolve it.
        let result = wallet.find_account_for_address(
            &zcash_protocol::consensus::Network::MainNetwork,
            &Address::Sapling(sapling_pa),
        );

        assert_eq!(result.unwrap(), Some(1));
    }

    #[test]
    fn find_account_for_address_returns_none_for_empty_wallet() {
        let wallet = MockWalletDb::from_account_addresses(
            zcash_protocol::consensus::Network::MainNetwork,
            std::iter::empty(),
        );

        let result = wallet.find_account_for_address(
            &zcash_protocol::consensus::Network::MainNetwork,
            &Address::Transparent(transparent_address_for_tag(1)),
        );
        assert_eq!(result.unwrap(), None);

        let result = wallet.find_account_for_address(
            &zcash_protocol::consensus::Network::MainNetwork,
            &Address::Sapling(sapling_address_for_tag(1)),
        );
        assert_eq!(result.unwrap(), None);
    }

    #[cfg(feature = "orchard")]
    #[test]
    fn find_account_for_unified_address_errors_when_receivers_map_to_different_accounts() {
        let ufvk1 = test_ufvk(1);
        let ufvk2 = test_ufvk(2);
        let wallet = MockWalletDb::from_account_ufvks(
            zcash_protocol::consensus::Network::MainNetwork,
            [(1, ufvk1.clone()), (2, ufvk2.clone())],
        );

        let (ua1, _) = ufvk1
            .default_address(UnifiedAddressRequest::AllAvailableKeys)
            .expect("default address must be derivable");
        let (ua2, _) = ufvk2
            .default_address(UnifiedAddressRequest::AllAvailableKeys)
            .expect("default address must be derivable");

        // A frankenstein UA whose Sapling receiver is from account 1 and whose Orchard
        // receiver is from account 2.
        let frankenstein = UnifiedAddress::from_receivers(
            Some(ua2.orchard().copied().expect("orchard receiver")),
            Some(ua1.sapling().copied().expect("sapling receiver")),
            None,
        )
        .expect("sapling+orchard UA must be valid");

        let result = wallet.find_account_for_address(
            &zcash_protocol::consensus::Network::MainNetwork,
            &Address::Unified(frankenstein),
        );

        assert!(matches!(
            result,
            Err(FindAccountForAddressError::UnifiedAddressConflict)
        ));
    }

    /// Each unshielded mutator updates only its own bucket, and transparent mutations leave the
    /// shielded aggregates untouched.
    #[test]
    fn account_balance_unshielded_split_mutators() {
        let mut balance = AccountBalance::ZERO;

        let regular_value = Zatoshis::const_from_u64(100_000);
        let coinbase_value = Zatoshis::const_from_u64(50_000);

        balance
            .with_unshielded_regular_balance_mut(|bal| bal.add_spendable_value(regular_value))
            .unwrap();
        balance
            .with_unshielded_coinbase_balance_mut(|bal| {
                bal.add_pending_spendable_value(coinbase_value)
            })
            .unwrap();

        // The regular bucket contains only the regular value.
        assert_eq!(
            balance.unshielded_regular_balance().spendable_value(),
            regular_value
        );
        assert_eq!(balance.unshielded_regular_balance().total(), regular_value);
        assert_eq!(
            balance
                .unshielded_regular_balance()
                .value_pending_spendability(),
            Zatoshis::ZERO
        );

        // The coinbase bucket contains only the coinbase value, as pending.
        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_coinbase_balance().total(),
            coinbase_value
        );

        // The shielded-only aggregates are unaffected by transparent mutations.
        assert_eq!(balance.spendable_value(), Zatoshis::ZERO);
        assert_eq!(balance.change_pending_confirmation(), Zatoshis::ZERO);
        assert_eq!(balance.value_pending_spendability(), Zatoshis::ZERO);
        assert_eq!(balance.sapling_balance(), &Balance::ZERO);
        assert_eq!(balance.orchard_balance(), &Balance::ZERO);
        assert_eq!(balance.ironwood_balance(), &Balance::ZERO);
    }

    /// `unshielded_balance` returns the sum of the regular and coinbase buckets, and the
    /// account-level aggregates include both buckets.
    #[test]
    fn account_balance_unshielded_balance_is_sum() {
        let mut balance = AccountBalance::ZERO;

        let regular_spendable = Zatoshis::const_from_u64(100_000);
        let regular_dust = Zatoshis::const_from_u64(100);
        let coinbase_pending = Zatoshis::const_from_u64(625_000_000);
        let coinbase_dust = Zatoshis::const_from_u64(42);

        balance
            .with_unshielded_regular_balance_mut(|bal| {
                bal.add_spendable_value(regular_spendable)?;
                bal.add_uneconomic_value(regular_dust)
            })
            .unwrap();
        balance
            .with_unshielded_coinbase_balance_mut(|bal| {
                bal.add_pending_spendable_value(coinbase_pending)?;
                bal.add_uneconomic_value(coinbase_dust)
            })
            .unwrap();

        // The by-value combined balance is the field-wise sum of both buckets.
        let combined = balance.unshielded_balance();
        assert_eq!(
            combined,
            (*balance.unshielded_regular_balance() + *balance.unshielded_coinbase_balance())
                .unwrap()
        );
        assert_eq!(combined.spendable_value(), regular_spendable);
        assert_eq!(combined.value_pending_spendability(), coinbase_pending);
        assert_eq!(
            combined.uneconomic_value(),
            (regular_dust + coinbase_dust).unwrap()
        );

        // The deprecated accessor reports the sum of both buckets' totals.
        #[allow(deprecated)]
        let unshielded = balance.unshielded();
        assert_eq!(
            unshielded,
            (balance.unshielded_regular_balance().total()
                + balance.unshielded_coinbase_balance().total())
            .unwrap()
        );

        // The account total and uneconomic value include both buckets. (`Balance::total`
        // excludes uneconomic value, so the dust does not appear in the account total.)
        assert_eq!(
            balance.total(),
            (regular_spendable + coinbase_pending).unwrap()
        );
        assert_eq!(
            balance.uneconomic_value(),
            (regular_dust + coinbase_dust).unwrap()
        );
    }

    /// The `check_total` invariant rejects mutations that would cause the sum of the regular and
    /// coinbase transparent buckets to exceed `MAX_MONEY`.
    #[test]
    fn account_balance_unshielded_overflow_rejected() {
        let max_money = Zatoshis::const_from_u64(zcash_protocol::value::MAX_MONEY);
        let mut balance = AccountBalance::ZERO;

        // Fill the regular bucket up to MAX_MONEY; this is fine on its own.
        balance
            .with_unshielded_regular_balance_mut(|bal| bal.add_spendable_value(max_money))
            .unwrap();
        assert_eq!(balance.total(), max_money);

        // Any further value in the coinbase bucket must be rejected by the account-level
        // invariant check, even though the coinbase bucket does not overflow on its own.
        let result: Result<(), BalanceError> =
            balance.with_unshielded_coinbase_balance_mut(|bal| {
                bal.add_pending_spendable_value(Zatoshis::const_from_u64(1))
            });
        assert!(matches!(result, Err(BalanceError::Overflow)));
    }
}