dig-account 0.26.2

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

use std::collections::HashSet;

use chia_protocol::{Bytes32, Coin, CoinSpend};
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{SpendContext, StandardLayer};
use chia_wallet_sdk::types::Conditions;
use chia_wallet_sdk::utils::Address;
use dig_chainsource_interface::{ChainSource, CoinRecord};

use crate::chain_confirm::{confirm_all_spendable_by_name, UnconfirmedInput};
use crate::keys::wallet_key::WalletKey;
use crate::mint::MIN_CONFIRMATION_DEPTH;
use crate::wallet::authorizer::WalletOps;
use crate::wallet::policy::CustodyPolicy;
use crate::wallet::reservation::{select_and_reserve, CoinReservations, ReservationId};

/// The most wallet coins one transfer will consume.
///
/// Multi-coin selection exists because a single-coin-only builder refuses to send funds the wallet
/// visibly holds, which is its own kind of dishonesty. It is capped because every extra input is
/// another puzzle reveal, another signature and another few hundred bytes of block space: an
/// unbounded selection turns a dusty wallet into a bundle no mempool will take, and the failure
/// would arrive after the push rather than before it.
pub const MAX_TRANSFER_INPUT_COINS: usize = 12;

/// How many times selection may re-run after losing its coins to a concurrent reservation.
///
/// Each attempt excludes at least one more coin, so the loop already terminates on its own. This
/// bound exists for the case the loop cannot reason about: a store that reports a conflict for a
/// coin it does not actually hold, which would otherwise spin here forever.
pub(crate) const MAX_RESERVATION_ATTEMPTS: usize = 16;

/// The only human-readable prefix a transfer will pay: Chia mainnet's.
///
/// Re-exported rather than defined here. The same value is what
/// [`WalletKey::address`](crate::WalletKey::address) encodes with and what the confirm ceremony
/// re-encodes for display, so a recipient bearing any other prefix is a destination this crate would
/// DISPLAY as an `xch` address while paying something else entirely — see
/// [`crate::constants::MAINNET_ADDRESS_PREFIX`] for why that agreement is structural and not a
/// convention.
pub use crate::constants::MAINNET_ADDRESS_PREFIX;

/// The message the lead coin announces and every secondary input asserts.
///
/// See [`build_transfer_spends`] for why the binding exists at all.
const INPUT_BINDING_MESSAGE: &[u8] = b"dig-account:transfer";

/// A transfer result.
pub type TransferResult<T> = std::result::Result<T, TransferError>;

/// Why a transfer could not be built, or could not be judged.
///
/// Every variant answers a different question for the surface rendering it, which is the whole point
/// of keeping them apart: "add funds", "consolidate your coins", "this tier cannot send", and "we do
/// not know" are four different things to tell a user about their money.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TransferError {
    /// The wallet's confirmed, unspent coins do not add up to the amount plus the fee.
    ///
    /// `available` counts ONLY confirmed unspent coins. An unconfirmed or already-spent coin cannot
    /// fund a spend, so counting it would report a balance the user is unable to spend.
    #[error("insufficient funds: the transfer needs {required} mojos, the wallet holds {available} spendable")]
    InsufficientFunds {
        /// The amount plus the fee.
        required: u64,
        /// The total of every confirmed, unspent coin the wallet holds.
        available: u64,
    },

    /// The wallet holds enough value, but every coin that could cover this transfer is already
    /// committed to an in-flight spend.
    ///
    /// SEPARATE from [`InsufficientFunds`](Self::InsufficientFunds), and the distinction is the
    /// whole point: `available` is the user's REAL balance, reserved coins included, because a
    /// reservation narrows what may be selected and never what the user holds. Collapsing the two
    /// would tell a person their money is gone when it is merely busy, and would invite the deposit
    /// that does not help.
    #[error("every coin that could fund this transfer is reserved by an in-flight spend: it needs {required} mojos, the wallet holds {available} but only {selectable} is free right now")]
    CoinsReserved {
        /// The amount plus the fee.
        required: u64,
        /// The total of every confirmed, unspent coin the wallet holds — reserved ones included.
        available: u64,
        /// The total of the coins that are not currently reserved.
        selectable: u64,
    },

    /// The reservation store could not be consulted, so what is already in flight is UNKNOWN.
    ///
    /// The build REFUSES rather than proceeding, because proceeding is exactly the double-select
    /// the reservation exists to prevent. A guard that fails open is not a guard.
    #[error("{0}")]
    ReservationUnusable(String),

    /// The wallet holds enough value, but only across more coins than one transfer may consume.
    ///
    /// Deliberately NOT [`InsufficientFunds`](Self::InsufficientFunds): the user's balance is
    /// sufficient and telling them otherwise would be false. The remedy is a consolidating self-spend,
    /// not a deposit.
    #[error(
        "this transfer would need {needed} input coins, above the {cap}-coin limit; consolidate \
         some coins first"
    )]
    TooManyInputCoins {
        /// How many coins covering the amount would take.
        needed: usize,
        /// The limit ([`MAX_TRANSFER_INPUT_COINS`]).
        cap: usize,
    },

    /// The profile is on the VAULT custody tier, which cannot pay a third party at all.
    ///
    /// Every vault outflow must first pass through the 24-hour clawback window to the profile's own
    /// hot wallet. This is a structural custody rule, not a shortfall and not a build failure.
    #[error(
        "this profile's funds are in the vault tier, which cannot send directly; move funds vault \
         -> hot wallet through the clawback window first, then send from the hot wallet"
    )]
    VaultTransferUnsupported,

    /// The recipient is this very wallet's own puzzle hash.
    ///
    /// Two things are wrong with a self-payment, and either alone would justify refusing it. It moves
    /// no money while costing a fee; and the custody summary excludes outputs that provably return to
    /// a puzzle the spend is already unlocking, so the confirmation ceremony would show a spend with
    /// NO recipient and a fee — a true statement that reads as a completely different transaction.
    #[error(
        "the recipient is this wallet's own address; a self-payment moves nothing and costs a fee"
    )]
    SelfPayment,

    /// The amount is zero. A zero-value coin is not a payment, and consensus has no use for one.
    #[error("a transfer must move a positive number of mojos")]
    ZeroAmount,

    /// The wallet's spendable coins sum to more than a `u64` can hold, so no shortfall check is
    /// meaningful.
    ///
    /// Unreachable on a real chain, where the mojo supply is bounded — which is exactly why it must
    /// be an explicit refusal rather than a clamp: a total silently pinned at `u64::MAX` would pass
    /// every "do I have enough" test, and the condition would surface later as arithmetic rather than
    /// as the unreadable balance it is.
    #[error("the wallet's spendable coins total more than u64 can represent, so the balance cannot be judged")]
    BalanceUnjudgeable,

    /// The amount plus the fee does not fit in a `u64`, so no wallet could ever cover it.
    #[error("the amount ({amount}) plus the fee ({fee}) overflows u64")]
    AmountOverflow {
        /// The requested amount.
        amount: u64,
        /// The requested fee.
        fee: u64,
    },

    /// The recipient address could not be decoded, so there is no destination to pay.
    #[error("recipient address {address:?} is not a valid address: {reason}")]
    InvalidRecipient {
        /// The address as supplied.
        address: String,
        /// Why it could not be decoded.
        reason: String,
    },

    /// A source coin of the transfer being REPLACED is no longer confirmed-and-unspent, so the
    /// original bundle's inputs can no longer be re-spent.
    ///
    /// Deliberately NOT [`InsufficientFunds`](Self::InsufficientFunds): the wallet's balance is not
    /// the subject. Either the original transfer has already been included — in which case a
    /// replacement would be a SECOND payment — or a different spend consumed the coin. Both demand a
    /// fresh [`transfer_status`] read, not a bigger fee.
    #[error(
        "input coin {coin_id} of the transfer being replaced is no longer confirmed and unspent"
    )]
    SourcesNoLongerSpendable {
        /// The coin that can no longer be spent.
        coin_id: Bytes32,
    },

    /// The transfer's ORIGINAL input coins cannot cover the amount plus the raised fee.
    ///
    /// Deliberately NOT [`InsufficientFunds`](Self::InsufficientFunds): that variant's `available` is
    /// the WALLET'S spendable balance everywhere else it is produced, and a surface rendering this one
    /// the same way would report a balance the user does not have. A replacement re-spends exactly the
    /// original inputs by design — that is what makes it conflict with the bundle it replaces — so a
    /// deposit cannot help.
    ///
    /// # The advice must never be "build another transfer"
    ///
    /// Rebuilding a retry through [`WalletOps::build_transfer`] is FORBIDDEN, because selection can
    /// choose a different lead and the two bundles then pay the recipient TWICE. This is a
    /// `Display` implementation that surfaces render verbatim, so the sentence is part of the safety
    /// property rather than commentary on it.
    ///
    /// "Lower the fee" is also not dependable advice: the largest affordable bump is
    /// `fee_mojos + change_mojos` of the original transfer, so a transfer whose inputs were consumed
    /// exactly — the case that most often produces this error — has NO legal lower fee at all,
    /// because a replacement must also strictly outbid the original. The only always-correct
    /// instruction is to wait and watch [`transfer_status`], which is what
    /// [`SourcesNoLongerSpendable`](Self::SourcesNoLongerSpendable) already says.
    ///
    /// A caller that wants to offer a bump control should read
    /// [`PendingTransfer::max_replacement_fee_mojos`] rather than discovering the ceiling by
    /// triggering this error.
    #[error(
        "this transfer cannot be sped up: its own input coins total {reused_total} mojos, which \
         cannot cover the {required} a fee this high would need. Wait for it to confirm or fail on \
         its own — a second payment to the same recipient risks paying them twice"
    )]
    ReplacementInputsInsufficient {
        /// The amount plus the raised fee.
        required: u64,
        /// The total of the transfer's original input coins.
        reused_total: u64,
    },

    /// A replacement transfer's fee does not exceed the fee it replaces.
    ///
    /// # A NECESSARY condition, not a sufficient one
    ///
    /// A bundle that does not outbid the one already in the mempool certainly cannot displace it, so
    /// refusing here saves the caller from constructing a spend that could only lose. Passing this
    /// check does NOT mean the replacement WILL displace the original: Chia's replace-by-fee rule is
    /// a property of the mempool implementation rather than of this crate, and nothing in this
    /// repository verifies it — the simulator has no replace-by-fee path at all, so no test here can
    /// establish it either way. Do not read this guard as a promise about which bundle wins.
    #[error(
        "a replacement must outbid the transfer it replaces: the current fee is {current} mojos \
         and the proposed fee is {proposed}"
    )]
    ReplacementFeeNotHigher {
        /// The fee the original transfer carries.
        current: u64,
        /// The fee that was proposed for the replacement.
        proposed: u64,
    },

    /// A coin at the wallet's puzzle hash carries NO confirmation height, so whether it is spendable
    /// cannot be established and the balance cannot be judged.
    ///
    /// `confirmed_height: None` means "not known BY THIS SOURCE", never "does not exist". Treating it
    /// as unspendable silently under-counts: a source that does not populate the field would make a
    /// funded wallet report a zero balance and refuse every transfer it could afford. Refusing by name
    /// tells the user the truth — the source cannot answer — instead of a false fact about their money.
    #[error(
        "coin {coin_id} has no confirmation height from this chain source, so its spendability is \
         unknown and the balance cannot be judged"
    )]
    SpendabilityUnknown {
        /// The coin whose confirmation height the source did not report.
        coin_id: Bytes32,
    },

    /// A coin this transfer RECORDED as one of its own inputs is now reported at a DIFFERENT puzzle
    /// hash, so the source is contradicting itself about a coin whose id we already hold.
    ///
    /// # Why this is a refusal here and only an exclusion during selection
    ///
    /// The two paths are answering different questions. Selection asks "what does this wallet own?"
    /// and gets a list the SOURCE chose — including, on a hint-indexing source, coins an attacker
    /// hinted at this wallet. A foreign coin there is simply not this wallet's, so it is excluded;
    /// refusing would let a stranger brick the wallet with one dust coin.
    ///
    /// A replacement asks "is coin X, which I already selected and spent in a bundle, still as I
    /// recorded it?" A coin id commits to `(parent, puzzle_hash, amount)`, so a record answering to
    /// that id cannot honestly carry a different puzzle hash. Nothing about the wallet's balance is
    /// in question; the source has said something impossible, and building a spend on it would be
    /// building on an answer that is known to be wrong.
    #[error(
        "coin {coin_id} is locked by puzzle hash {puzzle_hash}, not this wallet's; a transfer spends \
         only native XCH coins at the wallet's own puzzle hash"
    )]
    UnexpectedCoinPuzzleHash {
        /// The offending coin.
        coin_id: Bytes32,
        /// The puzzle hash it is actually locked by.
        puzzle_hash: Bytes32,
    },

    /// The chain could NOT be reached or could not answer.
    ///
    /// The outcome is UNKNOWN, never "no": a coin that could not be read may well exist, and a status
    /// that could not be established is not an absent one. Callers retry; they never record a result
    /// from this.
    #[error("chain unreachable: {0}")]
    ChainUnreachable(String),

    /// Building the unsigned spend failed inside the SDK drivers.
    #[error("could not build the transfer spend: {0}")]
    Build(String),
}

/// A coin that could not be confirmed spendable by name is a chain the builder could not read.
///
/// Every [`UnconfirmedInput`] means the same thing — the coin's state is UNKNOWN — which is exactly
/// what [`TransferError::ChainUnreachable`] already says. Mapping it to
/// [`InsufficientFunds`](TransferError::InsufficientFunds) would blame the user's balance for the
/// chain's disagreement, and there is no refusal here to report: the wallet may be perfectly funded
/// and the next read may be answered by a node that is caught up.
impl From<UnconfirmedInput> for TransferError {
    fn from(error: UnconfirmedInput) -> Self {
        TransferError::ChainUnreachable(error.to_string())
    }
}

/// A destination this crate is willing to PAY: a puzzle hash plus the evidence it is payable.
///
/// # Why a newtype rather than a `Bytes32` and a documented rule
///
/// A `Bytes32` carries no evidence of where it came from, and the two ways of obtaining one are not
/// equally safe. `Address::decode` validates that a string is bech32m with a 32-byte payload — it does
/// NOT validate the human-readable part, and hands it back for the caller to judge. So `nft1…`,
/// `did:chia:…`, `cat1…`, `txch1…` and outright invented prefixes all decode successfully and yield a
/// puzzle hash nobody holds a preimage for.
///
/// Paying one is not caught by anything downstream. It conserves value, returns honest change, signs,
/// confirms, and reports [`TransferStatus::Confirmed`] truthfully, because a coin really does exist at
/// that puzzle hash. The funds are permanently burned, and the confirmation ceremony re-encodes the
/// destination under [`MAINNET_ADDRESS_PREFIX`] for display — so the user is shown a plausible mainnet
/// address that is NOT the string they supplied, differing only in a prefix they have no reason to
/// inspect.
///
/// The check therefore has to happen where the STRING is, and the type makes that the only route: a
/// destination reaches [`TransferRequest`] having been either decoded here
/// ([`from_address`](Self::from_address)) or explicitly vouched for by the caller
/// ([`from_derived`](Self::from_derived)). A rule in a doc comment can be skipped by someone who never
/// reads it; a constructor cannot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PayableDestination(Bytes32);

impl PayableDestination {
    /// Decode a bech32m address, refusing any prefix but [`MAINNET_ADDRESS_PREFIX`].
    ///
    /// This is the constructor for anything that originated as a string a human typed, pasted,
    /// scanned, or received. The error names the offending prefix, so the user learns what they
    /// actually supplied rather than being told the address is merely "invalid".
    ///
    /// # Errors
    ///
    /// [`TransferError::InvalidRecipient`] if the string is not decodable bech32m with a 32-byte
    /// payload, or if its prefix is not `xch`.
    pub fn from_address(address: &str) -> TransferResult<Self> {
        let decoded = Address::decode(address).map_err(|e| TransferError::InvalidRecipient {
            address: address.to_string(),
            reason: e.to_string(),
        })?;
        if decoded.prefix != MAINNET_ADDRESS_PREFIX {
            return Err(TransferError::InvalidRecipient {
                address: address.to_string(),
                reason: format!(
                    "it is a {:?} address, not an {MAINNET_ADDRESS_PREFIX} payment address; paying \
                     the puzzle hash inside one would burn the funds",
                    decoded.prefix
                ),
            });
        }
        Ok(Self(decoded.puzzle_hash))
    }

    /// Vouch for a puzzle hash the CODE derived and already knows to be payable.
    ///
    /// # Calling this is an ASSERTION, and it is the way past the prefix rule
    ///
    /// [`from_address`](Self::from_address) refuses a non-`xch` address precisely because the puzzle
    /// hash inside one is unspendable and paying it burns the funds. Once a string has been reduced to
    /// a `Bytes32` that evidence is gone, so `Address::decode(user_input)?.puzzle_hash` handed to this
    /// function reconstructs the entire burn in the CALLER, with the prefix check bypassed rather than
    /// failed.
    ///
    /// Use it only for a puzzle hash the code itself produced and can vouch for: one computed from a
    /// public key, an address this wallet generated, or a destination a lower layer has already
    /// validated. Anything that began life as a string a human supplied MUST go through
    /// [`from_address`](Self::from_address).
    pub fn from_derived(puzzle_hash: Bytes32) -> Self {
        Self(puzzle_hash)
    }

    /// The destination puzzle hash.
    pub fn puzzle_hash(&self) -> Bytes32 {
        self.0
    }
}

/// What the caller wants moved, and to whom.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TransferRequest {
    recipient: PayableDestination,
    amount_mojos: u64,
    fee_mojos: u64,
}

impl TransferRequest {
    /// Pay `amount_mojos` to `recipient`, with no fee.
    ///
    /// The destination has already been judged payable by whichever [`PayableDestination`]
    /// constructor produced it; this function has nothing left to validate about it.
    pub fn new(recipient: PayableDestination, amount_mojos: u64) -> Self {
        Self {
            recipient,
            amount_mojos,
            fee_mojos: 0,
        }
    }

    /// Pay `amount_mojos` to a bech32m `xch1…` address, with no fee.
    ///
    /// A convenience for the common case, equivalent to
    /// [`PayableDestination::from_address`] followed by [`new`](Self::new). The address is decoded
    /// HERE so an unusable one is a named error before any chain read, rather than a comparison that
    /// silently never matches later.
    ///
    /// # Errors
    ///
    /// See [`PayableDestination::from_address`].
    pub fn to_address(address: &str, amount_mojos: u64) -> TransferResult<Self> {
        Ok(Self::new(
            PayableDestination::from_address(address)?,
            amount_mojos,
        ))
    }

    /// The same request, paying `fee_mojos` to a farmer.
    ///
    /// # There is no fee CEILING here, deliberately
    ///
    /// The DID mint carries [`MAX_MINT_FEE_MOJOS`](crate::MAX_MINT_FEE_MOJOS) because its bundle is a
    /// singleton launch, which the custody gate's summary derivation refuses to decode — so the mint's
    /// fee is genuinely ungated. A transfer is an ordinary standard-layer spend that goes through the
    /// FULL gate, and the gate's `native_total_mojos` counts recipients PLUS the fee. So the
    /// per-transaction auto-send limit already bounds amount + fee together, and anything larger
    /// escalates to a human who is shown the fee on its own line. A second ceiling here would bound
    /// nothing that is not already bounded, while adding a limit no user could raise.
    pub fn with_fee(mut self, fee_mojos: u64) -> Self {
        self.fee_mojos = fee_mojos;
        self
    }

    /// The destination puzzle hash.
    pub fn recipient(&self) -> Bytes32 {
        self.recipient.puzzle_hash()
    }

    /// The destination, with the evidence that it is payable.
    pub fn destination(&self) -> PayableDestination {
        self.recipient
    }

    /// The amount to pay the recipient, in mojos.
    pub fn amount_mojos(&self) -> u64 {
        self.amount_mojos
    }

    /// The farmer fee, in mojos.
    pub fn fee_mojos(&self) -> u64 {
        self.fee_mojos
    }

    /// The total the selected inputs must cover: the amount plus the fee.
    fn required_total(&self) -> TransferResult<u64> {
        self.amount_mojos
            .checked_add(self.fee_mojos)
            .ok_or(TransferError::AmountOverflow {
                amount: self.amount_mojos,
                fee: self.fee_mojos,
            })
    }
}

/// An unsigned, un-gated transfer: the coin spends plus what they are known to do.
///
/// The spends are the deliverable; every other field describes them so a caller does not have to
/// re-parse CLVM to render or track its own transaction. They are DESCRIPTIONS, and nothing in this
/// crate accepts one as a custody fact — the gate re-derives everything it rules on from the spends
/// themselves.
#[derive(Debug, Clone)]
pub struct TransferPlan {
    coin_spends: Vec<CoinSpend>,
    payment_coin_id: Bytes32,
    source_coin_ids: Vec<Bytes32>,
    recipient: Bytes32,
    amount_mojos: u64,
    fee_mojos: u64,
    change_mojos: u64,
    reservation: Option<ReservationId>,
}

impl TransferPlan {
    /// The spends to hand to
    /// [`PolicyAuthorizer::authorize_op`](crate::wallet::enforcer::PolicyAuthorizer::authorize_op),
    /// unchanged.
    pub fn coin_spends(&self) -> &[CoinSpend] {
        &self.coin_spends
    }

    /// The spends, by value.
    pub fn into_coin_spends(self) -> Vec<CoinSpend> {
        self.coin_spends
    }

    /// The pre-existing wallet coins this transfer consumes.
    pub fn source_coin_ids(&self) -> &[Bytes32] {
        &self.source_coin_ids
    }

    /// The reservation holding this plan's inputs, when the plan took one.
    ///
    /// Release it through
    /// [`CoinReservations::release`](crate::wallet::reservation::CoinReservations::release) the
    /// moment the transfer is known settled or known dead, rather than waiting out the TTL — the
    /// user's own coins should not stay held over a question the chain has already answered.
    ///
    /// `None` on a plan from
    /// [`build_transfer_replacing`](crate::wallet::authorizer::WalletOps::build_transfer_replacing),
    /// which re-spends coins the ORIGINAL plan already reserved and must not take a second,
    /// self-conflicting hold on them.
    pub fn reservation(&self) -> Option<ReservationId> {
        self.reservation
    }

    /// The id of the coin that will pay the recipient.
    pub fn payment_coin_id(&self) -> Bytes32 {
        self.payment_coin_id
    }

    /// The destination puzzle hash.
    pub fn recipient(&self) -> Bytes32 {
        self.recipient
    }

    /// What the recipient receives, in mojos.
    pub fn amount_mojos(&self) -> u64 {
        self.amount_mojos
    }

    /// What the farmer receives, in mojos.
    pub fn fee_mojos(&self) -> u64 {
        self.fee_mojos
    }

    /// What returns to this wallet, in mojos. `0` means the inputs were consumed exactly and no
    /// change coin is created at all.
    pub fn change_mojos(&self) -> u64 {
        self.change_mojos
    }

    /// Record that this plan is about to be broadcast, anchoring it to the chain's CURRENT peak.
    ///
    /// This is the path callers should use. It reads the peak itself, immediately before the push, so
    /// the anchor cannot be a number the caller invented, defaulted, or read at the wrong moment —
    /// which is the difference between a real backdating check and a decorative one.
    ///
    /// # Errors
    ///
    /// [`TransferError::ChainUnreachable`] when the peak cannot be established. That is a refusal to
    /// proceed, not a zero: a transfer pushed without a usable anchor can never have a confirmation
    /// bounded, so it would accept a back-dated one forever.
    pub fn pushed_now<C>(&self, chain: &C) -> TransferResult<PendingTransfer>
    where
        C: ChainSource + ?Sized,
    {
        Ok(self.pushed_at(peak_height(chain)?))
    }

    /// Record that this plan has been broadcast, at a caller-supplied chain peak of `pre_push_peak`.
    ///
    /// Prefer [`pushed_now`](Self::pushed_now), which reads the peak itself. This variant exists for
    /// callers that already hold a peak read at the right moment, and for tests that need to place
    /// the anchor deliberately.
    ///
    /// # `pre_push_peak` MUST be read BEFORE the push
    ///
    /// This is not a formality and it is not interchangeable with the peak afterwards. A transfer
    /// cannot be included in a block that already existed when it was broadcast, so this height is
    /// the ONLY thing that later makes a back-dated confirmation contradict something the chain
    /// itself said earlier. Read it after the push and a source that invents a confirmation is free
    /// to place it anywhere, because the number it would have to contradict is one it also supplied,
    /// after seeing the bundle.
    ///
    /// A `0` here makes the check VACUOUS — every height is at or above genesis — so a caller that
    /// cannot read a peak MUST refuse to push rather than anchor at zero.
    pub fn pushed_at(&self, pre_push_peak: u32) -> PendingTransfer {
        PendingTransfer {
            payment_coin_id: self.payment_coin_id,
            source_coin_ids: self.source_coin_ids.clone(),
            recipient: self.recipient,
            amount_mojos: self.amount_mojos,
            fee_mojos: self.fee_mojos,
            change_mojos: self.change_mojos,
            // The inputs balance the outputs exactly, so their total is recoverable from the plan
            // rather than needing to be carried alongside it. `build_transfer_spends` computed the
            // change by CHECKED subtraction from that same total, so this cannot overflow.
            input_total_mojos: self.amount_mojos + self.fee_mojos + self.change_mojos,
            pushed_at_height: pre_push_peak,
        }
    }
}

/// A transfer that has been broadcast and is NOT yet a payment.
///
/// Note what is absent: there is no `is_sent`, no `succeeded`, no `Option<ConfirmedTransfer>` to
/// unwrap optimistically. The only question this type can answer is "what should I watch, and since
/// when" — everything else must come from [`transfer_status`] and the chain. Making the wrong call
/// unexpressible is stronger than documenting that it is wrong.
///
/// # Not a bundle identity, and a naive retry can pay TWICE
///
/// [`payment_coin_id`](Self::payment_coin_id) identifies the PAYMENT, not the bundle that produced
/// it. It is the id of a coin determined by `(lead input, recipient, amount)` and commits to neither
/// the fee nor the change.
///
/// A fee-bumped retry built by calling [`WalletOps::build_transfer`] again is NOT safe. Selection
/// takes the smallest coin covering `amount + fee`, so raising the fee can cross a coin boundary and
/// pick a DIFFERENT lead. The two bundles then spend disjoint inputs, do not conflict, can sit in the
/// mempool together, and can BOTH confirm — the recipient is paid twice, out of two different coins,
/// under two different payment coin ids.
///
/// [`WalletOps::build_transfer_replacing`] is the only correct retry: it re-spends EXACTLY the
/// original inputs, so the lead is unchanged, `payment_coin_id` is identical, and the replacement
/// genuinely conflicts with the original — at most one can ever be included.
///
/// What remains once the retry is built that way is an ACCOUNTING hazard rather than a double
/// payment: the two bundles share a `payment_coin_id`, so watching the original pending record
/// reports the replacement's confirmation as its own, and the two `ConfirmedTransfer` values compare
/// equal. A ledger that counts confirmations rather than deduping on `payment_coin_id` will record
/// two settled payments where one occurred. Callers MUST dedupe on the id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingTransfer {
    payment_coin_id: Bytes32,
    source_coin_ids: Vec<Bytes32>,
    recipient: Bytes32,
    amount_mojos: u64,
    fee_mojos: u64,
    change_mojos: u64,
    input_total_mojos: u64,
    pushed_at_height: u32,
}

impl PendingTransfer {
    /// The coin whose confirmation is this transfer's evidence.
    pub fn payment_coin_id(&self) -> Bytes32 {
        self.payment_coin_id
    }

    /// The pre-existing wallet coins the transfer spends — its inputs from the chain's point of view.
    pub fn source_coin_ids(&self) -> &[Bytes32] {
        &self.source_coin_ids
    }

    /// The destination this transfer was built to pay.
    pub fn recipient(&self) -> Bytes32 {
        self.recipient
    }

    /// The amount this transfer was built to pay, in mojos.
    pub fn amount_mojos(&self) -> u64 {
        self.amount_mojos
    }

    /// The farmer fee this transfer was built with, in mojos.
    ///
    /// DESCRIPTIVE, like every other field here — it is what a replacement must outbid
    /// ([`WalletOps::build_transfer_replacing`]), never evidence about the chain.
    pub fn fee_mojos(&self) -> u64 {
        self.fee_mojos
    }

    /// What returns to this wallet, in mojos — `0` when the inputs were consumed exactly.
    ///
    /// DESCRIPTIVE, like every other field here. It is also the headroom a fee bump can draw on: see
    /// [`max_replacement_fee_mojos`](Self::max_replacement_fee_mojos).
    pub fn change_mojos(&self) -> u64 {
        self.change_mojos
    }

    /// The total value of the coins this transfer spends, in mojos.
    pub fn input_total_mojos(&self) -> u64 {
        self.input_total_mojos
    }

    /// The largest fee [`WalletOps::build_transfer_replacing`] could accept for this transfer.
    ///
    /// A replacement re-spends exactly these inputs, so the raised fee has to come out of the change:
    /// the ceiling is `fee_mojos + change_mojos`. A surface offering a "speed this up" control should
    /// bound it by this number, because the alternative is discovering the limit by triggering
    /// [`TransferError::ReplacementInputsInsufficient`] — and a user who reads that as "add funds" or
    /// "send it again" can end up paying the recipient twice.
    ///
    /// **A value equal to [`fee_mojos`](Self::fee_mojos) means no bump is possible at all**, since a
    /// replacement must also strictly outbid the original. That is the ordinary state of a transfer
    /// whose inputs were consumed exactly, and the honest control in that case is disabled, not
    /// merely capped.
    pub fn max_replacement_fee_mojos(&self) -> u64 {
        self.fee_mojos + self.change_mojos
    }

    /// The chain's peak immediately before the push.
    pub fn pushed_at_height(&self) -> u32 {
        self.pushed_at_height
    }
}

/// A payment that EXISTS on chain, and the evidence that it does.
///
/// Constructible only by [`from_confirmed`](Self::from_confirmed), which is private to this module,
/// from a sufficiently-buried record of the exact coin the pushed bundle creates. There is no
/// `Default`, no `Deserialize` and no other constructor, so nothing can assemble one from a push
/// receipt or an optimistic guess.
///
/// The same honest caveat as the mint applies: these fields are the chain source's TESTIMONY, and a
/// source that lies deliberately can satisfy every arithmetic check here. What the checks buy is
/// reorg safety against an honest source, and the exclusion of degenerate fabrications. Pass a
/// trusted or aggregating [`ChainSource`], never the same unvetted node the bundle was pushed to.
///
/// It identifies a PAYMENT and not the bundle that produced it — see
/// [`PendingTransfer`]'s "Not a bundle identity", which applies unchanged here: two
/// `ConfirmedTransfer`s for a transfer and its fee-bumped retry compare EQUAL, because they describe
/// the same coin.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfirmedTransfer {
    payment_coin_id: Bytes32,
    recipient: Bytes32,
    amount_mojos: u64,
    confirmed_height: u32,
}

impl ConfirmedTransfer {
    /// The only way to obtain a [`ConfirmedTransfer`]. `None` unless every one of these holds:
    ///
    /// 1. **The record is the coin the bundle creates.** A coin id commits to
    ///    `(parent, puzzle_hash, amount)`, so a matching id is itself the proof that the recipient and
    ///    the amount are the ones that were built — there is nothing separate left to compare.
    /// 2. **It carries a confirmed height.** An unconfirmed record is a mempool observation.
    /// 3. **That height is not genesis**, since no coin is created in block 0.
    /// 4. **It does not predate the push** (see [`TransferPlan::pushed_at`]). The comparison is
    ///    STRICTLY LESS THAN, and that is deliberate: `ChainSource::peak_height` reports the height
    ///    the NEXT block will take, not the last one that exists, so the first block able to contain
    ///    the bundle carries exactly the height read before the push. Tightening this to `<=` reads
    ///    like closing an off-by-one and instead rejects every first-block confirmation, turning a
    ///    settled payment into one that never confirms.
    /// 5. **It is buried under [`MIN_CONFIRMATION_DEPTH`] blocks**, so a shallow reorg cannot undo a
    ///    payment already reported as settled. This also rejects a height beyond the source's own
    ///    peak, whose computed depth is 1.
    fn from_confirmed(
        pending: &PendingTransfer,
        record: &CoinRecord,
        peak_height: u32,
    ) -> Option<Self> {
        if record.coin.coin_id() != pending.payment_coin_id {
            return None;
        }
        let confirmed_height = record.confirmed_height?;
        if confirmed_height == 0 || confirmed_height < pending.pushed_at_height {
            return None;
        }
        // `peak - confirmed` counts the blocks built ON TOP; the confirming block is the first of the
        // depth, hence the +1.
        if peak_height
            .saturating_sub(confirmed_height)
            .saturating_add(1)
            < MIN_CONFIRMATION_DEPTH
        {
            return None;
        }
        Some(Self {
            payment_coin_id: pending.payment_coin_id,
            recipient: pending.recipient,
            amount_mojos: pending.amount_mojos,
            confirmed_height,
        })
    }

    /// The confirmed coin that paid the recipient.
    pub fn payment_coin_id(&self) -> Bytes32 {
        self.payment_coin_id
    }

    /// Who was paid.
    pub fn recipient(&self) -> Bytes32 {
        self.recipient
    }

    /// How much they were paid, in mojos.
    pub fn amount_mojos(&self) -> u64 {
        self.amount_mojos
    }

    /// The block height at which the payment coin was confirmed.
    pub fn confirmed_height(&self) -> u32 {
        self.confirmed_height
    }
}

/// Where a pushed transfer stands — the three answers a polling surface must tell apart.
///
/// [`Failed`](Self::Failed) reports exactly ONE proven-dead cause: a source coin was consumed by a
/// different spend, which the chain can attest to. A bundle evicted from a mempool it never left
/// leaves its inputs unspent and is, on chain, indistinguishable from one that is merely slow — that
/// case stays [`Awaiting`](Self::Awaiting), where `blocks_since_push` grows monotonically so a caller
/// can set a real deadline instead of watching an unchanging absence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransferStatus {
    /// The payment coin exists and is buried deep enough to be treated as settled.
    Confirmed(ConfirmedTransfer),

    /// Still in flight, or quietly dead in a way the chain cannot attest to.
    Awaiting {
        /// Blocks the chain has advanced since the push.
        blocks_since_push: u32,
    },

    /// The transfer can NEVER confirm: a source coin was spent by a DIFFERENT spend, so the bundle
    /// can no longer be included. The caller builds a new transfer.
    Failed {
        /// What makes this transfer unable to confirm.
        reason: String,
    },
}

impl TransferStatus {
    /// The settled payment, if this transfer has produced one.
    ///
    /// A convenience for the success case only; it discards the difference between
    /// [`Awaiting`](Self::Awaiting) and [`Failed`](Self::Failed), so a polling loop MUST match on the
    /// variants rather than use this.
    pub fn confirmed(&self) -> Option<&ConfirmedTransfer> {
        match self {
            Self::Confirmed(settled) => Some(settled),
            Self::Awaiting { .. } | Self::Failed { .. } => None,
        }
    }
}

impl WalletOps {
    /// Build the unsigned coin spends for an ordinary XCH transfer out of this profile's wallet.
    ///
    /// The result is inert: it is not authorized, not signed and not broadcast. Hand
    /// [`TransferPlan::coin_spends`] to
    /// [`PolicyAuthorizer::authorize_op`](crate::wallet::enforcer::PolicyAuthorizer::authorize_op)
    /// and the resulting approval to
    /// [`MoneySigner::sign_approved`](crate::wallet::money_signer::MoneySigner::sign_approved).
    ///
    /// `reservations` is the in-flight coin set. The coins this build selects are RESERVED in it
    /// before the plan is returned, so a second build in the same confirmation window cannot choose
    /// them — the chain still reports them unspent while the first bundle sits in a mempool. Release
    /// the returned [`TransferPlan::reservation`] as soon as the transfer is known settled or known
    /// dead; the TTL is only the backstop for a build that is abandoned.
    ///
    /// `custody` is the profile's configured tier, and it is consulted for one reason: a
    /// [`Vault`](CustodyPolicy::Vault) profile cannot pay a third party at all, and the honest place
    /// to say so is before a spend is built rather than at the gate, where the refusal would arrive
    /// as a generic denial.
    ///
    /// # Errors
    ///
    /// See [`TransferError`]: a shortfall, a coin-count over the cap, a vault-tier profile, a
    /// self-payment, and an unreachable chain are all distinct, because a user is owed a different
    /// sentence for each.
    pub fn build_transfer<C>(
        &self,
        chain: &C,
        custody: &CustodyPolicy,
        request: &TransferRequest,
        reservations: &CoinReservations<'_>,
    ) -> TransferResult<TransferPlan>
    where
        C: ChainSource + ?Sized,
    {
        if let CustodyPolicy::Vault(_) = custody {
            return Err(TransferError::VaultTransferUnsupported);
        }
        if request.amount_mojos == 0 {
            return Err(TransferError::ZeroAmount);
        }

        let wallet = self.wallet_key();
        if request.recipient() == wallet.puzzle_hash() {
            return Err(TransferError::SelfPayment);
        }

        let required = request.required_total()?;
        // Selection and reservation are ONE step. Selecting first and reserving afterwards is
        // check-then-act: two builders both see the coin free and both take it, which is the defect
        // this closes rather than a smaller version of it.
        let (selected, held) = select_and_reserve(
            reservations,
            MAX_RESERVATION_ATTEMPTS,
            |excluded| {
                let coins = select_input_coins(chain, wallet.puzzle_hash(), required, excluded)?;
                let ids = coins.iter().map(Coin::coin_id).collect();
                Ok((coins, ids))
            },
            |e| TransferError::ReservationUnusable(e.to_string()),
        )?;

        // `held` stays alive across the build, so a build that fails releases the coins on its way
        // out instead of stranding them for the TTL over a plan that does not exist. It is committed
        // only once there IS a plan for it to guard.
        let mut plan = build_transfer_spends(&wallet, &selected, request, None)?;
        plan.reservation = Some(held.commit());
        Ok(plan)
    }

    /// Rebuild a pushed transfer at a HIGHER fee, re-spending EXACTLY the coins it already spends.
    ///
    /// # This exists because the obvious retry pays the recipient twice
    ///
    /// Calling [`build_transfer`](Self::build_transfer) again with a bigger fee re-runs selection,
    /// and selection takes the smallest coin covering `amount + fee`. Raising the fee can cross a
    /// coin boundary and choose a DIFFERENT lead, and two bundles spending disjoint inputs do not
    /// conflict: both are valid, both can sit in the mempool, and both can be included. The recipient
    /// is paid twice, out of two different coins.
    ///
    /// Re-spending the original inputs removes that possibility structurally rather than by warning.
    /// The lead is unchanged, so the payment coin — `(lead, recipient, amount)` — keeps the SAME id
    /// and the caller's existing [`PendingTransfer`] still describes what to watch; and because both
    /// bundles spend the same coins, consensus can include at most one of them.
    ///
    /// # Errors
    ///
    /// [`TransferError::ReplacementFeeNotHigher`] when the new fee would not outbid the original, and
    /// [`TransferError::SourcesNoLongerSpendable`] when an input can no longer be spent — which
    /// usually means the ORIGINAL transfer has already been included, so a replacement would be a
    /// second payment rather than a faster one. Neither is reported as a shortfall.
    ///
    /// [`TransferError::ReplacementInputsInsufficient`] when the original inputs cannot cover the
    /// raised total. It is a SEPARATE variant from [`InsufficientFunds`](TransferError::InsufficientFunds)
    /// on purpose: this method may not reach for another coin — doing so is the naive rebuild that
    /// pays the recipient twice — so the number it can report is the reused inputs' total, and a
    /// surface rendering that as a wallet balance would tell the user they hold far less than they do.
    /// A transfer whose inputs were consumed exactly cannot be fee-bumped at all; the remedy is a
    /// lower fee or a fresh transfer, never a deposit.
    pub fn build_transfer_replacing<C>(
        &self,
        chain: &C,
        custody: &CustodyPolicy,
        pending: &PendingTransfer,
        new_fee_mojos: u64,
    ) -> TransferResult<TransferPlan>
    where
        C: ChainSource + ?Sized,
    {
        if let CustodyPolicy::Vault(_) = custody {
            return Err(TransferError::VaultTransferUnsupported);
        }
        if new_fee_mojos <= pending.fee_mojos {
            return Err(TransferError::ReplacementFeeNotHigher {
                current: pending.fee_mojos,
                proposed: new_fee_mojos,
            });
        }

        let wallet = self.wallet_key();
        // `from_derived` is correct here and is not a bypass: this puzzle hash was judged payable
        // when the ORIGINAL request was built, and has been carried through the plan unchanged.
        let request = TransferRequest {
            recipient: PayableDestination::from_derived(pending.recipient),
            amount_mojos: pending.amount_mojos,
            fee_mojos: new_fee_mojos,
        };
        let required = request.required_total()?;

        // ORDER is preserved deliberately: `build_transfer_spends` takes the LAST coin as the lead,
        // so re-reading the ids in the order the original plan recorded them is what keeps the lead —
        // and therefore the payment coin id — identical.
        let mut inputs = Vec::with_capacity(pending.source_coin_ids.len());
        for coin_id in &pending.source_coin_ids {
            inputs.push(reread_spendable_input(chain, &wallet, *coin_id)?);
        }

        let reused_total = inputs
            .iter()
            .try_fold(0u64, |sum, coin: &Coin| sum.checked_add(coin.amount))
            .ok_or(TransferError::BalanceUnjudgeable)?;
        if reused_total < required {
            return Err(TransferError::ReplacementInputsInsufficient {
                required,
                reused_total,
            });
        }

        // Deliberately UNRESERVED. A replacement re-spends the coins the original plan already
        // holds, so taking a second reservation over them would conflict with the caller's own
        // in-flight transfer and refuse the fee bump it is supposed to enable. The original
        // reservation is still the one guarding these inputs, and it is still the one to release.
        build_transfer_spends(&wallet, &inputs, &request, None)
    }
}

/// Re-read one input of a transfer being replaced, refusing anything that is not still spendable.
///
/// The record is re-checked against the id it is supposed to describe before anything is read out of
/// it. A chain source may answer with a record for a DIFFERENT coin — an aggregating source is
/// several nodes stitched together — and taking the coin from an unverified record would rebuild the
/// bundle around inputs the wallet never selected.
fn reread_spendable_input<C>(
    chain: &C,
    wallet: &WalletKey,
    coin_id: Bytes32,
) -> TransferResult<Coin>
where
    C: ChainSource + ?Sized,
{
    let record = chain
        .coin_record(coin_id)
        .map_err(|e| TransferError::ChainUnreachable(e.to_string()))?
        .ok_or(TransferError::SourcesNoLongerSpendable { coin_id })?;

    if record.coin.coin_id() != coin_id {
        return Err(TransferError::ChainUnreachable(format!(
            "the chain source answered a request for coin {} with a record for {}",
            hex::encode(coin_id),
            hex::encode(record.coin.coin_id())
        )));
    }
    if record.confirmed_height.is_none() || record.is_spent() {
        return Err(TransferError::SourcesNoLongerSpendable { coin_id });
    }
    if record.coin.puzzle_hash != wallet.puzzle_hash() {
        return Err(TransferError::UnexpectedCoinPuzzleHash {
            coin_id,
            puzzle_hash: record.coin.puzzle_hash,
        });
    }
    Ok(record.coin)
}

/// Ask the chain where `pending` stands.
///
/// A free function rather than a method: judging a broadcast transfer needs the chain and the
/// pending record, and no key material at all, so requiring an unlocked wallet to check on a payment
/// would be a false coupling.
///
/// # Errors
///
/// [`TransferError::ChainUnreachable`] when the chain could not answer — including when it cannot
/// report a peak, without which a claimed confirmation height cannot be bounded at all. The
/// transfer's state is then UNKNOWN, never an absence.
pub fn transfer_status<C>(pending: &PendingTransfer, chain: &C) -> TransferResult<TransferStatus>
where
    C: ChainSource + ?Sized,
{
    let peak = peak_height(chain)?;

    let payment = chain
        .coin_record(pending.payment_coin_id)
        .map_err(|e| TransferError::ChainUnreachable(e.to_string()))?;

    if let Some(settled) = payment
        .as_ref()
        .and_then(|record| ConfirmedTransfer::from_confirmed(pending, record, peak))
    {
        return Ok(TransferStatus::Confirmed(settled));
    }

    // A payment coin seen HERE vetoes a death verdict outright, and that is a correctness rule
    // rather than an optimisation. `proof_of_death` re-reads the payment coin itself, so deleting
    // this line leaves every existing test green — but the two checks are not the same check. This
    // one remembers the FIRST read: once any read has reported the payment coin, no later answer
    // that omits it can be read as "the coin never existed". Without it, a source that showed the
    // payment and then stopped showing it — an aggregating source answering from a node that has
    // since fallen behind — turns an already-observed payment into a proof of death, and `Failed`
    // tells the caller to send the money again.
    if payment.is_none() {
        if let Some(reason) = proof_of_death(pending, chain, peak)? {
            return Ok(TransferStatus::Failed { reason });
        }
    }

    Ok(TransferStatus::Awaiting {
        blocks_since_push: peak.saturating_sub(pending.pushed_at_height),
    })
}

/// Why this transfer can never confirm, if the chain can actually prove that.
///
/// The bundle is atomic ON CHAIN: had it been included, every source would be spent AND the payment
/// coin would exist. So a spent source alongside an absent payment coin can only be a DIFFERENT
/// spend, which makes this bundle permanently un-includable.
///
/// # Atomicity is a property of the chain, not of three RPCs
///
/// [`transfer_status`] reads the peak, then the payment coin, then each source — three separate
/// questions, answered at three separate moments. [`ConfirmedTransfer`] itself recommends an
/// AGGREGATING chain source, which is exactly the deployment where those answers come from different
/// nodes at different heights: a node behind the inclusion says the payment coin does not exist, a
/// node ahead of it says the source is spent, and the pair reads as a proof of death for a transfer
/// that has already paid the recipient. Since [`TransferStatus::Failed`] tells the caller to build a
/// new transfer, that inconsistency spends the user's money a second time.
///
/// The payment coin is therefore RE-READ after a spent source is observed, and death is declared only
/// if it is still absent. That does not make the two reads simultaneous — nothing here can — but it
/// does mean the conclusion rests on an observation taken AFTER the evidence that would contradict
/// it, so a source that ever reports the payment coin cannot be read as never having produced one.
///
/// The payment record is checked for EXISTENCE rather than confirmation throughout: a payment coin
/// seen in the mempool, or confirmed but not yet buried, is this bundle succeeding, and calling that
/// dead would be a worse error than calling it slow.
///
/// # The spend must be BURIED, not merely reported
///
/// The re-read above narrows the window but does not close it: nothing forces the two reads to come
/// from the same node or the same height, so an aggregating source can still answer "payment absent"
/// from a lagging node twice while a node ahead of it reports the input spent.
///
/// Requiring the input's spend to be buried under [`MIN_CONFIRMATION_DEPTH`] blocks removes the
/// asymmetry that makes that pairing dangerous. A lagging node is behind by definition, so a spend it
/// has not yet seen cannot be deeply buried from the same source's own peak; by the time a spend IS
/// that deep, a source lagging far enough to still hide the payment coin would have to be
/// inconsistent with itself rather than merely stale.
///
/// This uses only [`CoinRecord`] data plus the peak, and it errs strictly toward
/// [`Awaiting`](TransferStatus::Awaiting). That matters more than the tightness of the bound: the
/// exact meaning of a peak height is not specified across chain sources, so an off-by-one here can
/// only make this marginally more or less conservative — it can never flip a correct verdict into a
/// wrong one. Declaring a live transfer dead is the expensive direction, because
/// [`Failed`](TransferStatus::Failed) tells the caller to send again.
fn proof_of_death<C>(
    pending: &PendingTransfer,
    chain: &C,
    peak_height: u32,
) -> TransferResult<Option<String>>
where
    C: ChainSource + ?Sized,
{
    let read = |coin_id: Bytes32| {
        chain
            .coin_record(coin_id)
            .map_err(|e| TransferError::ChainUnreachable(e.to_string()))
    };

    for source_id in &pending.source_coin_ids {
        let Some(spent_height) = read(*source_id)?.and_then(|record| record.spent_height) else {
            continue;
        };
        // GENESIS FLOOR, mirroring the one `ConfirmedTransfer::from_confirmed` and the mint's
        // evidence apply to a confirmation height. No coin is spent in block 0, so a `Some(0)` is a
        // height the chain cannot have produced — most plausibly a source that zero-filled the field
        // rather than leaving it `None`.
        //
        // Without this floor that value is the WORST possible input: a spend at height 0 computes a
        // burial depth of `peak + 1`, so it sails past the burial requirement and yields `Failed` —
        // and `Failed` tells the caller to build a new transfer, which is the double payment. A
        // fabricated height must not be the most convincing evidence in the system.
        if spent_height == 0 {
            continue;
        }
        // The confirming block is the first of the depth, hence the +1 — the same arithmetic
        // `ConfirmedTransfer::from_confirmed` uses to judge the payment coin's burial.
        let spend_depth = peak_height.saturating_sub(spent_height).saturating_add(1);
        if spend_depth < MIN_CONFIRMATION_DEPTH {
            continue;
        }
        if read(pending.payment_coin_id)?.is_some() {
            return Ok(None);
        }
        return Ok(Some(format!(
            "input coin {} was spent by a different spend at height {spent_height}, now buried \
             under {spend_depth} blocks; this transfer can never confirm",
            hex::encode(source_id)
        )));
    }
    Ok(None)
}

/// Reads the chain's peak, failing closed when it cannot be established.
///
/// A source that exposes no peak (`Ok(None)`) is not an absence to work around: without one, a
/// claimed confirmation height cannot be bounded, so the status refuses to evaluate evidence at all.
fn peak_height<C>(chain: &C) -> TransferResult<u32>
where
    C: ChainSource + ?Sized,
{
    chain
        .peak_height()
        .map_err(|e| TransferError::ChainUnreachable(e.to_string()))?
        .ok_or_else(|| {
            TransferError::ChainUnreachable(
                "the chain source reports no peak height, so a confirmation height cannot be \
                 checked"
                    .into(),
            )
        })
}

/// Picks the wallet coins to spend, using as FEW inputs as will cover `required`.
///
/// A coin that is spent, foreign, or unjudgeable is neither selected NOR counted toward `available`:
/// reporting any of them would tell the user they hold money they cannot move.
///
/// # No individual record may abort the build
///
/// The records come from the chain SOURCE, and a hint-indexing one returns coins an ATTACKER chose —
/// a hint is memo data anybody can write, so a single dust coin hinted at this wallet puts a record
/// of the attacker's choosing in front of this function on every call. Any rule that refused the
/// whole build because of one record's content would therefore be a remote, unauthenticated,
/// permanent denial of service on the wallet's ability to spend.
///
/// Exclusion achieves the entire security goal — a foreign or unjudgeable coin is never selected and
/// never counted — while leaving the wallet able to spend from the coins it genuinely owns.
///
/// [`TransferError::SpendabilityUnknown`] is raised ONLY when excluding an unjudgeable coin is what
/// makes the transfer fall short. That distinction is what keeps it honest: it says "we could not
/// judge some coins, and without them you are short", which is true, rather than either blaming the
/// user's balance or bricking a wallet that can plainly afford the send.
///
/// # Fewest inputs, not smallest inputs
///
/// The tempting rule is to spend the smallest coins first, so that paying quietly consolidates dust.
/// It is a trap, because the input cap turns it into a denial of service that a STRANGER can trigger:
/// anyone may send dust to an address, so a wallet holding two hundred 1-mojo coins plus one large
/// one would sweep the dust, never reach the amount, and refuse a send it could have made from the
/// large coin alone. The user would be told their transfer needs too many coins while a single coin
/// sat there covering it — the same lie about their money the cap exists to prevent, in different
/// words.
///
/// So selection minimises the input COUNT instead:
///
/// 1. the smallest SINGLE coin that covers the whole amount, when one exists — which also keeps the
///    wallet's larger coins intact and the change small (the same rule
///    [`mint`](crate::mint) uses to pick its funding coin); otherwise
/// 2. largest-first accumulation, so the fewest possible coins are consumed before the cap is
///    consulted.
///
/// # Reserved coins narrow SELECTION, never the balance
///
/// `reserved` names coins already committed to an in-flight spend. They are excluded from what may
/// be CHOSEN, and deliberately still counted in `available` — a reserved coin is the user's money,
/// and subtracting it would report a shortfall they do not have. That is why a wallet blocked only
/// by reservations raises [`TransferError::CoinsReserved`], which says the coins are busy, rather
/// than [`TransferError::InsufficientFunds`], which would say they are gone.
fn select_input_coins<C>(
    chain: &C,
    puzzle_hash: Bytes32,
    required: u64,
    reserved: &HashSet<Bytes32>,
) -> TransferResult<Vec<Coin>>
where
    C: ChainSource + ?Sized,
{
    let records = chain
        .coin_records_by_puzzle_hash(puzzle_hash, false)
        .map_err(|e| TransferError::ChainUnreachable(e.to_string()))?;

    // Nothing here REFUSES on the content of an individual record, and that is a security property
    // rather than leniency. The set of records is chosen by the chain SOURCE, and a hint-indexing
    // source returns coins an attacker selected: a hint is memo data anybody may write, so one dust
    // coin hinted at this wallet is enough to put a chosen record in this loop forever. A rule that
    // aborted the build on such a record would let a stranger permanently stop the wallet sending.
    //
    // So an unusable record is EXCLUDED, and the only thing that can fail is the outcome — see the
    // shortfall handling below, which reports what could not be judged when, and only when, it
    // actually changes the answer.
    let mut spendable: Vec<Coin> = Vec::with_capacity(records.len());
    let mut unjudgeable: Vec<Bytes32> = Vec::new();
    // A coin may appear in the listing more than once. An aggregating source is several nodes
    // stitched together — the same shape every other function in this module explicitly designs for
    // — and two nodes reporting the same coin is not a fault, it is the normal case.
    //
    // Both halves of the damage are silent. A duplicate is counted TWICE in `available`, so the
    // balance the user is shown, and the shortfall test that gates the whole build, are both
    // inflated; and it can be SELECTED twice, emitting a bundle with two `CoinSpend`s of one coin —
    // a self-double-spend that consensus rejects after the push rather than before it.
    //
    // So the set is made unique BEFORE the fold. Deduplicating after selection would fix only the
    // bundle and leave the balance figure lying, which is the half that misleads.
    let mut seen: HashSet<Bytes32> = HashSet::with_capacity(records.len());
    for record in &records {
        // SPENT is checked FIRST. `include_spent: false` is a request, not a guarantee, and a spent
        // coin is not spendable whatever else is unknown about it — judging its height first would
        // mean an unknown height on an already-irrelevant coin decided the whole build.
        if record.is_spent() {
            continue;
        }
        // A coin locked by a different puzzle is not part of this wallet's XCH balance at all, so
        // leaving it out under-counts NOTHING. It is a CAT, or somebody else's coin that a
        // hint-indexing source associated with this wallet; either way this builder cannot unlock it
        // and must not count its units as mojos.
        if record.coin.puzzle_hash != puzzle_hash {
            continue;
        }
        // `None` means "this source does not know", not "unconfirmed" and not "absent". The coin may
        // be perfectly spendable, so it is remembered rather than silently forgotten: if the wallet
        // turns out to be short WITHOUT it, the shortfall is reported as unjudgeable rather than as
        // a balance the user does not have.
        if record.confirmed_height.is_none() {
            unjudgeable.push(record.coin.coin_id());
            continue;
        }
        if !seen.insert(record.coin.coin_id()) {
            continue;
        }
        spendable.push(record.coin);
    }
    // Coin id breaks ties, so two coins of equal value are ordered by something stable rather than by
    // whatever order the chain source happened to answer in. CACHED, because the plain `sort_by_key`
    // re-invokes its closure on every comparison — and `coin_id()` is a SHA-256, so an attacker who
    // dusts the wallet (which needs nobody's permission) chooses `n` in an O(n log n) hashing cost.
    spendable.sort_by_cached_key(|coin| (coin.amount, coin.coin_id()));

    // `available` is the wallet's ENTIRE spendable balance, computed before any selection — it is
    // what the user would be told they hold, so it must not be an artefact of how far a selection
    // loop happened to get.
    //
    // CHECKED, not saturating: a total clamped to `u64::MAX` would sail through the shortfall test
    // below and turn "this balance cannot be judged" into "proceed, and be refused later by
    // arithmetic". The same discipline `SpendSummary::checked_native_total_mojos` applies.
    let available = spendable
        .iter()
        .try_fold(0u64, |sum, coin| sum.checked_add(coin.amount))
        .ok_or(TransferError::BalanceUnjudgeable)?;
    if available < required {
        // Which refusal is honest depends on whether the excluded coins MATTER. Reporting a
        // shortfall while silently having dropped coins that might have covered it would state a
        // balance as fact when it is only a lower bound; reporting "unjudgeable" for a wallet that is
        // plainly short anyway would blame the source for the user's balance.
        if let Some(coin_id) = unjudgeable.first() {
            return Err(TransferError::SpendabilityUnknown { coin_id: *coin_id });
        }
        return Err(TransferError::InsufficientFunds {
            required,
            available,
        });
    }

    // Reservations are applied HERE, after `available` and after the shortfall test, and the order is
    // the property rather than an implementation detail. Filtering reserved coins out earlier would
    // fold them out of the balance too, so a user with plenty of money and one busy coin would be
    // told they cannot afford their own transfer. Filtering later — at the bundle — would be too
    // late, because the coin would already have been chosen.
    spendable.retain(|coin| !reserved.contains(&coin.coin_id()));
    let selectable = spendable
        .iter()
        .try_fold(0u64, |sum, coin| sum.checked_add(coin.amount))
        .ok_or(TransferError::BalanceUnjudgeable)?;
    if selectable < required {
        return Err(TransferError::CoinsReserved {
            required,
            available,
            selectable,
        });
    }

    let selected = if let Some(single) = spendable.iter().find(|coin| coin.amount >= required) {
        vec![*single]
    } else {
        let mut selected = Vec::new();
        let mut total: u64 = 0;
        for coin in spendable.iter().rev() {
            total = total.saturating_add(coin.amount);
            selected.push(*coin);
            if total >= required {
                break;
            }
        }
        if selected.len() > MAX_TRANSFER_INPUT_COINS {
            return Err(TransferError::TooManyInputCoins {
                needed: selected.len(),
                cap: MAX_TRANSFER_INPUT_COINS,
            });
        }
        selected
    };

    // The listing has now had its say. Every coin it offered is re-read BY NAME — the question
    // consensus will ask — and the whole attempt is abandoned if any answer disagrees. See
    // [`crate::chain_confirm`] for why a listing alone is not enough, and why this is all-or-nothing.
    confirm_all_spendable_by_name(chain, &selected)?;
    Ok(selected)
}

/// Builds the unsigned spends: one LEAD coin that creates the outputs, and secondary coins that only
/// contribute value.
///
/// # Change is computed exactly, never left over
///
/// Chia treats any unspent input value as fee, silently. So a change figure that is short by even one
/// mojo does not fail — it donates the difference to a farmer, and the only place that would ever
/// show up is the user's balance. `change = total - amount - fee` is therefore a checked subtraction
/// over the very coins that were selected, and the change coin is omitted entirely when it is zero
/// (a zero-value coin is not a thing consensus wants).
///
/// # Why the secondary inputs are bound to the lead
///
/// A secondary spend creates nothing, so in isolation it is pure value handed to whoever includes
/// it. Each secondary therefore asserts a coin announcement made by the lead, which makes it
/// un-includable without it.
///
/// **What that does NOT defend against, stated plainly:** a third party cannot take this bundle,
/// drop the lead and submit the rest. The signature is an aggregate over every input's
/// `AGG_SIG_ME`, and a subset of the spends does not verify against it — so a stranger splitting the
/// bundle is stopped by BLS, not by this condition. Any rationale claiming otherwise is wrong, and
/// the test that proves this binding must re-sign the orphaned subset or it is measuring the
/// signature failure instead.
///
/// What it genuinely buys is defence in depth against shapes where the aggregate is not the
/// protection: a partially-signed or multi-signer bundle, a future builder that signs inputs
/// independently, or any assembly step that can recombine spends. It costs one condition per input,
/// and it makes the "secondaries alone" bundle invalid on its own terms rather than only by virtue of
/// a signature it happens to be paired with.
///
/// The binding runs in ONE direction only. The lead alone is already un-includable: without the
/// secondaries its outputs plus fee exceed its input, and consensus refuses a spend that creates
/// value. A reverse assertion would be a condition that can never do any work.
///
/// # There is no duplicate-coin-id case left to handle
///
/// A coin id is `(parent, puzzle_hash, amount)`, and the lead creates at most two coins with the same
/// parent — the payment and the change. They can only collide if the recipient IS this wallet's own
/// puzzle hash and the change happens to equal the amount, and a self-payment is refused before this
/// function is reached ([`TransferError::SelfPayment`]). That refusal is what makes the collision
/// unreachable rather than merely unlikely; the mint, which must pay its own wallet, has no such
/// escape and folds the colliding mojo into the fee instead.
fn build_transfer_spends(
    wallet: &WalletKey,
    selected: &[Coin],
    request: &TransferRequest,
    reservation: Option<ReservationId>,
) -> TransferResult<TransferPlan> {
    let (lead, secondaries) = selected
        .split_last()
        .ok_or_else(|| TransferError::Build("no input coins were selected".into()))?;

    let total = selected
        .iter()
        .try_fold(0u64, |sum, coin| sum.checked_add(coin.amount))
        .ok_or_else(|| TransferError::Build("the selected inputs overflow u64".into()))?;
    let change = total
        .checked_sub(request.required_total()?)
        .ok_or_else(|| {
            TransferError::Build("the selected inputs do not cover the transfer".into())
        })?;

    let mut ctx = SpendContext::new();
    let hint = ctx
        .hint(request.recipient())
        .map_err(|e| TransferError::Build(format!("recipient hint: {e}")))?;

    let mut lead_conditions =
        Conditions::new().create_coin(request.recipient(), request.amount_mojos, hint);
    if change > 0 {
        lead_conditions = lead_conditions.create_coin(wallet.puzzle_hash(), change, Memos::None);
    }
    if request.fee_mojos > 0 {
        lead_conditions = lead_conditions.reserve_fee(request.fee_mojos);
    }
    if !secondaries.is_empty() {
        lead_conditions =
            lead_conditions.create_coin_announcement(INPUT_BINDING_MESSAGE.to_vec().into());
    }

    let layer = StandardLayer::new(wallet.public_key());
    layer
        .spend(&mut ctx, *lead, lead_conditions)
        .map_err(|e| TransferError::Build(format!("lead input: {e}")))?;

    let binding = chia_wallet_sdk::types::announcement_id(lead.coin_id(), INPUT_BINDING_MESSAGE);
    for coin in secondaries {
        layer
            .spend(
                &mut ctx,
                *coin,
                Conditions::new().assert_coin_announcement(binding),
            )
            .map_err(|e| TransferError::Build(format!("secondary input: {e}")))?;
    }

    Ok(TransferPlan {
        coin_spends: ctx.take(),
        payment_coin_id: Coin::new(lead.coin_id(), request.recipient(), request.amount_mojos)
            .coin_id(),
        source_coin_ids: selected.iter().map(Coin::coin_id).collect(),
        recipient: request.recipient(),
        amount_mojos: request.amount_mojos,
        fee_mojos: request.fee_mojos,
        change_mojos: change,
        reservation,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::id::ProfileIx;
    use crate::session_residency::Residency;
    use crate::wallet::clock::{FixedClock, SystemClock, UnreadableClock};
    use crate::wallet::policy::{HotWallet, Vault};
    use crate::wallet::reservation::{
        CoinReservationStore, LocalReservations, ReservationError, DEFAULT_RESERVATION_TTL_SECS,
    };
    use chia_wallet_sdk::prelude::FromClvm;
    use chia_wallet_sdk::types::{run_puzzle, Condition};
    use clvmr::serde::node_from_bytes;
    use clvmr::Allocator;
    use dig_keystore::{BackendKey, MemoryBackend};
    use dig_session::{Password, Session, UnlockedMasterSeed, ENTROPY_LEN};
    use std::cell::Cell;
    use std::collections::HashSet;
    use std::sync::Arc;

    const ENTROPY: [u8; ENTROPY_LEN] = [0x37; ENTROPY_LEN];
    const RECIPIENT: Bytes32 = Bytes32::new([7u8; 32]);
    /// A peak far above genesis, so no fixture height is ever accidentally `0`.
    const PEAK: u32 = 4_200_000;

    fn seed() -> Arc<UnlockedMasterSeed> {
        Arc::new(
            Session::enroll_master_seed(
                Arc::new(MemoryBackend::new()),
                BackendKey::new("transfer-tests".to_string()),
                Password::new("pw"),
                &ENTROPY,
            )
            .expect("the fixture seed must enrol"),
        )
    }

    fn ops() -> WalletOps {
        WalletOps::new(seed(), ProfileIx::ROOT, Arc::new(Residency::new()))
    }

    /// An EMPTY reservation set, fresh for each call, for the tests that are not about reservations.
    ///
    /// Fresh rather than shared: these tests run in parallel in one process, and a shared table
    /// would let one test's reservation silently change another's selection — which is a false RED
    /// in one direction and a false GREEN in the other.
    ///
    /// The store is leaked so the borrow can be `'static` and the helper usable as an argument
    /// expression. It is a few dozen bytes per call, in test builds only.
    fn free() -> CoinReservations<'static> {
        let store: &'static LocalReservations = Box::leak(Box::new(LocalReservations::new()));
        CoinReservations::new(store, &SystemClock)
    }

    fn hot() -> CustodyPolicy {
        CustodyPolicy::Hot(HotWallet {
            auto_send_limit: u64::MAX,
        })
    }

    /// A chain source over a fixed set of records, with a controllable peak.
    ///
    /// Records are supplied whole rather than as bare coins because half of these tests are ABOUT the
    /// difference between a confirmed coin, an unconfirmed one and a spent one — a double that could
    /// only express "a coin exists" could not exhibit the property under test.
    ///
    /// [`answers_with`](Self::answers_with) exists for the same reason one level up. Looking a record
    /// up BY the requested id makes it structurally impossible for this double to answer about a
    /// different coin — so a source that returns a real, well-formed record for the WRONG coin, which
    /// is the whole threat `ConfirmedTransfer::from_confirmed`'s id check exists to stop, could not be
    /// expressed at all and the check could not be falsified by any test.
    struct FixedChain {
        records: Vec<CoinRecord>,
        peak: Option<u32>,
        offline: bool,
        /// When set, EVERY `coin_record` query is answered with this record, whatever was asked for.
        answers_with: Option<CoinRecord>,
        /// When set, `coin_records_by_puzzle_hash` answers with these records WITHOUT filtering.
        ///
        /// A source is not obliged to index by puzzle hash. One that indexes by HINT — plausible,
        /// since the hint is what makes a coin discoverable by its owner — returns coins locked by
        /// other puzzles, CAT coins among them. A double that filters by the requested puzzle hash
        /// cannot answer that way, so it cannot exhibit the property the XCH-only guard is about.
        answers_puzzle_hash_query_with: Option<Vec<CoinRecord>>,
        /// Records the BY-NAME read answers from, when it must disagree with the listing.
        ///
        /// The whole subject of the by-name confirmation is that the two questions are answered by
        /// different indexes, and on mainnet often by different peers. A double whose `coin_record`
        /// and `coin_records_by_puzzle_hash` are two views of ONE list cannot express a
        /// disagreement, so it could not exhibit the property under test at all.
        ///
        /// A coin ABSENT from this list is answered `None` by name — the vanished case.
        by_name: Option<Vec<CoinRecord>>,
    }

    impl FixedChain {
        /// Confirmed, unspent coins of the given amounts, all at `puzzle_hash`.
        fn holding(puzzle_hash: Bytes32, amounts: &[u64]) -> Self {
            Self {
                records: amounts
                    .iter()
                    .enumerate()
                    .map(|(ix, amount)| {
                        confirmed(Coin::new(
                            Bytes32::new([ix as u8 + 1; 32]),
                            puzzle_hash,
                            *amount,
                        ))
                    })
                    .collect(),
                peak: Some(PEAK),
                offline: false,
                answers_with: None,
                answers_puzzle_hash_query_with: None,
                by_name: None,
            }
        }

        fn with_records(records: Vec<CoinRecord>) -> Self {
            Self {
                records,
                peak: Some(PEAK),
                offline: false,
                answers_with: None,
                answers_puzzle_hash_query_with: None,
                by_name: None,
            }
        }

        fn at_peak(mut self, peak: u32) -> Self {
            self.peak = Some(peak);
            self
        }

        fn offline() -> Self {
            Self {
                records: Vec::new(),
                peak: Some(PEAK),
                offline: true,
                answers_with: None,
                answers_puzzle_hash_query_with: None,
                by_name: None,
            }
        }

        /// Answer every `coin_record` query with `record`, regardless of the id asked for.
        fn answering_every_query_with(mut self, record: CoinRecord) -> Self {
            self.answers_with = Some(record);
            self
        }

        /// Answer `coin_records_by_puzzle_hash` with `records`, without filtering by puzzle hash.
        fn answering_puzzle_hash_query_with(mut self, records: Vec<CoinRecord>) -> Self {
            self.answers_puzzle_hash_query_with = Some(records);
            self
        }

        /// Answer every BY-NAME read from `records` instead of from the listing, so the two indexes
        /// can disagree the way mainnet's do.
        fn answering_by_name_with(mut self, records: Vec<CoinRecord>) -> Self {
            self.by_name = Some(records);
            self
        }

        fn without_peak(mut self) -> Self {
            self.peak = None;
            self
        }

        fn unavailable<T>(&self) -> std::result::Result<T, String> {
            Err("simulated: no node answered".to_string())
        }
    }

    fn record(coin: Coin, confirmed_height: Option<u32>, spent_height: Option<u32>) -> CoinRecord {
        CoinRecord {
            coin,
            confirmed_height,
            spent_height,
            timestamp: None,
            coinbase: false,
        }
    }

    fn confirmed(coin: Coin) -> CoinRecord {
        record(coin, Some(PEAK - 100), None)
    }

    fn unconfirmed(coin: Coin) -> CoinRecord {
        record(coin, None, None)
    }

    fn spent(coin: Coin) -> CoinRecord {
        record(coin, Some(PEAK - 100), Some(PEAK - 50))
    }

    impl ChainSource for FixedChain {
        type Error = String;

        fn coin_record(&self, coin_id: Bytes32) -> std::result::Result<Option<CoinRecord>, String> {
            if self.offline {
                return self.unavailable();
            }
            if let Some(answer) = &self.answers_with {
                return Ok(Some(answer.clone()));
            }
            if let Some(by_name) = &self.by_name {
                return Ok(by_name
                    .iter()
                    .find(|record| record.coin.coin_id() == coin_id)
                    .cloned());
            }
            // A coherent source answers by name about every coin it also lists. Only `by_name` makes
            // the two indexes disagree; without it, a coin supplied through the listing override is
            // still a coin this double knows, and answering `None` for it would be the double
            // contradicting itself rather than the behaviour under test.
            Ok(self
                .records
                .iter()
                .chain(self.answers_puzzle_hash_query_with.iter().flatten())
                .find(|record| record.coin.coin_id() == coin_id)
                .cloned())
        }

        fn coin_records_by_puzzle_hash(
            &self,
            puzzle_hash: Bytes32,
            _include_spent: bool,
        ) -> std::result::Result<Vec<CoinRecord>, String> {
            if self.offline {
                return self.unavailable();
            }
            if let Some(answer) = &self.answers_puzzle_hash_query_with {
                return Ok(answer.clone());
            }
            Ok(self
                .records
                .iter()
                .filter(|record| record.coin.puzzle_hash == puzzle_hash)
                .cloned()
                .collect())
        }

        fn coin_records_by_parent(
            &self,
            _parent: Bytes32,
        ) -> std::result::Result<Vec<CoinRecord>, String> {
            Ok(Vec::new())
        }

        fn coin_spend(&self, _coin_id: Bytes32) -> std::result::Result<Option<CoinSpend>, String> {
            Ok(None)
        }

        fn resolve_singleton_lineage(
            &self,
            _launcher_id: Bytes32,
        ) -> std::result::Result<Option<dig_chainsource_interface::SingletonLineage>, String>
        {
            Err("not supported by this test double".to_string())
        }

        fn peak_height(&self) -> std::result::Result<Option<u32>, String> {
            if self.offline {
                return self.unavailable();
            }
            Ok(self.peak)
        }

        fn block_timestamp(&self, _height: u32) -> std::result::Result<Option<u64>, String> {
            Ok(None)
        }
    }

    /// Every coin the spends CREATE, re-derived by running the puzzles — never read off the plan's
    /// own description of itself.
    ///
    /// This is what makes the change and amount assertions load-bearing: a builder that reported the
    /// right numbers in its fields while emitting different `CREATE_COIN` conditions would satisfy an
    /// assertion on `change_mojos()` and fail here.
    fn created_coins(coin_spends: &[CoinSpend]) -> Vec<Coin> {
        conditions_of(coin_spends)
            .into_iter()
            .filter_map(|(spender, condition)| match condition {
                Condition::CreateCoin(create) => {
                    Some(Coin::new(spender, create.puzzle_hash, create.amount))
                }
                _ => None,
            })
            .collect()
    }

    /// Every condition the spends emit, paired with the id of the coin that emitted it.
    fn conditions_of(coin_spends: &[CoinSpend]) -> Vec<(Bytes32, Condition)> {
        let mut allocator = Allocator::new();
        let mut out = Vec::new();
        for spend in coin_spends {
            let puzzle = node_from_bytes(&mut allocator, &spend.puzzle_reveal).expect("puzzle");
            let solution = node_from_bytes(&mut allocator, &spend.solution).expect("solution");
            let output = run_puzzle(&mut allocator, puzzle, solution).expect("runs");
            for condition in Vec::<Condition>::from_clvm(&allocator, output).expect("conditions") {
                out.push((spend.coin.coin_id(), condition));
            }
        }
        out
    }

    // ------------------------------------------------------------------- coin selection

    /// The amounts of the coins a plan actually spends, sorted, for asserting on selection.
    fn inputs_of(plan: &TransferPlan) -> Vec<u64> {
        let mut amounts: Vec<u64> = plan
            .coin_spends()
            .iter()
            .map(|spend| spend.coin.amount)
            .collect();
        amounts.sort_unstable();
        amounts
    }

    /// **RED (dig-account#26): two builds in the same confirmation window select the SAME coin.**
    ///
    /// The chain double is deliberately STATIC across the two calls, because that is the real
    /// condition: the first bundle is in the mempool, so the coin it spends is still reported unspent
    /// to the second build. Nothing else is needed to reproduce the defect.
    ///
    /// The fixture holds TWO coins that each cover the transfer on their own. That is the truthful
    /// control: with a reservation in place the second build must SUCCEED on the other coin, so this
    /// test cannot be satisfied by an implementation that simply refuses every second build.
    #[test]
    fn two_builds_in_the_same_window_must_not_select_the_same_coin() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000, 1_100]);
        let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
        // ONE reservation set across both builds, because that is what two callers of one wallet
        // share. Handing each build its own would make this test pass while proving nothing.
        let store = LocalReservations::new();
        let reservations = store.reservations();

        let first = ops
            .build_transfer(&chain, &hot(), &request, &reservations)
            .expect("the first build is funded");
        let second = ops
            .build_transfer(&chain, &hot(), &request, &reservations)
            .expect("the second build is funded by the OTHER coin");

        assert_ne!(
            first.source_coin_ids(),
            second.source_coin_ids(),
            "two spends built in the same window selected the same coin"
        );
    }

    /// A reservation store that cannot answer, for proving the build REFUSES rather than proceeds.
    #[derive(Debug)]
    struct UnreadableReservations;

    impl CoinReservationStore for UnreadableReservations {
        fn held(&self, _now_unix: u64) -> std::result::Result<Vec<Bytes32>, ReservationError> {
            Err(ReservationError::Unavailable(
                "simulated: the store is gone".into(),
            ))
        }

        fn reserve_all(
            &self,
            _coins: &[Bytes32],
            _now_unix: u64,
            _expires_at_unix: u64,
        ) -> std::result::Result<ReservationId, ReservationError> {
            Err(ReservationError::Unavailable(
                "simulated: the store is gone".into(),
            ))
        }

        fn release(&self, _id: ReservationId) -> std::result::Result<(), ReservationError> {
            Ok(())
        }
    }

    /// A store whose READ fails while its WRITE succeeds — a read replica that is down, a cache
    /// that cannot be reached, a control-interface call that times out on the query but not on the
    /// command.
    ///
    /// This double exists because the obvious one does not test what it appears to. A store that
    /// fails on BOTH methods is caught by whichever check runs second, so it cannot distinguish an
    /// implementation that refuses on an unreadable `held` from one that quietly treats an
    /// unreadable `held` as "nothing is reserved". Only a store that fails on exactly one method
    /// can tell those two apart — and the second is the dangerous one, because it restores the
    /// double-select while every call still reports success.
    #[derive(Debug)]
    struct UnreadableButWritable(LocalReservations);

    impl CoinReservationStore for UnreadableButWritable {
        fn held(&self, _now_unix: u64) -> std::result::Result<Vec<Bytes32>, ReservationError> {
            Err(ReservationError::Unavailable(
                "simulated: the read replica is down".into(),
            ))
        }

        fn reserve_all(
            &self,
            coins: &[Bytes32],
            now_unix: u64,
            expires_at_unix: u64,
        ) -> std::result::Result<ReservationId, ReservationError> {
            self.0.reserve_all(coins, now_unix, expires_at_unix)
        }

        fn release(&self, id: ReservationId) -> std::result::Result<(), ReservationError> {
            self.0.release(id)
        }
    }

    /// A fixture instant, so every reservation lifetime in these tests is measured against a time
    /// the test names rather than against the wall clock. Passing a small literal through a
    /// wall-clock API would make every reservation already expired by ~1.8 billion seconds, and the
    /// tests would assert the lapsed path while claiming to assert the live one.
    const NOW: u64 = 1_800_000_000;

    /// **The user is told their coins are BUSY, never that their money is gone.**
    ///
    /// This is a PLACEMENT test, not an outcome test. Excluding reserved coins BEFORE the balance is
    /// computed also refuses the build — with `InsufficientFunds`, reporting an `available` of 0 for
    /// a wallet holding 1_000 mojos. Both placements produce "no plan"; only one of them tells the
    /// truth about the balance, so the assertion is on the ERROR and on both of its figures.
    #[test]
    fn a_reserved_coin_is_still_the_users_money() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
        let store = LocalReservations::new();
        let reservations = store.reservations();

        ops.build_transfer(&chain, &hot(), &request, &reservations)
            .expect("the first build takes the only coin");

        let error = ops
            .build_transfer(&chain, &hot(), &request, &reservations)
            .expect_err("the only coin is committed to the first build");

        match error {
            TransferError::CoinsReserved {
                required,
                available,
                selectable,
            } => {
                assert_eq!(required, 900);
                assert_eq!(
                    available, 1_000,
                    "a reserved coin is still the money the user holds and must still be counted"
                );
                assert_eq!(selectable, 0, "and none of it is free to select right now");
            }
            other => panic!(
                "a busy coin must not be reported as a shortfall - that asks a funded user to \
                 deposit for no reason: {other:?}"
            ),
        }
    }

    /// **RELEASE, on the confirm-or-reject path.** A settled or dead transfer hands its coins back
    /// at once rather than holding them for the rest of the TTL.
    ///
    /// The clock does NOT move, so nothing here can be satisfied by expiry — this test can only pass
    /// because `release` did something.
    #[test]
    fn releasing_a_reservation_frees_its_coin_immediately() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
        let store = LocalReservations::new();
        let clock = FixedClock::new(NOW);
        let reservations = CoinReservations::new(&store, &clock);

        let first = ops
            .build_transfer(&chain, &hot(), &request, &reservations)
            .expect("the first build takes the only coin");
        let held = first
            .reservation()
            .expect("an ordinary build reserves what it selected");

        assert!(
            ops.build_transfer(&chain, &hot(), &request, &reservations)
                .is_err(),
            "the control: while the reservation is live the coin is unavailable"
        );

        reservations.release(held).expect("release must succeed");

        let after = ops
            .build_transfer(&chain, &hot(), &request, &reservations)
            .expect("a released coin is selectable again");
        assert_eq!(after.source_coin_ids(), first.source_coin_ids());
    }

    /// **RELEASE, on the timeout path.** A build abandoned without a release — a crash, a user who
    /// walked away — must not hold the wallet's own coins for ever.
    ///
    /// The boundary is pinned from BOTH sides: at exactly `NOW + TTL` the reservation is still live,
    /// and one second later it is not. A test that only stepped far past the TTL would pass equally
    /// for a reservation that never expired and for one that expired immediately.
    #[test]
    fn a_reservation_lapses_after_its_ttl_and_not_before() {
        const TTL: u64 = 300;
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
        let store = LocalReservations::new();
        let clock = FixedClock::new(NOW);
        let reservations =
            CoinReservations::with_ttl_secs(&store, &clock, TTL).expect("a non-zero TTL is fine");

        ops.build_transfer(&chain, &hot(), &request, &reservations)
            .expect("the first build takes the only coin");

        clock.set(NOW + TTL);
        assert!(
            ops.build_transfer(&chain, &hot(), &request, &reservations)
                .is_err(),
            "at exactly the TTL the reservation is still holding the coin"
        );

        clock.set(NOW + TTL + 1);
        ops.build_transfer(&chain, &hot(), &request, &reservations)
            .expect("one second past the TTL the coin is selectable again");
    }

    /// **Expiry must not resurrect a SPENT coin.** The reservation is a filter layered on top of the
    /// chain read, never a replacement for it.
    ///
    /// The fixture holds two coins, one already spent on chain, and lets the reservation lapse. A
    /// reservation table allowed to stand in for the chain read would hand the spent coin back as
    /// selectable; the honest answer is that the wallet is short.
    #[test]
    fn a_lapsed_reservation_does_not_make_a_spent_coin_selectable() {
        let ops = ops();
        let ph = ops.puzzle_hash();
        let alive = Coin::new(Bytes32::new([2; 32]), ph, 100);
        let consumed = Coin::new(Bytes32::new([3; 32]), ph, 5_000);
        let chain = FixedChain::with_records(vec![confirmed(alive), spent(consumed)]);
        let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
        let store = LocalReservations::new();
        let clock = FixedClock::new(NOW);
        let reservations = CoinReservations::new(&store, &clock);

        clock.set(NOW + DEFAULT_RESERVATION_TTL_SECS * 10);
        let error = ops
            .build_transfer(&chain, &hot(), &request, &reservations)
            .expect_err("the only coin big enough is already spent on chain");

        assert!(
            matches!(
                error,
                TransferError::InsufficientFunds { available: 100, .. }
            ),
            "a spent coin is not spendable whatever the reservation table says: {error:?}"
        );
    }

    /// **FAIL DIRECTION: an unreadable store REFUSES the build.**
    ///
    /// The wallet can plainly afford this transfer, so nothing but the unreadable guard can be
    /// causing the refusal. Proceeding here would be the double-select the reservation exists to
    /// prevent, reached by ignoring the guard rather than by not having one.
    #[test]
    fn an_unreadable_reservation_store_refuses_rather_than_proceeds() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
        let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
        let store = UnreadableReservations;
        let clock = FixedClock::new(NOW);
        let reservations = CoinReservations::new(&store, &clock);

        let error = ops
            .build_transfer(&chain, &hot(), &request, &reservations)
            .expect_err("a guard that cannot be read must stop the build, not be skipped");

        assert!(
            matches!(error, TransferError::ReservationUnusable(_)),
            "and it must say so as itself, not as a shortfall or a chain fault: {error:?}"
        );
    }

    /// **A store whose READ fails must refuse too, even though its WRITE would have worked.**
    ///
    /// Separate from the test above, and the separation is the point: that store fails on both
    /// methods, so it stays green even if an unreadable `held` is silently treated as "nothing is
    /// reserved" — the write path catches it instead. Reverting the `held` guard alone leaves that
    /// test passing, which is how a fail-open would have shipped.
    ///
    /// Here the write path CANNOT catch it. The only thing standing between this build and a
    /// selection made over an unknown reservation set is the refusal on the read.
    #[test]
    fn a_store_that_cannot_be_read_refuses_even_when_it_could_be_written() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
        let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
        let store = UnreadableButWritable(LocalReservations::new());
        let clock = FixedClock::new(NOW);
        let reservations = CoinReservations::new(&store, &clock);

        // The control: this store DOES grant reservations, so a refusal here cannot be blamed on a
        // store that simply never works.
        store
            .reserve_all(&[Bytes32::new([0xAB; 32])], NOW, NOW + 300)
            .expect("the write path of this double genuinely works");

        let error = ops
            .build_transfer(&chain, &hot(), &request, &reservations)
            .expect_err("what is already reserved is UNKNOWN, so selection cannot be trusted");

        assert!(
            matches!(error, TransferError::ReservationUnusable(_)),
            "{error:?}"
        );
    }

    /// **An unreadable CLOCK refuses too.** A "now" that cannot be read makes every expiry
    /// judgement meaningless, and a guard whose expiry cannot be judged is not a guard.
    ///
    /// Worth its own test because the failure is silent in the dangerous direction: a clock read as
    /// a huge number expires every reservation at once, turning the mechanism off while every call
    /// still reports success.
    #[test]
    fn an_unreadable_clock_refuses_rather_than_guesses() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
        let store = LocalReservations::new();
        let reservations = CoinReservations::new(&store, &UnreadableClock);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900),
                &reservations,
            )
            .expect_err("an unreadable clock cannot judge expiry, so it must stop the build");

        assert!(
            matches!(error, TransferError::ReservationUnusable(_)),
            "{error:?}"
        );
    }

    /// **A fee bump must not be blocked by its own transfer's reservation.**
    ///
    /// `build_transfer_replacing` deliberately re-spends the coins the original plan holds. Taking a
    /// second reservation over them would conflict with itself and refuse the very operation it
    /// exists to enable — the wallet locking itself out of its own funds, which is a worse failure
    /// than the double-select it was added to prevent.
    #[test]
    fn a_fee_bump_is_not_blocked_by_its_own_reservation() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let store = LocalReservations::new();
        let reservations = store.reservations();

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 500)
                    .with_fee(10),
                &reservations,
            )
            .expect("the first build is funded");
        assert!(plan.reservation().is_some(), "the control: it did reserve");
        let pending = plan.pushed_at(PEAK);

        let bumped = ops
            .build_transfer_replacing(&chain, &hot(), &pending, 50)
            .expect("a fee bump re-spends coins its own transfer already reserved");

        assert_eq!(
            bumped.source_coin_ids(),
            plan.source_coin_ids(),
            "a replacement re-spends the SAME inputs, which is what makes it a replacement"
        );
        assert!(
            bumped.reservation().is_none(),
            "and it takes no second hold on them"
        );
    }

    /// One coin that covers the whole amount is preferred, and it is the SMALLEST such coin — the
    /// wallet's larger coins stay intact and the change stays small.
    ///
    /// The amounts distinguish this from three other rules: `5_000` comes FIRST in source order (so a
    /// first-fit takes it), it is the LARGEST (so a largest-first takes it), and `20 + 50 + 900` would
    /// be a smallest-first sweep.
    #[test]
    fn selection_prefers_the_smallest_single_coin_that_covers_the_transfer() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[5_000, 900, 50, 20]);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900),
                &free(),
            )
            .expect("the 900 coin covers it exactly");

        assert_eq!(inputs_of(&plan), vec![900]);
        assert_eq!(plan.change_mojos(), 0);
    }

    /// **A stranger must not be able to make a wallet unspendable by dusting it.** Anyone can send
    /// dust to any address, so a selection that swept the smallest coins first would consume the
    /// whole cap on 1-mojo coins and refuse a transfer the wallet plainly affords.
    ///
    /// The fixture is exactly that attack: many more dust coins than the cap, plus one coin that
    /// covers the amount on its own. The right answer uses ONE input.
    #[test]
    fn a_wallet_dusted_beyond_the_cap_can_still_spend_its_large_coin() {
        let ops = ops();
        let mut amounts = vec![1u64; MAX_TRANSFER_INPUT_COINS * 10];
        amounts.push(1_000_000);
        let chain = FixedChain::holding(ops.puzzle_hash(), &amounts);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000),
                &free(),
            )
            .expect("one coin covers this transfer, however much dust surrounds it");
        assert_eq!(inputs_of(&plan), vec![1_000_000]);
    }

    /// When NO single coin covers the amount, selection takes the FEWEST coins that do — largest
    /// first. Here 600 + 500 reaches 1_000 in two inputs, where a smallest-first accumulation would
    /// have needed all four.
    #[test]
    fn a_transfer_no_single_coin_covers_uses_the_fewest_inputs() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[600, 500, 400, 300]);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("1_800 mojos cover 1_000");

        assert_eq!(inputs_of(&plan), vec![500, 600]);
        assert_eq!(plan.change_mojos(), 100);
    }

    /// `available` is the wallet's WHOLE spendable balance, not however far a selection loop got
    /// before giving up. A wallet holding several coins that together fall short must be told the
    /// true total, or it will look emptier than it is.
    #[test]
    fn insufficient_funds_reports_the_whole_spendable_balance() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[100, 200, 300, 400]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 5_000),
                &free(),
            )
            .expect_err("1_000 mojos cannot cover 5_000");
        assert!(
            matches!(
                error,
                TransferError::InsufficientFunds {
                    required: 5_000,
                    available: 1_000
                }
            ),
            "{error}"
        );
    }

    /// An already-spent coin cannot fund a spend, so it is neither selected NOR counted toward
    /// `available`. Reporting it would tell the user they hold money they cannot move.
    ///
    /// The fixture holds 20_005 mojos in total and only 5 of them spendable, so an implementation
    /// that filtered selection but not the reported balance fails on the number.
    #[test]
    fn spent_coins_are_neither_selected_nor_counted_as_available() {
        let ops = ops();
        let ph = ops.puzzle_hash();
        let chain = FixedChain::with_records(vec![
            spent(Coin::new(Bytes32::new([2; 32]), ph, 20_000)),
            confirmed(Coin::new(Bytes32::new([3; 32]), ph, 5)),
        ]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect_err("only 5 mojos are actually spendable");
        assert!(
            matches!(
                error,
                TransferError::InsufficientFunds {
                    required: 1_000,
                    available: 5
                }
            ),
            "{error}"
        );
    }

    /// **When an unjudgeable coin is what makes the wallet fall short, the shortfall is reported as
    /// UNJUDGEABLE rather than as a balance.**
    ///
    /// `dig-chainsource-interface` defines `confirmed_height: None` as "not known BY THIS SOURCE",
    /// never "does not exist". A source that does not populate the field would otherwise have every
    /// coin excluded and the user told `InsufficientFunds { available: 0 }` while holding a funded
    /// wallet — a false statement about their money, produced by a source limitation.
    ///
    /// The escalation is deliberately conditional on the OUTCOME, not on the record: excluding an
    /// unjudgeable coin from a wallet that can still afford the transfer changes nothing a user needs
    /// to hear, and refusing there would hand a hostile source a way to block every send. The
    /// companion test `an_unjudgeable_coin_does_not_block_a_wallet_that_can_afford_the_transfer`
    /// pins that side.
    ///
    /// Here the unknown-height coin holds the wallet's only 10_000 mojos against a 1_000 request, so
    /// excluding it is exactly what causes the shortfall — and pinning the variant is what separates
    /// "we could not judge this" from "you do not have it".
    #[test]
    fn a_shortfall_caused_by_an_unjudgeable_coin_is_reported_as_unjudgeable() {
        let ops = ops();
        let ph = ops.puzzle_hash();
        let unknown = Coin::new(Bytes32::new([1; 32]), ph, 10_000);
        let chain = FixedChain::with_records(vec![unconfirmed(unknown)]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect_err("a source that cannot report a height cannot judge the balance");
        assert!(
            matches!(
                error,
                TransferError::SpendabilityUnknown { coin_id } if coin_id == unknown.coin_id()
            ),
            "{error}"
        );
    }

    /// The truthful control: the SAME coin with a height DOES fund the transfer. Without it the
    /// refusal above would be equally satisfied by a builder that refuses everything.
    #[test]
    fn the_same_coin_with_a_confirmation_height_funds_the_transfer() {
        let ops = ops();
        let ph = ops.puzzle_hash();
        let chain = FixedChain::with_records(vec![confirmed(Coin::new(
            Bytes32::new([1; 32]),
            ph,
            10_000,
        ))]);

        assert!(ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .is_ok());
    }

    /// **A coin at a FOREIGN puzzle hash is EXCLUDED, and the wallet still spends what it owns.**
    ///
    /// XCH-only is enforced rather than assumed: a CAT coin lives at
    /// `CatArgs::curry_tree_hash(asset_id, p2)`, so a chain source that indexes by HINT rather than by
    /// puzzle hash returns coins this wallet can discover but not unlock, and counting their base
    /// units as mojos would overstate the balance and build a spend that cannot be validated.
    ///
    /// # Excluding, not refusing, is the security-relevant half
    ///
    /// A hint is memo data anybody may write. One dust coin hinted at this wallet is enough to put an
    /// attacker-chosen record in front of selection on every call, forever — so a builder that
    /// REFUSED on such a record would hand any stranger a permanent, unauthenticated kill switch on
    /// the wallet's ability to send. The exclusion achieves the whole goal: never selected, never
    /// counted, and the genuine coins still spend.
    ///
    /// The fixture is that attack. The genuine 5_000 coin alone covers the 1_000 request, and the
    /// foreign coin is ten times larger — so the build must succeed, spend only the genuine coin, and
    /// the foreign value must appear nowhere.
    #[test]
    fn a_coin_at_a_foreign_puzzle_hash_is_excluded_without_blocking_the_transfer() {
        let ops = ops();
        let ph = ops.puzzle_hash();
        let genuine = Coin::new(Bytes32::new([2; 32]), ph, 5_000);
        let foreign = Coin::new(Bytes32::new([1; 32]), Bytes32::new([0xCA; 32]), 10_000);
        let chain = FixedChain::with_records(Vec::new())
            .answering_puzzle_hash_query_with(vec![confirmed(genuine), confirmed(foreign)]);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("a foreign coin must not stop a wallet spending the coins it owns");

        assert_eq!(
            plan.source_coin_ids(),
            &[genuine.coin_id()],
            "only the wallet's own coin may be spent"
        );
        assert_eq!(
            plan.change_mojos(),
            4_000,
            "the change proves the spend came from the 5_000 coin, not the 10_000 foreign one"
        );
    }

    /// **The foreign coin is not COUNTED either, which is the other half of the rule.**
    ///
    /// Excluding a coin from selection while still adding it to `available` would report a balance
    /// the wallet cannot spend — and here the foreign coin alone would cover the request, so an
    /// implementation that counted it would report a shortfall of the wrong size rather than of the
    /// right one. The genuine holdings total 5 mojos and the request is 1_000, so the number in the
    /// error is the whole assertion.
    #[test]
    fn a_foreign_coin_is_not_counted_toward_the_spendable_balance() {
        let ops = ops();
        let ph = ops.puzzle_hash();
        let chain = FixedChain::with_records(Vec::new()).answering_puzzle_hash_query_with(vec![
            confirmed(Coin::new(Bytes32::new([2; 32]), ph, 5)),
            confirmed(Coin::new(
                Bytes32::new([1; 32]),
                Bytes32::new([0xCA; 32]),
                10_000,
            )),
        ]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect_err("5 spendable mojos cannot cover 1_000");
        assert!(
            matches!(
                error,
                TransferError::InsufficientFunds {
                    required: 1_000,
                    available: 5
                }
            ),
            "available must exclude the foreign coin's 10_000: {error}"
        );
    }

    /// **THE DENIAL-OF-SERVICE REGRESSION.** A stranger dusting this wallet through a hint-indexing
    /// source must not be able to stop it sending — not once, and not on any later call.
    ///
    /// The fixture is the cheapest version of the attack: many dust coins the attacker controls, at
    /// puzzle hashes this wallet does not own, alongside one genuine coin that covers the transfer
    /// several times over. Every send must still succeed.
    ///
    /// This is written as a LOOP because the defect it guards against was permanent: the refusal
    /// fired on every call for as long as the source kept returning the record, which it would.
    #[test]
    fn a_stranger_cannot_brick_the_wallet_by_dusting_it_with_foreign_coins() {
        let ops = ops();
        let ph = ops.puzzle_hash();
        let mut records = vec![confirmed(Coin::new(Bytes32::new([9; 32]), ph, 1_000_000))];
        for seed in 0..32u8 {
            records.push(confirmed(Coin::new(
                Bytes32::new([seed; 32]),
                Bytes32::new([seed ^ 0xFF; 32]),
                1,
            )));
        }
        let chain = FixedChain::with_records(Vec::new()).answering_puzzle_hash_query_with(records);

        for attempt in 0..3 {
            let plan = ops
                .build_transfer(
                    &chain,
                    &hot(),
                    &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                    &free(),
                )
                .unwrap_or_else(|e| {
                    panic!("attempt {attempt}: dust from a stranger must never block a send: {e}")
                });
            assert_eq!(plan.source_coin_ids().len(), 1);
        }
    }

    /// The same shape for an UNJUDGEABLE coin: it is excluded, and a wallet that can afford the
    /// transfer without it still sends. Escalating here would be the same remote kill switch, since
    /// a source that omits `confirmed_height` does so for records an attacker can also create.
    #[test]
    fn an_unjudgeable_coin_does_not_block_a_wallet_that_can_afford_the_transfer() {
        let ops = ops();
        let ph = ops.puzzle_hash();
        let genuine = Coin::new(Bytes32::new([2; 32]), ph, 5_000);
        let chain = FixedChain::with_records(vec![
            confirmed(genuine),
            unconfirmed(Coin::new(Bytes32::new([1; 32]), ph, 10_000)),
        ]);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("a coin of unknown status must not block an affordable transfer");
        assert_eq!(plan.source_coin_ids(), &[genuine.coin_id()]);
    }

    /// **A SPENT coin with an unknown height is skipped, not escalated.**
    ///
    /// The two checks used to run in the wrong order, so a record the source reported as SPENT — and
    /// which the very next line would have discarded — decided the whole build because its height was
    /// unknown. `include_spent: false` is a request, not a guarantee, and this file already treats a
    /// non-conforming answer as expected rather than exceptional.
    ///
    /// The fixture makes the ordering the only variable: the wallet's genuine coin cannot cover the
    /// request, so the transfer fails either way — what differs is WHICH error, and only the correct
    /// ordering reports the honest shortfall instead of blaming an unjudgeable coin that was never
    /// spendable.
    #[test]
    fn a_spent_coin_with_an_unknown_height_is_skipped_rather_than_escalated() {
        let ops = ops();
        let ph = ops.puzzle_hash();
        let chain = FixedChain::with_records(vec![
            confirmed(Coin::new(Bytes32::new([2; 32]), ph, 5)),
            record(
                Coin::new(Bytes32::new([1; 32]), ph, 10_000),
                None,
                Some(PEAK),
            ),
        ]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect_err("5 spendable mojos cannot cover 1_000");
        assert!(
            matches!(
                error,
                TransferError::InsufficientFunds {
                    required: 1_000,
                    available: 5
                }
            ),
            "a spent coin is not spendable whatever its height, so it must not become the story: \
             {error}"
        );
    }

    // ----------------------------------------------- by-name confirmation of every input (#2556)

    /// Two coins, both honestly spendable by both indexes, FUND the transfer.
    ///
    /// The positive control the refusal tests below need. A guard that refused every multi-input
    /// build — or one wired to a source that can never agree with itself — would satisfy all three
    /// refusals and none of them would notice.
    #[test]
    fn two_inputs_confirmed_by_name_fund_the_transfer() {
        let ops = ops();
        let wallet = ops.wallet_key();
        let listing = vec![
            confirmed(Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 600)),
            confirmed(Coin::new(Bytes32::new([2; 32]), wallet.puzzle_hash(), 600)),
        ];
        let chain = FixedChain::with_records(listing.clone())
            .answering_puzzle_hash_query_with(listing.clone())
            .answering_by_name_with(listing);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("both inputs agree, so the transfer must build");

        assert_eq!(
            inputs_of(&plan),
            vec![600, 600],
            "both coins must be spent when both indexes call them spendable"
        );
    }

    /// ONE stale input out of two fails the WHOLE attempt — never a build on the survivor.
    ///
    /// Only the SECOND coin is varied; the first stays honestly spendable. That is what makes this
    /// test see the guard: with every coin hostile, a builder that silently dropped the stale input
    /// and rebuilt on what was left would also refuse (nothing would remain to build from), and the
    /// all-or-nothing property would be invisible. Here the survivor alone still covers the
    /// transfer, so a builder that proceeded on it would return `Ok` and be caught.
    #[test]
    fn one_input_spent_by_name_fails_the_whole_attempt() {
        let ops = ops();
        let wallet = ops.wallet_key();
        let honest = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 900);
        let stale = Coin::new(Bytes32::new([2; 32]), wallet.puzzle_hash(), 900);
        let listing = vec![confirmed(honest), confirmed(stale)];
        let chain = FixedChain::with_records(listing.clone())
            .answering_puzzle_hash_query_with(listing)
            // The listing offered both; by name the network has already consumed one of them.
            .answering_by_name_with(vec![confirmed(honest), spent(stale)]);

        // 1_500 needs both coins, so selection takes both and the stale one is genuinely in the plan.
        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_500),
                &free(),
            )
            .expect_err("a selected input the network calls spent must abandon the attempt");

        assert!(
            matches!(error, TransferError::ChainUnreachable(_)),
            "a coin whose two answers disagree is UNKNOWN, not a shortfall and not a refusal: \
             {error}"
        );
    }

    /// A coin the listing offered and the by-name read cannot find is UNKNOWN, not absent.
    #[test]
    fn an_input_the_by_name_read_cannot_find_fails_the_attempt() {
        let ops = ops();
        let wallet = ops.wallet_key();
        let honest = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 900);
        let vanished = Coin::new(Bytes32::new([2; 32]), wallet.puzzle_hash(), 900);
        let listing = vec![confirmed(honest), confirmed(vanished)];
        let chain = FixedChain::with_records(listing.clone())
            .answering_puzzle_hash_query_with(listing)
            .answering_by_name_with(vec![confirmed(honest)]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_500),
                &free(),
            )
            .expect_err("an input the by-name read denies must abandon the attempt");

        assert!(
            matches!(error, TransferError::ChainUnreachable(_)),
            "two answers that cannot both be true make the coin's state unknown: {error}"
        );
    }

    /// The SINGLE-coin fast path is confirmed too.
    ///
    /// Selection has two exits — the smallest single covering coin, and largest-first accumulation —
    /// and they are different `return`s. A guard placed on only one of them would leave the most
    /// common transfer in the ecosystem, a one-coin send, entirely unguarded.
    #[test]
    fn the_single_covering_coin_is_confirmed_by_name_too() {
        let ops = ops();
        let wallet = ops.wallet_key();
        let only = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 5_000);
        let listing = vec![confirmed(only)];
        let chain = FixedChain::with_records(listing.clone())
            .answering_puzzle_hash_query_with(listing)
            .answering_by_name_with(vec![spent(only)]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect_err("the single-coin path must confirm its coin by name as well");

        assert!(
            matches!(error, TransferError::ChainUnreachable(_)),
            "a single stale input is the exact shape that produced a mainnet DOUBLE_SPEND: {error}"
        );
    }

    // -------------------------------------------------- duplicate records in the listing (#2494)

    /// A coin the source reports TWICE is worth its amount ONCE, in the balance the user is told.
    ///
    /// The request is set above the coin's real value and below its doubled value, which is the only
    /// band where the two behaviours differ: a builder that counted the duplicate would find itself
    /// "funded" and go on to build. The assertion is on `available`, because that number is the one
    /// a surface renders as the wallet's balance.
    #[test]
    fn a_duplicated_coin_is_counted_once_in_the_balance() {
        let ops = ops();
        let wallet = ops.wallet_key();
        let coin = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 1_000);
        let doubled = vec![confirmed(coin), confirmed(coin)];
        let chain = FixedChain::with_records(doubled.clone())
            .answering_puzzle_hash_query_with(doubled.clone())
            .answering_by_name_with(doubled);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_500),
                &free(),
            )
            .expect_err("one 1000-mojo coin cannot fund 1500, however many times it is listed");

        assert!(
            matches!(
                error,
                TransferError::InsufficientFunds {
                    required: 1_500,
                    available: 1_000
                }
            ),
            "the duplicate must not inflate the balance the user is shown: {error}"
        );
    }

    /// A duplicated coin is never SELECTED twice.
    ///
    /// The fixture makes the duplicate genuinely reachable, which the balance test above cannot
    /// show: `1_200` is covered by no single coin, so accumulation runs largest-first, and a list
    /// still holding both copies of the `1_000` reaches the target from that coin alone — twice —
    /// without ever looking at the `400`. The honest answer spends `1_000 + 400`, so the two
    /// behaviours differ in the bundle rather than only in a refusal.
    ///
    /// Two `CoinSpend`s of one coin is a self-double-spend consensus rejects AFTER the push, which
    /// is the most expensive place to learn it.
    #[test]
    fn a_duplicated_coin_is_never_selected_twice() {
        let ops = ops();
        let wallet = ops.wallet_key();
        let big = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 1_000);
        let small = Coin::new(Bytes32::new([2; 32]), wallet.puzzle_hash(), 400);
        let listing = vec![confirmed(big), confirmed(big), confirmed(small)];
        let chain = FixedChain::with_records(listing.clone())
            .answering_puzzle_hash_query_with(listing.clone())
            .answering_by_name_with(listing);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_200),
                &free(),
            )
            .expect("1000 + 400 covers 1200, so the transfer must build");

        let spent_ids: Vec<Bytes32> = plan
            .coin_spends()
            .iter()
            .map(|spend| spend.coin.coin_id())
            .collect();
        let unique: HashSet<Bytes32> = spent_ids.iter().copied().collect();
        assert_eq!(
            spent_ids.len(),
            unique.len(),
            "no coin may appear twice among the bundle's inputs: {spent_ids:?}"
        );
        assert_eq!(
            inputs_of(&plan),
            vec![400, 1_000],
            "the second copy of the 1000 coin is not a second coin, so the 400 must be reached for"
        );
    }

    // ------------------------------------------------------------------- change + outputs

    /// The recipient is paid EXACTLY, the change is EXACTLY the remainder, and the change returns to
    /// this wallet. Asserted over the coins the puzzles actually create, so a mis-computed change
    /// cannot hide behind a correct-looking field.
    #[test]
    fn the_recipient_is_paid_exactly_and_the_change_is_exact_and_wallet_owned() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000)
                    .with_fee(1_000),
                &free(),
            )
            .expect("builds");

        let created = created_coins(plan.coin_spends());
        assert_eq!(created.len(), 2, "a payment and a change coin: {created:?}");

        let payment = created
            .iter()
            .find(|coin| coin.puzzle_hash == RECIPIENT)
            .expect("the recipient is paid");
        assert_eq!(payment.amount, 600_000);
        assert_eq!(payment.coin_id(), plan.payment_coin_id());

        let change = created
            .iter()
            .find(|coin| coin.puzzle_hash == ops.puzzle_hash())
            .expect("the change returns to THIS wallet");
        assert_eq!(
            change.amount,
            1_000_000 - 600_000 - 1_000,
            "unspent input value silently becomes fee, so an inexact change donates the difference"
        );
        assert_eq!(plan.change_mojos(), change.amount);
    }

    /// **The payment coin carries the recipient as a hint.** The hint is how the recipient's wallet
    /// discovers the payment by hinted scan. A payment that confirms and conserves value but hints to
    /// a different puzzle hash (e.g. the sender's own) may never surface in the recipient's wallet.
    ///
    /// This test asserts EQUALITY with the recipient — not merely that a memo is present — so it goes
    /// red if the hint names any other puzzle hash.
    #[test]
    fn the_payment_coin_is_hinted_to_the_recipient() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000)
                    .with_fee(1_000),
                &free(),
            )
            .expect("builds");

        // Re-run the puzzles with a shared allocator so the NodePtrs in the memos are still
        // readable when we decode them.
        let mut allocator = Allocator::new();
        let mut payment_hint: Option<Bytes32> = None;
        'outer: for spend in plan.coin_spends() {
            let puzzle =
                node_from_bytes(&mut allocator, &spend.puzzle_reveal).expect("valid puzzle");
            let solution =
                node_from_bytes(&mut allocator, &spend.solution).expect("valid solution");
            let output = run_puzzle(&mut allocator, puzzle, solution).expect("runs");
            for condition in
                Vec::<Condition>::from_clvm(&allocator, output).expect("valid conditions")
            {
                if let Condition::CreateCoin(create) = condition {
                    if create.puzzle_hash == RECIPIENT {
                        let Memos::Some(ptr) = create.memos else {
                            panic!("the payment coin must carry a hint memo");
                        };
                        let hints: Vec<Bytes32> =
                            Vec::from_clvm(&allocator, ptr).expect("hint is a list of Bytes32");
                        assert_eq!(hints.len(), 1, "exactly one hint expected");
                        payment_hint = Some(hints[0]);
                        break 'outer;
                    }
                }
            }
        }
        assert_eq!(
            payment_hint.expect("a CREATE_COIN for RECIPIENT must exist"),
            RECIPIENT,
            "the hint must name the recipient, not the sender or any other puzzle hash"
        );
    }

    /// Inputs consumed to the mojo create NO change coin.
    #[test]
    fn an_exactly_covering_selection_creates_no_change_coin() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[601_000]);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000)
                    .with_fee(1_000),
                &free(),
            )
            .expect("builds");

        assert_eq!(plan.change_mojos(), 0);
        let created = created_coins(plan.coin_spends());
        assert_eq!(created.len(), 1, "only the payment coin: {created:?}");
        assert_eq!(created[0].puzzle_hash, RECIPIENT);
    }

    /// **A 1-mojo remainder is emitted as a change coin, not silently donated to the farmer.**
    ///
    /// This pins the `change > 0` boundary at its tightest value. The wallet holds exactly
    /// `amount + fee + 1` mojos, so the change is 1 — the smallest non-zero value. A condition
    /// `change > 1` would pass `plan.change_mojos() == 1` but omit the coin, making the plan
    /// describe an output the bundle does not contain; the second assertion catches that.
    #[test]
    fn a_one_mojo_remainder_is_emitted_as_a_change_coin() {
        let ops = ops();
        // amount=600_000, fee=1_000, input=601_001 → change=1
        let chain = FixedChain::holding(ops.puzzle_hash(), &[601_001]);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000)
                    .with_fee(1_000),
                &free(),
            )
            .expect("builds");

        assert_eq!(plan.change_mojos(), 1, "plan must report a 1-mojo change");

        let created = created_coins(plan.coin_spends());
        let change_coin = created
            .iter()
            .find(|coin| coin.puzzle_hash == ops.puzzle_hash())
            .expect("a change coin of 1 mojo must be created");
        assert_eq!(
            change_coin.amount, 1,
            "the change coin must carry the 1-mojo remainder, not lose it as fee"
        );
    }

    /// **The duplicate-coin-id class, closed at its root.** Two created coins sharing
    /// `(parent, puzzle_hash, amount)` are one coin id twice, which consensus rejects
    /// deterministically — and since re-selection picks the same coins every time, the wallet would
    /// wedge on that amount forever.
    ///
    /// The lead's two outputs can only collide when the payment goes to this wallet's OWN puzzle hash
    /// with an amount equal to the change, so the fixture asks for exactly that: half a coin, paid to
    /// itself. It is refused by name before any spend is built.
    #[test]
    fn a_payment_to_this_wallets_own_address_is_refused_by_name() {
        let ops = ops();
        let own = ops.puzzle_hash();
        let chain = FixedChain::holding(own, &[1_000]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(own), 500),
                &free(),
            )
            .expect_err("a self-payment moves nothing and would duplicate a coin id");
        assert!(matches!(error, TransferError::SelfPayment), "{error}");
    }

    /// The structural consequence: across a sweep of amounts — including the one that would collide
    /// if the recipient were this wallet — no bundle this builder emits creates two coins with the
    /// same id.
    #[test]
    fn no_bundle_ever_creates_two_coins_with_the_same_id() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);

        for amount in [1u64, 2, 499, 500, 501, 999] {
            let plan = ops
                .build_transfer(
                    &chain,
                    &hot(),
                    &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), amount),
                    &free(),
                )
                .expect("builds");
            let created = created_coins(plan.coin_spends());
            let ids: HashSet<Bytes32> = created.iter().map(Coin::coin_id).collect();
            assert_eq!(
                ids.len(),
                created.len(),
                "amount {amount} produced a duplicate coin id"
            );
        }
    }

    // ------------------------------------------------------------------- the input cap

    /// A wallet whose value is spread over more coins than the cap gets its OWN error, naming the
    /// cap — never "insufficient funds", which would be false about a wallet that holds the money.
    #[test]
    fn needing_more_coins_than_the_cap_is_its_own_error() {
        let ops = ops();
        let coins = vec![100u64; MAX_TRANSFER_INPUT_COINS + 1];
        let chain = FixedChain::holding(ops.puzzle_hash(), &coins);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(
                    PayableDestination::from_derived(RECIPIENT),
                    100 * coins.len() as u64,
                ),
                &free(),
            )
            .expect_err("one coin over the cap");
        assert!(
            matches!(
                error,
                TransferError::TooManyInputCoins { needed, cap }
                    if needed == MAX_TRANSFER_INPUT_COINS + 1 && cap == MAX_TRANSFER_INPUT_COINS
            ),
            "{error}"
        );
    }

    /// The bound from the other side: a transfer needing EXACTLY the cap's worth of coins is built. A
    /// bound tested only from above can only confirm itself.
    #[test]
    fn a_transfer_needing_exactly_the_cap_is_still_built() {
        let ops = ops();
        let coins = vec![100u64; MAX_TRANSFER_INPUT_COINS];
        let chain = FixedChain::holding(ops.puzzle_hash(), &coins);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(
                    PayableDestination::from_derived(RECIPIENT),
                    100 * coins.len() as u64,
                ),
                &free(),
            )
            .expect("exactly the cap is allowed");
        assert_eq!(plan.coin_spends().len(), MAX_TRANSFER_INPUT_COINS);
    }

    // ------------------------------------------------------------------- refusals

    /// A vault-tier profile cannot send, and says so in its own words — never as a shortfall or a
    /// build failure, which would send the user looking for a problem that does not exist.
    #[test]
    fn a_vault_profile_is_refused_with_its_own_error() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);

        let error = ops
            .build_transfer(
                &chain,
                &CustodyPolicy::Vault(Vault::default()),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000),
                &free(),
            )
            .expect_err("a vault outflow may only pay this profile's own hot wallet");
        assert!(
            matches!(error, TransferError::VaultTransferUnsupported),
            "{error}"
        );
        assert!(
            error.to_string().contains("vault"),
            "the sentence must name the tier: {error}"
        );
    }

    /// The control: the SAME wallet, SAME coins, SAME request under the HOT tier is built. So the
    /// refusal above is about the tier and not about the fixture.
    #[test]
    fn the_same_request_under_the_hot_tier_is_built() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
        assert!(ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000),
                &free(),
            )
            .is_ok());
    }

    /// A fee the inputs cannot cover is a shortfall of `amount + fee`, not of `amount`. The fixture
    /// covers the amount EXACTLY, so an implementation that forgot to count the fee would build a
    /// bundle paying the farmer out of the recipient's money.
    #[test]
    fn a_fee_the_inputs_cannot_cover_is_refused() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
                    .with_fee(1),
                &free(),
            )
            .expect_err("1_000 mojos cannot pay 1_000 plus a fee");
        assert!(
            matches!(
                error,
                TransferError::InsufficientFunds {
                    required: 1_001,
                    available: 1_000
                }
            ),
            "{error}"
        );
    }

    /// The control: the same amount with NO fee is built, so the refusal above is about the fee.
    #[test]
    fn the_same_amount_with_no_fee_is_built() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        assert!(ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .is_ok());
    }

    #[test]
    fn a_zero_amount_transfer_is_refused() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 0),
                &free(),
            )
            .expect_err("a transfer moves a positive amount");
        assert!(matches!(error, TransferError::ZeroAmount), "{error}");
    }

    /// An amount plus fee that overflows `u64` is named as such rather than wrapping into a small
    /// number a wallet could accidentally cover.
    #[test]
    fn an_amount_plus_fee_that_overflows_is_refused() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), u64::MAX)
                    .with_fee(1),
                &free(),
            )
            .expect_err("u64::MAX + 1 is not a spendable total");
        assert!(
            matches!(error, TransferError::AmountOverflow { .. }),
            "{error}"
        );
    }

    /// An unreachable chain is UNKNOWN, not a shortfall: a builder that said "insufficient funds"
    /// when it simply could not read the wallet would tell the user something false about their
    /// balance.
    #[test]
    fn an_unreachable_chain_is_not_reported_as_a_shortfall() {
        let ops = ops();
        let error = ops
            .build_transfer(
                &FixedChain::offline(),
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect_err("an unanswerable chain is not an empty wallet");
        assert!(
            matches!(error, TransferError::ChainUnreachable(_)),
            "{error}"
        );
    }

    /// An undecodable recipient address is refused before any chain read.
    #[test]
    fn an_undecodable_recipient_address_is_refused() {
        let error = TransferRequest::to_address("not-an-address", 1_000)
            .expect_err("a malformed address has no destination");
        assert!(
            matches!(error, TransferError::InvalidRecipient { .. }),
            "{error}"
        );
    }

    /// **A well-formed address with the WRONG prefix is refused, and that refusal is what stops the
    /// funds being burned.**
    ///
    /// `Address::decode` checks bech32m and a 32-byte payload — never the human-readable part — so an
    /// NFT launcher id, a DID, a CAT asset id and a testnet address all decode happily and yield a
    /// puzzle hash. Paying one conserves value, signs, confirms, and reports `Confirmed` truthfully,
    /// because a coin really does exist at a puzzle hash nobody can spend.
    ///
    /// The fixture is the SAME 32 bytes under each prefix, so the only difference between these cases
    /// and the accepted one below is the prefix itself. `not-an-address` is deliberately not used
    /// here: it fails bech32 PARSING, which proves the error is reachable for garbage and says
    /// nothing about a well-formed wrong destination.
    #[test]
    fn a_well_formed_address_with_a_non_xch_prefix_is_refused_by_prefix() {
        for prefix in ["nft", "txch", "did:chia", "cat", "totally-bogus"] {
            let encoded = Address::new(RECIPIENT, prefix.to_string())
                .encode()
                .expect("a 32-byte payload encodes under any prefix");

            // The control for the whole test: this string really does decode, so the refusal below is
            // the prefix rule and not a parse failure.
            assert_eq!(
                Address::decode(&encoded).expect("it decodes").puzzle_hash,
                RECIPIENT,
                "{prefix} must be a decodable address, or this case proves nothing"
            );

            let error = TransferRequest::to_address(&encoded, 1_000)
                .expect_err("paying the puzzle hash inside a non-payment address burns the funds");
            match &error {
                TransferError::InvalidRecipient { reason, .. } => assert!(
                    reason.contains(prefix),
                    "the refusal must name the prefix the user actually pasted: {reason}"
                ),
                other => panic!("{prefix}: {other}"),
            }
        }
    }

    /// A balance that cannot be summed is REFUSED rather than clamped. A saturating total pinned at
    /// `u64::MAX` would pass the shortfall check and surface later as arithmetic, turning "this
    /// cannot be judged" into "proceed and be refused".
    #[test]
    fn a_spendable_balance_that_overflows_u64_is_refused_rather_than_clamped() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[u64::MAX, u64::MAX]);

        let error = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect_err("a balance past u64 cannot be judged");
        assert!(
            matches!(error, TransferError::BalanceUnjudgeable),
            "{error}"
        );
    }

    /// **The unsafe destination is no longer expressible from a raw `Bytes32` by accident.**
    ///
    /// `TransferRequest::new` takes a [`PayableDestination`], so every destination has passed through
    /// one of exactly two constructors: one that CHECKS a string, and one whose name says the caller
    /// is vouching for a hash the code derived. The old `to_puzzle_hash(Bytes32, u64)` allowed a
    /// decoded `nft1…` payload straight in with nothing said about it, and it was as prominent in the
    /// public API as the safe path.
    ///
    /// This test pins the SHAPE rather than a behaviour: the two routes must agree on the puzzle hash
    /// when the address really is an `xch` one, which is what makes `from_derived` a genuine
    /// alternative rather than a different meaning.
    #[test]
    fn the_checked_and_vouched_destinations_agree_on_a_real_xch_address() {
        let address = Address::new(RECIPIENT, MAINNET_ADDRESS_PREFIX.to_string())
            .encode()
            .expect("encodes");

        let checked = PayableDestination::from_address(&address).expect("an xch address");
        let vouched = PayableDestination::from_derived(RECIPIENT);

        assert_eq!(checked, vouched);
        assert_eq!(checked.puzzle_hash(), RECIPIENT);
    }

    /// The prefix rule lives in [`PayableDestination::from_address`] now, so it is enforced for every
    /// caller of every constructor that takes a string — including `TransferRequest::to_address`,
    /// which delegates to it.
    ///
    /// The fixture is the SAME 32 bytes under each prefix, so the only difference between these cases
    /// and an accepted one is the prefix itself.
    #[test]
    fn a_payable_destination_refuses_every_non_xch_prefix() {
        for prefix in ["nft", "txch", "did:chia", "cat", "totally-bogus"] {
            let encoded = Address::new(RECIPIENT, prefix.to_string())
                .encode()
                .expect("a 32-byte payload encodes under any prefix");

            // The control for the whole test: this string really does decode, so the refusal below
            // is the prefix rule and not a parse failure.
            assert_eq!(
                Address::decode(&encoded).expect("it decodes").puzzle_hash,
                RECIPIENT,
                "{prefix} must be a decodable address, or this case proves nothing"
            );

            let error = PayableDestination::from_address(&encoded)
                .expect_err("paying the puzzle hash inside a non-payment address burns the funds");
            match &error {
                TransferError::InvalidRecipient { reason, .. } => assert!(
                    reason.contains(prefix),
                    "the refusal must name the prefix the user actually pasted: {reason}"
                ),
                other => panic!("{prefix}: {other}"),
            }

            // And the same refusal reaches the request constructor that delegates to it.
            assert!(TransferRequest::to_address(&encoded, 1_000).is_err());
        }
    }

    /// A well-formed address decodes to the puzzle hash it names, so the two constructors agree.
    #[test]
    fn a_valid_address_decodes_to_its_puzzle_hash() {
        let address = Address::new(RECIPIENT, "xch".to_string()).encode().unwrap();
        let request = TransferRequest::to_address(&address, 42).expect("a valid address");
        assert_eq!(request.recipient(), RECIPIENT);
        assert_eq!(request.amount_mojos(), 42);
        assert_eq!(request.fee_mojos(), 0);
    }

    /// **The address this crate DISPLAYS is an address this crate will PAY.**
    ///
    /// The display path ([`WalletKey::address`]) and the payment path
    /// ([`TransferRequest::to_address`]) are written in different modules and were, until they were
    /// converged on [`MAINNET_ADDRESS_PREFIX`], two independent `"xch"` literals. A divergence
    /// between them is SILENT — nothing fails, the wallet simply hands out a receive address the
    /// builder refuses, or worse renders a destination under a prefix it did not pay.
    ///
    /// This test cannot be satisfied by either module alone: it takes a string produced by the
    /// display path and requires the payment path to accept it AND to recover the very puzzle hash it
    /// was encoded from. Re-inline a different literal at either site and it fails.
    #[test]
    fn the_wallets_displayed_address_is_one_the_transfer_builder_will_pay() {
        let ops = ops();
        let displayed = ops
            .wallet_key()
            .address()
            .expect("the wallet renders its own receive address");

        let request = TransferRequest::to_address(&displayed, 42)
            .expect("an address this crate displays must be one it will pay");
        assert_eq!(
            request.recipient(),
            ops.puzzle_hash(),
            "the payment path must recover the puzzle hash the display path encoded"
        );
        assert!(
            displayed.starts_with(MAINNET_ADDRESS_PREFIX),
            "the displayed address must bear the one prefix: {displayed}"
        );
    }

    /// `pushed_now` anchors to the chain's OWN peak, so the backdating check cannot be defeated by a
    /// caller that supplies a convenient number.
    #[test]
    fn pushed_now_anchors_to_the_chains_own_peak() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]).at_peak(PEAK + 42);
        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600),
                &free(),
            )
            .expect("builds");

        let pending = plan.pushed_now(&chain).expect("the chain reports a peak");
        assert_eq!(pending.pushed_at_height(), PEAK + 42);
    }

    /// A source that cannot report a peak makes `pushed_now` REFUSE rather than anchor at zero. An
    /// anchor of `0` would make the backdating check vacuous, and a caller acting on it would accept
    /// any invented confirmation height forever.
    #[test]
    fn pushed_now_refuses_when_the_chain_has_no_peak() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let plan = ops
            .build_transfer(
                &source,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600),
                &free(),
            )
            .expect("builds");

        let error = plan
            .pushed_now(&source.without_peak())
            .expect_err("no peak, no anchor");
        assert!(
            matches!(error, TransferError::ChainUnreachable(_)),
            "{error}"
        );
    }

    // ------------------------------------------------------------------- fee-bump replacement

    /// **THE DEFECT, pinned so it cannot silently return.** Two plans built by the ORDINARY
    /// `build_transfer` path at fees that straddle a coin boundary select DIFFERENT leads.
    ///
    /// Selection takes the smallest coin covering `amount + fee`. With coins of 1_000 and 1_200 and
    /// an amount of 1_000, a fee of 0 needs 1_000 and takes the 1_000 coin; a fee of 100 needs 1_100
    /// and takes the 1_200 coin. The two bundles spend DISJOINT inputs, so they do not conflict,
    /// both are valid, and both can be included — paying the recipient twice.
    ///
    /// This test asserts the hazard rather than the fix. If selection is ever changed so that a fee
    /// bump keeps the lead, this goes red and the reason `build_transfer_replacing` exists should be
    /// re-examined; until then it is the standing proof that a naive retry is unsafe.
    #[test]
    fn a_naive_fee_bump_can_select_a_different_lead_and_pay_twice() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000, 1_200]);

        let original = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("builds");
        let naive_retry = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
                    .with_fee(100),
                &free(),
            )
            .expect("builds");

        assert_ne!(
            original.source_coin_ids(),
            naive_retry.source_coin_ids(),
            "the fee bump must cross a coin boundary, or this fixture proves nothing"
        );
        assert_ne!(
            original.payment_coin_id(),
            naive_retry.payment_coin_id(),
            "disjoint inputs mean two payment coins, so BOTH bundles can confirm"
        );
    }

    /// The identity contract: a replacement keeps the SAME inputs, lead, recipient, amount and
    /// payment coin id, and takes the extra fee out of the CHANGE rather than out of the amount.
    ///
    /// # What this test does NOT prove, stated because it looks like it does
    ///
    /// It does not distinguish reuse from re-selection, and no fixture in which the replacement
    /// SUCCEEDS can. Selection takes the smallest single coin covering `required`, else accumulates
    /// largest-first; both rules are monotone in `required`, so if the original inputs still cover
    /// the raised total, re-running selection picks exactly the same coins. Replacing the reuse with
    /// a fresh `select_input_coins` call leaves this test green — verified by mutation.
    ///
    /// The reuse earns its keep in the REFUSAL cases, which is also where the money is lost:
    /// `a_replacement_the_reused_inputs_cannot_cover_is_refused_by_its_own_name` and
    /// `a_replacement_over_a_spent_input_is_refused_by_name` both go red under that mutation, because
    /// re-selection quietly reaches for a DIFFERENT coin and builds a bundle that does not conflict
    /// with the original. Those two are the falsifiers; this one pins the contract they operate under.
    #[test]
    fn a_replacement_reuses_the_exact_inputs_and_keeps_the_payment_coin_id() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_500, 5_000]);

        let original = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("builds");
        let pending = original.pushed_at(PEAK);

        let replacement = ops
            .build_transfer_replacing(&chain, &hot(), &pending, 100)
            .expect("a higher fee over the same inputs");

        assert_eq!(
            replacement.source_coin_ids(),
            original.source_coin_ids(),
            "a replacement must re-spend exactly the coins the original spends"
        );
        assert_eq!(
            replacement.payment_coin_id(),
            original.payment_coin_id(),
            "the same lead yields the same payment coin, so the pending record still applies"
        );
        assert_eq!(replacement.fee_mojos(), 100);
        assert_eq!(replacement.amount_mojos(), original.amount_mojos());
        assert_eq!(replacement.recipient(), original.recipient());
        assert_eq!(
            replacement.change_mojos(),
            original.change_mojos() - 100,
            "the extra fee comes out of the change, never out of the recipient"
        );
    }

    /// **A replacement whose reused inputs cannot cover the higher fee is refused BY ITS OWN NAME.**
    ///
    /// The original here consumes its lead exactly (1_000 mojos, no fee, no change), so there is no
    /// headroom to raise a fee from. Reaching for the wallet's other coin is exactly what a
    /// replacement must NOT do — that is the naive rebuild that pays twice — so refusing is correct.
    ///
    /// What this test pins is the VARIANT. `InsufficientFunds` would be wrong here even though the
    /// sentence fits: its `available` is the wallet's spendable balance everywhere else it is
    /// produced, so a surface rendering this one the same way would report a balance the user does
    /// not have.
    #[test]
    fn a_replacement_the_reused_inputs_cannot_cover_is_refused_by_its_own_name() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000, 1_200]);
        let pending = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);

        let error = ops
            .build_transfer_replacing(&chain, &hot(), &pending, 100)
            .expect_err("an exactly-consumed input has no headroom for a bigger fee");
        assert!(
            matches!(
                error,
                TransferError::ReplacementInputsInsufficient {
                    required: 1_100,
                    reused_total: 1_000
                }
            ),
            "{error}"
        );
    }

    /// **The assertion the variant exists for: a WEALTHY wallet is refused with the REUSED INPUTS'
    /// total, and nothing in the error resembles its balance.**
    ///
    /// The wallet holds 10_000_000 mojos across other coins while the transfer's own input is 1_000.
    /// Under the old shape this refused with `InsufficientFunds { available: 1_000 }`, and a surface
    /// rendering `available` as a balance — the natural rendering, and the one #2404 is about to
    /// write — would have told a user holding 10 million that they had a thousand. That is the UI lie
    /// this variant exists to make unexpressible.
    ///
    /// The fixture is what makes it able to fail: the gap between `reused_total` and the wallet
    /// balance is four orders of magnitude, so a regression that reported either the balance or a
    /// wallet-wide shortfall cannot coincide with the expected numbers. A fixture where the wallet
    /// held only the input coin would have passed under both shapes and proven nothing.
    ///
    /// It does NOT prove how a consumer renders the field — no test here can. It proves the error
    /// carries no number a consumer could mistake for a balance.
    #[test]
    fn a_wealthy_wallet_is_refused_with_the_reused_total_not_its_balance() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000, 10_000_000]);
        let pending = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);
        assert_eq!(
            pending.source_coin_ids().len(),
            1,
            "the transfer must rest on the SMALL coin, or the gap this test needs does not exist"
        );

        let error = ops
            .build_transfer_replacing(&chain, &hot(), &pending, 500)
            .expect_err("the 1_000 input cannot cover 1_500");
        match error {
            TransferError::ReplacementInputsInsufficient {
                required,
                reused_total,
            } => {
                assert_eq!(required, 1_500);
                assert_eq!(
                    reused_total, 1_000,
                    "the figure must be the reused inputs' total, never the 10_001_000 balance"
                );
            }
            other => panic!("a replacement shortfall must not borrow the balance variant: {other}"),
        }
    }

    /// The positive control: a SMALLER raise, over the same wallet and the same input, succeeds. So
    /// the refusals above are about the headroom and not about the method refusing every replacement.
    #[test]
    fn a_replacement_the_reused_inputs_can_cover_is_built() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_500, 10_000_000]);
        let pending = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);

        let replacement = ops
            .build_transfer_replacing(&chain, &hot(), &pending, 400)
            .expect("1_400 fits inside the 1_500 input");
        assert_eq!(replacement.fee_mojos(), 400);
        assert_eq!(replacement.change_mojos(), 100);
    }

    /// A replacement that does not OUTBID the original is refused by name. It could not displace the
    /// bundle already in the mempool, so building one produces a second bundle that simply loses.
    #[test]
    fn a_replacement_fee_that_does_not_outbid_is_refused_by_name() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
        let pending = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
                    .with_fee(50),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);

        for proposed in [0u64, 49, 50] {
            let error = ops
                .build_transfer_replacing(&chain, &hot(), &pending, proposed)
                .expect_err("a replacement must outbid the transfer it replaces");
            assert!(
                matches!(
                    error,
                    TransferError::ReplacementFeeNotHigher { current: 50, proposed: p } if p == proposed
                ),
                "{error}"
            );
        }
    }

    /// The bound from the other side: ONE mojo above the original fee IS accepted. Without this the
    /// refusal above would be satisfied by a method that refuses every replacement.
    #[test]
    fn a_replacement_fee_one_mojo_higher_is_accepted() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
        let pending = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
                    .with_fee(50),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);

        let replacement = ops
            .build_transfer_replacing(&chain, &hot(), &pending, 51)
            .expect("one mojo more is a higher bid");
        assert_eq!(replacement.fee_mojos(), 51);
    }

    /// **A source coin that is no longer spendable is refused BY NAME, never as a shortfall.**
    ///
    /// The likeliest cause is the one that matters: the ORIGINAL transfer has already been included,
    /// so its inputs are spent. A replacement built anyway would be a SECOND payment, and reporting
    /// this as `InsufficientFunds` would send the user to top up their wallet and try again — which
    /// is precisely the action that pays twice.
    #[test]
    fn a_replacement_over_a_spent_input_is_refused_by_name() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
        let original = ops
            .build_transfer(
                &source,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
                    .with_fee(50),
                &free(),
            )
            .expect("builds");
        let pending = original.pushed_at(PEAK);
        let input = source.records[0].coin;

        let consumed = FixedChain::with_records(vec![spent(input)]);
        let error = ops
            .build_transfer_replacing(&consumed, &hot(), &pending, 100)
            .expect_err("a spent input cannot be re-spent");
        assert!(
            matches!(
                error,
                TransferError::SourcesNoLongerSpendable { coin_id } if coin_id == input.coin_id()
            ),
            "{error}"
        );

        // The same refusal when the coin has vanished from the source entirely.
        let absent = FixedChain::with_records(Vec::new());
        let error = ops
            .build_transfer_replacing(&absent, &hot(), &pending, 100)
            .expect_err("an input the source no longer reports cannot be re-spent");
        assert!(
            matches!(
                error,
                TransferError::SourcesNoLongerSpendable { coin_id } if coin_id == input.coin_id()
            ),
            "{error}"
        );
    }

    /// The truthful control: the SAME pending transfer over the SAME still-spendable input builds.
    /// Without it the refusals above could be a method that never succeeds.
    #[test]
    fn a_replacement_over_a_still_spendable_input_builds() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
        let pending = ops
            .build_transfer(
                &source,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
                    .with_fee(50),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);

        assert!(ops
            .build_transfer_replacing(&source, &hot(), &pending, 100)
            .is_ok());
    }

    /// A chain source that answers a re-read with a record for a DIFFERENT coin is a contract
    /// violation, and the replacement fails CLOSED rather than rebuilding around a coin the wallet
    /// never selected. `SourcesNoLongerSpendable` would be the wrong answer: nothing is known to be
    /// unspendable, the source simply did not answer the question asked.
    #[test]
    fn a_replacement_refuses_a_record_for_a_different_coin() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
        let pending = ops
            .build_transfer(
                &source,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
                    .with_fee(50),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);

        let impostor = confirmed(Coin::new(
            Bytes32::new([0xAB; 32]),
            ops.puzzle_hash(),
            10_000,
        ));
        let chain = FixedChain::with_records(Vec::new()).answering_every_query_with(impostor);

        let error = ops
            .build_transfer_replacing(&chain, &hot(), &pending, 100)
            .expect_err("a record about another coin answers nothing about this input");
        assert!(
            matches!(error, TransferError::ChainUnreachable(_)),
            "{error}"
        );
    }

    /// A vault-tier profile cannot replace a transfer either — the tier rule is about the profile,
    /// not about which builder was called.
    #[test]
    fn a_vault_profile_cannot_build_a_replacement() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
        let pending = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
                    .with_fee(50),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);

        let error = ops
            .build_transfer_replacing(
                &chain,
                &CustodyPolicy::Vault(Vault::default()),
                &pending,
                100,
            )
            .expect_err("a vault profile cannot pay a third party by any route");
        assert!(
            matches!(error, TransferError::VaultTransferUnsupported),
            "{error}"
        );
    }

    /// **No refusal from the replacement path may advise building another transfer.**
    ///
    /// `SPEC.md` §6.7.6 makes rebuilding a retry through `build_transfer` FORBIDDEN, because
    /// selection can pick a different lead and the two bundles then pay the recipient twice —
    /// `a_naive_fee_bumped_rebuild_pays_the_recipient_twice` proves exactly that against consensus.
    /// These are `Display` strings that surfaces render verbatim, so a sentence telling the user to
    /// send again is not a documentation slip; it is an instruction to perform the double payment.
    ///
    /// The test walks EVERY refusal reachable from `build_transfer_replacing`, driving each from a
    /// real fixture rather than constructing the variants by hand, so a variant added later without a
    /// case here shows up as an unhandled match arm rather than silently escaping the rule.
    ///
    /// It asserts the invariant, not the prose: the phrasing may change freely, and only advice to
    /// build or send another transfer is forbidden.
    #[test]
    fn no_replacement_refusal_ever_advises_building_another_transfer() {
        let ops = ops();
        let wallet = FixedChain::holding(ops.puzzle_hash(), &[1_000, 10_000_000]);
        let exact = ops
            .build_transfer(
                &wallet,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);
        let funded = ops
            .build_transfer(
                &wallet,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 500)
                    .with_fee(50),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);

        let consumed = FixedChain::with_records(vec![spent(wallet.records[0].coin)]);
        let refusals = [
            // The fee cannot be covered by the transfer's own inputs.
            ops.build_transfer_replacing(&wallet, &hot(), &exact, 100),
            // The proposed fee does not outbid the original.
            ops.build_transfer_replacing(&wallet, &hot(), &funded, 50),
            // An input is gone — usually because the original already confirmed.
            ops.build_transfer_replacing(&consumed, &hot(), &exact, 100),
            // The profile's tier cannot pay a third party at all.
            ops.build_transfer_replacing(
                &wallet,
                &CustodyPolicy::Vault(Vault::default()),
                &exact,
                100,
            ),
        ];

        for refusal in refusals {
            let error = refusal.expect_err("each fixture must actually refuse");
            let rendered = error.to_string().to_lowercase();
            if let Some(forbidden) = forbidden_advice_in(&rendered) {
                panic!(
                    "{error:?} tells the user to {forbidden:?}, which is the action that pays the \
                     recipient twice: {rendered}"
                );
            }
        }
    }

    /// Instructions to rebuild a transfer, in the forms a refusal might plausibly use.
    ///
    /// Shared by the invariant and its control so the control proves the list that is ACTUALLY
    /// applied. A control checking its own private copy would stay green through a typo in the real
    /// one, which is the failure it exists to prevent.
    const REBUILD_INSTRUCTIONS: [&str; 6] = [
        "build another transfer",
        "build a new transfer",
        "send another transfer",
        "send it again",
        "try again",
        "a fresh transfer",
    ];

    /// The first rebuild instruction `rendered` contains, if any.
    fn forbidden_advice_in(rendered: &str) -> Option<&'static str> {
        REBUILD_INSTRUCTIONS
            .into_iter()
            .find(|forbidden| rendered.contains(forbidden))
    }

    /// The control: the check can actually SEE forbidden advice, through the same function and the
    /// same list the invariant uses. Without it, a needle list that matched nothing would leave the
    /// invariant asserting nothing at all — the vacuous-green shape this whole suite exists to avoid.
    #[test]
    fn the_forbidden_advice_check_detects_every_instruction_it_screens_for() {
        for instruction in REBUILD_INSTRUCTIONS {
            let rendered = format!("this transfer cannot be sped up; {instruction} instead");
            assert_eq!(
                forbidden_advice_in(&rendered),
                Some(instruction),
                "the screen must catch {instruction:?}, or the invariant is measuring nothing"
            );
        }
    }

    /// And it does not fire on the sentence the crate actually renders — a warning ABOUT a second
    /// payment is not an instruction to make one. This is what separates the invariant from a rule
    /// that would ban discussing the hazard at all.
    #[test]
    fn the_forbidden_advice_check_does_not_fire_on_a_warning() {
        let rendered = TransferError::ReplacementInputsInsufficient {
            required: 1_100,
            reused_total: 1_000,
        }
        .to_string()
        .to_lowercase();

        assert_eq!(forbidden_advice_in(&rendered), None, "{rendered}");
        assert!(
            rendered.contains("wait for it to confirm"),
            "the refusal must still give the one always-correct instruction: {rendered}"
        );
    }

    /// `max_replacement_fee_mojos` is the ceiling a bump control must respect, and it equals the
    /// original fee plus its change — the headroom a replacement can draw on without reaching for a
    /// coin it must not touch.
    ///
    /// The two cases are the ones a surface has to tell apart: a transfer with change can be bumped,
    /// and one whose inputs were consumed exactly cannot be bumped AT ALL, because a replacement must
    /// also strictly outbid the original.
    #[test]
    fn the_replacement_fee_ceiling_is_the_original_fee_plus_its_change() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_500, 10_000_000]);

        let with_change = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
                    .with_fee(50),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);
        assert_eq!(with_change.change_mojos(), 450);
        assert_eq!(with_change.input_total_mojos(), 1_500);
        assert_eq!(with_change.max_replacement_fee_mojos(), 500);

        // The ceiling is real: exactly it is accepted, one over is refused.
        assert!(ops
            .build_transfer_replacing(&chain, &hot(), &with_change, 500)
            .is_ok());
        assert!(matches!(
            ops.build_transfer_replacing(&chain, &hot(), &with_change, 501),
            Err(TransferError::ReplacementInputsInsufficient { .. })
        ));

        let exact = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_500),
                &free(),
            )
            .expect("builds")
            .pushed_at(PEAK);
        assert_eq!(exact.change_mojos(), 0);
        assert_eq!(
            exact.max_replacement_fee_mojos(),
            exact.fee_mojos(),
            "a ceiling equal to the current fee means no bump is possible, and the control must be \
             disabled rather than merely capped"
        );
    }

    // ------------------------------------------------------------------- the input binding

    /// Every secondary input asserts the announcement the LEAD makes, so a secondary — which creates
    /// nothing — cannot be included without it. Unbound, a node could take the secondaries alone and
    /// burn the user's coins into fees. (The simulator suite proves consensus actually refuses the
    /// orphaned half; this pins the shape.)
    #[test]
    fn every_secondary_input_is_bound_to_the_lead() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[100, 200, 300]);

        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 550),
                &free(),
            )
            .expect("builds");

        let conditions = conditions_of(plan.coin_spends());
        let lead_id = conditions
            .iter()
            .find_map(|(coin_id, condition)| {
                matches!(condition, Condition::CreateCoinAnnouncement(_)).then_some(*coin_id)
            })
            .expect("the lead announces");
        let expected = chia_wallet_sdk::types::announcement_id(lead_id, INPUT_BINDING_MESSAGE);

        let asserting: Vec<Bytes32> = conditions
            .iter()
            .filter_map(|(coin_id, condition)| match condition {
                Condition::AssertCoinAnnouncement(assertion) => {
                    assert_eq!(assertion.announcement_id, expected);
                    Some(*coin_id)
                }
                _ => None,
            })
            .collect();
        assert_eq!(
            asserting.len(),
            2,
            "both secondary inputs must be bound to the lead"
        );
        assert!(!asserting.contains(&lead_id));
    }

    /// **The binding, proven against the real consensus validator.**
    ///
    /// The orphaned subset is RE-SIGNED here, correctly, for exactly the spends it contains, so that
    /// a signature failure cannot be what the refusal is measuring. The full bundle is then submitted
    /// to the SAME simulator and accepted, which proves the refusal was about the missing lead and
    /// not about the coins, the keys or the fixture.
    ///
    /// # What the re-signing does and does not buy, measured rather than assumed
    ///
    /// Replacing the correct signature with `Signature::default()` leaves this test PASSING, still
    /// reporting `AssertCoinAnnouncementFailed` — so THIS validator evaluates the announcement before
    /// it verifies signatures, and the signature is not the confounder it would be under a validator
    /// that checked in the other order. The re-signing is kept because it costs little and makes the
    /// test independent of that ordering; the claim that it is REQUIRED here would be false.
    ///
    /// What the test genuinely proves is the binding itself. Removing the
    /// `assert_coin_announcement` and re-running leaves the orphaned subset ACCEPTED — three
    /// 200_000-mojo coins spent at height 1 with no output at all, which is the user's money burned
    /// into fees. That is the outcome this condition exists to make impossible.
    ///
    /// This lives in the crate rather than the integration suite because re-signing needs the wallet's
    /// secret key, which dig-account deliberately does not expose.
    #[test]
    fn an_orphaned_secondary_input_is_refused_by_consensus_even_when_correctly_signed() {
        use chia_bls::Signature;
        use chia_consensus::validation_error::ErrorCode;
        use chia_sdk_test::{Simulator, SimulatorError};
        use chia_wallet_sdk::prelude::TESTNET11_CONSTANTS;
        use chia_wallet_sdk::signer::{AggSigConstants, RequiredSignature};

        /// Sign exactly `coin_spends` with `wallet`'s key, under the simulator's consensus constants.
        fn sign(wallet: &WalletKey, coin_spends: &[CoinSpend]) -> Signature {
            let constants = AggSigConstants::from(&*TESTNET11_CONSTANTS);
            let mut allocator = Allocator::new();
            let required =
                RequiredSignature::from_coin_spends(&mut allocator, coin_spends, &constants)
                    .expect("required signatures");
            let mut aggregate = Signature::default();
            for requirement in required {
                let RequiredSignature::Bls(bls) = requirement else {
                    panic!("a standard-layer send never requires a secp signature");
                };
                aggregate += &chia_bls::sign(wallet.secret_key(), bls.message());
            }
            aggregate
        }

        let ops = ops();
        let wallet = ops.wallet_key();
        let mut sim = Simulator::new();
        let coins: Vec<Coin> = (0..4)
            .map(|_| sim.new_coin(wallet.puzzle_hash(), 200_000))
            .collect();
        sim.create_block();

        let chain =
            FixedChain::with_records(coins.iter().copied().map(confirmed).collect::<Vec<_>>());
        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 700_000)
                    .with_fee(1_000),
                &free(),
            )
            .expect("builds");
        assert!(
            plan.coin_spends().len() > 1,
            "the fixture must actually exercise secondary inputs"
        );

        // The lead is the spend whose child is the payment coin; the rest are the orphans.
        let lead_id = plan
            .coin_spends()
            .iter()
            .find(|spend| {
                Coin::new(spend.coin.coin_id(), RECIPIENT, 700_000).coin_id()
                    == plan.payment_coin_id()
            })
            .map(|spend| spend.coin.coin_id())
            .expect("one spend creates the payment coin");
        let orphans: Vec<CoinSpend> = plan
            .coin_spends()
            .iter()
            .filter(|spend| spend.coin.coin_id() != lead_id)
            .cloned()
            .collect();
        assert!(!orphans.is_empty());

        let orphan_signature = sign(&wallet, &orphans);
        let refused = sim.new_transaction(chia_protocol::SpendBundle::new(
            orphans.clone(),
            orphan_signature.clone(),
        ));
        // Pinned to the SPECIFIC consensus refusal. A bare `is_err()` here would be satisfied by a
        // signature failure, a malformed bundle, or a simulator misconfiguration — every one of which
        // would leave the binding untested while the test stayed green, since the validator never
        // reaches the announcement check once it has already rejected the bundle for another reason.
        // `AssertCoinAnnouncementFailed` is the announcement the lead never made, and nothing else.
        match refused {
            Err(SimulatorError::Validation(ErrorCode::AssertCoinAnnouncementFailed)) => {}
            other => panic!(
                "the orphaned subset must be refused for the UNSATISFIED ANNOUNCEMENT specifically,                  not for some other reason that would hide a missing binding: {other:?}"
            ),
        }

        // The control: the SAME coins, the SAME keys, the SAME simulator — with the lead restored.
        let whole = plan.coin_spends().to_vec();
        let signature = sign(&wallet, &whole);
        sim.new_transaction(chia_protocol::SpendBundle::new(whole, signature))
            .expect(
                "the complete bundle is valid, so the refusal above was about the missing lead",
            );
    }

    /// A single-input transfer carries no binding at all: there is no secondary to orphan, and an
    /// unnecessary announcement is block space the user pays for.
    #[test]
    fn a_single_input_transfer_carries_no_binding() {
        let ops = ops();
        let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let plan = ops
            .build_transfer(
                &chain,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 500),
                &free(),
            )
            .expect("builds");

        assert!(conditions_of(plan.coin_spends())
            .iter()
            .all(|(_, condition)| !matches!(condition, Condition::CreateCoinAnnouncement(_))));
    }

    // ------------------------------------------------------------------- status

    /// A pending transfer plus the payment coin the chain would show once it is included.
    fn pending_and_payment(ops: &WalletOps, source: &FixedChain) -> (PendingTransfer, Coin) {
        let plan = ops
            .build_transfer(
                source,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600),
                &free(),
            )
            .expect("builds");
        // Derived from the coins the puzzles CREATE rather than from an assumed spend ordering, so
        // the fixture cannot drift away from the bundle it is meant to describe.
        let payment = created_coins(plan.coin_spends())
            .into_iter()
            .find(|coin| coin.puzzle_hash == RECIPIENT)
            .expect("the recipient is paid");
        assert_eq!(payment.coin_id(), plan.payment_coin_id());
        (plan.pushed_at(PEAK), payment)
    }

    /// A payment coin buried past [`MIN_CONFIRMATION_DEPTH`] is settled, and the evidence names the
    /// recipient and the exact amount.
    #[test]
    fn a_buried_payment_coin_is_confirmed_evidence() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);

        let chain = FixedChain::with_records(vec![record(payment, Some(PEAK + 1), None)])
            .at_peak(PEAK + MIN_CONFIRMATION_DEPTH);

        let settled = transfer_status(&pending, &chain)
            .expect("readable")
            .confirmed()
            .cloned()
            .expect("a buried payment is settled");
        assert_eq!(settled.recipient(), RECIPIENT);
        assert_eq!(settled.amount_mojos(), 600);
        assert_eq!(settled.confirmed_height(), PEAK + 1);
        assert_eq!(settled.payment_coin_id(), payment.coin_id());
    }

    /// **A record for a DIFFERENT coin is not evidence, however impeccable it otherwise looks.**
    ///
    /// The id check is the ENTIRE argument that a confirmation is about the right recipient and the
    /// right amount: a coin id commits to `(parent, puzzle_hash, amount)`, so a matching id is the
    /// proof and nothing separate is compared. `ConfirmedTransfer` also recommends an AGGREGATING
    /// chain source, i.e. several nodes stitched together — a deployment where a mis-addressed or
    /// mis-attributed record is a realistic answer rather than a hypothetical one.
    ///
    /// The fixture differs from a genuine confirmation in the id and in NOTHING ELSE: the same
    /// recipient, the same amount, a post-push height, and a burial well past
    /// [`MIN_CONFIRMATION_DEPTH`]. Only the parent differs, which is what makes the id differ. Every
    /// other condition `from_confirmed` tests is satisfied, so the id check is the only thing that
    /// can refuse it.
    ///
    /// The assertion is `Awaiting` SPECIFICALLY, not `confirmed().is_none()`. A source that answered
    /// nothing at all would satisfy the weaker form equally, and that is a different property — it
    /// would leave the guard exactly as unfalsifiable as before.
    #[test]
    fn a_confirmed_record_for_a_different_coin_is_not_this_transfers_evidence() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);

        let impostor = Coin::new(
            Bytes32::new([0xAB; 32]),
            payment.puzzle_hash,
            payment.amount,
        );
        assert_ne!(
            impostor.coin_id(),
            pending.payment_coin_id(),
            "the impostor must be a different coin, or this test proves nothing"
        );

        let chain = FixedChain::with_records(Vec::new())
            .at_peak(PEAK + MIN_CONFIRMATION_DEPTH)
            .answering_every_query_with(record(impostor, Some(PEAK + 1), None));

        assert_eq!(
            transfer_status(&pending, &chain).expect("readable"),
            TransferStatus::Awaiting {
                blocks_since_push: MIN_CONFIRMATION_DEPTH
            },
            "a record about some other coin says nothing about this payment"
        );
    }

    /// The truthful control for the impostor test: the SAME double, the SAME heights and the SAME
    /// peak, answering with the CORRECT coin, reaches `Confirmed`. Without it the refusal above would
    /// be equally satisfied by a fixture that can never confirm anything.
    #[test]
    fn the_same_double_answering_with_the_correct_coin_is_confirmed() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);

        let chain = FixedChain::with_records(Vec::new())
            .at_peak(PEAK + MIN_CONFIRMATION_DEPTH)
            .answering_every_query_with(record(payment, Some(PEAK + 1), None));

        let settled = transfer_status(&pending, &chain)
            .expect("readable")
            .confirmed()
            .cloned()
            .expect("the correct coin, buried, IS the payment");
        assert_eq!(settled.payment_coin_id(), pending.payment_coin_id());
        assert_eq!(settled.recipient(), RECIPIENT);
        assert_eq!(settled.amount_mojos(), 600);
    }

    /// The same payment coin confirmed only ONE block deep is NOT settled: a shallow confirmation is
    /// reversible, and reporting it would let a reorg silently unmake a payment the user was told
    /// about.
    #[test]
    fn a_shallow_confirmation_is_not_yet_settled() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);

        let chain =
            FixedChain::with_records(vec![record(payment, Some(PEAK + 1), None)]).at_peak(PEAK + 1);

        assert!(matches!(
            transfer_status(&pending, &chain).expect("readable"),
            TransferStatus::Awaiting { .. }
        ));
    }

    /// **A payment coin the node has SEEN but no block has confirmed is not evidence.** A
    /// mempool-aware node (and the coinset API, whose `created_height` is `None` for a mempool coin)
    /// answers with the real coin and no height — so the record exists, names the right recipient and
    /// the right amount, and still proves nothing.
    ///
    /// The peak here is deep enough that a burial check alone would pass, which is the point: this
    /// pins the CONFIRMED-HEIGHT requirement specifically, and it is the only test that can see an
    /// implementation which substitutes the push height for a missing one.
    #[test]
    fn a_payment_coin_observed_without_a_confirmed_height_is_not_evidence() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);

        let chain = FixedChain::with_records(vec![record(payment, None, None)])
            .at_peak(PEAK + MIN_CONFIRMATION_DEPTH * 10);

        assert!(
            matches!(
                transfer_status(&pending, &chain).expect("readable"),
                TransferStatus::Awaiting { .. }
            ),
            "a mempool observation is not a confirmation, however deep the chain has since gone"
        );
    }

    /// A confirmation BACK-DATED to before the push is not evidence: a transfer cannot appear in a
    /// block that already existed when it was broadcast.
    #[test]
    fn a_confirmation_predating_the_push_is_not_evidence() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);

        let chain = FixedChain::with_records(vec![record(payment, Some(PEAK - 1), None)])
            .at_peak(PEAK + MIN_CONFIRMATION_DEPTH);

        assert!(matches!(
            transfer_status(&pending, &chain).expect("readable"),
            TransferStatus::Awaiting { .. }
        ));
    }

    /// **A payment coin confirmed at height 0 (genesis) is not evidence, even for a transfer pushed
    /// at height 0.** No real coin is created in the genesis block, so `confirmed_height: Some(0)` is
    /// the chain reporting a height that cannot be genuine — it must not be accepted as confirmation.
    ///
    /// This test makes the `confirmed_height == 0` guard in `from_confirmed` falsifiable. The
    /// positive control uses the SAME `pushed_at_height: 0` pending transfer and the SAME fixture
    /// chain, but reports the coin at height 1, which IS accepted once the chain is sufficiently
    /// deep. Without it the refusal above would be equally satisfied by a fixture that can never
    /// confirm anything.
    #[test]
    fn a_payment_coin_confirmed_at_genesis_height_is_not_evidence() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);

        // Build a real plan and derive the payment coin from what the bundle actually creates,
        // then construct a PendingTransfer that was pushed at height 0.
        let plan = ops
            .build_transfer(
                &source,
                &hot(),
                &TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600),
                &free(),
            )
            .expect("builds");
        let payment = created_coins(plan.coin_spends())
            .into_iter()
            .find(|coin| coin.puzzle_hash == RECIPIENT)
            .expect("recipient is paid");
        let pending = plan.pushed_at(0);

        // The chain reports the payment coin at confirmed_height == 0: genesis.
        // This must be refused regardless of burial depth.
        let chain = FixedChain::with_records(vec![record(payment, Some(0), None)])
            .at_peak(MIN_CONFIRMATION_DEPTH);
        assert!(
            matches!(
                transfer_status(&pending, &chain).expect("readable"),
                TransferStatus::Awaiting { .. }
            ),
            "a genesis-height confirmation must not be accepted"
        );

        // Positive control: same pending transfer (pushed_at 0), same fixture, same burial depth —
        // but the coin is now at height 1.  This reaches `Confirmed` and proves the fixture is
        // otherwise capable of confirming; the refusal above is entirely about the zero height.
        let chain_at_one = FixedChain::with_records(vec![record(payment, Some(1), None)])
            .at_peak(MIN_CONFIRMATION_DEPTH);
        assert!(
            matches!(
                transfer_status(&pending, &chain_at_one).expect("readable"),
                TransferStatus::Confirmed(_)
            ),
            "the same fixture at height 1 must confirm"
        );
    }

    /// **The burial bound, pinned from BOTH sides.** `MIN_CONFIRMATION_DEPTH` blocks of burial is
    /// enough and one fewer is not, so what the test measures is the constant's value rather than
    /// whichever side happens to be checked. A bound tested from one side can only confirm itself.
    #[test]
    fn the_confirmation_depth_bound_holds_from_both_sides() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);
        let confirmed_at = PEAK + 1;

        // At the bound: the confirming block is the first of the depth, so a peak of
        // `confirmed + DEPTH - 1` is exactly DEPTH blocks deep.
        let at_bound = FixedChain::with_records(vec![record(payment, Some(confirmed_at), None)])
            .at_peak(confirmed_at + MIN_CONFIRMATION_DEPTH - 1);
        assert!(
            transfer_status(&pending, &at_bound)
                .expect("readable")
                .confirmed()
                .is_some(),
            "exactly MIN_CONFIRMATION_DEPTH blocks of burial must be enough"
        );

        // One block shallower must NOT be.
        let one_under = FixedChain::with_records(vec![record(payment, Some(confirmed_at), None)])
            .at_peak(confirmed_at + MIN_CONFIRMATION_DEPTH - 2);
        assert!(
            matches!(
                transfer_status(&pending, &one_under).expect("readable"),
                TransferStatus::Awaiting { .. }
            ),
            "one block short of the bound must not be treated as settled"
        );
    }

    /// **A confirmation at EXACTLY the pre-push peak is legitimate, and this pins that it is
    /// accepted.** It reads like an impossibility — a block that already existed cannot contain a
    /// bundle pushed afterwards — and that reading is wrong here, which is why it is written down.
    ///
    /// `ChainSource::peak_height` reports the height the NEXT block will take, not the height of the
    /// last one that exists: the simulator this crate tests against stamps a new coin with
    /// `created_height = height()` and only then increments. So the first block that can contain a
    /// bundle carries exactly the height read before the push, and tightening the comparison to `<=`
    /// would reject every genuinely first-block confirmation — turning a settled payment into one
    /// that never confirms, and inviting a caller to send it twice.
    #[test]
    fn a_confirmation_at_exactly_the_pre_push_peak_is_accepted() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);
        assert_eq!(
            pending.pushed_at_height(),
            PEAK,
            "the fixture pins the boundary"
        );

        let chain = FixedChain::with_records(vec![record(payment, Some(PEAK), None)])
            .at_peak(PEAK + MIN_CONFIRMATION_DEPTH);

        assert!(
            transfer_status(&pending, &chain)
                .expect("readable")
                .confirmed()
                .is_some(),
            "the first block that can contain the bundle carries the pre-push peak's own height"
        );
    }

    /// A source coin spent with NO payment coin means a different spend consumed it, so this bundle
    /// can never be included. That is a proof of death, not an eternal wait.
    #[test]
    fn a_source_coin_spent_elsewhere_is_a_failure_not_a_wait() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, _) = pending_and_payment(&ops, &source);

        let chain = FixedChain::with_records(vec![spent(source.records[0].coin)]);

        assert!(
            matches!(
                transfer_status(&pending, &chain).expect("readable"),
                TransferStatus::Failed { .. }
            ),
            "a consumed input can never confirm"
        );
    }

    /// **A SHALLOW competing spend is not yet a proof of death.** The verdict rests on three reads
    /// taken at three moments, and an aggregating source answers them from different nodes: one ahead
    /// of the chain reports the input spent, one behind it still shows no payment coin, and the pair
    /// reads as death for a transfer that may be perfectly alive. Since `Failed` tells the caller to
    /// send again, that mistake costs a second payment.
    ///
    /// Requiring the spend to be BURIED removes the asymmetry — a node lagging far enough to hide the
    /// payment coin cannot also have seen a deeply-buried spend. The fixture is one block short of the
    /// bound, and the control below is the same fixture at the bound.
    #[test]
    fn a_shallow_competing_spend_is_not_yet_a_proof_of_death() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, _) = pending_and_payment(&ops, &source);
        let input = source.records[0].coin;

        let spent_at = PEAK;
        let chain = FixedChain::with_records(vec![record(input, Some(PEAK - 100), Some(spent_at))])
            .at_peak(spent_at + MIN_CONFIRMATION_DEPTH - 2);

        assert!(
            matches!(
                transfer_status(&pending, &chain).expect("readable"),
                TransferStatus::Awaiting { .. }
            ),
            "one block short of the bound must not be reported as dead"
        );
    }

    /// The other side of that bound: the SAME competing spend, buried to exactly
    /// [`MIN_CONFIRMATION_DEPTH`], IS a proof of death. Without it the refusal above would be equally
    /// satisfied by an implementation that had stopped reporting `Failed` at all.
    #[test]
    fn a_competing_spend_buried_to_the_bound_is_a_proof_of_death() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, _) = pending_and_payment(&ops, &source);
        let input = source.records[0].coin;

        let spent_at = PEAK;
        let chain = FixedChain::with_records(vec![record(input, Some(PEAK - 100), Some(spent_at))])
            .at_peak(spent_at + MIN_CONFIRMATION_DEPTH - 1);

        assert!(
            matches!(
                transfer_status(&pending, &chain).expect("readable"),
                TransferStatus::Failed { .. }
            ),
            "exactly MIN_CONFIRMATION_DEPTH blocks of burial is enough to declare death"
        );
    }

    /// **A source coin reported as spent at GENESIS is not a proof of death.**
    ///
    /// No coin is spent in block 0, so `spent_height: Some(0)` is a height the chain cannot have
    /// produced — most plausibly a source that zero-filled the field instead of leaving it `None`.
    ///
    /// It is also the worst possible input to the burial rule: a spend at height 0 computes a depth
    /// of `peak + 1`, which clears `MIN_CONFIRMATION_DEPTH` by a wider margin than any genuine spend
    /// ever could. So without the floor, the ONE value that is certainly fabricated becomes the most
    /// convincing evidence in the system — and it produces `Failed`, which tells the caller to build
    /// a new transfer and pay the recipient a second time.
    ///
    /// The peak here is deep enough that burial alone would pass, which is what makes this pin the
    /// genesis rule specifically rather than the depth rule.
    #[test]
    fn a_source_coin_spent_at_genesis_is_not_a_proof_of_death() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, _) = pending_and_payment(&ops, &source);
        let input = source.records[0].coin;

        let chain = FixedChain::with_records(vec![record(input, Some(PEAK - 100), Some(0))])
            .at_peak(PEAK + MIN_CONFIRMATION_DEPTH);

        assert!(
            matches!(
                transfer_status(&pending, &chain).expect("readable"),
                TransferStatus::Awaiting { .. }
            ),
            "a spend the chain could not have recorded must not be the evidence that kills a transfer"
        );
    }

    /// The other side: the SAME fixture with the spend at height 1 — the first height a spend can
    /// really occupy — IS a proof of death. Without it the refusal above would be equally satisfied
    /// by an implementation that had stopped reporting `Failed`.
    #[test]
    fn a_source_coin_spent_at_the_first_real_height_is_a_proof_of_death() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, _) = pending_and_payment(&ops, &source);
        let input = source.records[0].coin;

        let chain = FixedChain::with_records(vec![record(input, Some(PEAK - 100), Some(1))])
            .at_peak(PEAK + MIN_CONFIRMATION_DEPTH);

        assert!(matches!(
            transfer_status(&pending, &chain).expect("readable"),
            TransferStatus::Failed { .. }
        ));
    }

    /// **The control that makes the failure test load-bearing, and it must be an INCONSISTENT one.**
    ///
    /// A control built from one consistent snapshot — a spent input and a present payment coin,
    /// answered identically on every read — proves only that the two facts are weighed in the right
    /// order WITHIN a snapshot. The hazard is across reads: `transfer_status` asks three separate
    /// questions, and the aggregating chain source it recommends answers them from different nodes at
    /// different heights.
    ///
    /// So this double answers `coin_record(payment)` as ABSENT the first time and PRESENT afterwards,
    /// which is exactly what a node behind the inclusion followed by a node ahead of it looks like.
    /// The source is reported spent throughout. Without the re-read, that pair is a proof of death for
    /// a transfer that has already paid the recipient — and `Failed` tells the caller to send again.
    #[test]
    fn a_payment_coin_absent_on_the_first_read_and_present_on_the_second_is_not_a_failure() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);

        let chain = FlickeringChain {
            payment: record(payment, Some(PEAK + 1), None),
            other: vec![spent(source.records[0].coin)],
            payment_reads: Cell::new(0),
            peak: PEAK + 1,
            vanishing: false,
        };

        let status = transfer_status(&pending, &chain).expect("readable");
        assert!(
            !matches!(status, TransferStatus::Failed { .. }),
            "a payment coin that ANY read reports must not be called never-includable: {status:?}"
        );
        assert!(
            chain.payment_reads.get() >= 2,
            "the conclusion must rest on a read taken after the spent-source observation"
        );
    }

    /// The truthful control for the flickering double: when the payment coin is absent on EVERY read,
    /// the same fixture still reports the death. Without this, the test above would pass against an
    /// implementation that had simply stopped reporting `Failed` at all.
    #[test]
    fn a_payment_coin_absent_on_every_read_is_still_a_failure() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);

        let chain = FlickeringChain {
            // Never returned: `payment_reads` only ever reaches the absent branch below.
            payment: record(payment, Some(PEAK + 1), None),
            other: vec![spent(source.records[0].coin)],
            payment_reads: Cell::new(usize::MAX),
            peak: PEAK + 1,
            vanishing: false,
        };

        assert!(matches!(
            transfer_status(&pending, &chain).expect("readable"),
            TransferStatus::Failed { .. }
        ));
    }

    /// **A payment coin seen on the FIRST read is never a proof of death, even if the source stops
    /// reporting it.**
    ///
    /// This is what the `payment.is_none()` veto in [`transfer_status`] buys, and it is a different
    /// property from the re-read inside [`proof_of_death`]. The re-read protects the case where the
    /// payment appears LATE; this protects the case where it appears EARLY and then vanishes — an
    /// aggregating source answering the first question from a node that is current and the rest from
    /// one that has fallen behind.
    ///
    /// Both spellings look equivalent because `proof_of_death` also returns `None` when it can see
    /// the payment coin. They diverge exactly here: the veto remembers an observation the later reads
    /// have lost. Deleting the guard makes this test go red while every other test stays green.
    #[test]
    fn a_payment_coin_seen_on_the_first_read_is_never_a_failure() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);
        let input = source.records[0].coin;

        let chain = FlickeringChain {
            payment: record(payment, Some(PEAK + 1), None),
            // Spent, and buried well past the bound, so the death path is genuinely reachable.
            other: vec![record(input, Some(PEAK - 100), Some(PEAK - 50))],
            payment_reads: Cell::new(0),
            peak: PEAK,
            vanishing: true,
        };

        let status = transfer_status(&pending, &chain).expect("readable");
        assert!(
            !matches!(status, TransferStatus::Failed { .. }),
            "a payment coin this source has already reported must not become a death: {status:?}"
        );
    }

    /// The truthful control: the SAME fixture, the SAME buried spend, with the payment coin absent on
    /// EVERY read, IS a proof of death. Without it the test above would pass against an
    /// implementation that had simply stopped reporting `Failed`.
    #[test]
    fn the_same_fixture_with_the_payment_never_seen_is_a_failure() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, payment) = pending_and_payment(&ops, &source);
        let input = source.records[0].coin;

        let chain = FlickeringChain {
            payment: record(payment, Some(PEAK + 1), None),
            other: vec![record(input, Some(PEAK - 100), Some(PEAK - 50))],
            payment_reads: Cell::new(usize::MAX),
            peak: PEAK,
            vanishing: false,
        };

        assert!(matches!(
            transfer_status(&pending, &chain).expect("readable"),
            TransferStatus::Failed { .. }
        ));
    }

    /// A chain source whose answer about the payment coin CHANGES between reads.
    ///
    /// `payment_reads` counts calls for the payment coin: by default the first is answered absent and
    /// later ones present. Setting it to `usize::MAX` makes every read absent, which is how the same
    /// double serves as its own control.
    ///
    /// `vanishing` INVERTS that — present first, absent afterwards. A double that can only appear
    /// cannot express a source that has fallen behind after answering, and that direction is the one
    /// the `payment.is_none()` veto in [`transfer_status`] exists to handle.
    struct FlickeringChain {
        payment: CoinRecord,
        other: Vec<CoinRecord>,
        payment_reads: Cell<usize>,
        peak: u32,
        vanishing: bool,
    }

    impl ChainSource for FlickeringChain {
        type Error = String;

        fn coin_record(&self, coin_id: Bytes32) -> std::result::Result<Option<CoinRecord>, String> {
            if coin_id == self.payment.coin.coin_id() {
                let seen = self.payment_reads.get();
                self.payment_reads.set(seen.saturating_add(1));
                let present = if self.vanishing {
                    seen == 0
                } else {
                    seen > 0 && seen != usize::MAX
                };
                return Ok(present.then(|| self.payment.clone()));
            }
            Ok(self
                .other
                .iter()
                .find(|record| record.coin.coin_id() == coin_id)
                .cloned())
        }

        fn coin_records_by_puzzle_hash(
            &self,
            _puzzle_hash: Bytes32,
            _include_spent: bool,
        ) -> std::result::Result<Vec<CoinRecord>, String> {
            Ok(Vec::new())
        }

        fn coin_records_by_parent(
            &self,
            _parent: Bytes32,
        ) -> std::result::Result<Vec<CoinRecord>, String> {
            Ok(Vec::new())
        }

        fn coin_spend(&self, _coin_id: Bytes32) -> std::result::Result<Option<CoinSpend>, String> {
            Ok(None)
        }

        fn resolve_singleton_lineage(
            &self,
            _launcher_id: Bytes32,
        ) -> std::result::Result<Option<dig_chainsource_interface::SingletonLineage>, String>
        {
            Err("not supported by this test double".to_string())
        }

        fn peak_height(&self) -> std::result::Result<Option<u32>, String> {
            Ok(Some(self.peak))
        }

        fn block_timestamp(&self, _height: u32) -> std::result::Result<Option<u64>, String> {
            Ok(None)
        }
    }

    /// An unreachable chain fails CLOSED: the status is unknown, never "not confirmed".
    #[test]
    fn an_unreachable_chain_makes_the_status_unknown() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, _) = pending_and_payment(&ops, &source);

        let error = transfer_status(&pending, &FixedChain::offline())
            .expect_err("an unanswerable chain yields no status");
        assert!(
            matches!(error, TransferError::ChainUnreachable(_)),
            "{error}"
        );
    }

    /// A source that answers reads but exposes no PEAK also fails closed: without a peak, a claimed
    /// confirmation height cannot be bounded at all.
    #[test]
    fn a_source_without_a_peak_fails_closed() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, _) = pending_and_payment(&ops, &source);

        let error =
            transfer_status(&pending, &source.without_peak()).expect_err("no peak, no bound");
        assert!(
            matches!(error, TransferError::ChainUnreachable(_)),
            "{error}"
        );
    }

    /// Blocks-since-push is a real elapsed measure a caller can time out on, not a spinner.
    ///
    /// The fixture is a genuine in-flight transfer — the input still present and UNSPENT, the payment
    /// coin not yet created — rather than an empty record set, which would have exercised the
    /// subtraction while saying nothing about the predicate that chooses `Awaiting`.
    #[test]
    fn a_transfer_still_in_flight_reports_the_blocks_elapsed_since_the_push() {
        let ops = ops();
        let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
        let (pending, _) = pending_and_payment(&ops, &source);

        let chain =
            FixedChain::with_records(vec![confirmed(source.records[0].coin)]).at_peak(PEAK + 9);
        assert_eq!(
            transfer_status(&pending, &chain).expect("readable"),
            TransferStatus::Awaiting {
                blocks_since_push: 9
            }
        );
    }
}