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
//! Types related to the process of selecting inputs to be spent given a transaction request.
#[cfg(feature = "transparent-inputs")]
use {
    crate::{
        data_api::CoinbaseFilter,
        fees::{ChangeValue, StandardFeeRule},
        proposal::{Step, StepOutput, StepOutputIndex},
    },
    std::convert::Infallible,
    transparent::{address::TransparentAddress, bundle::OutPoint, keys::TransparentKeyScope},
    zcash_primitives::transaction::fees::{
        transparent as transparent_fees, transparent::InputSize, zip317::P2PKH_STANDARD_INPUT_SIZE,
    },
    zcash_protocol::constants::MAX_BLOCK_BYTES,
    zip321::Payment,
};

use core::marker::PhantomData;
use nonempty::NonEmpty;
use std::{
    collections::{BTreeMap, BTreeSet},
    error,
    fmt::{self, Debug, Display},
};

use transparent::bundle::TxOut;
use zcash_address::{ConversionError, ZcashAddress};
use zcash_keys::address::{Address, UnifiedAddress};
use zcash_primitives::transaction::{
    TxVersion,
    fees::{FeeRule, zip317::P2PKH_STANDARD_OUTPUT_SIZE},
};
use zcash_protocol::{
    PoolType, ShieldedPool,
    consensus::{self, BlockHeight},
    memo::MemoBytes,
    value::{BalanceError, MAX_MONEY, Zatoshis},
};
use zip321::TransactionRequest;

use crate::{
    data_api::{
        InputSource, MaxSpendMode, ReceivedNotes, SimpleNoteRetention, TargetValue,
        anchor_retention::PoolMigrationParams, wallet::TargetHeight,
    },
    fees::{ChangeError, ChangeStrategy, EphemeralBalance, TransactionBalance, sapling},
    proposal::{Proposal, ProposalError, ShieldedInputs},
    wallet::WalletTransparentOutput,
};

pub use crate::data_api::locking::{LockFilter, LockedInputPolicy};

use super::ConfirmationsPolicy;

#[cfg(feature = "orchard")]
use crate::{data_api::wallet::ironwood_active_at, fees::orchard as orchard_fees};

/// The type of errors that may be produced in input selection.
#[derive(Debug)]
#[non_exhaustive]
pub enum InputSelectorError<DbErrT, SelectorErrT, ChangeErrT, N> {
    /// An error occurred accessing the underlying data store.
    DataSource(DbErrT),
    /// An error occurred specific to the provided input selector's selection rules.
    Selection(SelectorErrT),
    /// An error occurred in computing the change or fee for the proposed transfer.
    Change(ChangeError<ChangeErrT, N>),
    /// Input selection attempted to generate an invalid transaction proposal.
    Proposal(ProposalError),
    /// An error occurred parsing the address from a payment request.
    Address(ConversionError<&'static str>),
    /// Insufficient funds were available to satisfy the payment request that inputs were being
    /// selected to attempt to satisfy.
    InsufficientFunds {
        available: Zatoshis,
        required: Zatoshis,
    },
    /// The data source does not have enough information to choose an expiry height
    /// for the transaction.
    SyncRequired,
}

impl<DE: fmt::Display, SE: fmt::Display, CE: fmt::Display, N: fmt::Display> fmt::Display
    for InputSelectorError<DE, SE, CE, N>
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self {
            InputSelectorError::DataSource(e) => {
                write!(
                    f,
                    "The underlying datasource produced the following error: {e}"
                )
            }
            InputSelectorError::Selection(e) => {
                write!(f, "Note selection encountered the following error: {e}")
            }
            InputSelectorError::Change(e) => write!(
                f,
                "Proposal generation failed due to an error in computing change or transaction fees: {e}"
            ),
            InputSelectorError::Proposal(e) => {
                write!(
                    f,
                    "Input selection attempted to generate an invalid proposal: {e}"
                )
            }
            InputSelectorError::Address(e) => {
                write!(
                    f,
                    "An error occurred decoding the address from a payment request: {e}."
                )
            }
            InputSelectorError::InsufficientFunds {
                available,
                required,
            } => write!(
                f,
                "Insufficient balance (have {}, need {} including fee)",
                u64::from(*available),
                u64::from(*required)
            ),
            InputSelectorError::SyncRequired => {
                write!(f, "Insufficient chain data is available, sync required.")
            }
        }
    }
}

impl<DE, SE, CE, N> error::Error for InputSelectorError<DE, SE, CE, N>
where
    DE: Debug + Display + error::Error + 'static,
    SE: Debug + Display + error::Error + 'static,
    CE: Debug + Display + error::Error + 'static,
    N: Debug + Display + 'static,
{
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match &self {
            Self::DataSource(e) => Some(e),
            Self::Selection(e) => Some(e),
            Self::Change(e) => Some(e),
            Self::Proposal(e) => Some(e),
            _ => None,
        }
    }
}

impl<E, S, F, N> From<ConversionError<&'static str>> for InputSelectorError<E, S, F, N> {
    fn from(value: ConversionError<&'static str>) -> Self {
        InputSelectorError::Address(value)
    }
}

impl<E, S, C, N> From<ChangeError<C, N>> for InputSelectorError<E, S, C, N> {
    fn from(err: ChangeError<C, N>) -> Self {
        InputSelectorError::Change(err)
    }
}

impl<E, S, C, N> From<ProposalError> for InputSelectorError<E, S, C, N> {
    fn from(err: ProposalError) -> Self {
        InputSelectorError::Proposal(err)
    }
}

/// A strategy for selecting transaction inputs and proposing transaction outputs.
///
/// Proposals should include only economically useful inputs, as determined by `Self::FeeRule`;
/// that is, do not return inputs that cause fees to increase by an amount greater than the value
/// of the input.
pub trait InputSelector {
    /// The type of errors that may be generated in input selection
    type Error;

    /// The type of data source that the input selector expects to access to obtain input notes.
    /// This associated type permits input selectors that may use specialized knowledge of the
    /// internals of a particular backing data store, if the generic API of `InputSource` does not
    /// provide sufficiently fine-grained operations for a particular backing store to optimally
    /// perform input selection.
    type InputSource: InputSource;

    /// Performs input selection and returns a proposal for transaction construction including
    /// change and fee outputs.
    ///
    /// Implementations of this method should return inputs sufficient to satisfy the given
    /// transaction request using a best-effort strategy to preserve user privacy, as follows:
    /// * If it is possible to satisfy the specified transaction request by creating
    ///   a fully-shielded transaction without requiring value to cross pool boundaries,
    ///   return the inputs necessary to construct such a transaction; otherwise
    /// * If it is possible to satisfy the transaction request by creating a fully-shielded
    ///   transaction with some amounts crossing between shielded pools, return the inputs
    ///   necessary.
    ///
    /// If insufficient funds are available to satisfy the required outputs for the shielding
    /// request, this operation must fail and return [`InputSelectorError::InsufficientFunds`].
    ///
    /// `spend_policy` controls which sources of funds the implementation may draw upon. It names
    /// the shielded pools from which notes may be selected — the implementation must not select
    /// notes from a pool the policy does not permit, returning
    /// [`InputSelectorError::InsufficientFunds`] rather than crossing into a non-permitted pool —
    /// and, behind the `transparent-inputs` feature flag, whether and from which addresses the
    /// account's transparent UTXOs may additionally be spent. Spending transparent funds, or
    /// combining notes across shielded pools, reduces privacy, so the caller must opt in
    /// explicitly by naming the permitted sources.
    #[allow(clippy::type_complexity)]
    #[allow(clippy::too_many_arguments)]
    fn propose_transaction<ParamsT, ChangeT>(
        &self,
        params: &ParamsT,
        wallet_db: &Self::InputSource,
        target_height: TargetHeight,
        anchor_height: BlockHeight,
        zip318: &PoolMigrationParams,
        confirmations_policy: ConfirmationsPolicy,
        account: <Self::InputSource as InputSource>::AccountId,
        transaction_request: TransactionRequest,
        change_strategy: &ChangeT,
        spend_policy: &SpendPolicy,
        proposed_version: Option<TxVersion>,
    ) -> Result<
        Proposal<<ChangeT as ChangeStrategy>::FeeRule, <Self::InputSource as InputSource>::NoteRef>,
        InputSelectorError<
            <Self::InputSource as InputSource>::Error,
            Self::Error,
            ChangeT::Error,
            <Self::InputSource as InputSource>::NoteRef,
        >,
    >
    where
        ParamsT: consensus::Parameters,
        ChangeT: ChangeStrategy<MetaSource = Self::InputSource>;
}

/// A strategy for selecting transaction inputs and proposing transaction outputs
/// for shielding-only transactions (transactions which spend transparent UTXOs and
/// send all transaction outputs to the wallet's shielded internal address(es)).
#[cfg(feature = "transparent-inputs")]
pub trait ShieldingSelector {
    /// The type of errors that may be generated in input selection
    type Error;
    /// The type of data source that the input selector expects to access to obtain input
    /// transparent UTXOs. This associated type permits input selectors that may use specialized
    /// knowledge of the internals of a particular backing data store, if the generic API of
    /// [`InputSource`] does not provide sufficiently fine-grained operations for a
    /// particular backing store to optimally perform input selection.
    type InputSource: InputSource;

    /// Performs input selection and returns a proposal for the construction of a shielding
    /// transaction.
    ///
    /// Implementations should return the maximum possible number of economically useful inputs
    /// required to supply at least the requested value, choosing only inputs received at the
    /// specified source addresses. If insufficient funds are available to satisfy the required
    /// outputs for the shielding request, this operation must fail and return
    /// [`InputSelectorError::InsufficientFunds`].
    ///
    /// The `output_filter` parameter controls which transparent outputs are eligible for
    /// inclusion in the proposal. See [`CoinbaseFilter`] for details.
    #[allow(clippy::type_complexity)]
    #[allow(clippy::too_many_arguments)]
    fn propose_shielding<ParamsT, ChangeT>(
        &self,
        params: &ParamsT,
        wallet_db: &Self::InputSource,
        change_strategy: &ChangeT,
        shielding_threshold: Zatoshis,
        source_addrs: &[TransparentAddress],
        to_account: <Self::InputSource as InputSource>::AccountId,
        target_height: TargetHeight,
        anchor_height: BlockHeight,
        zip318: &PoolMigrationParams,
        confirmations_policy: ConfirmationsPolicy,
        output_filter: CoinbaseFilter,
    ) -> Result<
        Proposal<<ChangeT as ChangeStrategy>::FeeRule, Infallible>,
        InputSelectorError<
            <Self::InputSource as InputSource>::Error,
            Self::Error,
            ChangeT::Error,
            Infallible,
        >,
    >
    where
        ParamsT: consensus::Parameters,
        ChangeT: ChangeStrategy<MetaSource = Self::InputSource>;

    /// Performs input selection and returns a proposal for the construction of a transaction
    /// that shields coinbase transparent outputs to an arbitrary shielded recipient.
    ///
    /// This method differs from [`Self::propose_shielding`] in the following ways:
    ///
    /// - Only coinbase transparent outputs are eligible for inclusion in the proposal. This
    ///   restriction is hard-coded; callers cannot opt in to selecting non-coinbase outputs
    ///   via this method. Coinbase outputs are uniquely suited to being sent to arbitrary
    ///   shielded recipients because they have no prior transparent transaction graph that
    ///   could be exposed to the recipient.
    /// - The `to_address` argument specifies the destination of the shielded value. It must
    ///   be a shielded address (Sapling, or a Unified Address with a shielded receiver). It
    ///   may be an external address not belonging to any account we control.
    /// - The resulting proposal carries an explicit ZIP-321 payment to `to_address` for the
    ///   full available value (input total minus fee). **No change is produced**, in either
    ///   the transparent or any shielded pool. This is a privacy invariant: producing a
    ///   shielded change output would allow the recipient (or any chain observer) to learn
    ///   the sender's total selected-coinbase value by summing the public transparent input
    ///   values and subtracting the visible payment amount. Since this method targets the
    ///   `z_shieldcoinbase`-style "sweep coinbase to a recipient" workflow, where the
    ///   recipient may not belong to the sender's wallet, change is forbidden by design.
    ///
    /// Because no change is produced, this method takes a `fee_rule` directly rather than a
    /// [`ChangeStrategy`]: there is no change to compute, and no per-account metadata is
    /// required.
    ///
    /// The `memo` parameter is stored in the shielded output's memo field; it is always
    /// permitted because a shielded payment is always present.
    ///
    /// The `limit` parameter, when `Some(n)`, caps the number of transparent inputs to at
    /// most `n`, keeping the highest-value UTXOs (with a stable tiebreaker by outpoint).
    /// `Some(0)` selects no inputs and will therefore return
    /// [`InputSelectorError::InsufficientFunds`].
    ///
    /// If the total value of selected inputs (after any cap imposed by `limit`), minus the
    /// fee, is less than `shielding_threshold`, this method returns
    /// [`InputSelectorError::InsufficientFunds`].
    #[allow(clippy::type_complexity)]
    #[allow(clippy::too_many_arguments)]
    fn propose_shielding_coinbase<ParamsT, FeeRuleT>(
        &self,
        params: &ParamsT,
        wallet_db: &Self::InputSource,
        fee_rule: &FeeRuleT,
        shielding_threshold: Zatoshis,
        source_addrs: &[TransparentAddress],
        to_address: ZcashAddress,
        memo: Option<MemoBytes>,
        limit: Option<usize>,
        target_height: TargetHeight,
        anchor_height: BlockHeight,
    ) -> Result<
        Proposal<FeeRuleT, Infallible>,
        InputSelectorError<
            <Self::InputSource as InputSource>::Error,
            Self::Error,
            FeeRuleT::Error,
            Infallible,
        >,
    >
    where
        ParamsT: consensus::Parameters,
        FeeRuleT: FeeRule + Clone;
}

/// Errors that can occur as a consequence of greedy input selection.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum GreedyInputSelectorError {
    /// An intermediate value overflowed or underflowed the valid monetary range.
    Balance(BalanceError),
    /// A unified address did not contain a supported receiver.
    UnsupportedAddress(Box<UnifiedAddress>),
    /// Support for transparent-source-only (TEX) addresses requires the transparent-inputs feature.
    UnsupportedTexAddress,
}

impl fmt::Display for GreedyInputSelectorError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self {
            GreedyInputSelectorError::Balance(e) => write!(
                f,
                "A balance calculation violated amount validity bounds: {e:?}."
            ),
            GreedyInputSelectorError::UnsupportedAddress(_) => {
                // we can't encode the UA to its string representation because we
                // don't have network parameters here
                write!(f, "Unified address contains no supported receivers.")
            }
            GreedyInputSelectorError::UnsupportedTexAddress => {
                write!(
                    f,
                    "Support for transparent-source-only (TEX) addresses requires the transparent-inputs feature."
                )
            }
        }
    }
}

impl<DbErrT, ChangeErrT, N> From<GreedyInputSelectorError>
    for InputSelectorError<DbErrT, GreedyInputSelectorError, ChangeErrT, N>
{
    fn from(err: GreedyInputSelectorError) -> Self {
        InputSelectorError::Selection(err)
    }
}

impl<DbErrT, ChangeErrT, N> From<BalanceError>
    for InputSelectorError<DbErrT, GreedyInputSelectorError, ChangeErrT, N>
{
    fn from(err: BalanceError) -> Self {
        InputSelectorError::Selection(GreedyInputSelectorError::Balance(err))
    }
}

pub(crate) struct SaplingPayment(Zatoshis);

#[cfg(test)]
impl SaplingPayment {
    pub(crate) fn new(amount: Zatoshis) -> Self {
        SaplingPayment(amount)
    }
}

impl sapling::OutputView for SaplingPayment {
    fn value(&self) -> Zatoshis {
        self.0
    }
}

#[cfg(feature = "orchard")]
pub(crate) struct OrchardPayment(Zatoshis);

#[cfg(test)]
#[cfg(feature = "orchard")]
impl OrchardPayment {
    pub(crate) fn new(amount: Zatoshis) -> Self {
        OrchardPayment(amount)
    }
}

#[cfg(feature = "orchard")]
impl orchard_fees::OutputView for OrchardPayment {
    fn value(&self) -> Zatoshis {
        self.0
    }
}

/// The default maximum fraction of a block's space, as an integer percentage, that a single
/// shielding transaction's transparent inputs may occupy.
#[cfg(feature = "transparent-inputs")]
const DEFAULT_SHIELDING_BLOCK_SPACE_PERCENT: u32 = 10;

/// The largest existing action envelope and input set used for optional consolidation.
///
/// Necessary funding inputs are not subject to this limit.
const CONSOLIDATION_LIMIT: usize = 5;

/// A `BTreeSet` that is guaranteed to contain at least one element.
///
/// Non-emptiness is maintained by construction: every constructor requires at least one
/// element, and no mutating operations are exposed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NonEmptyBTreeSet<T>(BTreeSet<T>);

impl<T: Ord> NonEmptyBTreeSet<T> {
    /// Constructs a set containing only the given element.
    pub fn singleton(value: T) -> Self {
        Self(BTreeSet::from_iter([value]))
    }

    /// Constructs a set containing the elements of the given non-empty list, collapsing
    /// duplicates.
    pub fn from_nonempty(values: NonEmpty<T>) -> Self {
        Self(values.into_iter().collect())
    }

    /// Constructs a set from the given `BTreeSet`, or returns `None` if the set is empty.
    pub fn from_set(values: BTreeSet<T>) -> Option<Self> {
        (!values.is_empty()).then_some(Self(values))
    }
}

impl<T> NonEmptyBTreeSet<T> {
    /// Returns a reference to the wrapped set.
    pub fn as_set(&self) -> &BTreeSet<T> {
        &self.0
    }

    /// Returns an iterator over the elements of the set, in ascending order.
    pub fn iter(&self) -> std::collections::btree_set::Iter<'_, T> {
        self.0.iter()
    }
}

/// The sources of funds an [`InputSelector`] is permitted to draw upon when satisfying a
/// transaction request.
///
/// Crossing a shielded pool boundary reduces privacy, so it must be an explicit choice of the
/// caller: the selector only spends notes from the shielded pools named in [`Self::shielded`], and
/// only spends transparent UTXOs when a [`TransparentSpendPolicy`] is provided. When a single
/// permitted pool cannot cover the request, the selector may combine the permitted pools (drawing
/// on the legacy Orchard pool last); if no combination of permitted sources suffices it returns
/// [`InputSelectorError::InsufficientFunds`] rather than reaching into a pool the caller did not
/// permit.
///
/// The default permits every shielded pool present in the build and no transparent spending,
/// preserving the historical fully-shielded behavior while letting a caller restrict the set to,
/// for example, `{Orchard}` to forbid pool crossing.
#[derive(Clone, Debug)]
pub struct SpendPolicy {
    shielded: BTreeSet<ShieldedPool>,
    #[cfg(feature = "transparent-inputs")]
    transparent: Option<TransparentSpendPolicy>,
    locked_input_policy: LockedInputPolicy,
    note_selection: NoteSelection,
}

/// How an [`InputSelector`] chooses among eligible notes when funding a payment.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NoteSelection {
    /// Accumulate the oldest eligible notes until the target value is covered.
    #[default]
    Accumulate,
    /// Prefer funding from a SINGLE note — the oldest eligible note whose value alone covers the
    /// target — falling back to accumulation when no such note exists.
    ///
    /// A ZIP 318 migration transfer spends exactly one note, so a canonical pool crossing is
    /// achievable only under single-note funding; multi-note funding is not an error, but the
    /// resulting proposal does not have the canonical shape.
    PreferSingle,
    /// Prefer a small funding set while opportunistically consolidating additional notes without
    /// changing the transaction's fee or observable shape.
    ///
    /// Necessary funding is not capped. When the selected pool's existing transaction shape has
    /// no more than five actions, the selector may add the smallest eligible notes while keeping
    /// the total selected from that pool at no more than five and preserving the existing shape.
    /// Pool and locked-input preferences still take precedence; if no single permitted pool can
    /// fund the payment, selection falls back to ordinary multi-pool funding. If consolidation is
    /// not possible, the funding-only proposal is returned.
    PreferConsolidation,
}

impl Default for SpendPolicy {
    fn default() -> Self {
        Self::shielded_pools([
            ShieldedPool::Sapling,
            #[cfg(feature = "orchard")]
            ShieldedPool::Orchard,
            #[cfg(feature = "orchard")]
            ShieldedPool::Ironwood,
        ])
    }
}

impl SpendPolicy {
    /// Constructs a policy permitting selection from exactly the given shielded pools, with no
    /// transparent spending.
    pub fn shielded_pools(pools: impl IntoIterator<Item = ShieldedPool>) -> Self {
        Self {
            shielded: pools.into_iter().collect(),
            #[cfg(feature = "transparent-inputs")]
            transparent: None,
            locked_input_policy: LockedInputPolicy::Exclude,
            note_selection: NoteSelection::Accumulate,
        }
    }

    /// Returns whether notes may be selected from the given shielded pool.
    pub fn permits_shielded(&self, pool: ShieldedPool) -> bool {
        self.shielded.contains(&pool)
    }

    /// Returns the set of shielded pools from which notes may be selected.
    pub fn shielded(&self) -> &BTreeSet<ShieldedPool> {
        &self.shielded
    }

    /// Adds a transparent spend policy, permitting transparent UTXOs to be spent as described.
    #[cfg(feature = "transparent-inputs")]
    pub fn with_transparent(mut self, transparent: TransparentSpendPolicy) -> Self {
        self.transparent = Some(transparent);
        self
    }

    /// Returns the transparent spend policy, or `None` if transparent UTXOs may not be spent.
    #[cfg(feature = "transparent-inputs")]
    pub fn transparent(&self) -> Option<&TransparentSpendPolicy> {
        self.transparent.as_ref()
    }

    /// Sets how input selection treats locked outputs (default: `LockedInputPolicy::Exclude`).
    pub fn with_locked_input_policy(mut self, policy: LockedInputPolicy) -> Self {
        self.locked_input_policy = policy;
        self
    }

    /// Returns the policy governing selection of locked outputs.
    pub fn locked_input_policy(&self) -> &LockedInputPolicy {
        &self.locked_input_policy
    }

    /// Sets how the selector chooses among eligible notes (default:
    /// [`NoteSelection::Accumulate`]).
    pub fn with_note_selection(mut self, note_selection: NoteSelection) -> Self {
        self.note_selection = note_selection;
        self
    }

    /// Returns how the selector chooses among eligible notes.
    pub fn note_selection(&self) -> NoteSelection {
        self.note_selection
    }
}

/// The caller's choice of which coinbase transparent outputs a transparent spend may draw upon.
///
/// Consensus requires coinbase funds to be spent to a single shielded output with no change and
/// without being mixed with non-coinbase inputs, so a transparent spend commits to one or the
/// other rather than combining them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CoinbasePolicy {
    /// Spend only coinbase transparent outputs.
    OnlyCoinbase,
    /// Spend only non-coinbase transparent outputs.
    NonCoinbase,
}

#[cfg(feature = "transparent-inputs")]
impl From<CoinbasePolicy> for CoinbaseFilter {
    fn from(policy: CoinbasePolicy) -> Self {
        match policy {
            CoinbasePolicy::OnlyCoinbase => CoinbaseFilter::CoinbaseOnly,
            CoinbasePolicy::NonCoinbase => CoinbaseFilter::NonCoinbaseOnly,
        }
    }
}

/// Specifies how transparent UTXOs may be spent in a transfer, when a [`SpendPolicy`] permits
/// transparent spending.
///
/// Spending transparent funds links the chosen transparent addresses on-chain, reducing privacy,
/// so a caller opts in by attaching this to a [`SpendPolicy`] via [`SpendPolicy::with_transparent`]
/// (the absence of a policy — the default — spends no transparent UTXOs). The policy names the
/// [`TransparentSource`] the UTXOs may be drawn from and, via [`CoinbasePolicy`], whether coinbase
/// or non-coinbase outputs are spent.
#[cfg(feature = "transparent-inputs")]
#[derive(Clone, Debug)]
pub struct TransparentSpendPolicy {
    source: TransparentSource,
    coinbase: CoinbasePolicy,
}

#[cfg(feature = "transparent-inputs")]
impl TransparentSpendPolicy {
    /// Spends non-coinbase UTXOs from arbitrary transparent receivers belonging to the account,
    /// as needed to satisfy the request. The proposer chooses the addresses, potentially linking
    /// them. (The legacy `ANY_TADDR` behavior.)
    pub fn any_account_addr() -> Self {
        Self {
            source: TransparentSource::AnyAccountAddr,
            coinbase: CoinbasePolicy::NonCoinbase,
        }
    }

    /// Spends non-coinbase UTXOs only from the specified transparent addresses, intentionally
    /// linking them.
    pub fn from_addresses(taddrs: NonEmpty<TransparentAddress>) -> Self {
        Self {
            source: TransparentSource::FromAddresses(NonEmptyBTreeSet::from_nonempty(taddrs)),
            coinbase: CoinbasePolicy::NonCoinbase,
        }
    }

    /// Spends non-coinbase UTXOs only from a single transparent address.
    pub fn from_one_address(taddr: TransparentAddress) -> Self {
        Self {
            source: TransparentSource::FromAddresses(NonEmptyBTreeSet::singleton(taddr)),
            coinbase: CoinbasePolicy::NonCoinbase,
        }
    }

    /// Returns a copy of this policy with the given coinbase policy in effect.
    pub fn with_coinbase(mut self, coinbase: CoinbasePolicy) -> Self {
        self.coinbase = coinbase;
        self
    }

    /// Returns the transparent source from which UTXOs may be drawn.
    pub fn source(&self) -> &TransparentSource {
        &self.source
    }

    /// Returns the coinbase policy in effect for this transparent spend.
    pub fn coinbase(&self) -> CoinbasePolicy {
        self.coinbase
    }

    /// Returns the explicit list of transparent addresses UTXOs may be drawn from, or `None` if
    /// any of the account's transparent receivers are permitted.
    fn address_allow_list(&self) -> Option<Vec<TransparentAddress>> {
        match &self.source {
            TransparentSource::FromAddresses(addrs) => Some(addrs.iter().copied().collect()),
            TransparentSource::AnyAccountAddr => None,
        }
    }
}

/// The transparent receivers a [`TransparentSpendPolicy`] may draw UTXOs from.
#[cfg(feature = "transparent-inputs")]
#[derive(Clone, Debug)]
pub enum TransparentSource {
    /// Any transparent receiver belonging to the account. The proposer chooses which, potentially
    /// linking them.
    AnyAccountAddr,
    /// Only the specified transparent addresses.
    FromAddresses(NonEmptyBTreeSet<TransparentAddress>),
}

/// An [`InputSelector`] implementation that uses a greedy strategy to select between available
/// notes.
///
/// This implementation performs input selection using methods available via the
/// [`InputSource`] interface.
pub struct GreedyInputSelector<DbT> {
    /// The maximum fraction of a block's space, as an integer percentage (0–100), that a
    /// single transaction's transparent inputs may occupy. Bounds both shielding
    /// transactions and the transparent gather performed for general (non-shielding)
    /// transfers when the active [`TransparentSpendPolicy`] requires it.
    #[cfg(feature = "transparent-inputs")]
    shielding_block_space_percent: u32,
    /// The policy governing whether the transparent UTXOs gathered by
    /// [`ShieldingSelector::propose_shielding`] and
    /// [`ShieldingSelector::propose_shielding_coinbase`] may be drawn from locked outputs.
    /// Defaults to [`LockedInputPolicy::Exclude`]. Unlike [`SpendPolicy::locked_input_policy`],
    /// which a caller supplies per call to [`InputSelector::propose_transaction`], shielding has
    /// no per-call policy argument, so this is configured once on the selector instance via
    /// [`Self::with_locked_input_policy`].
    #[cfg(feature = "transparent-inputs")]
    locked_input_policy: LockedInputPolicy,
    _ds_type: PhantomData<DbT>,
}

impl<DbT> GreedyInputSelector<DbT> {
    /// Constructs a new greedy input selector that uses the provided change strategy to determine
    /// change values and fee amounts.
    ///
    /// The [`ChangeStrategy`] provided must produce exactly one ephemeral change value when
    /// computing a transaction balance if an [`EphemeralBalance::Output`] value is provided for
    /// its ephemeral balance, or the resulting [`GreedyInputSelector`] will return an error when
    /// attempting to construct a transaction proposal that requires such an output.
    ///
    /// [`EphemeralBalance::Output`]: crate::fees::EphemeralBalance::Output
    pub fn new() -> Self {
        GreedyInputSelector {
            #[cfg(feature = "transparent-inputs")]
            shielding_block_space_percent: DEFAULT_SHIELDING_BLOCK_SPACE_PERCENT,
            #[cfg(feature = "transparent-inputs")]
            locked_input_policy: LockedInputPolicy::Exclude,
            _ds_type: PhantomData,
        }
    }

    /// Sets the maximum fraction of a block's space, as an integer percentage (0–100), that a
    /// single transaction's transparent inputs may occupy.
    ///
    /// When shielding gathers more spendable transparent outputs than will fit within this
    /// bound, the highest-value outputs are selected first and the remainder are left unspent,
    /// to be consolidated by a subsequent shielding transaction. When a general (non-shielding)
    /// transfer's transparent gather would otherwise require more inputs than fit within this
    /// bound, the gather stops at the cap even if the requested value has not yet been
    /// reached; the caller's input-selection loop surfaces this as an `InsufficientFunds`
    /// error, the same as for any other value shortfall. Values above 100 are clamped to 100.
    /// Defaults to 10.
    #[cfg(feature = "transparent-inputs")]
    pub fn with_shielding_block_space_percent(mut self, percent: u32) -> Self {
        self.shielding_block_space_percent = percent.min(100);
        self
    }

    /// Sets the policy governing whether shielding (via
    /// [`ShieldingSelector::propose_shielding`] and
    /// [`ShieldingSelector::propose_shielding_coinbase`]) may draw on transparent UTXOs locked
    /// by one of the given policy's owners (default: [`LockedInputPolicy::Exclude`], which never
    /// selects a locked output). This overrides a lock only for the purpose of *selecting through*
    /// it during shielding; it does not release the lock.
    #[cfg(feature = "transparent-inputs")]
    pub fn with_locked_input_policy(mut self, policy: LockedInputPolicy) -> Self {
        self.locked_input_policy = policy;
        self
    }

    #[cfg(feature = "transparent-inputs")]
    #[allow(clippy::too_many_arguments)]
    #[allow(clippy::type_complexity)]
    fn gather_transparent<ChangeT>(
        &self,
        wallet_db: &DbT,
        target_height: TargetHeight,
        confirmations_policy: ConfirmationsPolicy,
        account: <DbT as InputSource>::AccountId,
        // The list used to filter addresses.
        // If `None`, any address is allowed.
        address_allow_list: Option<&[TransparentAddress]>,
        // Which coinbase outputs are eligible for selection.
        coinbase: CoinbaseFilter,
        transaction_request: &TransactionRequest,
        amount_at_transparent_gather: &mut Zatoshis,
        locked_input_policy: &LockedInputPolicy,
    ) -> Result<
        Vec<WalletTransparentOutput<()>>,
        InputSelectorError<
            <DbT as InputSource>::Error,
            <GreedyInputSelector<DbT> as InputSelector>::Error,
            <ChangeT as ChangeStrategy>::Error,
            <DbT as InputSource>::NoteRef,
        >,
    >
    where
        DbT: InputSource,
        ChangeT: ChangeStrategy<MetaSource = DbT>,
    {
        let max_money = Zatoshis::const_from_u64(zcash_protocol::value::MAX_MONEY);
        let mut total_opt: Option<Zatoshis> = Some(Zatoshis::ZERO);
        for payment in transaction_request.payments().values() {
            let Some(payment_amount) = payment.amount() else {
                total_opt = None;
                break;
            };
            if let Some(t) = total_opt {
                match t + payment_amount {
                    Some(sum) => total_opt = Some(sum),
                    None => {
                        return Err(InputSelectorError::InsufficientFunds {
                            available: Zatoshis::ZERO,
                            required: max_money,
                        });
                    }
                }
            }
        }
        let (target_value, amount_at_gather) = match total_opt {
            Some(z) => (TargetValue::AtLeast(z), z),
            None => (
                TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
                Zatoshis::ZERO,
            ),
        };
        *amount_at_transparent_gather = amount_at_gather;
        // Input selection honors the caller's `SpendPolicy::locked_input_policy`: by default
        // (`Exclude`) a locked output is never drawn upon, since it belongs to another in-flight
        // proposal and spending it would recreate the conflict that locking exists to prevent; the
        // `PreferUnlocked`/`PreferLocked` overrides let a caller draw through a lock it recognizes
        // (e.g. its own pool-migration PCZTs).
        Ok(wallet_db
            .select_spendable_transparent_outputs(
                account,
                target_height,
                confirmations_policy,
                coinbase,
                address_allow_list,
                target_value,
                shielding_max_inputs(self.shielding_block_space_percent),
                &StandardFeeRule::Zip317,
                LockFilter::Policy(locked_input_policy),
            )
            .map_err(InputSelectorError::DataSource)?
            .into_iter()
            .map(|utxo| utxo.redact_account_data())
            .collect::<Vec<_>>())
    }
}

/// Returns the maximum number of transparent inputs that a single transaction may select,
/// given the configured fraction of a block's space (as an integer percentage) that its
/// inputs may occupy. Used to bound both shielding transactions and the transparent gather
/// for general (non-shielding) transfers.
#[cfg(feature = "transparent-inputs")]
fn shielding_max_inputs(block_space_percent: u32) -> usize {
    (MAX_BLOCK_BYTES.saturating_mul(block_space_percent as usize) / 100) / P2PKH_STANDARD_INPUT_SIZE
}

impl<DbT> Default for GreedyInputSelector<DbT> {
    fn default() -> Self {
        Self::new()
    }
}

impl<DbT: InputSource> InputSelector for GreedyInputSelector<DbT> {
    type Error = GreedyInputSelectorError;
    type InputSource = DbT;

    #[allow(clippy::type_complexity)]
    fn propose_transaction<ParamsT, ChangeT>(
        &self,
        params: &ParamsT,
        wallet_db: &Self::InputSource,
        target_height: TargetHeight,
        anchor_height: BlockHeight,
        zip318: &PoolMigrationParams,
        confirmations_policy: ConfirmationsPolicy,
        account: <DbT as InputSource>::AccountId,
        transaction_request: TransactionRequest,
        change_strategy: &ChangeT,
        spend_policy: &SpendPolicy,
        proposed_version: Option<TxVersion>,
    ) -> Result<
        Proposal<<ChangeT as ChangeStrategy>::FeeRule, DbT::NoteRef>,
        InputSelectorError<<DbT as InputSource>::Error, Self::Error, ChangeT::Error, DbT::NoteRef>,
    >
    where
        ParamsT: consensus::Parameters,
        Self::InputSource: InputSource,
        ChangeT: ChangeStrategy<MetaSource = DbT>,
    {
        let (sapling_supported, orchard_supported) =
            proposed_version.map_or(Ok((true, true)), |v| {
                let branch_id =
                    consensus::BranchId::for_height(params, BlockHeight::from(target_height));
                if v.valid_in_branch(branch_id) {
                    Ok((
                        v.has_sapling(),
                        cfg!(feature = "orchard") && v.has_orchard(),
                    ))
                } else {
                    Err(ProposalError::IncompatibleTxVersion(branch_id))
                }
            })?;
        // Without the `orchard` feature there are no Orchard-family pools to select from, so
        // `orchard_supported` (always false) is only referenced by Orchard-gated code.
        #[cfg(not(feature = "orchard"))]
        let _ = orchard_supported;

        let mut transparent_outputs = vec![];
        let mut sapling_outputs = vec![];
        #[cfg(feature = "orchard")]
        let mut orchard_outputs = vec![];
        let mut payment_pools = BTreeMap::new();

        // In a ZIP 320 pair, tr0 refers to the first transaction request that
        // collects shielded value and sends it to an ephemeral address, and tr1
        // refers to the second transaction request that pays the TEX addresses.
        #[cfg(feature = "transparent-inputs")]
        let mut tr1_transparent_outputs = vec![];
        #[cfg(feature = "transparent-inputs")]
        let mut tr1_payments = vec![];
        #[cfg(feature = "transparent-inputs")]
        let mut tr1_payment_pools = BTreeMap::new();
        // This balance value is just used for overflow checking; the actual value of ephemeral
        // outputs will be computed from the constructed `tr1_transparent_outputs` value
        // constructed below.
        #[cfg(feature = "transparent-inputs")]
        let mut total_ephemeral = Zatoshis::ZERO;

        for (idx, payment) in transaction_request.payments() {
            let payment_amount = payment
                .amount()
                .ok_or(ProposalError::PaymentAmountMissing(*idx))?;
            let recipient_address: Address = payment
                .recipient_address()
                .clone()
                .convert_if_network(params.network_type())?;

            match recipient_address {
                Address::Transparent(addr) => {
                    payment_pools.insert(*idx, PoolType::TRANSPARENT);
                    transparent_outputs.push(TxOut::new(payment_amount, addr.script().into()));
                }
                #[cfg(feature = "transparent-inputs")]
                Address::Tex(data) => {
                    let p2pkh_addr = TransparentAddress::PublicKeyHash(data);

                    tr1_payment_pools.insert(*idx, PoolType::TRANSPARENT);
                    tr1_transparent_outputs
                        .push(TxOut::new(payment_amount, p2pkh_addr.script().into()));
                    tr1_payments.push(
                        Payment::new(
                            payment.recipient_address().clone(),
                            payment.amount(),
                            None,
                            payment.label().cloned(),
                            payment.message().cloned(),
                            payment.other_params().to_vec(),
                        )
                        .expect("cannot fail because memo is None and amount is nonzero"),
                    );
                    total_ephemeral = (total_ephemeral + payment_amount)
                        .ok_or(GreedyInputSelectorError::Balance(BalanceError::Overflow))?;
                }
                #[cfg(not(feature = "transparent-inputs"))]
                Address::Tex(_) => {
                    return Err(InputSelectorError::Selection(
                        GreedyInputSelectorError::UnsupportedTexAddress,
                    ));
                }
                Address::Sapling(_) => {
                    payment_pools.insert(*idx, PoolType::SAPLING);
                    sapling_outputs.push(SaplingPayment(payment_amount));
                }
                Address::Unified(addr) => {
                    #[cfg(feature = "orchard")]
                    if addr.has_orchard() && orchard_supported {
                        // Represent an Orchard-receiver payment as an Ironwood-pool output once
                        // Ironwood is active (its value is accounted to the Ironwood bundle
                        // below), and as an Orchard-pool output otherwise.
                        let pool = if ironwood_active_at(params, target_height) {
                            // After NU6.3 the Orchard turnstile (a consensus rule) forbids adding
                            // value to the Orchard pool, so the payment must be delivered through
                            // the Ironwood bundle, which only a version 6 transaction carries. If a
                            // transaction version was explicitly requested that cannot carry an
                            // Ironwood bundle, reject the proposal here rather than constructing one
                            // that could only fail at build time.
                            if let Some(v) = proposed_version
                                && !v.has_ironwood()
                            {
                                return Err(
                                    ProposalError::OrchardReceiverRequiresIronwood(v).into()
                                );
                            }
                            PoolType::IRONWOOD
                        } else {
                            PoolType::ORCHARD
                        };
                        payment_pools.insert(*idx, pool);
                        orchard_outputs.push(OrchardPayment(payment_amount));
                        continue;
                    }

                    if addr.has_sapling() && sapling_supported {
                        payment_pools.insert(*idx, PoolType::SAPLING);
                        sapling_outputs.push(SaplingPayment(payment_amount));
                        continue;
                    }

                    if let Some(addr) = addr.transparent() {
                        payment_pools.insert(*idx, PoolType::TRANSPARENT);
                        transparent_outputs.push(TxOut::new(payment_amount, addr.script().into()));
                        continue;
                    }

                    return Err(InputSelectorError::Selection(
                        GreedyInputSelectorError::UnsupportedAddress(Box::new(addr)),
                    ));
                }
            }
        }

        #[cfg(not(feature = "transparent-inputs"))]
        let transparent_inputs = vec![];
        #[cfg(feature = "transparent-inputs")]
        let mut amount_at_transparent_gather = Zatoshis::ZERO;
        #[cfg(feature = "transparent-inputs")]
        let mut transparent_inputs = match spend_policy.transparent() {
            None => {
                // No transparent spending is permitted; skip the gather entirely.
                Vec::new()
            }
            Some(transparent) => {
                let address_allow_list = transparent.address_allow_list();
                self.gather_transparent::<ChangeT>(
                    wallet_db,
                    target_height,
                    confirmations_policy,
                    account,
                    address_allow_list.as_deref(),
                    transparent.coinbase().into(),
                    &transaction_request,
                    &mut amount_at_transparent_gather,
                    spend_policy.locked_input_policy(),
                )?
            }
        };
        // Outpoints of gathered transparent inputs that the change strategy has identified as
        // dust. Accumulated across loop iterations so that a re-gather (triggered by
        // `ChangeError::InsufficientFunds`, below) does not re-introduce previously pruned
        // outputs.
        #[cfg(feature = "transparent-inputs")]
        let mut transparent_dust: BTreeSet<OutPoint> = BTreeSet::new();

        let mut shielded_inputs = ReceivedNotes::empty();
        let mut prior_available = Zatoshis::ZERO;
        let mut amount_required = Zatoshis::ZERO;
        let mut consolidation_target = Zatoshis::ZERO;
        let mut consolidation_source = None;
        let mut consolidation_additional = ReceivedNotes::empty();
        let mut exclude: Vec<DbT::NoteRef> = vec![];

        // The single pool-preference order that governs both which pools notes are
        // selected from and which of the selected notes are spent: the pool matching
        // the payment's outputs comes first, and later pools are drawn upon only when
        // the earlier ones cannot cover the required amount, so that pool crossing is
        // minimized. For a payment to an Orchard receiver the Orchard-family pools
        // lead: once NU6.3 is active such payments are constructed in the Ironwood
        // bundle — moving their value into the Ironwood pool — so Ironwood is
        // preferred, with the legacy Orchard pool last within the family.
        #[cfg(feature = "orchard")]
        let mut pool_preference = selectable_pool_preference(
            params,
            target_height,
            sapling_supported,
            orchard_supported,
            !orchard_outputs.is_empty(),
        );
        #[cfg(not(feature = "orchard"))]
        let mut pool_preference = {
            let mut pools = vec![];
            if sapling_supported {
                pools.push(ShieldedPool::Sapling);
            }
            pools
        };

        // Restrict selection to the shielded pools the caller's spend policy permits. Crossing a
        // pool boundary is privacy-breaking, so a pool the policy does not name is never drawn
        // upon — not even as a fallback when the permitted pools cannot cover the request, in
        // which case input selection reports `InsufficientFunds`.
        pool_preference.retain(|pool| spend_policy.permits_shielded(*pool));

        // This loop is guaranteed to terminate because on each iteration we check that the amount
        // of funds selected is strictly increasing. The loop will either return a successful
        // result or the wallet will eventually run out of funds to select.
        loop {
            #[cfg(not(feature = "orchard"))]
            let sapling_bundle_required = true;
            #[cfg(feature = "orchard")]
            let (sapling_bundle_required, orchard_bundle_required, ironwood_bundle_required) = {
                // Trim the selected notes to the pools that are actually needed: the first
                // pool (in `pool_preference` order) whose selected notes cover the required
                // amount is spent alone; otherwise pools are accumulated in preference order
                // until the running total covers the amount, or all pools are in use.
                let pool_values = [
                    (ShieldedPool::Sapling, shielded_inputs.sapling_value()?),
                    (ShieldedPool::Orchard, shielded_inputs.orchard_value()?),
                    (ShieldedPool::Ironwood, shielded_inputs.ironwood_value()?),
                ];
                let value_of = |pool: ShieldedPool| {
                    pool_values
                        .iter()
                        .find(|(p, _)| *p == pool)
                        .map(|(_, v)| *v)
                        .expect("all shielded pools are present in pool_values")
                };

                let shielded_amount_required =
                    if spend_policy.note_selection() == NoteSelection::PreferConsolidation {
                        consolidation_target
                    } else {
                        amount_required
                    };
                let use_pools: Vec<ShieldedPool> = if let Some(single) = pool_preference
                    .iter()
                    .find(|p| value_of(**p) >= shielded_amount_required)
                {
                    vec![*single]
                } else {
                    let mut running = Zatoshis::ZERO;
                    let mut used = vec![];
                    for pool in &pool_preference {
                        if running >= shielded_amount_required {
                            break;
                        }
                        running = (running + value_of(*pool))
                            .ok_or(GreedyInputSelectorError::Balance(BalanceError::Overflow))?;
                        used.push(*pool);
                    }
                    used
                };

                (
                    use_pools.contains(&ShieldedPool::Sapling),
                    use_pools.contains(&ShieldedPool::Orchard),
                    use_pools.contains(&ShieldedPool::Ironwood),
                )
            };

            let sapling_inputs = if sapling_bundle_required {
                shielded_inputs
                    .sapling()
                    .iter()
                    .map(|i| (*i.internal_note_id(), i.note().value()))
                    .collect()
            } else {
                vec![]
            };

            #[cfg(feature = "orchard")]
            let orchard_inputs = if orchard_bundle_required {
                shielded_inputs
                    .orchard()
                    .iter()
                    .map(|i| (*i.internal_note_id(), i.note().value()))
                    .collect()
            } else {
                vec![]
            };

            // Ironwood inputs are attributed to the Ironwood bundle for action-count and fee
            // purposes.
            #[cfg(feature = "orchard")]
            let ironwood_inputs = if ironwood_bundle_required {
                shielded_inputs
                    .ironwood()
                    .iter()
                    .map(|i| (*i.internal_note_id(), i.note().value()))
                    .collect()
            } else {
                vec![]
            };

            let selected_input_ids = sapling_inputs.iter().map(|(id, _)| id);
            #[cfg(feature = "orchard")]
            let selected_input_ids =
                selected_input_ids.chain(orchard_inputs.iter().map(|(id, _)| id));
            #[cfg(feature = "orchard")]
            let selected_input_ids =
                selected_input_ids.chain(ironwood_inputs.iter().map(|(id, _)| id));

            let selected_input_ids = selected_input_ids.cloned().collect::<Vec<_>>();

            let wallet_meta = change_strategy
                .fetch_wallet_meta(wallet_db, account, target_height, &selected_input_ids)
                .map_err(InputSelectorError::DataSource)?;

            #[cfg(not(feature = "transparent-inputs"))]
            let ephemeral_output_value = None;

            #[cfg(feature = "transparent-inputs")]
            let (ephemeral_output_value, tr1_balance_opt) = {
                if tr1_transparent_outputs.is_empty() {
                    (None, None)
                } else {
                    // The ephemeral input going into transaction 1 must be able to pay that
                    // transaction's fee, as well as the TEX address payments.

                    // Transaction 1 carries no shielded spends or outputs, but the change
                    // strategy may still model hypothetical shielded change against these
                    // views, so they carry the bundle versions in effect at the target
                    // height rather than a fixed default.
                    #[cfg(feature = "orchard")]
                    let empty_orchard_view = (
                        orchard_bundle_version_for_height(params, target_height),
                        &[] as &[Infallible],
                        &[] as &[Infallible],
                    );
                    #[cfg(feature = "orchard")]
                    let empty_ironwood_view = (
                        ironwood_bundle_version_for_height(params, target_height),
                        &[] as &[Infallible],
                        &[] as &[Infallible],
                    );

                    // First compute the required total with an additional zero input,
                    // catching the `InsufficientFunds` error to obtain the required amount
                    // given the provided change strategy. Ignore the change memo in order
                    // to avoid adding a change output.
                    let tr1_required_input_value = match change_strategy
                        .compute_balance::<_, DbT::NoteRef>(
                            params,
                            target_height,
                            anchor_height,
                            zip318,
                            &[] as &[WalletTransparentOutput<<DbT as InputSource>::AccountId>],
                            &tr1_transparent_outputs,
                            &sapling::EmptyBundleView,
                            #[cfg(feature = "orchard")]
                            &empty_orchard_view,
                            #[cfg(feature = "orchard")]
                            &empty_ironwood_view,
                            Some(EphemeralBalance::Input(Zatoshis::ZERO)),
                            &wallet_meta,
                        ) {
                        Err(ChangeError::InsufficientFunds { required, .. }) => required,
                        Err(ChangeError::DustInputs { .. }) => {
                            unreachable!("no inputs were supplied")
                        }
                        Err(other) => return Err(InputSelectorError::Change(other)),
                        Ok(_) => Zatoshis::ZERO, // shouldn't happen
                    };

                    // Now recompute to obtain the `TransactionBalance` and verify that it
                    // fully accounts for the required fees.
                    let tr1_balance = change_strategy.compute_balance::<_, DbT::NoteRef>(
                        params,
                        target_height,
                        anchor_height,
                        zip318,
                        &[] as &[WalletTransparentOutput<<DbT as InputSource>::AccountId>],
                        &tr1_transparent_outputs,
                        &sapling::EmptyBundleView,
                        #[cfg(feature = "orchard")]
                        &empty_orchard_view,
                        #[cfg(feature = "orchard")]
                        &empty_ironwood_view,
                        Some(EphemeralBalance::Input(tr1_required_input_value)),
                        &wallet_meta,
                    )?;
                    assert_eq!(tr1_balance.total(), tr1_balance.fee_required());

                    (Some(tr1_required_input_value), Some(tr1_balance))
                }
            };

            // The Orchard bundle keeps the Orchard (version 2) spends; its outputs move to the
            // Ironwood bundle when routing is active. The Ironwood bundle takes the Ironwood
            // (version 3) spends, and its outputs when routing is active. Attributing each pool's
            // spends to its own bundle keeps the action counts (and hence the fee) matching the
            // transaction the builder produces.
            #[cfg(feature = "orchard")]
            let orchard_view = (
                orchard_bundle_version_for_height(params, target_height),
                &orchard_inputs[..],
                if ironwood_active_at(params, target_height) {
                    &[]
                } else {
                    &orchard_outputs[..]
                },
            );
            #[cfg(feature = "orchard")]
            let ironwood_view = (
                ironwood_bundle_version_for_height(params, target_height),
                &ironwood_inputs[..],
                if ironwood_active_at(params, target_height) {
                    &orchard_outputs[..]
                } else {
                    &[]
                },
            );

            // Tracks whether this iteration's error handling changed the transparent input
            // set, either by re-gathering with a corrected value bound (`InsufficientFunds`)
            // or by pruning dust (`DustInputs`). A changed transparent input set is a valid
            // form of progress in its own right (distinct from the shielded-note progress
            // tracked by `prior_available`/`new_available` below): without this, an account
            // with no spendable shielded notes at all (or none beyond what's already
            // excluded) would spuriously report `InsufficientFunds` on the very next check
            // below, even though the changed transparent input set might already be
            // sufficient to satisfy the request on the next iteration. Termination is
            // preserved: `amount_at_transparent_gather` increases strictly across
            // re-gathers, and each outpoint can be pruned as dust at most once (pruned
            // outpoints accumulate in `transparent_dust` and are never re-gathered).
            #[cfg(not(feature = "transparent-inputs"))]
            let transparent_inputs_changed = false;
            #[cfg(feature = "transparent-inputs")]
            let mut transparent_inputs_changed = false;

            // In the ZIP 320 case, this is the balance for transaction 0, taking into account
            // the ephemeral output.
            let tr0_balance = change_strategy.compute_balance(
                params,
                target_height,
                anchor_height,
                zip318,
                &transparent_inputs,
                &transparent_outputs,
                &(
                    ::sapling::builder::BundleType::DEFAULT,
                    &sapling_inputs[..],
                    &sapling_outputs[..],
                ),
                #[cfg(feature = "orchard")]
                &orchard_view,
                #[cfg(feature = "orchard")]
                &ironwood_view,
                ephemeral_output_value.map(EphemeralBalance::Output),
                &wallet_meta,
            );

            match tr0_balance {
                Ok(mut tr0_balance) => {
                    #[cfg(not(feature = "transparent-inputs"))]
                    let consolidation_supported = true;
                    #[cfg(feature = "transparent-inputs")]
                    let consolidation_supported = tr1_balance_opt.is_none();

                    if spend_policy.note_selection() == NoteSelection::PreferConsolidation
                        && consolidation_supported
                        && let Some(source) = consolidation_source
                        // A Sapling spend is separately visible even when ZIP 317's grace actions
                        // keep the fee unchanged. Orchard-family spends may instead replace dummy
                        // spend sides in an already-visible action.
                        && source != ShieldedPool::Sapling
                    {
                        let funding_count = note_count_for_pool(&shielded_inputs, source);
                        let payment_output_count = match source {
                            ShieldedPool::Sapling => sapling_outputs.len(),
                            #[cfg(feature = "orchard")]
                            ShieldedPool::Orchard => {
                                if ironwood_active_at(params, target_height) {
                                    0
                                } else {
                                    orchard_outputs.len()
                                }
                            }
                            #[cfg(feature = "orchard")]
                            ShieldedPool::Ironwood => {
                                if ironwood_active_at(params, target_height) {
                                    orchard_outputs.len()
                                } else {
                                    0
                                }
                            }
                            #[cfg(not(feature = "orchard"))]
                            ShieldedPool::Orchard | ShieldedPool::Ironwood => 0,
                        };

                        if let Some(baseline_action_count) =
                            consolidation_action_count(&tr0_balance, source, payment_output_count)
                            && baseline_action_count <= CONSOLIDATION_LIMIT
                            && funding_count < baseline_action_count
                            && funding_count < CONSOLIDATION_LIMIT
                        {
                            let optional_count =
                                note_count_for_pool(&consolidation_additional, source)
                                    .min(CONSOLIDATION_LIMIT - funding_count)
                                    .min(baseline_action_count - funding_count);

                            // Try the largest shape-neutral cleanup first, then smaller prefixes.
                            // This matters when excluding all candidates changes the split-change
                            // decision but excluding a smaller prefix does not.
                            for count in (1..=optional_count).rev() {
                                let candidate_notes =
                                    note_prefix_for_pool(&consolidation_additional, source, count);

                                let mut candidate_sapling_inputs = sapling_inputs.clone();
                                candidate_sapling_inputs.extend(
                                    candidate_notes.sapling().iter().map(|note| {
                                        (*note.internal_note_id(), note.note().value())
                                    }),
                                );
                                #[cfg(feature = "orchard")]
                                let mut candidate_orchard_inputs = orchard_inputs.clone();
                                #[cfg(feature = "orchard")]
                                candidate_orchard_inputs.extend(
                                    candidate_notes.orchard().iter().map(|note| {
                                        (*note.internal_note_id(), note.note().value())
                                    }),
                                );
                                #[cfg(feature = "orchard")]
                                let mut candidate_ironwood_inputs = ironwood_inputs.clone();
                                #[cfg(feature = "orchard")]
                                candidate_ironwood_inputs.extend(
                                    candidate_notes.ironwood().iter().map(|note| {
                                        (*note.internal_note_id(), note.note().value())
                                    }),
                                );

                                let candidate_input_ids =
                                    candidate_sapling_inputs.iter().map(|(id, _)| id);
                                #[cfg(feature = "orchard")]
                                let candidate_input_ids = candidate_input_ids
                                    .chain(candidate_orchard_inputs.iter().map(|(id, _)| id));
                                #[cfg(feature = "orchard")]
                                let candidate_input_ids = candidate_input_ids
                                    .chain(candidate_ironwood_inputs.iter().map(|(id, _)| id));
                                let candidate_input_ids =
                                    candidate_input_ids.cloned().collect::<Vec<_>>();

                                let candidate_wallet_meta = change_strategy
                                    .fetch_wallet_meta(
                                        wallet_db,
                                        account,
                                        target_height,
                                        &candidate_input_ids,
                                    )
                                    .map_err(InputSelectorError::DataSource)?;

                                #[cfg(feature = "orchard")]
                                let candidate_orchard_view = (
                                    orchard_bundle_version_for_height(params, target_height),
                                    &candidate_orchard_inputs[..],
                                    if ironwood_active_at(params, target_height) {
                                        &[]
                                    } else {
                                        &orchard_outputs[..]
                                    },
                                );
                                #[cfg(feature = "orchard")]
                                let candidate_ironwood_view = (
                                    ironwood_bundle_version_for_height(params, target_height),
                                    &candidate_ironwood_inputs[..],
                                    if ironwood_active_at(params, target_height) {
                                        &orchard_outputs[..]
                                    } else {
                                        &[]
                                    },
                                );

                                let candidate_balance = change_strategy.compute_balance(
                                    params,
                                    target_height,
                                    anchor_height,
                                    zip318,
                                    &transparent_inputs,
                                    &transparent_outputs,
                                    &(
                                        ::sapling::builder::BundleType::DEFAULT,
                                        &candidate_sapling_inputs[..],
                                        &sapling_outputs[..],
                                    ),
                                    #[cfg(feature = "orchard")]
                                    &candidate_orchard_view,
                                    #[cfg(feature = "orchard")]
                                    &candidate_ironwood_view,
                                    ephemeral_output_value.map(EphemeralBalance::Output),
                                    &candidate_wallet_meta,
                                );

                                if let Ok(candidate_balance) = candidate_balance
                                    && same_change_shape(&tr0_balance, &candidate_balance)
                                    && consolidation_action_count(
                                        &candidate_balance,
                                        source,
                                        payment_output_count,
                                    ) == Some(baseline_action_count)
                                {
                                    shielded_inputs.append(candidate_notes);
                                    tr0_balance = candidate_balance;
                                    break;
                                }
                            }
                        }
                    }

                    // At this point, we have enough input value to pay for everything, so we
                    // return here.
                    let shielded_inputs =
                        NonEmpty::from_vec(shielded_inputs.into_vec(&SimpleNoteRetention {
                            sapling: sapling_bundle_required,
                            #[cfg(feature = "orchard")]
                            orchard: orchard_bundle_required,
                            #[cfg(feature = "orchard")]
                            ironwood: ironwood_bundle_required,
                        }))
                        .map(ShieldedInputs::from_parts);

                    return build_proposal(
                        change_strategy.fee_rule(),
                        tr0_balance,
                        target_height,
                        anchor_height,
                        confirmations_policy,
                        shielded_inputs,
                        transparent_inputs,
                        transaction_request,
                        payment_pools,
                        #[cfg(feature = "orchard")]
                        ironwood_active_at(params, target_height),
                        #[cfg(feature = "transparent-inputs")]
                        ephemeral_output_value.zip(tr1_balance_opt).map(
                            |(ephemeral_output_value, tr1_balance)| EphemeralStepConfig {
                                ephemeral_output_value,
                                tr1_balance,
                                tr1_payments,
                                tr1_payment_pools,
                            },
                        ),
                    )
                    .map_err(InputSelectorError::Proposal);
                }
                Err(ChangeError::DustInputs {
                    #[cfg(feature = "transparent-inputs")]
                    transparent,
                    mut sapling,
                    #[cfg(feature = "orchard")]
                    mut orchard,
                    #[cfg(feature = "orchard")]
                    mut ironwood,
                    ..
                }) => {
                    exclude.append(&mut sapling);
                    #[cfg(feature = "orchard")]
                    exclude.append(&mut orchard);
                    #[cfg(feature = "orchard")]
                    exclude.append(&mut ironwood);
                    #[cfg(feature = "transparent-inputs")]
                    {
                        let len_before = transparent_inputs.len();
                        transparent_dust.extend(transparent);
                        transparent_inputs.retain(|i| !transparent_dust.contains(i.outpoint()));
                        // Pruning dust changes the balance computation, so give the loop a
                        // chance to re-evaluate the pruned set before concluding that funds
                        // are insufficient.
                        if transparent_inputs.len() != len_before {
                            transparent_inputs_changed = true;
                        }
                    }
                }
                Err(ChangeError::InsufficientFunds { required, .. }) => {
                    amount_required = required;
                    // The initial transparent-input gather was bounded by the payouts
                    // alone, but `required` includes the fee. If the bound was too
                    // low, re-gather transparents with the corrected value as a
                    // defensive fallback. The common case (fee estimate was close) is
                    // a no-op.
                    #[cfg(feature = "transparent-inputs")]
                    if let Some(transparent) = spend_policy.transparent()
                        && required > amount_at_transparent_gather
                    {
                        let address_allow_list = transparent.address_allow_list();
                        // Honor the caller's `SpendPolicy::locked_input_policy`, as at the
                        // initial gather above.
                        transparent_inputs = wallet_db
                            .select_spendable_transparent_outputs(
                                account,
                                target_height,
                                confirmations_policy,
                                transparent.coinbase().into(),
                                address_allow_list.as_deref(),
                                TargetValue::AtLeast(required),
                                shielding_max_inputs(self.shielding_block_space_percent),
                                &StandardFeeRule::Zip317,
                                LockFilter::Policy(spend_policy.locked_input_policy()),
                            )
                            .map_err(InputSelectorError::DataSource)?
                            .into_iter()
                            // Do not re-introduce outputs previously pruned as dust; the
                            // value they would contribute is (approximately) consumed by
                            // their own fee cost, so their absence does not meaningfully
                            // reduce the gathered value.
                            .filter(|utxo| !transparent_dust.contains(utxo.outpoint()))
                            .map(|utxo| utxo.redact_account_data())
                            .collect::<Vec<_>>();
                        amount_at_transparent_gather = required;
                        transparent_inputs_changed = true;
                    }

                    if spend_policy.note_selection() == NoteSelection::PreferConsolidation {
                        #[cfg(feature = "transparent-inputs")]
                        {
                            let transparent_value = transparent_inputs
                                .iter()
                                .map(WalletTransparentOutput::value)
                                .try_fold(Zatoshis::ZERO, |total, value| total + value)
                                .ok_or(InputSelectorError::Selection(
                                    GreedyInputSelectorError::Balance(BalanceError::Overflow),
                                ))?;
                            consolidation_target =
                                (required - transparent_value).unwrap_or(Zatoshis::ZERO);
                        }
                        #[cfg(not(feature = "transparent-inputs"))]
                        {
                            consolidation_target = required;
                        }
                    }
                }
                Err(other) => return Err(InputSelectorError::Change(other)),
            }

            // Candidate notes are selected from the pools of `pool_preference` — the
            // same order the pool-usage trimming at the top of the loop applies — so
            // the notes offered for spending and the notes actually spent are governed
            // by one policy: pool crossing is minimized, and a payment to an Orchard
            // receiver draws on the pool its output is constructed in (the Ironwood
            // pool once NU6.3 is active).
            // Input selection honors the caller's `SpendPolicy::locked_input_policy`: by default
            // (`Exclude`) a locked output is never drawn upon, since it belongs to another
            // in-flight proposal and spending it would recreate the conflict that locking exists
            // to prevent; the `PreferUnlocked`/`PreferLocked` overrides let a caller draw through
            // a lock it recognizes (e.g. its own pool-migration PCZTs).
            //
            // `PreferSingle` falls back to ordinary accumulation when no note covers the target.
            // `PreferConsolidation` tries minimum-cardinality funding from each pool in preference
            // order. If no single pool can cover the target, every partial result is discarded and
            // the ordinary multi-pool path is used so the preference never breaks payment liveness
            // or changes pool-affinity fallback.
            let preferred_notes = match spend_policy.note_selection() {
                NoteSelection::PreferSingle => Some(
                    wallet_db
                        .select_single_spendable_note(
                            account,
                            amount_required,
                            &pool_preference,
                            target_height,
                            confirmations_policy,
                            &exclude,
                            LockFilter::Policy(spend_policy.locked_input_policy()),
                        )
                        .map_err(InputSelectorError::DataSource)?,
                )
                .filter(|notes| !notes.is_empty()),
                NoteSelection::PreferConsolidation => {
                    consolidation_source = None;
                    consolidation_additional = ReceivedNotes::empty();

                    if consolidation_target == Zatoshis::ZERO {
                        Some(ReceivedNotes::empty())
                    } else {
                        let mut covering = None;
                        for source in pool_preference.iter().copied() {
                            let (funding, additional) = wallet_db
                                .select_spendable_notes_for_consolidation(
                                    account,
                                    consolidation_target,
                                    source,
                                    target_height,
                                    confirmations_policy,
                                    &exclude,
                                    LockFilter::Policy(spend_policy.locked_input_policy()),
                                    CONSOLIDATION_LIMIT - 1,
                                )
                                .map_err(InputSelectorError::DataSource)?
                                .into_parts();

                            if funding.total_value()? >= consolidation_target {
                                covering = Some((source, funding, additional));
                                break;
                            }
                        }

                        covering.map(|(source, funding, additional)| {
                            consolidation_source = Some(source);
                            consolidation_additional = additional;
                            funding
                        })
                    }
                }
                NoteSelection::Accumulate => None,
            };
            let selection_target =
                if spend_policy.note_selection() == NoteSelection::PreferConsolidation {
                    consolidation_target
                } else {
                    amount_required
                };
            shielded_inputs = match preferred_notes {
                Some(notes) => notes,
                None => wallet_db
                    .select_spendable_notes(
                        account,
                        TargetValue::AtLeast(selection_target),
                        &pool_preference,
                        target_height,
                        confirmations_policy,
                        &exclude,
                        LockFilter::Policy(spend_policy.locked_input_policy()),
                    )
                    .map_err(InputSelectorError::DataSource)?,
            };

            let new_available = shielded_inputs.total_value()?;
            if new_available <= prior_available && !transparent_inputs_changed {
                return Err(InputSelectorError::InsufficientFunds {
                    required: amount_required,
                    available: new_available,
                });
            } else {
                // If the set of selected shielded notes has grown, or the transparent
                // input set changed this iteration, we will loop again and see whether
                // we now have enough funds.
                prior_available = new_available;
            }
        }
    }
}

/// Returns the number of notes in `pool` without exposing pool-specific vectors to the selector.
fn note_count_for_pool<NoteRef>(notes: &ReceivedNotes<NoteRef>, pool: ShieldedPool) -> usize {
    match pool {
        ShieldedPool::Sapling => notes.sapling().len(),
        #[cfg(feature = "orchard")]
        ShieldedPool::Orchard => notes.orchard().len(),
        #[cfg(feature = "orchard")]
        ShieldedPool::Ironwood => notes.ironwood().len(),
        #[cfg(not(feature = "orchard"))]
        ShieldedPool::Orchard | ShieldedPool::Ironwood => 0,
    }
}

/// Copies the first `count` notes from one pool into an otherwise-empty collection.
fn note_prefix_for_pool<NoteRef: Clone>(
    notes: &ReceivedNotes<NoteRef>,
    pool: ShieldedPool,
    count: usize,
) -> ReceivedNotes<NoteRef> {
    match pool {
        ShieldedPool::Sapling => ReceivedNotes::new(
            notes.sapling().iter().take(count).cloned().collect(),
            #[cfg(feature = "orchard")]
            vec![],
            #[cfg(feature = "orchard")]
            vec![],
        ),
        #[cfg(feature = "orchard")]
        ShieldedPool::Orchard => ReceivedNotes::new(
            vec![],
            notes.orchard().iter().take(count).cloned().collect(),
            vec![],
        ),
        #[cfg(feature = "orchard")]
        ShieldedPool::Ironwood => ReceivedNotes::new(
            vec![],
            vec![],
            notes.ironwood().iter().take(count).cloned().collect(),
        ),
        #[cfg(not(feature = "orchard"))]
        ShieldedPool::Orchard | ShieldedPool::Ironwood => ReceivedNotes::empty(),
    }
}

/// Returns the shielded action count recorded by a balance for `pool`.
///
/// Real outputs and recorded dummy outputs jointly occupy every output side of an Orchard-family
/// action, so their sum is the exact action count the balance was costed for.
fn consolidation_action_count(
    balance: &TransactionBalance,
    pool: ShieldedPool,
    payment_output_count: usize,
) -> Option<usize> {
    let dummy_outputs = balance.dummy_outputs()?;
    let change_output_count = balance
        .proposed_change()
        .iter()
        .filter(|change| change.output_pool() == PoolType::Shielded(pool))
        .count();
    let dummy_output_count = match pool {
        ShieldedPool::Sapling => dummy_outputs.sapling(),
        #[cfg(feature = "orchard")]
        ShieldedPool::Orchard => dummy_outputs.orchard(),
        #[cfg(feature = "orchard")]
        ShieldedPool::Ironwood => dummy_outputs.ironwood(),
        #[cfg(not(feature = "orchard"))]
        ShieldedPool::Orchard | ShieldedPool::Ironwood => return None,
    };

    payment_output_count
        .checked_add(change_output_count)?
        .checked_add(dummy_output_count)
}

/// Returns whether optional inputs preserved the balance's observable and fee-relevant shape.
///
/// Change values may increase by the value of the optional inputs, but the destination pools,
/// memos, output roles, dummy-output counts, and fee must remain identical.
fn same_change_shape(baseline: &TransactionBalance, candidate: &TransactionBalance) -> bool {
    baseline.fee_required() == candidate.fee_required()
        && baseline.dummy_outputs().is_some()
        && baseline.dummy_outputs() == candidate.dummy_outputs()
        && baseline.proposed_change().len() == candidate.proposed_change().len()
        && baseline
            .proposed_change()
            .iter()
            .zip(candidate.proposed_change())
            .all(|(baseline, candidate)| {
                baseline.output_pool() == candidate.output_pool()
                    && baseline.memo() == candidate.memo()
                    && baseline.is_ephemeral() == candidate.is_ephemeral()
            })
}

/// Returns the shielded pools from which the greedy input selector may spend at the
/// given target height, in preference order.
///
/// The pool family matching the payment's outputs comes first, so that single-pool
/// coverage avoids unnecessary pool crossings: for an Orchard-family payment this is
/// Ironwood (when active) and then Orchard — an Orchard-receiver payment is delivered
/// via the Ironwood bundle once Ironwood is active — and for other payments it is
/// Sapling. The legacy Orchard pool comes last otherwise, so that it is drawn upon
/// only when the more current pools cannot cover the required amount.
#[cfg(feature = "orchard")]
fn selectable_pool_preference<ParamsT: consensus::Parameters>(
    params: &ParamsT,
    target_height: TargetHeight,
    sapling_supported: bool,
    orchard_supported: bool,
    prefer_orchard_family: bool,
) -> Vec<ShieldedPool> {
    let ironwood_selectable = orchard_supported && ironwood_active_at(params, target_height);
    let mut preference = Vec::with_capacity(3);
    if prefer_orchard_family {
        if ironwood_selectable {
            preference.push(ShieldedPool::Ironwood);
        }
        if orchard_supported {
            preference.push(ShieldedPool::Orchard);
        }
        if sapling_supported {
            preference.push(ShieldedPool::Sapling);
        }
    } else {
        if sapling_supported {
            preference.push(ShieldedPool::Sapling);
        }
        if ironwood_selectable {
            preference.push(ShieldedPool::Ironwood);
        }
        if orchard_supported {
            preference.push(ShieldedPool::Orchard);
        }
    }
    preference
}

/// Returns the Orchard bundle version whose action-count policy applies to
/// transactions constructed for the given target height.
#[cfg(feature = "orchard")]
fn orchard_bundle_version_for_height<ParamsT: consensus::Parameters, H: Into<BlockHeight>>(
    params: &ParamsT,
    target_height: H,
) -> ::orchard::bundle::BundleVersion {
    zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
        consensus::BranchId::for_height(params, target_height.into()),
        ::orchard::ValuePool::Orchard,
    )
    // Orchard did not exist prior to NU5, so no Orchard bundle (and no Orchard
    // action) can be produced for a pre-NU5 target height; every bundle version
    // yields the correct action count (zero) for an empty bundle.
    .unwrap_or(::orchard::bundle::BundleVersion::orchard_insecure_v1())
}

/// Returns the Ironwood bundle version whose action-count policy applies to
/// transactions constructed for the given target height.
#[cfg(feature = "orchard")]
fn ironwood_bundle_version_for_height<ParamsT: consensus::Parameters, H: Into<BlockHeight>>(
    params: &ParamsT,
    target_height: H,
) -> ::orchard::bundle::BundleVersion {
    zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
        consensus::BranchId::for_height(params, target_height.into()),
        ::orchard::ValuePool::Ironwood,
    )
    // The Ironwood pool did not exist prior to NU6.3, so no Ironwood bundle (and
    // no Ironwood action) can be produced for an earlier target height; every
    // bundle version yields the correct action count (zero) for an empty bundle.
    .unwrap_or(::orchard::bundle::BundleVersion::ironwood_v3())
}

#[allow(clippy::type_complexity, clippy::too_many_arguments)]
pub(crate) fn propose_send_max<ParamsT, InputSourceT, FeeRuleT>(
    params: &ParamsT,
    wallet_db: &InputSourceT,
    fee_rule: &FeeRuleT,
    source_account: InputSourceT::AccountId,
    spend_pools: &[ShieldedPool],
    target_height: TargetHeight,
    anchor_height: BlockHeight,
    mode: MaxSpendMode,
    confirmations_policy: ConfirmationsPolicy,
    recipient: ZcashAddress,
    memo: Option<MemoBytes>,
    locked_input_policy: &LockedInputPolicy,
) -> Result<
    Proposal<FeeRuleT, InputSourceT::NoteRef>,
    InputSelectorError<
        InputSourceT::Error,
        GreedyInputSelectorError,
        FeeRuleT::Error,
        InputSourceT::NoteRef,
    >,
>
where
    ParamsT: consensus::Parameters,
    InputSourceT: InputSource,
    FeeRuleT: FeeRule + Clone,
{
    // Input selection honors the caller's `locked_input_policy`: by default (`Exclude`) a
    // locked output is never drawn upon, since it belongs to another in-flight proposal and
    // spending it would recreate the conflict that locking exists to prevent; the
    // `PreferUnlocked`/`PreferLocked` overrides let a caller draw through a lock it recognizes
    // (e.g. its own pool-migration PCZTs).
    let spendable_notes = wallet_db
        .select_spendable_notes(
            source_account,
            TargetValue::AllFunds(mode),
            spend_pools,
            target_height,
            confirmations_policy,
            &[],
            LockFilter::Policy(locked_input_policy),
        )
        .map_err(InputSelectorError::DataSource)?;

    let input_total = spendable_notes
        .total_value()
        .map_err(|e| InputSelectorError::Selection(GreedyInputSelectorError::Balance(e)))?;

    let mut payment_pools = BTreeMap::new();

    // An Orchard receiver takes delivery precedence over a Sapling receiver only when
    // this build is able to produce Orchard-family outputs; without the `orchard`
    // feature, a payment to a recipient having both receivers is delivered via the
    // Sapling receiver.
    #[cfg(feature = "orchard")]
    let orchard_receiver_payable = recipient.can_receive_as(PoolType::ORCHARD);
    #[cfg(not(feature = "orchard"))]
    let orchard_receiver_payable = false;

    let sapling_output_count = {
        // we require a sapling output if the recipient has a Sapling receiver and its
        // payment is not deliverable via an Orchard receiver.
        let requested_sapling_outputs: usize =
            if recipient.can_receive_as(PoolType::SAPLING) && !orchard_receiver_payable {
                payment_pools.insert(0, PoolType::SAPLING);
                1
            } else {
                0
            };

        ::sapling::builder::BundleType::DEFAULT
            .num_outputs(spendable_notes.sapling.len(), requested_sapling_outputs)
            .map_err(|s| InputSelectorError::Change(ChangeError::BundleError(s)))?
    };

    let sapling_bundle_required = !spendable_notes.sapling().is_empty() || sapling_output_count > 0;

    // A payment to an Orchard receiver is represented in the proposal as an Ironwood-pool output
    // once Ironwood is active (delivered to the Orchard receiver via the Ironwood bundle), and as
    // an Orchard-pool output otherwise. The per-bundle action counts below reflect that split.
    #[cfg(feature = "orchard")]
    let orchard_receivers_fill_ironwood = ironwood_active_at(params, target_height);
    #[cfg(feature = "orchard")]
    if orchard_receiver_payable {
        payment_pools.insert(
            0,
            if orchard_receivers_fill_ironwood {
                PoolType::IRONWOOD
            } else {
                PoolType::ORCHARD
            },
        );
    }

    #[cfg(feature = "orchard")]
    let orchard_action_count = orchard_fees::transactional_action_count(
        // Input selection estimates fees with the padded default bundle type; the
        // unpadded opt-in is applied later by the change strategy.
        ::orchard::builder::BundleType::DEFAULT,
        orchard_bundle_version_for_height(params, target_height),
        spendable_notes.orchard.len(),
        usize::from(orchard_receiver_payable && !orchard_receivers_fill_ironwood),
    )
    .map_err(|e| InputSelectorError::Change(ChangeError::BundleError(e)))?;
    #[cfg(not(feature = "orchard"))]
    let orchard_action_count: usize = 0;

    #[cfg(feature = "orchard")]
    let orchard_bundle_required = orchard_action_count > 0;

    #[cfg(feature = "orchard")]
    let ironwood_action_count = orchard_fees::transactional_action_count(
        ::orchard::builder::BundleType::DEFAULT,
        ironwood_bundle_version_for_height(params, target_height),
        spendable_notes.ironwood.len(),
        usize::from(orchard_receiver_payable && orchard_receivers_fill_ironwood),
    )
    .map_err(|s| InputSelectorError::Change(ChangeError::BundleError(s)))?;
    #[cfg(not(feature = "orchard"))]
    let ironwood_action_count: usize = 0;

    #[cfg(feature = "orchard")]
    let ironwood_bundle_required = ironwood_action_count > 0;

    let recipient_address: Address = recipient
        .clone()
        .convert_if_network(params.network_type())?;

    // A recipient that can only receive funds via a transparent output — a bare
    // transparent address, or a unified address with no shielded receiver — is paid
    // directly from the proposed transaction. TEX recipients are excluded: their
    // payment is delivered by the ephemeral second step, which carries its own
    // payment pool assignment.
    let pays_transparent_directly = match &recipient_address {
        Address::Transparent(_) => true,
        Address::Unified(addr) => {
            addr.has_transparent() && !(addr.has_sapling() || addr.has_orchard())
        }
        _ => false,
    };
    if pays_transparent_directly {
        payment_pools.insert(0, PoolType::Transparent);
    }

    // A unified address that has been assigned no payment pool by this point contains
    // no receiver that this build is able to pay (for example, an address containing
    // only an Orchard receiver, in a build made without the `orchard` feature). Other
    // recipient kinds always receive an assignment above, except for TEX addresses,
    // whose payment is delivered by the ephemeral second step.
    if payment_pools.is_empty()
        && let Address::Unified(addr) = &recipient_address
    {
        return Err(InputSelectorError::Selection(
            GreedyInputSelectorError::UnsupportedAddress(Box::new(addr.clone())),
        ));
    }

    let (tr0_fee, tr1_fee) = match recipient_address {
        Address::Sapling(_) => fee_rule
            .fee_required(
                params,
                BlockHeight::from(target_height),
                [],
                [],
                spendable_notes.sapling().len(),
                sapling_output_count,
                orchard_action_count,
                ironwood_action_count,
            )
            .map(|fee| (fee, None)),
        Address::Transparent(_) => fee_rule
            .fee_required(
                params,
                BlockHeight::from(target_height),
                [],
                [P2PKH_STANDARD_OUTPUT_SIZE],
                spendable_notes.sapling().len(),
                sapling_output_count,
                orchard_action_count,
                ironwood_action_count,
            )
            .map(|fee| (fee, None)),
        Address::Unified(_) => fee_rule
            .fee_required(
                params,
                BlockHeight::from(target_height),
                [],
                if pays_transparent_directly {
                    vec![P2PKH_STANDARD_OUTPUT_SIZE]
                } else {
                    vec![]
                },
                spendable_notes.sapling().len(),
                sapling_output_count,
                orchard_action_count,
                ironwood_action_count,
            )
            .map(|fee| (fee, None)),
        // Paying a TEX recipient requires a second, purely transparent transaction that
        // spends an ephemeral output of the first; constructing that ZIP 320 pair is
        // only supported when the `transparent-inputs` feature is enabled.
        #[cfg(not(feature = "transparent-inputs"))]
        Address::Tex(_) => {
            return Err(InputSelectorError::Selection(
                GreedyInputSelectorError::UnsupportedTexAddress,
            ));
        }
        #[cfg(feature = "transparent-inputs")]
        Address::Tex(_) => fee_rule
            .fee_required(
                params,
                BlockHeight::from(target_height),
                [],
                [P2PKH_STANDARD_OUTPUT_SIZE],
                spendable_notes.sapling().len(),
                sapling_output_count,
                orchard_action_count,
                ironwood_action_count,
            )
            .and_then(|tr0_fee| {
                let tr1_fee = fee_rule.fee_required(
                    params,
                    BlockHeight::from(target_height),
                    [InputSize::Known(P2PKH_STANDARD_INPUT_SIZE)],
                    [P2PKH_STANDARD_OUTPUT_SIZE],
                    0,
                    0,
                    0,
                    0,
                )?;

                Ok((tr0_fee, Some(tr1_fee)))
            }),
    }
    .map_err(|fee_error| InputSelectorError::Change(ChangeError::StrategyError(fee_error)))?;

    // the total fee required for the all the involved transactions. For the case
    // of TEX it means the fee requied to send the max value to the ephemeral
    // address + the fee to send the value in that ephemeral change address to
    // the TEX address. The sum can only exceed the maximum monetary amount for a
    // fee rule that produces fees outside that amount's intended bounds.
    let total_fee_required = (tr0_fee + tr1_fee.unwrap_or(Zatoshis::ZERO)).ok_or(
        InputSelectorError::Selection(GreedyInputSelectorError::Balance(BalanceError::Overflow)),
    )?;

    // the total amount involved in the "send max" operation. This is the total
    // spendable value present in the wallet minus the fees required to perform
    // the send max operation. The proposal must deliver a nonzero amount to the
    // recipient: a send-max operation on a wallet whose entire balance would be
    // consumed by fees is reported as insufficient funds rather than proposed as
    // a fee-only transaction.
    let total_to_recipient = (input_total - total_fee_required)
        .filter(|amount| *amount > Zatoshis::ZERO)
        .ok_or(InputSelectorError::InsufficientFunds {
            available: input_total,
            required: (total_fee_required + Zatoshis::const_from_u64(1))
                .unwrap_or(Zatoshis::const_from_u64(MAX_MONEY)),
        })?;

    // when the recipient of the send max operation is a TEX address this is the
    // amount that will be needed to send the max available amount accounting the
    // fees needed to propose a transaction involving one transparent input and
    // one transparent output (the TEX address recipient.)
    #[cfg(feature = "transparent-inputs")]
    let ephemeral_output_value =
        tr1_fee.map(|fee| (total_to_recipient + fee).expect("overflow already checked"));

    #[cfg(feature = "transparent-inputs")]
    let tr0_change = ephemeral_output_value
        .into_iter()
        .map(ChangeValue::ephemeral_transparent)
        .collect();
    #[cfg(not(feature = "transparent-inputs"))]
    let tr0_change = vec![];

    // The transaction produces no change, unless this is a transaction to a TEX address; in this
    // case, the first transaction produces a single ephemeral change output.
    let tr0_balance = TransactionBalance::new(tr0_change, tr0_fee)
        .expect("the sum of an single-element vector of fee values cannot overflow");

    let payment = zip321::Payment::new(
        recipient,
        Some(total_to_recipient),
        memo,
        None,
        None,
        vec![],
    )
    .map_err(|e| InputSelectorError::Proposal(ProposalError::Zip321(e.with_index(0))))?;

    let transaction_request =
        TransactionRequest::new(vec![payment.clone()]).map_err(|payment_error| {
            InputSelectorError::Proposal(ProposalError::Zip321(payment_error))
        })?;

    let shielded_inputs = NonEmpty::from_vec(spendable_notes.into_vec(&SimpleNoteRetention {
        sapling: sapling_bundle_required,
        #[cfg(feature = "orchard")]
        orchard: orchard_bundle_required,
        #[cfg(feature = "orchard")]
        ironwood: ironwood_bundle_required,
    }))
    .map(ShieldedInputs::from_parts);

    build_proposal(
        fee_rule,
        tr0_balance,
        target_height,
        anchor_height,
        confirmations_policy,
        shielded_inputs,
        vec![],
        transaction_request,
        payment_pools,
        #[cfg(feature = "orchard")]
        ironwood_active_at(params, target_height),
        #[cfg(feature = "transparent-inputs")]
        ephemeral_output_value
            .zip(tr1_fee)
            .map(|(ephemeral_output_value, tr1_fee)| EphemeralStepConfig {
                ephemeral_output_value,
                tr1_balance: TransactionBalance::new(vec![], tr1_fee)
                    .expect("the sum of an empty vector of fee values cannot overflow"),
                tr1_payments: vec![payment],
                tr1_payment_pools: BTreeMap::from_iter([(0, PoolType::Transparent)]),
            }),
    )
    .map_err(InputSelectorError::Proposal)
}

#[cfg(feature = "transparent-inputs")]
struct EphemeralStepConfig {
    ephemeral_output_value: Zatoshis,
    tr1_balance: TransactionBalance,
    tr1_payments: Vec<Payment>,
    tr1_payment_pools: BTreeMap<usize, PoolType>,
}

#[allow(clippy::too_many_arguments)]
fn build_proposal<FeeRuleT: FeeRule + Clone, NoteRef>(
    fee_rule: &FeeRuleT,
    tr0_balance: TransactionBalance,
    target_height: TargetHeight,
    anchor_height: BlockHeight,
    confirmations_policy: ConfirmationsPolicy,
    shielded_inputs: Option<ShieldedInputs<NoteRef>>,
    transparent_inputs: Vec<WalletTransparentOutput<()>>,
    transaction_request: TransactionRequest,
    payment_pools: BTreeMap<usize, PoolType>,
    #[cfg(feature = "orchard")] ironwood_active: bool,
    #[cfg(feature = "transparent-inputs")] ephemeral_step_opt: Option<EphemeralStepConfig>,
) -> Result<Proposal<FeeRuleT, NoteRef>, ProposalError> {
    #[cfg(feature = "transparent-inputs")]
    if let Some(ephemeral_step) = ephemeral_step_opt {
        let tr1_balance = ephemeral_step.tr1_balance;
        // Construct two new `TransactionRequest`s:
        // * `tr0` excludes the TEX outputs, and in their place includes
        //   a single additional ephemeral output to the transparent pool.
        // * `tr1` spends from that ephemeral output to each TEX output.

        // Find exactly one ephemeral change output.
        let ephemeral_outputs = tr0_balance
            .proposed_change()
            .iter()
            .enumerate()
            .filter(|(_, c)| c.is_ephemeral())
            .collect::<Vec<_>>();

        let ephemeral_output_index = match &ephemeral_outputs[..] {
            [(i, change_value)]
                if change_value.value() == ephemeral_step.ephemeral_output_value =>
            {
                Ok(*i)
            }
            _ => Err(ProposalError::EphemeralOutputsInvalid),
        }?;

        let ephemeral_stepoutput =
            StepOutput::new(0, StepOutputIndex::Change(ephemeral_output_index));

        let tr0 = TransactionRequest::from_indexed(
            transaction_request
                .payments()
                .iter()
                .filter(|(idx, _payment)| !ephemeral_step.tr1_payment_pools.contains_key(idx))
                .map(|(k, v)| (*k, v.clone()))
                .collect(),
        )
        .expect("removing payments from a TransactionRequest preserves validity");

        let mut steps = vec![];
        steps.push(Step::from_parts(
            &[],
            tr0,
            payment_pools,
            transparent_inputs,
            shielded_inputs,
            Some(anchor_height),
            vec![],
            tr0_balance,
            false,
            #[cfg(feature = "orchard")]
            ironwood_active,
        )?);

        let tr1 =
            TransactionRequest::new(ephemeral_step.tr1_payments).expect("valid by construction");
        steps.push(Step::from_parts(
            &steps,
            tr1,
            ephemeral_step.tr1_payment_pools,
            vec![],
            None,
            Some(anchor_height),
            vec![ephemeral_stepoutput],
            tr1_balance,
            false,
            #[cfg(feature = "orchard")]
            ironwood_active,
        )?);

        return Proposal::multi_step(
            fee_rule.clone(),
            target_height,
            confirmations_policy,
            NonEmpty::from_vec(steps).expect("steps is known to be nonempty"),
        );
    }

    Proposal::single_step(
        transaction_request,
        payment_pools,
        transparent_inputs,
        shielded_inputs,
        anchor_height,
        tr0_balance,
        fee_rule.clone(),
        target_height,
        confirmations_policy,
        false,
        #[cfg(feature = "orchard")]
        ironwood_active,
    )
}

#[cfg(feature = "transparent-inputs")]
impl<DbT: InputSource> ShieldingSelector for GreedyInputSelector<DbT> {
    type Error = GreedyInputSelectorError;
    type InputSource = DbT;

    #[allow(clippy::type_complexity)]
    fn propose_shielding<ParamsT, ChangeT>(
        &self,
        params: &ParamsT,
        wallet_db: &Self::InputSource,
        change_strategy: &ChangeT,
        shielding_threshold: Zatoshis,
        source_addrs: &[TransparentAddress],
        to_account: <Self::InputSource as InputSource>::AccountId,
        target_height: TargetHeight,
        anchor_height: BlockHeight,
        zip318: &PoolMigrationParams,
        confirmations_policy: ConfirmationsPolicy,
        output_filter: CoinbaseFilter,
    ) -> Result<
        Proposal<<ChangeT as ChangeStrategy>::FeeRule, Infallible>,
        InputSelectorError<<DbT as InputSource>::Error, Self::Error, ChangeT::Error, Infallible>,
    >
    where
        ParamsT: consensus::Parameters,
        ChangeT: ChangeStrategy<MetaSource = Self::InputSource>,
    {
        let mut transparent_inputs = gather_shielding_inputs::<DbT, ChangeT::Error>(
            wallet_db,
            source_addrs,
            target_height,
            confirmations_policy,
            output_filter,
            shielding_max_inputs(self.shielding_block_space_percent),
            &self.locked_input_policy,
        )?;

        let wallet_meta = change_strategy
            .fetch_wallet_meta(wallet_db, to_account, target_height, &[])
            .map_err(InputSelectorError::DataSource)?;

        let balance = compute_shielding_balance_with_dust_retry::<DbT, ChangeT, ParamsT>(
            change_strategy,
            params,
            target_height,
            anchor_height,
            zip318,
            &mut transparent_inputs,
            &wallet_meta,
        )?;

        if balance.total() >= shielding_threshold {
            Proposal::single_step(
                TransactionRequest::empty(),
                BTreeMap::new(),
                transparent_inputs,
                None,
                anchor_height,
                balance,
                (*change_strategy.fee_rule()).clone(),
                target_height,
                confirmations_policy,
                true,
                #[cfg(feature = "orchard")]
                ironwood_active_at(params, target_height),
            )
            .map_err(InputSelectorError::Proposal)
        } else {
            Err(InputSelectorError::InsufficientFunds {
                available: balance.total(),
                required: shielding_threshold,
            })
        }
    }

    #[allow(clippy::type_complexity)]
    fn propose_shielding_coinbase<ParamsT, FeeRuleT>(
        &self,
        params: &ParamsT,
        wallet_db: &Self::InputSource,
        fee_rule: &FeeRuleT,
        shielding_threshold: Zatoshis,
        source_addrs: &[TransparentAddress],
        to_address: ZcashAddress,
        memo: Option<MemoBytes>,
        limit: Option<usize>,
        target_height: TargetHeight,
        anchor_height: BlockHeight,
    ) -> Result<
        Proposal<FeeRuleT, Infallible>,
        InputSelectorError<<DbT as InputSource>::Error, Self::Error, FeeRuleT::Error, Infallible>,
    >
    where
        ParamsT: consensus::Parameters,
        FeeRuleT: FeeRule + Clone,
    {
        // Coinbase-only is enforced here at the API boundary: callers cannot bypass
        // it. This is the privacy property that motivates having a dedicated method
        // rather than a more general "shield to address" path; only coinbase
        // outputs are eligible because they have no prior transparent transaction
        // graph that could be exposed to the shielded recipient.
        // The block-space cap and the caller-supplied `limit` (when present) both bound the number
        // of transparent inputs; `gather_shielding_inputs` applies the more restrictive of the two,
        // keeping the highest-value UTXOs first. When `limit` is `Some(0)` this empties the set, and
        // the subsequent `InsufficientFunds` check fires; this is the documented behavior.
        let transparent_inputs = gather_shielding_inputs::<DbT, FeeRuleT::Error>(
            wallet_db,
            source_addrs,
            target_height,
            // It doesn't matter here if we pass a 100 confirmations or 1 confirmations policy,
            // as coinbase txs require 100, which will be enforced by note selection.
            ConfirmationsPolicy::MIN,
            CoinbaseFilter::CoinbaseOnly,
            limit
                .unwrap_or(usize::MAX)
                .min(shielding_max_inputs(self.shielding_block_space_percent)),
            &self.locked_input_policy,
        )?;

        let destination_pool = resolve_shielded_destination::<DbT, FeeRuleT::Error, ParamsT>(
            &to_address,
            params,
            target_height,
        )?;

        let (sapling_output_count, orchard_action_count, ironwood_action_count) =
            match destination_pool {
                PoolType::SAPLING => {
                    let count = ::sapling::builder::BundleType::DEFAULT
                        .num_outputs(0, 1)
                        .expect("sapling DEFAULT bundle type permits any (spends, outputs) count");
                    (count, 0usize, 0usize)
                }
                // A pre-NU6.3 payment to an Orchard receiver; after Ironwood activation,
                // `resolve_shielded_destination` assigns such payments to the Ironwood pool.
                #[cfg(feature = "orchard")]
                PoolType::ORCHARD => {
                    let count = orchard_fees::transactional_action_count(
                        ::orchard::builder::BundleType::DEFAULT,
                        orchard_bundle_version_for_height(params, target_height),
                        0,
                        1,
                    )
                    .expect("every Orchard bundle version permits spending and output creation");
                    (0usize, count, 0usize)
                }
                // A post-NU6.3 payment to an Orchard receiver, delivered via the Ironwood
                // bundle and charged to its action count.
                #[cfg(feature = "orchard")]
                PoolType::IRONWOOD => {
                    let count = orchard_fees::transactional_action_count(
                        ::orchard::builder::BundleType::DEFAULT,
                        ironwood_bundle_version_for_height(params, target_height),
                        0,
                        1,
                    )
                    .expect("the Ironwood bundle version permits spending and output creation");
                    (0usize, 0usize, count)
                }
                // Unreachable: `resolve_shielded_destination` rejects transparent
                // destinations earlier with `ShieldingRequiresShieldedRecipient`.
                _ => {
                    return Err(InputSelectorError::Proposal(
                        ProposalError::ShieldingRequiresShieldedRecipient,
                    ));
                }
            };

        let fee = fee_rule
            .fee_required(
                params,
                BlockHeight::from(target_height),
                transparent_inputs
                    .iter()
                    .map(transparent_fees::InputView::serialized_size),
                std::iter::empty::<usize>(),
                0,
                sapling_output_count,
                orchard_action_count,
                ironwood_action_count,
            )
            // The `InputSelectorError::Change` variant is the only existing
            // carrier capable of holding an arbitrary fee-rule error
            // (`ChangeError::StrategyError` wraps `FeeRuleT::Error` in the
            // generic position). We reuse it here rather than introduce a new
            // top-level variant.
            .map_err(|e| InputSelectorError::Change(ChangeError::StrategyError(e)))?;

        // Route the full available value (input_total - fee) as an explicit
        // payment to the supplied destination. No change is produced.
        let input_total = transparent_inputs
            .iter()
            .map(|utxo| utxo.value())
            .try_fold(Zatoshis::ZERO, |acc, v| acc + v)
            .ok_or(InputSelectorError::Selection(
                GreedyInputSelectorError::Balance(BalanceError::Overflow),
            ))?;
        let payment_amount =
            (input_total - fee).ok_or_else(|| InputSelectorError::InsufficientFunds {
                available: input_total,
                required: fee,
            })?;

        if payment_amount < shielding_threshold {
            return Err(InputSelectorError::InsufficientFunds {
                available: payment_amount,
                required: shielding_threshold,
            });
        }

        let payment = Payment::new(to_address, Some(payment_amount), memo, None, None, vec![])
            .map_err(|payment_error| {
                InputSelectorError::Proposal(ProposalError::Zip321(payment_error.with_index(0)))
            })?;
        let request = TransactionRequest::new(vec![payment]).map_err(|payment_error| {
            InputSelectorError::Proposal(ProposalError::Zip321(payment_error))
        })?;
        let mut payment_pools = BTreeMap::new();
        payment_pools.insert(0usize, destination_pool);
        let final_balance = TransactionBalance::new(vec![], fee).map_err(|_| {
            InputSelectorError::Selection(GreedyInputSelectorError::Balance(BalanceError::Overflow))
        })?;

        // `is_shielding` is `false` because the proposal layer reserves
        // `is_shielding = true` for the legacy "no payment, all value in change"
        // shape produced by `propose_shielding`. From the wallet's perspective
        // this is still a transparent -> shielded transfer of coinbase value.
        Proposal::single_step(
            request,
            payment_pools,
            transparent_inputs,
            None,
            anchor_height,
            final_balance,
            fee_rule.clone(),
            target_height,
            // Coinbase shielding spends no shielded notes, so the anchor the resulting step defers
            // to is resolved from this policy at interpretation; the exact confirmation depth does
            // not matter for an input-less step.
            ConfirmationsPolicy::default(),
            false,
            #[cfg(feature = "orchard")]
            ironwood_active_at(params, target_height),
        )
        .map_err(InputSelectorError::Proposal)
    }
}

/// Gathers spendable transparent UTXOs from each source address, applying the
/// supplied [`CoinbaseFilter`] and rejecting input sets that would
/// link activity on an ephemeral address to other wallet activity.
///
/// Shared between `propose_shielding` and `propose_shielding_coinbase`.
#[cfg(feature = "transparent-inputs")]
#[allow(clippy::type_complexity)]
fn gather_shielding_inputs<DbT, ChangeErrT>(
    wallet_db: &DbT,
    source_addrs: &[TransparentAddress],
    target_height: TargetHeight,
    confirmations_policy: ConfirmationsPolicy,
    output_filter: CoinbaseFilter,
    max_inputs: usize,
    locked_input_policy: &LockedInputPolicy,
) -> Result<
    Vec<WalletTransparentOutput<()>>,
    InputSelectorError<
        <DbT as InputSource>::Error,
        GreedyInputSelectorError,
        ChangeErrT,
        Infallible,
    >,
>
where
    DbT: InputSource,
{
    // Gather the spendable UTXOs for every source address in a single query. This avoids issuing
    // one query per address (including for the many addresses that have no spendable outputs),
    // which is prohibitively expensive for wallets that hold large numbers of transparent
    // addresses.
    // Input selection honors the selector's configured `locked_input_policy` (see
    // `GreedyInputSelector::with_locked_input_policy`): by default (`Exclude`) a locked output is
    // never drawn upon, since it belongs to another in-flight proposal and spending it would
    // recreate the conflict that locking exists to prevent.
    let mut utxos = wallet_db
        .get_spendable_transparent_outputs_for_addresses(
            source_addrs,
            target_height,
            confirmations_policy,
            output_filter,
            LockFilter::Policy(locked_input_policy),
        )
        .map_err(InputSelectorError::DataSource)?;

    // Cap the number of transparent inputs that a single shielding transaction may consume,
    // keeping the highest-value UTXOs first (stable tiebreaker by outpoint for determinism). UTXOs
    // beyond the cap are left unspent, to be consolidated by a subsequent shielding transaction.
    // When `max_inputs` is 0 this empties the set, and the caller's `InsufficientFunds` check
    // fires. The cap is applied before the linkability check below so that the check reflects the
    // outputs that will actually be spent.
    utxos.sort_by(|a, b| {
        b.value()
            .cmp(&a.value())
            .then_with(|| a.outpoint().cmp(b.outpoint()))
    });
    utxos.truncate(max_inputs);

    // We use `recipient_key_scope()` and `recipient_address()` from the returned outputs to
    // determine the set of input addresses and which of them are ephemeral, rather than querying
    // the wallet again per address.
    let ephemeral_addrs = utxos
        .iter()
        .filter_map(|utxo| {
            (utxo.recipient_key_scope() == Some(TransparentKeyScope::EPHEMERAL))
                .then_some(utxo.recipient_address())
        })
        .collect::<BTreeSet<_>>();
    let input_addrs = utxos
        .iter()
        .map(|utxo| utxo.recipient_address())
        .collect::<BTreeSet<_>>();

    // Funds may be spent from at most one ephemeral address at a time. If there are no
    // ephemeral addresses, we allow shielding from multiple transparent addresses.
    if !ephemeral_addrs.is_empty() && input_addrs.len() > 1 {
        return Err(InputSelectorError::Proposal(
            ProposalError::EphemeralAddressLinkability,
        ));
    }

    Ok(utxos
        .into_iter()
        .map(|utxo| utxo.redact_account_data())
        .collect())
}

/// Resolves a [`ZcashAddress`] destination for a shielding proposal to the
/// shielded pool it should be received in.
///
/// Rejects transparent and TEX addresses with
/// [`ProposalError::ShieldingRequiresShieldedRecipient`], and rejects Unified
/// Addresses without a shielded receiver with
/// [`GreedyInputSelectorError::UnsupportedAddress`].
#[cfg(feature = "transparent-inputs")]
#[allow(clippy::type_complexity)]
fn resolve_shielded_destination<DbT, ChangeErrT, ParamsT>(
    addr: &ZcashAddress,
    params: &ParamsT,
    target_height: TargetHeight,
) -> Result<
    PoolType,
    InputSelectorError<
        <DbT as InputSource>::Error,
        GreedyInputSelectorError,
        ChangeErrT,
        Infallible,
    >,
>
where
    DbT: InputSource,
    ParamsT: consensus::Parameters,
{
    #[cfg(not(feature = "orchard"))]
    let _ = target_height;

    let resolved: Address = addr
        .clone()
        .convert_if_network(params.network_type())
        .map_err(InputSelectorError::Address)?;
    match resolved {
        Address::Sapling(_) => Ok(PoolType::SAPLING),
        // A payment to an Orchard-protocol receiver is an Ironwood-pool output once
        // Ironwood is active (delivered to the recipient's Orchard receiver via the
        // Ironwood bundle), and an Orchard-pool output otherwise.
        #[cfg(feature = "orchard")]
        Address::Unified(ua) if ua.has_orchard() => {
            Ok(if ironwood_active_at(params, target_height) {
                PoolType::IRONWOOD
            } else {
                PoolType::ORCHARD
            })
        }
        Address::Unified(ua) if ua.has_sapling() => Ok(PoolType::SAPLING),
        Address::Unified(ua) => Err(InputSelectorError::Selection(
            GreedyInputSelectorError::UnsupportedAddress(Box::new(ua)),
        )),
        Address::Transparent(_) | Address::Tex(_) => Err(InputSelectorError::Proposal(
            ProposalError::ShieldingRequiresShieldedRecipient,
        )),
    }
}

/// Helper that performs the dust-input retry pattern used by `propose_shielding`.
///
/// On the first call to [`ChangeStrategy::compute_balance`], if the strategy
/// reports [`ChangeError::DustInputs`], those inputs are removed from
/// `transparent_inputs` and the balance is recomputed. The resulting proposal
/// directs all available value into change (the legacy `propose_shielding`
/// "all-change" shape).
#[cfg(feature = "transparent-inputs")]
#[allow(clippy::type_complexity)]
fn compute_shielding_balance_with_dust_retry<DbT, ChangeT, ParamsT>(
    change_strategy: &ChangeT,
    params: &ParamsT,
    target_height: TargetHeight,
    anchor_height: BlockHeight,
    zip318: &PoolMigrationParams,
    transparent_inputs: &mut Vec<WalletTransparentOutput<()>>,
    wallet_meta: &<ChangeT as ChangeStrategy>::AccountMetaT,
) -> Result<
    TransactionBalance,
    InputSelectorError<
        <DbT as InputSource>::Error,
        GreedyInputSelectorError,
        ChangeT::Error,
        Infallible,
    >,
>
where
    DbT: InputSource,
    ChangeT: ChangeStrategy<MetaSource = DbT>,
    ParamsT: consensus::Parameters,
{
    let trial = compute_shielding_balance::<DbT, ChangeT, ParamsT>(
        change_strategy,
        params,
        target_height,
        anchor_height,
        zip318,
        transparent_inputs,
        wallet_meta,
    );

    match trial {
        Ok(balance) => Ok(balance),
        Err(ChangeError::DustInputs { transparent, .. }) => {
            let exclusions: BTreeSet<OutPoint> = transparent.into_iter().collect();
            transparent_inputs.retain(|i| !exclusions.contains(i.outpoint()));

            compute_shielding_balance::<DbT, ChangeT, ParamsT>(
                change_strategy,
                params,
                target_height,
                anchor_height,
                zip318,
                transparent_inputs,
                wallet_meta,
            )
            .map_err(InputSelectorError::Change)
        }
        Err(other) => Err(InputSelectorError::Change(other)),
    }
}

/// Helper for `propose_shielding`'s balance computation that calls
/// `change_strategy.compute_balance` with empty shielded bundle views, allowing
/// the change strategy to direct all available transparent input value into
/// change.
///
/// The empty Orchard-family views carry the bundle versions in effect at the
/// target height (rather than a fixed default), because the change the strategy
/// directs into a shielded pool is charged against that pool's bundle under its
/// version's action-count policy.
#[cfg(feature = "transparent-inputs")]
#[allow(clippy::type_complexity)]
fn compute_shielding_balance<DbT, ChangeT, ParamsT>(
    change_strategy: &ChangeT,
    params: &ParamsT,
    target_height: TargetHeight,
    anchor_height: BlockHeight,
    zip318: &PoolMigrationParams,
    transparent_inputs: &[WalletTransparentOutput<()>],
    wallet_meta: &<ChangeT as ChangeStrategy>::AccountMetaT,
) -> Result<TransactionBalance, ChangeError<ChangeT::Error, Infallible>>
where
    DbT: InputSource,
    ChangeT: ChangeStrategy<MetaSource = DbT>,
    ParamsT: consensus::Parameters,
{
    #[cfg(feature = "orchard")]
    let empty_orchard_view = (
        orchard_bundle_version_for_height(params, target_height),
        &[] as &[Infallible],
        &[] as &[Infallible],
    );
    #[cfg(feature = "orchard")]
    let empty_ironwood_view = (
        ironwood_bundle_version_for_height(params, target_height),
        &[] as &[Infallible],
        &[] as &[Infallible],
    );

    change_strategy.compute_balance(
        params,
        target_height,
        anchor_height,
        zip318,
        transparent_inputs,
        &[] as &[TxOut],
        &sapling::EmptyBundleView,
        #[cfg(feature = "orchard")]
        &empty_orchard_view,
        #[cfg(feature = "orchard")]
        &empty_ironwood_view,
        None,
        wallet_meta,
    )
}

#[cfg(all(test, feature = "transparent-inputs"))]
mod tests {
    use super::shielding_max_inputs;

    #[test]
    fn shielding_max_inputs_from_block_space_percent() {
        // max_inputs = (MAX_BLOCK_BYTES * percent / 100) / P2PKH_STANDARD_INPUT_SIZE
        //            = (2_000_000 * percent / 100) / 150
        assert_eq!(shielding_max_inputs(0), 0);
        assert_eq!(shielding_max_inputs(1), 133); // 20_000 / 150
        assert_eq!(shielding_max_inputs(10), 1333); // 200_000 / 150
        assert_eq!(shielding_max_inputs(100), 13333); // 2_000_000 / 150
    }
}

#[cfg(test)]
mod spend_policy_tests {
    use super::*;
    #[cfg(feature = "transparent-inputs")]
    use crate::data_api::CoinbaseFilter;
    use crate::wallet::LockOwner;

    // The default spend policy preserves the historical `ShieldedOnly` behavior: notes may be
    // selected from every shielded pool present in the build, and no transparent UTXOs are
    // spent. Restricting the set is what a caller does to prevent pool crossing.
    #[test]
    fn default_permits_all_shielded_pools_and_no_transparent() {
        let policy = SpendPolicy::default();
        assert!(policy.permits_shielded(ShieldedPool::Sapling));
        #[cfg(feature = "orchard")]
        {
            assert!(policy.permits_shielded(ShieldedPool::Orchard));
            assert!(policy.permits_shielded(ShieldedPool::Ironwood));
        }
        #[cfg(feature = "transparent-inputs")]
        assert!(policy.transparent().is_none());
    }

    // A caller can restrict selection to a single pool; other pools are then not permitted.
    #[test]
    fn shielded_pools_restricts_the_permitted_set() {
        let policy = SpendPolicy::shielded_pools([ShieldedPool::Orchard]);
        assert!(policy.permits_shielded(ShieldedPool::Orchard));
        assert!(!policy.permits_shielded(ShieldedPool::Sapling));
        assert!(!policy.permits_shielded(ShieldedPool::Ironwood));
    }

    // The caller-facing coinbase choice maps onto the internal `CoinbaseFilter` query control.
    #[cfg(feature = "transparent-inputs")]
    #[test]
    fn coinbase_policy_maps_to_filter() {
        assert_eq!(
            CoinbaseFilter::from(CoinbasePolicy::OnlyCoinbase),
            CoinbaseFilter::CoinbaseOnly
        );
        assert_eq!(
            CoinbaseFilter::from(CoinbasePolicy::NonCoinbase),
            CoinbaseFilter::NonCoinbaseOnly
        );
    }

    // A transparent spend policy spends non-coinbase UTXOs by default, and `with_coinbase`
    // overrides that choice while preserving the source.
    #[cfg(feature = "transparent-inputs")]
    #[test]
    fn transparent_policy_coinbase_defaults_and_override() {
        let policy = TransparentSpendPolicy::any_account_addr();
        assert_eq!(policy.coinbase(), CoinbasePolicy::NonCoinbase);

        let policy = policy.with_coinbase(CoinbasePolicy::OnlyCoinbase);
        assert_eq!(policy.coinbase(), CoinbasePolicy::OnlyCoinbase);
        assert!(matches!(policy.source(), TransparentSource::AnyAccountAddr));
    }

    // The default `SpendPolicy` excludes locked inputs, and `with_locked_input_policy` overrides
    // that choice.
    #[test]
    fn spend_policy_locked_input_policy_roundtrips() {
        let default = SpendPolicy::default();
        assert_eq!(default.locked_input_policy(), &LockedInputPolicy::Exclude);
        let owners = NonEmptyBTreeSet::singleton(LockOwner::new([9u8; 32]));
        let policy = SpendPolicy::default()
            .with_locked_input_policy(LockedInputPolicy::PreferLocked(owners.clone()));
        assert_eq!(
            policy.locked_input_policy(),
            &LockedInputPolicy::PreferLocked(owners)
        );
    }
}