dig-node-control-interface 0.12.0

Canonical client <-> dig-node CONTROL interface contract: the method catalog for controlling/querying a running dig-node (config, status, peers, subscriptions, cache, wallet), transport-agnostic. SSOT so client and node can't drift.
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
//! Conformance known-answer tests (KATs) — the anti-drift layer.
//!
//! These pin the exact wire shapes both sides must agree on: golden JSON-RPC request vectors for
//! every method, golden response vectors that the typed results decode-then-re-encode byte-for-byte,
//! and an end-to-end route through a mock [`ControlHandler`] proving the dispatcher maps every
//! method to its typed handler and back. Any client (extension/CLI/hub, T8–T10) and the node side
//! (T7) pin against these; a change that alters a wire shape fails here first.

use futures::executor::block_on;
use serde_json::{json, Value};

use crate::envelope::{JsonRpcRequest, JsonRpcResponse, RequestId};
use crate::error::{ControlError, ControlErrorCode};
use crate::method::ControlMethod;
use crate::params::*;
use crate::results;
use crate::traits::{build_request, parse_response, ControlHandler};

/// The one bundle [`MockNode`] refuses, so the accepted and rejected branches are both reachable
/// from the SAME handler — a mock that could only accept could not express a refusal at all.
const REJECTED_BUNDLE: &str = "beef";

/// The one upstream [`MockNode`] refuses, so a handler error stays reachable from the SAME handler
/// even though `every_catalog_method_dispatches_without_panicking` requires every method to SUCCEED
/// under its minimal params. The refusal has to hang off a value the minimal fixture never uses;
/// making a whole method unsupported instead would trip that test, and silencing it there would put
/// back the tolerate-any-error hole the test exists to close.
const UNSUPPORTED_UPSTREAM: &str = "__not_supported__";

/// The one coin id [`MockNode`] knows about — SPENT, which is the state `control.wallet.coins`
/// can never report and the state a mint observation turns on.
const SPENT_COIN: &str = "abababababababababababababababababababababababababababababababab";

/// A well-formed coin id [`MockNode`] has never heard of, so "absent" is reachable from the same
/// handler as "found" and the two answers can be told apart.
const ABSENT_COIN: &str = "0101010101010101010101010101010101010101010101010101010101010101";

/// The children [`SPENT_COIN`]'s spend created, ASCENDING by coin id — the order the contract fixes.
///
/// FOUR of them, and every id DISTINCT from the parent, so three different wrong implementations are
/// visible: one that echoes the id it was asked about, one that ignores `after_coin_id`, and one
/// that reports completeness from the page LENGTH. Four children paged two at a time is the fixture
/// that kills the last of those — both pages carry exactly two rows, and only one of them is the
/// last, so `complete` is the only thing that tells them apart.
const CHILD_COINS: [&str; 4] = [
    "1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a",
    "2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b",
    "3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c",
    "4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d",
];

/// The two halves of a spend, given DIFFERENT values so a serialization that transposed the fields
/// cannot pass. Short stand-ins for serialized CLVM — the contract fixes the encoding (lowercase hex)
/// and not the programs, which belong to whatever puzzle was actually revealed.
const REVEAL_HEX: &str = "ff01ff8080";
const SOLUTION_HEX: &str = "ff8203e880";

const STORE: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const ROOT: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";

/// A golden request vector: build the typed call, assert it serializes to the exact envelope bytes.
fn assert_request<C: crate::traits::ControlCall>(call: &C, expected: Value) {
    let req = build_request(RequestId::Number(1), call);
    assert_eq!(
        serde_json::to_value(&req).unwrap(),
        expected,
        "request wire shape drifted for {}",
        C::METHOD.name()
    );
}

/// A golden response vector: the typed result decodes from `wire` and re-encodes byte-identically.
fn assert_result_round_trips<T>(wire: Value)
where
    T: serde::Serialize + serde::de::DeserializeOwned,
{
    let parsed: T = serde_json::from_value(wire.clone()).expect("golden result must decode");
    assert_eq!(
        serde_json::to_value(&parsed).unwrap(),
        wire,
        "result wire shape is not byte-stable"
    );
}

#[test]
fn golden_request_vectors() {
    assert_request(
        &StatusParams {},
        json!({"jsonrpc":"2.0","id":1,"method":"control.status","params":{}}),
    );
    assert_request(
        &SetUpstreamParams {
            upstream: "https://rpc.dig.net".into(),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.config.setUpstream","params":{"upstream":"https://rpc.dig.net"}}),
    );
    assert_request(
        &SetLevelParams {
            filter: "info,dig_node_core=debug".into(),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.log.setLevel","params":{"filter":"info,dig_node_core=debug"}}),
    );
    assert_request(
        &SetCapParams {
            cap_bytes: 67108864,
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.cache.setCap","params":{"cap_bytes":67108864}}),
    );
    assert_request(
        &PinParams {
            store: format!("{STORE}:{ROOT}"),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.hostedStores.pin","params":{"store":format!("{STORE}:{ROOT}")}}),
    );
    assert_request(
        &SyncTriggerParams {
            store: format!("{STORE}:{ROOT}"),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.sync.trigger","params":{"store":format!("{STORE}:{ROOT}")}}),
    );
    assert_request(
        &PauseParams {
            until: Some(1_800_000_000),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.updater.pause","params":{"until":1800000000}}),
    );
    assert_request(
        &ApproveParams {
            pairing_id: "pid-1".into(),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.pairing.approve","params":{"pairing_id":"pid-1"}}),
    );
    assert_request(
        &PeersConnectParams {
            peer: "1.2.3.4:9257".into(),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.peers.connect","params":{"peer":"1.2.3.4:9257"}}),
    );
    assert_request(
        &SubscribeParams {
            store_id: STORE.into(),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.subscribe","params":{"store_id":STORE}}),
    );
    assert_request(
        &RequestParams {
            client_name: "DIG extension".into(),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"pairing.request","params":{"client_name":"DIG extension"}}),
    );
    assert_request(
        &WalletBalanceParams {
            address: "xch1exampleaddr".into(),
            asset: Asset::Dig,
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.balance","params":{"address":"xch1exampleaddr","asset":"dig"}}),
    );
    assert_request(
        &WalletCoinsParams {
            address: "xch1exampleaddr".into(),
            asset: Asset::Xch,
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.coins","params":{"address":"xch1exampleaddr","asset":"xch"}}),
    );
    assert_request(
        &WalletCoinByIdParams {
            coin_id: "ab".repeat(32),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.coinById","params":{"coin_id":"ab".repeat(32)}}),
    );
    assert_request(
        &WalletCoinSpendParams {
            coin_id: "ab".repeat(32),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.coinSpend","params":{"coin_id":"ab".repeat(32)}}),
    );
    // The by-parent read spells its field `parent_coin_id`, not `coin_id`: the coin named is the one
    // being asked ABOUT, never the one coming back. Pinned literally so the two by-coin reads cannot
    // drift into sharing a field name that reads as a request for the parent itself.
    // A first page names neither a cursor nor a size, and MUST NOT emit either key: an omitted
    // `limit` is the contract's default, and a `null` on the wire is a different thing to parse.
    assert_request(
        &WalletCoinsByParentParams::first_page("ab".repeat(32)),
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.coinsByParent","params":{"parent_coin_id":"ab".repeat(32)}}),
    );
    // A resumed, bounded page carries both, and the cursor is spelled `after_coin_id` -- the id the
    // caller was HANDED, never a marker for where the chain got to.
    assert_request(
        &WalletCoinsByParentParams {
            parent_coin_id: "ab".repeat(32),
            after_coin_id: Some(CHILD_COINS[1].into()),
            limit: Some(2),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.coinsByParent","params":{"parent_coin_id":"ab".repeat(32),"after_coin_id":CHILD_COINS[1],"limit":2}}),
    );
    assert_request(
        &WalletPeakParams {},
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.peak","params":{}}),
    );
    assert_request(
        &PeerCountsParams {},
        json!({"jsonrpc":"2.0","id":1,"method":"control.peerCounts","params":{}}),
    );
    assert_request(
        &WalletSyncStatusParams {},
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.syncStatus","params":{}}),
    );
    assert_request(
        &WalletBroadcastParams {
            signed_bundle_hex: "deadbeef".into(),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.broadcast","params":{"signed_bundle_hex":"deadbeef"}}),
    );
}

#[test]
fn golden_response_result_vectors_are_byte_stable() {
    assert_result_round_trips::<results::StatusResult>(json!({
        "running": true, "service": "dig-node", "version": "0.30.0", "commit": "deadbee",
        "protocol": "21", "uptime_secs": 42, "addr": "127.0.0.1:9256",
        "upstream": "https://rpc.dig.net",
        "cache": {"cap_bytes": 67108864, "used_bytes": 1024, "dir": "/var/cache/dig", "shared": true},
        "hosted_store_count": 3, "cached_capsule_count": 5, "pinned_store_count": 2,
        "sync": {"available": true}
    }));
    assert_result_round_trips::<results::ConfigResult>(json!({
        "addr": "127.0.0.1:9256", "port": "9256", "upstream": "https://rpc.dig.net",
        "upstream_override": null, "cache_dir": "/var/cache/dig", "cache_shared": true,
        "config_path": "/etc/dig/config.json", "sync_available": false
    }));
    assert_result_round_trips::<results::CacheView>(json!({
        "cap_bytes": 67108864, "used_bytes": 0, "dir": "/c", "shared": false
    }));
    assert_result_round_trips::<results::HostedStoresListResult>(json!({
        "stores": [{
            "store_id": STORE, "pinned": true, "capsule_count": 1, "total_bytes": 10,
            "capsules": [{"capsule": format!("{STORE}:{ROOT}"), "root": ROOT,
                          "size_bytes": 10, "last_used_unix_ms": 1700000000000u64}]
        }]
    }));
    assert_result_round_trips::<results::SyncStatusResult>(json!({
        "available": true, "method": "section-21-whole-store-sync",
        "pinned_total": 2, "pinned_synced": 1, "whole_store_trigger_supported": false
    }));
    assert_result_round_trips::<results::SyncTriggerResult>(json!({
        "store_id": STORE, "root": ROOT, "status": "synced",
        "size_bytes": 2048, "served_root": ROOT
    }));
    assert_result_round_trips::<results::SubscribeResult>(json!({
        "subscribed": true, "added": true, "store_id": STORE
    }));
    assert_result_round_trips::<results::ListSubscriptionsResult>(json!({
        "subscriptions": [STORE], "count": 1
    }));
    assert_result_round_trips::<results::PairingApproveResult>(json!({
        "approved": true, "client_name": "DIG extension", "token_id": "abcd1234"
    }));
    assert_result_round_trips::<results::PairingPollResult>(json!({
        "status": "approved", "token": "deadbeef"
    }));
    assert_result_round_trips::<results::WalletBalanceResult>(json!({
        "balance": 1234u64, "pending": 0u64,
        "source": "db", "synced": true, "peak_height": 5000000u32
    }));
    assert_result_round_trips::<results::WalletCoinsResult>(json!({
        "coins": [{
            "coin_id": "aa".repeat(32), "asset": "xch", "amount": 1_750_000_000_000u64,
            "parent_coin_info": "bb".repeat(32), "puzzle_hash": "cc".repeat(32),
            "created_height": 5_000_000u32, "spent_height": null
        }],
        "source": "db", "synced": true, "peak_height": 5_000_000u32
    }));
    // A chain that was consulted and holds nothing. It must be expressible as a SUCCESS, because
    // that is the only shape that leaves "unreachable" free to be an error.
    assert_result_round_trips::<results::WalletCoinsResult>(json!({
        "coins": [], "source": "fallback", "synced": false, "peak_height": null
    }));
    // `control.wallet.coinById` — the SPENT coin. No `.coins` vector can carry one: that method
    // answers with unspent coins only, which is exactly why observing a mint needs this method.
    // `asset` is null because a coin id alone does not classify a coin (see `WalletCoinRecord`).
    assert_result_round_trips::<results::WalletCoinByIdResult>(json!({
        "coin": {
            "coin_id": "ab".repeat(32), "asset": null, "amount": 1_000_000_000_000u64,
            "parent_coin_info": "bb".repeat(32), "puzzle_hash": "cc".repeat(32),
            "created_height": 5_000_000u32, "spent_height": 5_000_042u32
        },
        "source": "fallback", "synced": false, "peak_height": null
    }));
    // A chain that was consulted and holds no such coin. A SUCCESS, so that "unreachable" stays
    // free to be an error.
    assert_result_round_trips::<results::WalletCoinByIdResult>(json!({
        "coin": null, "source": "fallback", "synced": false, "peak_height": null
    }));
    // The DB tier, which every other by-id vector leaves unexercised. `source:"db"` means the node's
    // OWN replica answered, so it carries `synced:true` and that replica's peak — the same binding
    // the by-address reads have always had. A db answer reporting `synced:false` would be a stale
    // view issuing a verdict; see `WalletCoinByIdResult`.
    assert_result_round_trips::<results::WalletCoinByIdResult>(json!({
        "coin": {
            "coin_id": "ab".repeat(32), "asset": null, "amount": 1_000_000_000_000u64,
            "parent_coin_info": "bb".repeat(32), "puzzle_hash": "cc".repeat(32),
            "created_height": 5_000_000u32, "spent_height": null
        },
        "source": "db", "synced": true, "peak_height": 5_000_100u32
    }));
    // `control.wallet.coinSpend` — a spend, carrying the two programs a coin record cannot supply.
    // The spent coin's `spent_height` is non-null, because a spend exists only where one is.
    assert_result_round_trips::<results::WalletCoinSpendResult>(json!({
        "spend": {
            "coin": {
                "coin_id": "ab".repeat(32), "asset": null, "amount": 1_000_000_000_000u64,
                "parent_coin_info": "bb".repeat(32), "puzzle_hash": "cc".repeat(32),
                "created_height": 5_000_000u32, "spent_height": 5_000_042u32
            },
            "puzzle_reveal": REVEAL_HEX, "solution": SOLUTION_HEX
        },
        "source": "db", "synced": true, "peak_height": 5_000_100u32
    }));
    // A chain that was consulted and holds no spend of that coin — unspent, or unknown. A SUCCESS,
    // so that "could not answer" stays free to be an error.
    assert_result_round_trips::<results::WalletCoinSpendResult>(json!({
        "spend": null, "source": "fallback", "synced": false, "peak_height": null
    }));
    // `control.wallet.coinsByParent` — one hop. `asset` is null on the child, because naming a coin
    // by its parent classifies nothing.
    assert_result_round_trips::<results::WalletCoinsByParentResult>(json!({
        "coins": [{
            "coin_id": CHILD_COINS[0], "asset": null, "amount": 999_999_999_999u64,
            "parent_coin_info": "ab".repeat(32), "puzzle_hash": "33".repeat(32),
            "created_height": 5_000_042u32, "spent_height": null
        }],
        "complete": true, "cursor": CHILD_COINS[0],
        "source": "db", "synced": true, "peak_height": 5_000_100u32
    }));
    // A TRUNCATED page: same shape, `complete:false`, and a cursor to resume from. Pinned beside the
    // complete vector above so the two are visibly different payloads rather than one shape read two
    // ways.
    assert_result_round_trips::<results::WalletCoinsByParentResult>(json!({
        "coins": [{
            "coin_id": CHILD_COINS[0], "asset": null, "amount": 999_999_999_999u64,
            "parent_coin_info": "ab".repeat(32), "puzzle_hash": "33".repeat(32),
            "created_height": 5_000_042u32, "spent_height": null
        }],
        "complete": false, "cursor": CHILD_COINS[0],
        "source": "db", "synced": true, "peak_height": 5_000_100u32
    }));
    // A parent that created no known children. A SUCCESS, for the same reason an empty `.coins` is.
    // An empty page is COMPLETE and has no cursor: there was nothing to be handed.
    assert_result_round_trips::<results::WalletCoinsByParentResult>(json!({
        "coins": [], "complete": true, "cursor": null,
        "source": "fallback", "synced": false, "peak_height": null
    }));
    assert_result_round_trips::<results::WalletPeakResult>(json!({
        "peak_height": 5_000_000u32, "synced": true
    }));
    assert_result_round_trips::<results::WalletPeakResult>(json!({
        "peak_height": null, "synced": false
    }));
    // `control.wallet.syncStatus`, every phase. `not_started` carries a null height rather
    // than 0 -- a wallet that has never synced and a wallet synced to the genesis block must not
    // wear the same shape -- and `chia_peer_count` is present in every one of them, because the
    // count is what turns "syncing" into either "syncing" or "syncing, connected to nothing".
    assert_result_round_trips::<results::WalletSyncStatusResult>(json!({
        "phase": "not_started", "peak_height": null, "chia_peer_count": 0u32,
        "watched_addresses": 0u32
    }));
    assert_result_round_trips::<results::WalletSyncStatusResult>(json!({
        "phase": "syncing", "peak_height": 4_000_000u32, "chia_peer_count": 3u32,
        "watched_addresses": 12u32
    }));
    assert_result_round_trips::<results::WalletSyncStatusResult>(json!({
        "phase": "synced", "peak_height": 5_000_000u32, "chia_peer_count": 5u32,
        "watched_addresses": 12u32
    }));
    // THE RESTART STATE: a height with no sync running. Not a contradiction -- the height is
    // persisted in the wallet DB while the phase describes this PROCESS -- so the contract permits
    // it explicitly and this vector pins that it stays expressible. A shape that forbade it would
    // force a restarted node to fabricate a phase or discard a height it genuinely has.
    assert_result_round_trips::<results::WalletSyncStatusResult>(json!({
        "phase": "not_started", "peak_height": 4_900_000u32, "chia_peer_count": 0u32,
        "watched_addresses": 12u32
    }));
    // A node that cannot observe the peer count at all: `null`, which is NOT `0`. `0` is a measured
    // zero and licenses "syncing -- no peers"; `null` licenses no claim about connectivity.
    assert_result_round_trips::<results::WalletSyncStatusResult>(json!({
        "phase": "syncing", "peak_height": null, "chia_peer_count": null,
        "watched_addresses": null
    }));
    // THE TWO IDLE STATES, which differ only in the phase token and mean opposite things. Pinned
    // adjacently and with an identical `watched_addresses: 0`, because the count alone cannot tell
    // them apart -- the token is the only thing carrying "and that is fine" versus "and it is not".
    assert_result_round_trips::<results::WalletSyncStatusResult>(json!({
        "phase": "no_wallet_enrolled", "peak_height": null, "chia_peer_count": 0u32,
        "watched_addresses": 0u32
    }));
    assert_result_round_trips::<results::WalletSyncStatusResult>(json!({
        "phase": "wallet_not_unlocked", "peak_height": 4_900_000u32, "chia_peer_count": 2u32,
        "watched_addresses": 0u32
    }));
    // A TOKEN FROM A NEWER NODE, round-tripping VERBATIM. This vector is the contract's promise that
    // an unrecognised phase survives a decode-re-encode unchanged: a consumer that relays or logs
    // the payload hands on what the node actually said, rather than a token this build invented.
    assert_result_round_trips::<results::WalletSyncStatusResult>(json!({
        "phase": "a_phase_from_a_newer_node", "peak_height": 5_000_000u32, "chia_peer_count": 3u32,
        "watched_addresses": 12u32
    }));
    // `control.peerCounts` — the two networks, each named. A node connected to both.
    assert_result_round_trips::<results::PeerCountsResult>(json!({
        "dig_peer_count": 6u32, "chia_peer_count": 3u32
    }));
    // Observed zeros on BOTH networks: the node looked and found nothing connected. Pinned
    // separately from the null case below, because a node with no peer network RUNNING has an
    // unknown count and must not report it as a measured zero.
    assert_result_round_trips::<results::PeerCountsResult>(json!({
        "dig_peer_count": 0u32, "chia_peer_count": 0u32
    }));
    // Unobservable on BOTH networks. `null` is not `0` for either count.
    assert_result_round_trips::<results::PeerCountsResult>(json!({
        "dig_peer_count": null, "chia_peer_count": null
    }));
    // One of each, and this vector is the one that matters: it varies the two counts INDEPENDENTLY,
    // so a serialization that transposed the two field names — the nearest wrong implementation, and
    // exactly the confusion this method exists to end — cannot survive it.
    assert_result_round_trips::<results::PeerCountsResult>(json!({
        "dig_peer_count": 6u32, "chia_peer_count": null
    }));
    assert_result_round_trips::<results::WalletBroadcastResult>(json!({
        "accepted": true, "transaction_id": "dd".repeat(32), "rejection": null
    }));
    assert_result_round_trips::<results::WalletBroadcastResult>(json!({
        "accepted": false, "transaction_id": null, "rejection": "DOUBLE_SPEND"
    }));
    // A fallback-tier answer: `synced` is false and `peak_height` is present as `null` (never
    // omitted), because neither describes a figure the node's own replica did not produce.
    assert_result_round_trips::<results::WalletBalanceResult>(json!({
        "balance": 0u64, "pending": 7u64,
        "source": "fallback", "synced": false, "peak_height": null
    }));
}

/// `source` is ADDITIVE in BOTH directions (dig_ecosystem#2233), which is the property that lets
/// this crate ship ahead of the nodes that emit the field.
///
/// The fixture that matters is the one WITHOUT the key: a node released before tier disclosure
/// emits no `source` at all, and 0.5.0 must still parse that payload. A test that only round-trips
/// a payload carrying the field cannot see a missing `#[serde(default)]` — the field is required on
/// deserialize, every fixture supplies it, and the break surfaces only against a real older node.
#[test]
fn a_pre_disclosure_nodes_payload_still_parses_with_the_tier_unknown() {
    let legacy = json!({
        "balance": 1234u64, "pending": 0u64, "synced": true, "peak_height": 5000000u32
    });
    let parsed: results::WalletBalanceResult =
        serde_json::from_value(legacy).expect("a node predating `source` must still deserialize");

    assert_eq!(parsed.balance, 1234);
    assert_eq!(
        parsed.source, None,
        "an absent tier is UNKNOWN -- never silently reported as one of the two tiers"
    );
}

/// The two tiers spell themselves on the wire as the lowercase tokens dig-node emits, pinned
/// literally so a Rust variant rename cannot silently change what a consumer must match on.
#[test]
fn the_tier_tokens_are_the_lowercase_wire_spellings() {
    for (src, wire) in [
        (results::WalletReadSource::Db, "db"),
        (results::WalletReadSource::Fallback, "fallback"),
    ] {
        assert_eq!(serde_json::to_value(src).unwrap(), json!(wire));
        assert_eq!(
            serde_json::from_value::<results::WalletReadSource>(json!(wire)).unwrap(),
            src
        );
    }
}

/// The wallet-sync phases spell themselves on the wire as these exact snake_case tokens, pinned
/// literally so renaming a Rust variant cannot silently change what a consumer must match on.
///
/// [`results::WalletSyncPhase::ALL`] is checked against the pinned list in BOTH directions, because
/// it is the anchor the node side derives its own conformance assertion from: a variant missing from
/// `ALL` would quietly shrink that safety net, and a variant in `ALL` with no pinned spelling would
/// leave a real wire token unpinned.
#[test]
fn the_wallet_sync_phase_tokens_are_the_snake_case_wire_spellings() {
    let pinned: &[(results::WalletSyncPhase, &str)] = &[
        (results::WalletSyncPhase::NotStarted, "not_started"),
        (results::WalletSyncPhase::Syncing, "syncing"),
        (results::WalletSyncPhase::Synced, "synced"),
        (
            results::WalletSyncPhase::NoWalletEnrolled,
            "no_wallet_enrolled",
        ),
        (
            results::WalletSyncPhase::WalletNotUnlocked,
            "wallet_not_unlocked",
        ),
    ];
    for (phase, wire) in pinned {
        assert_eq!(serde_json::to_value(phase).unwrap(), json!(wire));
        assert_eq!(
            &serde_json::from_value::<results::WalletSyncPhase>(json!(wire)).unwrap(),
            phase
        );
        assert_eq!(phase.as_wire(), *wire, "as_wire must be the same spelling");
    }

    for phase in results::WalletSyncPhase::ALL {
        assert!(
            pinned.iter().any(|(pinned_phase, _)| pinned_phase == phase),
            "{phase:?} is in ALL but has no pinned wire spelling"
        );
        assert!(
            phase.is_recognized(),
            "ALL enumerates the KNOWN phases; Unrecognized is the absence of one"
        );
        assert_eq!(
            expected_wire(phase),
            Some(phase.as_wire()),
            "{phase:?} disagrees with the compiler-checked spelling table"
        );
    }

    // DISTINCT, or the length check below is satisfiable by a duplicate standing in for a dropped
    // variant — the pigeonhole hole in a bare count comparison.
    for (i, phase) in results::WalletSyncPhase::ALL.iter().enumerate() {
        assert!(
            !results::WalletSyncPhase::ALL[..i].contains(phase),
            "{phase:?} appears twice in ALL"
        );
    }
    assert_eq!(
        results::WalletSyncPhase::ALL.len(),
        pinned.len(),
        "every pinned phase must also appear in ALL — the node side derives its conformance \
         assertion from ALL, so a variant missing here disables that check silently"
    );
}

/// The wire spelling of every phase, as a match the COMPILER checks for exhaustiveness.
///
/// This is the guard the two hand-written tables above cannot provide for themselves. `ALL`, the
/// `pinned` list, and [`results::WalletSyncPhase::as_wire`] are three separate enumerations of the
/// same set; a sixth variant added to the enum and to `as_wire` but forgotten in the other two would
/// leave a real wire token unpinned, and every test would stay green while dig-node's derived
/// conformance assertion silently shrank.
///
/// Adding a variant fails to COMPILE here instead. Whoever fixes the compile error must give the new
/// phase a spelling, and the assertions above then force it into `ALL` and into `pinned` before the
/// suite can pass again.
fn expected_wire(phase: &results::WalletSyncPhase) -> Option<&'static str> {
    match phase {
        results::WalletSyncPhase::NotStarted => Some("not_started"),
        results::WalletSyncPhase::Syncing => Some("syncing"),
        results::WalletSyncPhase::Synced => Some("synced"),
        results::WalletSyncPhase::NoWalletEnrolled => Some("no_wallet_enrolled"),
        results::WalletSyncPhase::WalletNotUnlocked => Some("wallet_not_unlocked"),
        // Not a wire token: it is whatever a newer node said, and has no fixed spelling to pin.
        results::WalletSyncPhase::Unrecognized(_) => None,
    }
}

/// **No phase value can call itself unrecognised while spelling itself as a known token.**
///
/// The defect this pins was real and shipped in an earlier revision of this branch: with a public
/// `String` inside the variant, `Unrecognized("synced".to_owned())` was constructible by any
/// consumer. It reported `is_recognized() == false` locally, went onto the wire as the bare token
/// `"synced"`, and arrived at the far side as a confident `Synced` — the money-lie this family exists
/// to prevent, reintroduced by the very variant meant to prevent it. It was also the one value in
/// the type that did not round-trip.
///
/// [`results::UnknownPhaseToken`] now has a private field and no public constructor, so the only
/// route to `Unrecognized` from outside is the TOTAL `From<&str>`, which hands back a known variant
/// for a known spelling. The property below is what that buys, stated as an invariant over every
/// value the public API can produce: **decoding a phase's own wire spelling always returns that same
/// phase.**
#[test]
fn every_phase_decodes_back_to_itself_from_its_own_wire_spelling() {
    let unknown_spellings = [
        "no_addresses_to_watch",
        "a_newer_token",
        "",
        "SYNCED",
        " synced",
    ];

    let reachable = results::WalletSyncPhase::ALL
        .iter()
        .map(|phase| phase.as_wire().to_owned())
        .chain(unknown_spellings.iter().map(|s| (*s).to_owned()));

    for spelling in reachable {
        let phase = results::WalletSyncPhase::from(spelling.as_str());

        assert_eq!(
            results::WalletSyncPhase::from(phase.as_wire()),
            phase,
            "{spelling:?} produced a phase whose own spelling decodes to something else"
        );
        assert_eq!(
            phase.is_recognized(),
            results::WalletSyncPhase::ALL.contains(&phase),
            "{spelling:?}: is_recognized() must agree with membership of the known set"
        );
        // The decisive one: a value calling itself unrecognised must never spell itself as ANY
        // known token. Checking only synced/syncing would leave `no_wallet_enrolled` -- equally an
        // all-clear -- reachable by a future forging route.
        if !phase.is_recognized() {
            assert!(
                !results::WalletSyncPhase::ALL
                    .iter()
                    .any(|known| known.as_wire() == phase.as_wire()),
                "{spelling:?} is unrecognised locally but spells itself as a known phase"
            );
        }
    }
}

/// **`not_started` and a synced-at-genesis wallet are different values.** The fixture varies ONLY the
/// phase while holding the height at the one value a bool-plus-height shape would collapse, so an
/// implementation that reported progress as `synced: false` + `peak_height: 0` -- the nearest wrong
/// shape, and the one `WalletPeakResult` already has -- cannot pass.
#[test]
fn never_started_is_distinguishable_from_synced_at_height_zero() {
    let never_started = serde_json::to_value(results::WalletSyncStatusResult {
        phase: results::WalletSyncPhase::NotStarted,
        peak_height: None,
        chia_peer_count: Some(0),
        watched_addresses: Some(0),
    })
    .unwrap();
    let synced_at_genesis = serde_json::to_value(results::WalletSyncStatusResult {
        phase: results::WalletSyncPhase::Synced,
        peak_height: Some(0),
        chia_peer_count: Some(1),
        watched_addresses: Some(4),
    })
    .unwrap();

    assert_ne!(never_started, synced_at_genesis);
    assert_eq!(never_started["peak_height"], json!(null));
    assert_eq!(
        synced_at_genesis["peak_height"],
        json!(0),
        "height 0 is a real height and must survive the round trip as one"
    );
}

/// **The prose documents name every catalogued method.**
///
/// Prose has no compiler, so a method added to the catalog can leave `SPEC.md` and `README.md`
/// describing an older, smaller surface — and both documents CLAIM to be exhaustive, which is what
/// makes the drift harmful rather than merely untidy. `README.md` is read as the agent-facing
/// interface reference and `SPEC.md` §2.1/§4 as the normative token-gating rule, so a missing method
/// there is a reimplementer gating the wrong set.
///
/// This is deliberately a MEMBERSHIP check, not a count: a hardcoded number in prose drifts
/// silently, whereas an absent name fails here by construction the moment the catalog grows.
#[test]
fn the_spec_and_readme_name_every_catalogued_method() {
    for (doc, text) in [
        ("SPEC.md", include_str!("../SPEC.md")),
        ("README.md", include_str!("../README.md")),
    ] {
        for &m in ControlMethod::ALL {
            assert!(
                text.contains(m.name()),
                "{doc} never mentions `{}` -- the document claims to be exhaustive",
                m.name()
            );
        }
        // The phase tokens are normative wire contract too, and are spelled out by hand in BOTH
        // documents. A reimplementer reads them as the definitive set, so a token added to the enum
        // and forgotten in the prose is a real defect, not a tidiness one -- the same reason the
        // method names above are guarded rather than trusted.
        //
        // The QUOTED spelling is what is searched for, not the bare word. `synced` and `syncing`
        // occur throughout both documents as ordinary English and as the unrelated
        // `WalletPeakResult.synced` FIELD, so a bare `contains` would pass for those two even if the
        // token itself were deleted -- vacuous for exactly the tokens with the most prose around
        // them. Every token appears quoted, so requiring the quotes costs nothing and restores the
        // guard's teeth.
        for phase in results::WalletSyncPhase::ALL {
            let quoted = format!("{:?}", phase.as_wire());
            assert!(
                text.contains(&quoted),
                "{doc} never mentions the {quoted} phase token in its quoted wire spelling"
            );
        }
    }

    // The catalog's own summary string is the third hand-written copy, and the one a machine reads
    // when it introspects the surface (§6.2 self-describing).
    let summary = ControlMethod::WalletSyncStatus.summary();
    for phase in results::WalletSyncPhase::ALL {
        assert!(
            summary.contains(phase.as_wire()),
            "control.wallet.syncStatus's summary omits the `{}` token",
            phase.as_wire()
        );
    }
}

/// **Each count names its own network, and the two are not interchangeable.**
///
/// The wire keys are pinned as LITERALS rather than derived from the struct, because the whole
/// reason this method exists is that a consumer reaching for a bare `peers`/`connected_peers`/
/// `peer_count` eventually reaches for the wrong network and gets a plausible number. A rename that
/// dropped a network out of a key would be invisible to a derived assertion.
///
/// The fixture gives the two counts DIFFERENT values, so an implementation that transposed the
/// fields — the nearest wrong one — fails here rather than passing on a shape both share.
#[test]
fn each_peer_count_key_names_its_network() {
    let wire = serde_json::to_value(results::PeerCountsResult {
        dig_peer_count: Some(6),
        chia_peer_count: Some(3),
    })
    .unwrap();

    assert_eq!(wire["dig_peer_count"], json!(6));
    assert_eq!(wire["chia_peer_count"], json!(3));
    // The KEY SET, exactly -- so a bare `peers` / `connected_peers` / `peer_count` cannot appear
    // alongside the named pair either. (`serde_json::Value` orders its map, so this is a set
    // assertion by construction; the emitted TEXT below is what a consumer actually parses.)
    let keys: Vec<&str> = wire
        .as_object()
        .unwrap()
        .keys()
        .map(String::as_str)
        .collect();
    assert_eq!(keys, vec!["chia_peer_count", "dig_peer_count"]);
    assert_eq!(
        serde_json::to_string(&results::PeerCountsResult {
            dig_peer_count: Some(6),
            chia_peer_count: Some(3),
        })
        .unwrap(),
        r#"{"dig_peer_count":6,"chia_peer_count":3}"#,
        "the emitted bytes name each network and give the two counts independently"
    );
}

/// **The two `chia_peer_count` fields are ONE observation under ONE key.**
///
/// The field is deliberately duplicated across `control.peerCounts` and
/// `control.wallet.syncStatus`, and the contract's answer to that duplication is that a conforming
/// node serves both from a single source. That is a node obligation this crate cannot execute — but
/// it can pin the half that makes the obligation expressible: the two payloads must spell the count
/// with the IDENTICAL key, so a node reading one type's field name and emitting the other's cannot
/// arise, and a consumer can compare the two answers at all.
#[test]
fn both_results_spell_the_chia_count_with_the_same_key() {
    const KEY: &str = "chia_peer_count";

    let counts = serde_json::to_value(results::PeerCountsResult {
        dig_peer_count: None,
        chia_peer_count: Some(3),
    })
    .unwrap();
    let sync = serde_json::to_value(results::WalletSyncStatusResult {
        phase: results::WalletSyncPhase::Syncing,
        peak_height: Some(4_000_000),
        chia_peer_count: Some(3),
        watched_addresses: Some(4),
    })
    .unwrap();

    assert_eq!(counts[KEY], json!(3));
    assert_eq!(sync[KEY], json!(3));
    assert_eq!(
        counts[KEY], sync[KEY],
        "a single node's two answers describe the same observation and must agree"
    );
}

/// **`null` and `0` are different answers for each count, independently.**
///
/// Varies ONE count at a time against a truthful control, so a shape that collapsed absent into zero
/// on either field alone is caught. A node with no peer network running has an UNKNOWN count; a
/// zero there would report "nothing is connected" about a network it never asked.
#[test]
fn an_unobservable_count_is_null_not_zero_on_either_network() {
    let dig_unknown = serde_json::to_value(results::PeerCountsResult {
        dig_peer_count: None,
        chia_peer_count: Some(0),
    })
    .unwrap();
    assert_eq!(dig_unknown["dig_peer_count"], json!(null));
    assert_eq!(
        dig_unknown["chia_peer_count"],
        json!(0),
        "an observed zero must survive as a zero beside an unknown"
    );

    let chia_unknown = serde_json::to_value(results::PeerCountsResult {
        dig_peer_count: Some(0),
        chia_peer_count: None,
    })
    .unwrap();
    assert_eq!(chia_unknown["dig_peer_count"], json!(0));
    assert_eq!(chia_unknown["chia_peer_count"], json!(null));

    assert_ne!(dig_unknown, chia_unknown);
}

/// The "no dig-app code change" guarantee, pinned: the node's richer `WalletBalanceResult` is a
/// strict SUPERSET of dig-app's frozen `BalanceResponse { balance }`, so dig-app deserializes the
/// node's payload losslessly (its struct does not deny unknown fields) and reads the confirmed
/// balance. This mirrors dig-app's `dig-app-core::wallet::engine::BalanceResponse` byte-for-byte.
#[test]
fn node_balance_superset_is_readable_by_dig_apps_balance_struct() {
    /// Byte-identical mirror of dig-app's frozen `BalanceResponse` — NO `deny_unknown_fields`, so the
    /// node's extra fields (`pending`/`source`/`synced`/`peak_height`) are ignored, not rejected.
    #[derive(serde::Deserialize)]
    struct DigAppBalanceResponse {
        balance: u64,
    }

    // The node emits the full superset...
    let node_payload = serde_json::to_value(results::WalletBalanceResult {
        balance: 9_999,
        pending: 42,
        source: Some(results::WalletReadSource::Db),
        synced: true,
        peak_height: Some(6_123_456),
    })
    .unwrap();

    // ...and dig-app's `{balance}` struct reads it without any code change on dig-app's side.
    let app: DigAppBalanceResponse =
        serde_json::from_value(node_payload).expect("dig-app must read the node's richer payload");
    assert_eq!(
        app.balance, 9_999,
        "dig-app must read the confirmed balance verbatim"
    );
}

#[test]
fn error_envelope_golden_vector() {
    let resp = JsonRpcResponse::error(
        RequestId::Number(1),
        ControlError::of(ControlErrorCode::Unauthorized, "control.* requires a token"),
    );
    assert_eq!(
        serde_json::to_value(&resp).unwrap(),
        json!({
            "jsonrpc": "2.0", "id": 1,
            "error": {
                "code": -32030,
                "message": "control.* requires a token",
                "data": {"code": "UNAUTHORIZED", "origin": "shell"}
            }
        })
    );
}

/// A mock node that serves canned typed results — exercises the [`ControlHandler`] dispatcher for
/// every method group without a running node.
struct MockNode;

#[async_trait::async_trait]
impl ControlHandler for MockNode {
    async fn status(&self) -> Result<results::StatusResult, ControlError> {
        Ok(results::StatusResult {
            running: true,
            service: "dig-node".into(),
            version: "0.30.0".into(),
            commit: "deadbee".into(),
            protocol: "21".into(),
            uptime_secs: 1,
            addr: "127.0.0.1:9256".into(),
            upstream: "https://rpc.dig.net".into(),
            cache: results::CacheView {
                cap_bytes: 67108864,
                used_bytes: 0,
                dir: "/c".into(),
                shared: false,
            },
            hosted_store_count: 0,
            cached_capsule_count: 0,
            pinned_store_count: 0,
            sync: results::SyncAvailability { available: false },
        })
    }
    async fn config_get(&self) -> Result<results::ConfigResult, ControlError> {
        Ok(results::ConfigResult {
            addr: "127.0.0.1".into(),
            port: "9256".into(),
            upstream: "https://rpc.dig.net".into(),
            upstream_override: None,
            cache_dir: "/tmp/cache".into(),
            cache_shared: false,
            config_path: "/tmp/config.json".into(),
            sync_available: true,
        })
    }
    async fn config_set_upstream(
        &self,
        params: SetUpstreamParams,
    ) -> Result<results::SetUpstreamResult, ControlError> {
        if params.upstream == UNSUPPORTED_UPSTREAM {
            return Err(unimpl("config_set_upstream"));
        }
        Ok(results::SetUpstreamResult {
            upstream: params.upstream,
            requires_restart: true,
        })
    }
    async fn log_set_level(
        &self,
        params: SetLevelParams,
    ) -> Result<results::SetLevelResult, ControlError> {
        Ok(results::SetLevelResult {
            filter: params.filter,
        })
    }
    async fn cache_get(&self) -> Result<results::CacheView, ControlError> {
        Ok(results::CacheView {
            cap_bytes: 64 * 1024 * 1024,
            used_bytes: 1024,
            dir: "/tmp/cache".into(),
            shared: false,
        })
    }
    async fn cache_set_cap(
        &self,
        params: SetCapParams,
    ) -> Result<results::SetCapResult, ControlError> {
        Ok(results::SetCapResult {
            cap_bytes: params.cap_bytes.max(64 * 1024 * 1024),
        })
    }
    async fn cache_clear(&self) -> Result<results::CacheClearResult, ControlError> {
        Ok(results::CacheClearResult { cleared: true })
    }
    async fn hosted_stores_list(&self) -> Result<results::HostedStoresListResult, ControlError> {
        Ok(results::HostedStoresListResult { stores: vec![] })
    }
    async fn hosted_stores_pin(
        &self,
        params: PinParams,
    ) -> Result<results::PinResult, ControlError> {
        Ok(results::PinResult {
            store_id: params.store,
            root: None,
            pinned: true,
            fetch: json!({"status": "skipped"}),
        })
    }
    async fn hosted_stores_unpin(
        &self,
        params: UnpinParams,
    ) -> Result<results::UnpinResult, ControlError> {
        Ok(results::UnpinResult {
            store_id: params.store,
            unpinned: true,
            evicted_capsules: 0,
        })
    }
    async fn hosted_stores_status(
        &self,
        params: HostedStoreStatusParams,
    ) -> Result<results::HostedStoreStatusResult, ControlError> {
        Ok(results::HostedStoreStatusResult {
            store_id: params.store,
            pinned: false,
            capsule_count: 0,
            total_bytes: 0,
            capsules: vec![],
        })
    }
    async fn sync_status(&self) -> Result<results::SyncStatusResult, ControlError> {
        Ok(results::SyncStatusResult {
            available: true,
            method: "dig-sync".into(),
            pinned_total: 0,
            pinned_synced: 0,
            whole_store_trigger_supported: true,
        })
    }
    async fn sync_trigger(
        &self,
        params: SyncTriggerParams,
    ) -> Result<results::SyncTriggerResult, ControlError> {
        let (store_id, root) = params.store.split_once(':').unwrap_or((&params.store, ""));
        Ok(results::SyncTriggerResult {
            store_id: store_id.into(),
            root: root.into(),
            status: "synced".into(),
            size_bytes: 1,
            served_root: root.into(),
        })
    }
    async fn updater_status(&self) -> Result<Value, ControlError> {
        Ok(json!({"channel": "stable"}))
    }
    async fn updater_set_channel(&self, params: SetChannelParams) -> Result<Value, ControlError> {
        Ok(json!({"channel": params.channel}))
    }
    async fn updater_pause(&self, params: PauseParams) -> Result<Value, ControlError> {
        Ok(json!({"paused": true, "until": params.until}))
    }
    async fn updater_resume(&self) -> Result<Value, ControlError> {
        Ok(json!({"paused": false}))
    }
    async fn updater_check_now(&self) -> Result<Value, ControlError> {
        Ok(json!({"checked": true}))
    }
    async fn pairing_list(&self) -> Result<Value, ControlError> {
        Ok(json!({"pending": [], "tokens": []}))
    }
    async fn pairing_approve(
        &self,
        params: ApproveParams,
    ) -> Result<results::PairingApproveResult, ControlError> {
        Ok(results::PairingApproveResult {
            approved: true,
            client_name: params.pairing_id,
            token_id: "abcd1234".into(),
        })
    }
    async fn pairing_revoke(
        &self,
        params: RevokeParams,
    ) -> Result<results::PairingRevokeResult, ControlError> {
        Ok(results::PairingRevokeResult {
            revoked: true,
            token_id: params.token_id,
        })
    }
    async fn peer_status(&self) -> Result<Value, ControlError> {
        Ok(json!({"running": false}))
    }
    async fn peers_connect(
        &self,
        params: PeersConnectParams,
    ) -> Result<results::PeersConnectResult, ControlError> {
        Ok(results::PeersConnectResult {
            connected: true,
            peer_id: params.peer,
        })
    }
    async fn peers_disconnect(
        &self,
        params: PeersDisconnectParams,
    ) -> Result<results::PeersDisconnectResult, ControlError> {
        Ok(results::PeersDisconnectResult {
            disconnected: true,
            peer_id: params.peer,
        })
    }
    async fn subscribe(
        &self,
        params: SubscribeParams,
    ) -> Result<results::SubscribeResult, ControlError> {
        Ok(results::SubscribeResult {
            subscribed: true,
            added: true,
            store_id: params.store_id,
        })
    }
    async fn unsubscribe(
        &self,
        params: UnsubscribeParams,
    ) -> Result<results::UnsubscribeResult, ControlError> {
        Ok(results::UnsubscribeResult {
            subscribed: false,
            removed: true,
            store_id: params.store_id,
        })
    }
    async fn list_subscriptions(&self) -> Result<results::ListSubscriptionsResult, ControlError> {
        Ok(results::ListSubscriptionsResult {
            subscriptions: vec![],
            count: 0,
        })
    }
    async fn wallet_balance(
        &self,
        _params: WalletBalanceParams,
    ) -> Result<results::WalletBalanceResult, ControlError> {
        Ok(results::WalletBalanceResult {
            balance: 1234,
            pending: 0,
            source: Some(results::WalletReadSource::Db),
            synced: true,
            peak_height: Some(5_000_000),
        })
    }
    /// Echoes the REQUEST into the coin so a mis-routed dispatch cannot look like a hit: the coin
    /// id carries the address and the amount carries the asset.
    async fn wallet_coins(
        &self,
        params: WalletCoinsParams,
    ) -> Result<results::WalletCoinsResult, ControlError> {
        Ok(results::WalletCoinsResult {
            coins: vec![results::WalletCoinRecord {
                coin_id: params.address,
                asset: Some(params.asset),
                amount: match params.asset {
                    Asset::Xch => 1,
                    Asset::Dig => 2,
                },
                parent_coin_info: "11".repeat(32),
                puzzle_hash: "22".repeat(32),
                created_height: Some(5_000_000),
                spent_height: None,
            }],
            source: Some(results::WalletReadSource::Db),
            synced: true,
            peak_height: Some(5_000_000),
        })
    }
    /// Knows exactly one coin — [`SPENT_COIN`] — and reports every other id as absent. Two ids, not
    /// one, so a handler that answered `coin: null` unconditionally (or echoed whatever it was
    /// asked) could not pass the routing test below.
    async fn wallet_coin_by_id(
        &self,
        params: WalletCoinByIdParams,
    ) -> Result<results::WalletCoinByIdResult, ControlError> {
        let coin = (params.coin_id == SPENT_COIN).then(|| results::WalletCoinRecord {
            coin_id: SPENT_COIN.into(),
            asset: None,
            amount: 1_000_000_000_000,
            parent_coin_info: "11".repeat(32),
            puzzle_hash: "22".repeat(32),
            created_height: Some(5_000_000),
            spent_height: Some(5_000_042),
        });
        Ok(results::WalletCoinByIdResult {
            coin,
            source: Some(results::WalletReadSource::Fallback),
            synced: false,
            peak_height: None,
        })
    }
    /// Reports a spend ONLY for [`SPENT_COIN`], and absence for every other id — so a handler that
    /// answered `spend: null` unconditionally is distinguishable from a correct one. The reveal and
    /// the solution differ from each other, so a serialization that transposed the two fields fails
    /// the routing test below rather than passing on a shape they share.
    async fn wallet_coin_spend(
        &self,
        params: WalletCoinSpendParams,
    ) -> Result<results::WalletCoinSpendResult, ControlError> {
        let spend = (params.coin_id == SPENT_COIN).then(|| results::WalletCoinSpend {
            coin: results::WalletCoinRecord {
                coin_id: SPENT_COIN.into(),
                asset: None,
                amount: 1_000_000_000_000,
                parent_coin_info: "11".repeat(32),
                puzzle_hash: "22".repeat(32),
                created_height: Some(5_000_000),
                // A spend exists only because the coin was spent, so this is never null.
                spent_height: Some(5_000_042),
            },
            puzzle_reveal: REVEAL_HEX.into(),
            solution: SOLUTION_HEX.into(),
        });
        Ok(results::WalletCoinSpendResult {
            spend,
            source: Some(results::WalletReadSource::Fallback),
            synced: false,
            peak_height: None,
        })
    }
    /// Serves [`SPENT_COIN`]'s four children as a real PAGED read — honouring `after_coin_id` and
    /// the effective limit — and reports every other parent as childless.
    ///
    /// A mock that ignored the page bound could not express a truncated answer at all, so the
    /// truncation tests below would assert a property the fixture cannot exhibit. `complete` is
    /// computed from what REMAINS after the page rather than from the page's own length, which is
    /// the distinction those tests exist to pin.
    async fn wallet_coins_by_parent(
        &self,
        params: WalletCoinsByParentParams,
    ) -> Result<results::WalletCoinsByParentResult, ControlError> {
        let known: &[&str] = if params.parent_coin_id == SPENT_COIN {
            &CHILD_COINS
        } else {
            &[]
        };
        let remaining = known
            .iter()
            .skip_while(|id| params.after_coin_id.as_deref().is_some_and(|a| **id <= a));
        let limit = params.effective_limit() as usize;
        let page: Vec<&str> = remaining.take(limit + 1).copied().collect();
        let complete = page.len() <= limit;
        let coins: Vec<results::WalletCoinRecord> = page
            .into_iter()
            .take(limit)
            .map(|coin_id| results::WalletCoinRecord {
                coin_id: coin_id.into(),
                // Naming a coin by its parent classifies nothing.
                asset: None,
                amount: 999_999_999_999,
                parent_coin_info: SPENT_COIN.into(),
                puzzle_hash: "33".repeat(32),
                created_height: Some(5_000_042),
                spent_height: None,
            })
            .collect();
        Ok(results::WalletCoinsByParentResult {
            cursor: coins.last().map(|c| c.coin_id.clone()),
            coins,
            complete,
            source: Some(results::WalletReadSource::Fallback),
            synced: false,
            peak_height: None,
        })
    }
    /// Answers with a `seq` no neighbouring wallet handler produces, and a `latest` one ABOVE the
    /// page's own cursor — so a handler that collapsed the two, or a dispatch arm wired to another
    /// wallet read, is distinguishable from a correct one.
    async fn wallet_arrivals(
        &self,
        params: WalletArrivalsParams,
    ) -> Result<results::WalletArrivalsResult, ControlError> {
        let arrivals = vec![results::WalletArrivalRecord {
            seq: 4_242,
            coin_id: SPENT_COIN.into(),
            puzzle_hash: "22".repeat(32),
            amount: "1000000000000".into(),
            asset_id: None,
            confirmed_height: 5_000_000,
        }];
        let cursor = arrivals.last().map_or(params.after_seq, |a| a.seq);
        Ok(results::WalletArrivalsResult {
            arrivals,
            cursor,
            latest: 4_243,
        })
    }
    async fn wallet_peak(&self) -> Result<results::WalletPeakResult, ControlError> {
        Ok(results::WalletPeakResult {
            peak_height: Some(5_000_000),
            synced: true,
        })
    }
    /// Reports two DIFFERENT counts, so a handler that answered one number twice — or a dispatch
    /// arm wired to the wallet's sync status, whose chia count this deliberately matches — is
    /// distinguishable from a correct one by the DIG count alone.
    async fn peer_counts(&self) -> Result<results::PeerCountsResult, ControlError> {
        Ok(results::PeerCountsResult {
            dig_peer_count: Some(6),
            chia_peer_count: Some(3),
        })
    }
    /// Reports a phase and a height NEITHER neighbouring wallet read can produce — `syncing` beside
    /// a height the peak handler never returns — so a dispatch arm wired to `control.wallet.peak`
    /// (whose payload is otherwise a plausible sync status) fails the routing test below.
    async fn wallet_sync_status(&self) -> Result<results::WalletSyncStatusResult, ControlError> {
        Ok(results::WalletSyncStatusResult {
            phase: results::WalletSyncPhase::Syncing,
            peak_height: Some(4_999_000),
            chia_peer_count: Some(3),
            watched_addresses: Some(4),
        })
    }
    /// Accepts anything except [`REJECTED_BUNDLE`], which it refuses the way a mempool does — as a
    /// successful call reporting a refusal, never as an error.
    async fn wallet_broadcast(
        &self,
        params: WalletBroadcastParams,
    ) -> Result<results::WalletBroadcastResult, ControlError> {
        if params.signed_bundle_hex == REJECTED_BUNDLE {
            return Ok(results::WalletBroadcastResult {
                accepted: false,
                transaction_id: None,
                rejection: Some("DOUBLE_SPEND".into()),
            });
        }
        Ok(results::WalletBroadcastResult {
            accepted: true,
            transaction_id: Some("cc".repeat(32)),
            rejection: None,
        })
    }
    async fn pairing_request(
        &self,
        _params: RequestParams,
    ) -> Result<results::PairingRequestResult, ControlError> {
        Ok(results::PairingRequestResult {
            pairing_id: "pid-1".into(),
            pairing_code: "012345".into(),
            expires_ms: 1_700_000_000_000,
        })
    }
    async fn pairing_poll(
        &self,
        _params: PollParams,
    ) -> Result<results::PairingPollResult, ControlError> {
        Ok(results::PairingPollResult {
            status: "pending".into(),
            token: None,
        })
    }
}

fn unimpl(what: &str) -> ControlError {
    ControlError::of(ControlErrorCode::NotSupported, format!("{what} not mocked"))
}

/// Route a typed call through the mock node's dispatcher and parse the typed result back.
fn round_trip<C: crate::traits::ControlCall>(call: &C) -> Result<C::Output, ControlError> {
    let node = MockNode;
    let req = build_request(RequestId::Number(1), call);
    let resp = block_on(node.dispatch(req));
    parse_response::<C>(resp)
}

#[test]
fn dispatcher_routes_every_taking_params_method_to_its_typed_handler() {
    assert!(round_trip(&StatusParams {}).unwrap().running);
    assert_eq!(
        round_trip(&SetCapParams { cap_bytes: 1 })
            .unwrap()
            .cap_bytes,
        64 * 1024 * 1024,
        "the node floors the cap"
    );
    assert!(round_trip(&CacheClearParams {}).unwrap().cleared);
    let pin = round_trip(&PinParams {
        store: STORE.into(),
    })
    .unwrap();
    assert_eq!(pin.store_id, STORE);
    let sync = round_trip(&SyncTriggerParams {
        store: format!("{STORE}:{ROOT}"),
    })
    .unwrap();
    assert_eq!(sync.root, ROOT);
    let sub = round_trip(&SubscribeParams {
        store_id: STORE.into(),
    })
    .unwrap();
    assert!(sub.added);
    let conn = round_trip(&PeersConnectParams { peer: "p".into() }).unwrap();
    assert_eq!(conn.peer_id, "p");
    assert_eq!(
        round_trip(&UpdaterStatusParams {}).unwrap(),
        json!({"channel": "stable"})
    );
    assert_eq!(
        round_trip(&PollParams {
            pairing_id: "x".into()
        })
        .unwrap()
        .status,
        "pending"
    );
}

#[test]
fn default_control_client_builds_and_parses_via_the_trait() {
    use crate::traits::{ControlClient, DefaultControlClient};
    let client = DefaultControlClient;
    let req = client.build_request(RequestId::Number(9), &SetCapParams { cap_bytes: 5 });
    assert_eq!(req.id, RequestId::Number(9));
    assert_eq!(req.method, "control.cache.setCap");
    let resp = JsonRpcResponse::success(RequestId::Number(9), json!({"cap_bytes": 5}));
    let out = client
        .parse_response::<SetCapParams>(resp)
        .expect("typed parse");
    assert_eq!(out.cap_bytes, 5);
}

#[test]
fn every_method_maps_to_a_category() {
    use crate::method::Category;
    // Touch the category of every method so the grouping table can't silently lose an arm.
    assert_eq!(ControlMethod::Status.category(), Category::Status);
    assert_eq!(ControlMethod::PeerStatus.category(), Category::Peers);
    for &m in ControlMethod::ALL {
        let _ = m.category();
    }
}

#[test]
fn dispatcher_rejects_an_unknown_method_with_method_not_found() {
    let node = MockNode;
    let req = JsonRpcRequest::new(RequestId::Number(1), "control.nope", json!({}));
    let resp = block_on(node.dispatch(req));
    let err = resp.into_result().unwrap_err();
    assert_eq!(err.code_enum(), Some(ControlErrorCode::MethodNotFound));
}

#[test]
fn dispatcher_maps_malformed_params_to_invalid_params() {
    let node = MockNode;
    // `control.cache.setCap` needs a numeric `cap_bytes`; a string is malformed.
    let req = JsonRpcRequest::new(
        RequestId::Number(1),
        ControlMethod::CacheSetCap.name(),
        json!({"cap_bytes": "not-a-number"}),
    );
    let resp = block_on(node.dispatch(req));
    let err = resp.into_result().unwrap_err();
    assert_eq!(err.code_enum(), Some(ControlErrorCode::InvalidParams));
}

#[test]
fn dispatcher_surfaces_a_handler_error_verbatim() {
    let node = MockNode;
    let req = build_request(
        RequestId::Number(1),
        &SetUpstreamParams {
            upstream: UNSUPPORTED_UPSTREAM.into(),
        },
    );
    let resp = block_on(node.dispatch(req));
    let err = resp.into_result().unwrap_err();
    assert_eq!(err.code_enum(), Some(ControlErrorCode::NotSupported));
}

#[test]
fn every_catalog_method_dispatches_without_panicking() {
    // The dispatcher must have an arm for EVERY catalog method, and each method's minimal params
    // fixture must be complete enough that the route succeeds rather than erroring.
    let node = MockNode;
    for &m in ControlMethod::ALL {
        let req = JsonRpcRequest::new(RequestId::Number(1), m.name(), minimal_params(m));
        let resp = block_on(node.dispatch(req));
        assert!(
            resp.error.is_none(),
            "{} errored under minimal_params: {:?}",
            m.name(),
            resp.error
        );
    }
}

/// **dig_ecosystem#2215** — the `software` member every `control.peerStatus` peer entry carries.
///
/// `control.peerStatus` is a PROXIED result: SPEC §4.1 forbids freezing a struct over the snapshot,
/// because its shape belongs to the node's peer pool. So this KAT pins the one member this contract
/// DOES own — `software` — in situ, inside a representative `connected` array, rather than pinning
/// the envelope around it.
///
/// The vector carries one REPORTED peer and one UNKNOWN peer together. A vector with only a
/// reported peer would pass against an implementation that omits `software` whenever it is Unknown,
/// which is precisely the bug the always-present rule exists to prevent.
#[test]
fn peer_status_software_member_golden_vector() {
    let snapshot = json!({
        "connected": [
            {
                "peer_id": "aa00",
                "address": "[2001:db8::1]:9444",
                "outbound": true,
                "software": {
                    "kind": "reported",
                    "product": "dig-node",
                    "version": "0.99.1",
                    "raw": "dig-node/0.99.1"
                }
            },
            {
                "peer_id": "bb11",
                "address": "[2001:db8::2]:9444",
                "outbound": false,
                "software": { "kind": "unknown" }
            }
        ]
    });

    let entries = snapshot["connected"].as_array().expect("connected array");

    // Always present: EVERY entry carries `software`, including the peer whose build is unknown.
    for entry in entries {
        assert!(
            entry.get("software").is_some(),
            "every peerStatus entry must carry `software`; omitting it is a serialization bug,              not an Unknown peer"
        );
    }

    // Each member decodes to the typed value and re-encodes byte-identically.
    for entry in entries {
        let wire = entry["software"].clone();
        let parsed: results::PeerSoftware =
            serde_json::from_value(wire.clone()).expect("software member must decode");
        assert_eq!(
            serde_json::to_value(&parsed).unwrap(),
            wire,
            "the software member is not byte-stable"
        );
    }

    // And the decoded values are the ones the vector names, so a decode that silently collapsed
    // both entries to the same value could not pass.
    let reported: results::PeerSoftware =
        serde_json::from_value(entries[0]["software"].clone()).unwrap();
    assert_eq!(reported, results::PeerSoftware::parse("dig-node/0.99.1"));
    let unknown: results::PeerSoftware =
        serde_json::from_value(entries[1]["software"].clone()).unwrap();
    assert_eq!(unknown, results::PeerSoftware::Unknown);
    assert_ne!(reported, unknown);
}

/// The legacy sentinel a peer is advertising RIGHT NOW must reach a reader as Unknown, not as a
/// version — the whole live fleet depends on this one mapping (dig_ecosystem#2215).
#[test]
fn a_legacy_peer_entry_reads_as_unknown_not_as_version_zero() {
    let software = results::PeerSoftware::parse("0.0.0");
    assert_eq!(software, results::PeerSoftware::Unknown);
    let wire = serde_json::to_value(&software).unwrap();
    assert_eq!(wire, json!({"kind": "unknown"}));
    assert_eq!(
        wire.to_string().find("0.0.0"),
        None,
        "no rendering of a legacy peer may contain the sentinel as a version"
    );
}

/// The smallest valid params object for a method, so the coverage sweep above never trips
/// `INVALID_PARAMS` for a param-taking method.
fn minimal_params(m: ControlMethod) -> Value {
    match m {
        ControlMethod::ConfigSetUpstream => json!({"upstream": ""}),
        ControlMethod::LogSetLevel => json!({"filter": "info"}),
        ControlMethod::CacheSetCap => json!({"cap_bytes": 0}),
        ControlMethod::HostedStoresPin
        | ControlMethod::HostedStoresUnpin
        | ControlMethod::HostedStoresStatus
        | ControlMethod::SyncTrigger => json!({"store": STORE}),
        ControlMethod::UpdaterSetChannel => json!({"channel": "stable"}),
        ControlMethod::UpdaterPause => json!({}),
        ControlMethod::PairingApprove => json!({"pairing_id": "x"}),
        ControlMethod::PairingRevoke => json!({"token_id": "x"}),
        ControlMethod::PeersConnect | ControlMethod::PeersDisconnect => json!({"peer": "p"}),
        ControlMethod::Subscribe | ControlMethod::Unsubscribe => json!({"store_id": STORE}),
        ControlMethod::PairingRequest => json!({"client_name": "c"}),
        ControlMethod::PairingPoll => json!({"pairing_id": "x"}),
        ControlMethod::WalletBalance | ControlMethod::WalletCoins => {
            json!({"address": "xch1abc", "asset": "dig"})
        }
        ControlMethod::WalletCoinById | ControlMethod::WalletCoinSpend => {
            json!({ "coin_id": ABSENT_COIN })
        }
        ControlMethod::WalletCoinsByParent => json!({ "parent_coin_id": ABSENT_COIN }),
        ControlMethod::WalletBroadcast => json!({"signed_bundle_hex": "deadbeef"}),
        _ => json!({}),
    }
}

/// **The three new methods reach their own handlers, over the real dispatcher.**
///
/// Each assertion is keyed to something only THAT handler could have produced — the coin echoes the
/// address and asset it was asked for — so an arm wired to the neighbouring method fails here
/// rather than passing on a shape both happen to share.
#[test]
fn the_dispatcher_routes_each_wallet_chain_method_to_its_own_handler() {
    let coins = round_trip(&WalletCoinsParams {
        address: "xch1mintfunder".into(),
        asset: Asset::Dig,
    })
    .expect("coins must route");
    assert_eq!(coins.coins[0].coin_id, "xch1mintfunder");
    assert_eq!(
        coins.coins[0].asset,
        Some(Asset::Dig),
        "an address+asset read KNOWS the asset and must keep reporting it concretely --          `null` is reserved for a read that classified nothing"
    );
    assert_eq!(
        coins.coins[0].amount, 2,
        "the DIG amount proves the ASSET reached the handler, not just the address"
    );

    assert_eq!(
        round_trip(&WalletPeakParams {})
            .expect("peak must route")
            .peak_height,
        Some(5_000_000)
    );

    // Keyed to what only the sync-status handler produces: `control.wallet.peak` answers with a
    // DIFFERENT height and carries no phase at all, so an arm wired to it cannot land here.
    let sync = round_trip(&WalletSyncStatusParams {}).expect("syncStatus must route");
    assert_eq!(sync.phase, results::WalletSyncPhase::Syncing);
    assert_eq!(sync.peak_height, Some(4_999_000));
    assert_eq!(sync.chia_peer_count, Some(3));

    // `control.peerCounts` reaches its OWN handler: it is the only one that produces a DIG count at
    // all, so an arm wired to the sync status (whose chia count is the same 3) cannot land here.
    let counts = round_trip(&PeerCountsParams {}).expect("peerCounts must route");
    assert_eq!(counts.dig_peer_count, Some(6));
    assert_eq!(
        counts.chia_peer_count,
        Some(3),
        "the same observation control.wallet.syncStatus reports"
    );

    let pushed = round_trip(&WalletBroadcastParams {
        signed_bundle_hex: "deadbeef".into(),
    })
    .expect("broadcast must route");
    assert!(pushed.accepted);
    assert_eq!(pushed.rejection, None);
}

/// **`control.wallet.coinById` reaches its own handler, and reports a SPENT coin.**
///
/// The assertion is keyed to something only this handler could produce: a non-null `spent_height`.
/// `control.wallet.coins` answers by address with unspent coins only, so an arm mis-wired to it
/// could not report a spend height at all — which is the fact `mint_status` needs.
#[test]
fn the_dispatcher_routes_coin_by_id_to_its_own_handler() {
    let found = round_trip(&WalletCoinByIdParams {
        coin_id: SPENT_COIN.into(),
    })
    .expect("coinById must route");

    let coin = found.coin.expect("the mock knows this coin");
    assert_eq!(coin.coin_id, SPENT_COIN);
    assert_eq!(
        coin.spent_height,
        Some(5_000_042),
        "the spend height is the whole reason this method exists"
    );
    assert_eq!(
        coin.asset, None,
        "a by-id read classifies nothing; `null` says so rather than asserting a class"
    );
}

/// **An absent coin is an ANSWER, not an error.**
///
/// The nearest wrong implementation maps "no such coin" onto the error channel, where a caller
/// cannot tell it from an unreachable chain — and `mint_status` would then report a mint whose coin
/// genuinely does not exist as merely pending, forever, with the money already gone.
///
/// The fixture varies ONE thing against the found case above: which coin id is asked for. Both
/// answers come from the same handler, so a handler that could only ever answer one way fails here.
#[test]
fn an_absent_coin_is_a_result_not_an_error() {
    let absent = round_trip(&WalletCoinByIdParams {
        coin_id: ABSENT_COIN.into(),
    })
    .expect("an unknown coin must arrive on the Ok channel, never as a control error");

    assert_eq!(absent.coin, None);

    // And it is distinguishable, on the wire, from every error envelope: an error response carries
    // no `result` at all, so a client can never read one as "the chain says no such coin".
    let ok = JsonRpcResponse::success(RequestId::Number(1), serde_json::to_value(&absent).unwrap());
    assert!(ok.error.is_none(), "an absent coin is not an error");
    assert_eq!(ok.into_result().unwrap()["coin"], json!(null));

    for code in [
        ControlErrorCode::WalletNoChainSource,
        ControlErrorCode::WalletReadFailed,
        ControlErrorCode::WalletRateLimited,
    ] {
        let failed =
            JsonRpcResponse::error(RequestId::Number(1), ControlError::of(code, "unreachable"));
        assert!(
            parse_response::<WalletCoinByIdParams>(failed).is_err(),
            "{} must not decode into an absent-coin result",
            code.name()
        );
    }
}

/// A coin id that is not lowercase 64-hex is refused BEFORE any chain is consulted, as
/// `-32602 INVALID_PARAMS` — a malformed request, never a "no such coin" answer.
///
/// The `0x` prefix is the one tolerated decoration, because callers hand-copy ids out of block
/// explorers that print it. It is normalized away, never echoed.
#[test]
fn a_malformed_coin_id_is_invalid_params_not_an_absent_coin() {
    for bad in [
        "",
        "ab",                              // too short
        &"ab".repeat(33),                  // too long
        &"AB".repeat(32),                  // uppercase is not the wire form
        &format!("{}zz", "ab".repeat(31)), // non-hex
        &format!("0x{}", "ab".repeat(31)), // 0x-prefixed but short
        &format!(" {} ", "ab".repeat(32)), // padded
    ] {
        let node = MockNode;
        let req = JsonRpcRequest::new(
            RequestId::Number(1),
            ControlMethod::WalletCoinById.name(),
            json!({ "coin_id": bad }),
        );
        let err = block_on(node.dispatch(req)).into_result().unwrap_err();
        assert_eq!(
            err.code_enum(),
            Some(ControlErrorCode::InvalidParams),
            "{bad:?} must be refused as malformed params"
        );
    }

    // The tolerated decoration: `0x` + 64 hex reaches the handler as the unprefixed id.
    let node = MockNode;
    let req = JsonRpcRequest::new(
        RequestId::Number(1),
        ControlMethod::WalletCoinById.name(),
        json!({ "coin_id": format!("0x{SPENT_COIN}") }),
    );
    let found: results::WalletCoinByIdResult =
        serde_json::from_value(block_on(node.dispatch(req)).into_result().unwrap()).unwrap();
    assert_eq!(
        found
            .coin
            .expect("the 0x form names a coin the mock knows")
            .coin_id,
        SPENT_COIN,
        "the prefix is normalized away and never emitted"
    );
}

/// **A verdict must be stated, never inferred from silence.** `coin:null` says the chain holds no
/// such coin, so an ABSENT `coin` key must not decode into one. Serde's default treatment of
/// `Option` makes the two indistinguishable, which would let almost any JSON object — including
/// three sibling wallet results — decode into a confident "your coin does not exist".
#[test]
fn an_omitted_coin_field_is_a_decode_error_not_a_null_verdict() {
    // Explicit null still decodes: the verdict is expressible, just not by omission.
    let stated = serde_json::from_value::<results::WalletCoinByIdResult>(json!({
        "coin": null, "source": "fallback", "synced": false, "peak_height": null
    }))
    .expect("an explicitly null coin is a valid verdict");
    assert_eq!(stated.coin, None);

    // Omission does not. Each of these decoded to a complete "no such coin" before the field was
    // made required; the last three are other methods' result shapes.
    for wire in [
        json!({ "source": "fallback", "synced": false, "peak_height": null }),
        json!({ "synced": false }),
        json!({ "peak_height": 5_000_000u32, "synced": true }),
        json!({ "coins": [], "source": "db", "synced": true, "peak_height": 5_000_000u32 }),
    ] {
        assert!(
            serde_json::from_value::<results::WalletCoinByIdResult>(wire.clone()).is_err(),
            "a payload without a `coin` key must not decode into a no-such-coin verdict: {wire}"
        );
    }
}

/// **The spend and the children reach their OWN handlers, over the real dispatcher.**
///
/// Each assertion is keyed to something only that handler could have produced. The spend carries a
/// puzzle reveal and a solution, which no other wallet read emits at all; the children answer names
/// [`CHILD_COIN`], an id no other handler here produces. So an arm wired to the neighbouring by-id
/// read — the nearest wrong wiring, since all three are asked with a 64-hex coin id — fails rather
/// than passing on a shape they share.
#[test]
fn the_dispatcher_routes_the_spend_and_the_children_to_their_own_handlers() {
    let found = round_trip(&WalletCoinSpendParams {
        coin_id: SPENT_COIN.into(),
    })
    .expect("coinSpend must route");

    let spend = found.spend.expect("the mock knows this coin's spend");
    assert_eq!(spend.coin.coin_id, SPENT_COIN);
    assert_eq!(
        spend.puzzle_reveal, REVEAL_HEX,
        "the reveal is the half a coin record cannot supply, and is why this method exists"
    );
    assert_eq!(
        spend.solution, SOLUTION_HEX,
        "reveal and solution hold DIFFERENT values, so a transposition cannot pass here"
    );
    assert!(
        spend.coin.spent_height.is_some(),
        "a spend exists only because the coin was spent -- an unspent coin here is a contradiction"
    );

    let children = round_trip(&WalletCoinsByParentParams::first_page(SPENT_COIN))
        .expect("coinsByParent must route");

    assert_eq!(children.coins.len(), CHILD_COINS.len());
    assert_eq!(
        children.coins[0].coin_id, CHILD_COINS[0],
        "the answer is the CHILD -- a handler echoing the parent it was asked about fails here"
    );
    assert_eq!(
        children.coins[0].parent_coin_info, SPENT_COIN,
        "and the child names the parent that was asked for, so the id reached the handler"
    );
    assert_eq!(
        children.coins[0].asset, None,
        "naming a coin by its parent classifies nothing; `null` says so rather than asserting"
    );
}

/// **An unspent coin and a childless parent are ANSWERS, not errors.**
///
/// The nearest wrong implementation maps "nothing there" onto the error channel, where a caller
/// cannot tell it from "the chain was unreachable" — and reads the failure as *this is the tip*.
///
/// The fixture varies ONE thing, the coin asked about, against a truthful control in the same test:
/// [`SPENT_COIN`] genuinely has a spend and genuinely has a child. Without that control a handler
/// that answered absent/empty for EVERY id would pass, which is a different implementation and one
/// that can see nothing at all.
#[test]
fn an_absent_spend_and_a_childless_parent_are_answers_not_errors() {
    let no_spend = round_trip(&WalletCoinSpendParams {
        coin_id: ABSENT_COIN.into(),
    })
    .expect("an absent spend is a SUCCESS -- the error channel is reserved for could-not-answer");
    assert_eq!(no_spend.spend, None);

    let no_children = round_trip(&WalletCoinsByParentParams::first_page(ABSENT_COIN))
        .expect("a childless parent is a SUCCESS, for the same reason an empty `.coins` is");
    assert!(no_children.coins.is_empty());
    assert!(
        no_children.complete,
        "a childless parent is COMPLETELY answered -- nothing was withheld"
    );
    assert_eq!(
        no_children.cursor, None,
        "an empty page hands back nothing, so there is nothing to resume from"
    );

    // The control: the same handlers DO answer positively for a coin they know, so neither
    // assertion above is passing on a handler that can only ever say nothing.
    assert!(round_trip(&WalletCoinSpendParams {
        coin_id: SPENT_COIN.into()
    })
    .unwrap()
    .spend
    .is_some());
    assert!(
        !round_trip(&WalletCoinsByParentParams::first_page(SPENT_COIN))
            .unwrap()
            .coins
            .is_empty()
    );
}

/// **An omitted `spend` key is a decode error, not a no-spend verdict.**
///
/// The same hazard [`results::WalletCoinByIdResult`] guards, on the read where it costs the most: a
/// caller following a singleton forward reads "no spend" as *this is the tip*. Serde's default
/// treatment of `Option` would let any unrelated or truncated payload carrying a `synced` field
/// decode into a confident "this coin was never spent".
///
/// The fixtures are the neighbouring methods' real result shapes, so the test proves the guard
/// against payloads a client could actually receive by mis-routing — not against invented rubbish.
#[test]
fn an_omitted_spend_field_is_a_decode_error_not_a_no_spend_verdict() {
    // Explicit null still decodes: the verdict is expressible, just not by omission.
    let stated = serde_json::from_value::<results::WalletCoinSpendResult>(json!({
        "spend": null, "source": "fallback", "synced": false, "peak_height": null
    }))
    .expect("an explicitly null spend is a valid verdict");
    assert_eq!(stated.spend, None);

    for wire in [
        json!({ "source": "fallback", "synced": false, "peak_height": null }),
        json!({ "synced": false }),
        // `control.wallet.peak`'s shape, and `control.wallet.coinsByParent`'s: both would decode
        // into "never spent" under serde's default.
        json!({ "peak_height": 5_000_000u32, "synced": true }),
        json!({ "coins": [], "source": "db", "synced": true, "peak_height": 5_000_000u32 }),
    ] {
        assert!(
            serde_json::from_value::<results::WalletCoinSpendResult>(wire.clone()).is_err(),
            "a payload without a `spend` key must not decode into a never-spent verdict: {wire}"
        );
    }
}

/// **The by-parent read enforces the SAME id rule as the by-id reads, under its own field name.**
///
/// The rule is shared by macro, and a macro applied to the wrong field name silently produces a type
/// that validates nothing — the field would simply be absent and the decode would fail for an
/// unrelated reason. So the test pins both directions: a malformed id is refused, and a well-formed
/// one is accepted and normalized, under the key `parent_coin_id` specifically.
#[test]
fn wallet_coins_by_parent_params_enforce_the_coin_id_rule_on_their_own_field() {
    for bad in [
        json!({"parent_coin_id": "AB".repeat(32)}),
        json!({"parent_coin_id": "abc"}),
    ] {
        assert!(
            serde_json::from_value::<WalletCoinsByParentParams>(bad.clone()).is_err(),
            "a malformed parent id must be refused at deserialization: {bad}"
        );
    }
    // A `coin_id` key is NOT this method's field, so it must not satisfy it either.
    assert!(
        serde_json::from_value::<WalletCoinsByParentParams>(json!({"coin_id": "ab".repeat(32)}))
            .is_err(),
        "the by-parent read is asked with `parent_coin_id`; `coin_id` is a different question"
    );

    let prefixed = serde_json::from_value::<WalletCoinsByParentParams>(
        json!({"parent_coin_id": format!("0x{}", "ab".repeat(32))}),
    )
    .expect("a 0x-prefixed id is tolerated on input");
    assert_eq!(
        prefixed.parent_coin_id,
        "ab".repeat(32),
        "the prefix is normalized away and never emitted"
    );
}

/// **A truncated page and a final page can carry the SAME number of rows.**
///
/// The fixture is four children read two at a time, so both pages hold exactly two records and only
/// one of them is the last. Every length-based inference of completeness — `coins.len() < limit`,
/// `coins.is_empty()`, "a full page means more" — gives the same answer for both, so this is the
/// fixture that makes `complete` load-bearing rather than decorative.
///
/// The dangerous direction is the one asserted first: reading page ONE as complete ends a lineage
/// walk at a branch that has more children, and presents a partial lineage as a whole one.
#[test]
fn a_truncated_page_and_a_final_page_are_told_apart_by_complete_not_by_length() {
    let first = round_trip(&WalletCoinsByParentParams {
        parent_coin_id: SPENT_COIN.into(),
        after_coin_id: None,
        limit: Some(2),
    })
    .expect("a bounded first page must route");

    assert_eq!(first.coins.len(), 2);
    assert!(
        !first.complete,
        "two of four children were withheld -- reporting this page as complete ends the walk early"
    );
    assert_eq!(
        first.cursor.as_deref(),
        Some(CHILD_COINS[1]),
        "the cursor is the last child actually HANDED over, never a chain-head marker"
    );

    let second = round_trip(&WalletCoinsByParentParams {
        parent_coin_id: SPENT_COIN.into(),
        after_coin_id: first.cursor.clone(),
        limit: Some(2),
    })
    .expect("resuming from the handed-back cursor must route");

    assert_eq!(
        second.coins.len(),
        first.coins.len(),
        "both pages carry the same row count -- which is exactly why length cannot decide          completeness"
    );
    assert!(
        second.complete,
        "the last two children fit, so this page IS the end of the hop"
    );

    // The two pages are different children, in ascending order, with nothing repeated and nothing
    // skipped -- so a handler ignoring `after_coin_id` (and re-serving page one) fails here.
    let walked: Vec<&str> = first
        .coins
        .iter()
        .chain(second.coins.iter())
        .map(|c| c.coin_id.as_str())
        .collect();
    assert_eq!(walked, CHILD_COINS.to_vec());
}

/// **The page bound is refused above its maximum, and pinned from BOTH sides.**
///
/// A bound tested only from below can only confirm itself. The at-maximum case MUST be accepted and
/// the one-over case MUST be refused, or the constant in the docs is not the constant in the code.
///
/// Zero is refused for a different reason than "too large": a page that can hold nothing makes no
/// progress, so a caller looping until a short page arrives would loop forever.
#[test]
fn the_page_bound_is_refused_out_of_range_rather_than_clamped() {
    let at_max = serde_json::from_value::<WalletCoinsByParentParams>(json!({
        "parent_coin_id": "ab".repeat(32), "limit": COINS_BY_PARENT_MAX_LIMIT
    }))
    .expect("the documented maximum must be ACCEPTED, or the constant is not the real bound");
    assert_eq!(at_max.limit, Some(COINS_BY_PARENT_MAX_LIMIT));
    assert_eq!(at_max.effective_limit(), COINS_BY_PARENT_MAX_LIMIT);

    for over in [COINS_BY_PARENT_MAX_LIMIT + 1, u32::MAX, 0] {
        let wire = json!({"parent_coin_id": "ab".repeat(32), "limit": over});
        assert!(
            serde_json::from_value::<WalletCoinsByParentParams>(wire).is_err(),
            "limit {over} must be REFUSED, never clamped: a silently shrunk page hands back a              cursor for a position the caller never asked about"
        );
        // ...and the same rule at the validation seam the dispatcher uses, not only at decode.
        assert!(WalletCoinsByParentParams {
            parent_coin_id: "ab".repeat(32),
            after_coin_id: None,
            limit: Some(over),
        }
        .validated()
        .is_err());
    }

    // An omitted limit is the contract's default -- resolved in ONE place so a node and a client
    // cannot page to two different boundaries.
    assert_eq!(
        WalletCoinsByParentParams::first_page("ab".repeat(32)).effective_limit(),
        COINS_BY_PARENT_DEFAULT_LIMIT
    );
}

/// **The maximum page still fits the transport, with room to spare.**
///
/// [`COINS_BY_PARENT_MAX_LIMIT`] is derived from dig-ipc-protocol's `MAX_FRAME_BYTES`, and a
/// constant derived from another crate's constant drifts the moment somebody raises it "because it
/// looked small". This pins the arithmetic instead of the folklore.
///
/// The record size is measured from a WORST-CASE record — every hash at full length, a `u64::MAX`
/// amount, both heights present — rather than from a typical one, because a bound proved against a
/// small fixture is not a bound.
#[test]
fn the_largest_legal_page_fits_inside_the_transport_frame() {
    /// dig-ipc-protocol `MAX_FRAME_BYTES` (its SPEC.md bounds table). Replicated rather than
    /// imported: dig-ipc-protocol sits at the SAME crate level as this one, so depending on it would
    /// be an illegal same-level edge.
    const MAX_FRAME_BYTES: usize = 1024 * 1024;

    let worst_case = serde_json::to_string(&results::WalletCoinRecord {
        coin_id: "f".repeat(64),
        asset: None,
        amount: u64::MAX,
        parent_coin_info: "f".repeat(64),
        puzzle_hash: "f".repeat(64),
        created_height: Some(u32::MAX),
        spent_height: Some(u32::MAX),
    })
    .unwrap()
    .len()
        + 1; // the comma joining it to the next record

    let largest_page = worst_case * COINS_BY_PARENT_MAX_LIMIT as usize;
    assert!(
        largest_page * 3 < MAX_FRAME_BYTES,
        "the maximum page ({largest_page} B) must fit the 1 MiB frame with 3x headroom for the          envelope and any future additive field; raising the cap past that puts a conforming          node's honest answer beyond what the transport can deliver"
    );
}

/// **An omitted `cursor` key is a decode error, not "there was nothing to resume from".**
///
/// The same guard `spend` and `coin` carry, on the field a paged walk resumes by. Under serde's
/// default treatment of `Option`, any payload carrying `coins` and `complete` would decode with
/// `cursor: None` — so a mis-routed or truncated response would tell a caller the page handed back
/// nothing, and the walk would restart from the beginning or stop, rather than fail loudly.
///
/// The fixtures are the neighbouring reads' REAL result shapes, so this proves the guard against
/// payloads a client could actually receive rather than against invented rubbish.
#[test]
fn an_omitted_cursor_field_is_a_decode_error_not_an_empty_page() {
    // Explicit null still decodes: an empty page genuinely has nothing to resume from.
    let empty = serde_json::from_value::<results::WalletCoinsByParentResult>(json!({
        "coins": [], "complete": true, "cursor": null,
        "source": "fallback", "synced": false, "peak_height": null
    }))
    .expect("an explicitly null cursor is a valid empty page");
    assert_eq!(empty.cursor, None);

    for wire in [
        json!({ "coins": [], "complete": true, "source": "fallback", "synced": false,
                "peak_height": null }),
        // `control.wallet.coins`' shape: same `coins` key, no cursor, no completeness.
        json!({ "coins": [], "source": "db", "synced": true, "peak_height": 5_000_000u32 }),
    ] {
        assert!(
            serde_json::from_value::<results::WalletCoinsByParentResult>(wire.clone()).is_err(),
            "a payload without a `cursor` key must not decode into a nothing-to-resume-from \
             page: {wire}"
        );
    }

    // And `complete` is required for the same reason -- it has no default, so a payload that omits
    // it MUST NOT decode into the dangerous reading that the page was whole.
    assert!(
        serde_json::from_value::<results::WalletCoinsByParentResult>(json!({
            "coins": [], "cursor": null, "source": "fallback", "synced": false,
            "peak_height": null
        }))
        .is_err(),
        "a payload without `complete` must not decode into a claim that the page is whole"
    );
}

/// **A caller-supplied page bound reaches the node instead of being silently dropped.**
#[test]
fn a_by_parent_request_carries_its_page_bound() {
    let params: WalletCoinsByParentParams =
        serde_json::from_value(json!({"parent_coin_id": "ab".repeat(32), "limit": 5}))
            .expect("a bounded request must decode");
    let wire = serde_json::to_value(&params).unwrap();
    assert_eq!(
        wire["limit"],
        json!(5),
        "a page bound the caller asked for must not be discarded on the way to the node"
    );
}

#[test]
fn wallet_coin_by_id_params_refuse_malformed_ids_at_deserialization() {
    let bad_id = "AB".repeat(32);
    let upper = serde_json::from_value::<WalletCoinByIdParams>(json!({"coin_id": bad_id}));
    assert!(
        upper.is_err(),
        "uppercase ids must fail during deserialization"
    );
}

/// **A mempool refusal is a successful call.** The nearest wrong implementation maps a refusal onto
/// the error channel, where it becomes indistinguishable from a network that could not be reached —
/// and the two demand opposite remedies (retry this bundle, versus build a different one).
///
/// The fixture varies ONE thing against the accepting case above: which bundle is pushed.
#[test]
fn a_mempool_refusal_arrives_as_a_value_not_as_an_error() {
    let outcome = round_trip(&WalletBroadcastParams {
        signed_bundle_hex: REJECTED_BUNDLE.into(),
    })
    .expect("a refusal must arrive on the Ok channel, never as a control error");

    assert!(!outcome.accepted);
    assert_eq!(outcome.rejection.as_deref(), Some("DOUBLE_SPEND"));
    assert_eq!(
        outcome.transaction_id, None,
        "a refused bundle has no transaction to report"
    );
}

/// **dig-app's frozen shapes read our results losslessly.** These local structs are transcribed
/// from `dig-app-core::wallet::engine` — the consumer's own types, which this crate cannot depend
/// on — so the superset relationship is proven here rather than assumed at adoption time.
///
/// Written as SEPARATE structs, not as a field-name string comparison: a name check would pass on a
/// field whose TYPE had drifted, and `amount: u64` versus a string is exactly the drift a
/// hand-copied contract produces.
#[test]
fn dig_apps_frozen_engine_shapes_deserialize_our_wallet_results() {
    use serde::Deserialize;

    #[derive(Debug, Deserialize, PartialEq)]
    struct AppCoinRecord {
        coin_id: String,
        asset: Asset,
        amount: u64,
    }
    #[derive(Debug, Deserialize)]
    struct AppCoinsResponse {
        coins: Vec<AppCoinRecord>,
    }
    #[derive(Debug, Deserialize)]
    struct AppBroadcastResponse {
        accepted: bool,
        #[serde(default)]
        transaction_id: Option<String>,
    }

    let coins = serde_json::to_value(results::WalletCoinsResult {
        coins: vec![results::WalletCoinRecord {
            coin_id: "aa".repeat(32),
            asset: Some(Asset::Dig),
            amount: 2_000_000_000_000,
            parent_coin_info: "bb".repeat(32),
            puzzle_hash: "cc".repeat(32),
            created_height: Some(5_000_000),
            spent_height: None,
        }],
        source: Some(results::WalletReadSource::Db),
        synced: true,
        peak_height: Some(5_000_000),
    })
    .unwrap();
    let read: AppCoinsResponse =
        serde_json::from_value(coins).expect("dig-app must read our coins");
    assert_eq!(
        read.coins,
        vec![AppCoinRecord {
            coin_id: "aa".repeat(32),
            asset: Asset::Dig,
            amount: 2_000_000_000_000,
        }]
    );

    let pushed = serde_json::to_value(results::WalletBroadcastResult {
        accepted: true,
        transaction_id: Some("dd".repeat(32)),
        rejection: None,
    })
    .unwrap();
    let read: AppBroadcastResponse =
        serde_json::from_value(pushed).expect("dig-app must read our broadcast outcome");
    assert!(read.accepted);
    assert_eq!(read.transaction_id, Some("dd".repeat(32)));
}

#[test]
fn dig_apps_frozen_coin_shape_rejects_null_asset_in_wallet_coins() {
    use serde::Deserialize;

    #[allow(dead_code)]
    #[derive(Debug, Deserialize)]
    struct AppCoinRecord {
        coin_id: String,
        asset: Asset,
        amount: u64,
    }
    #[allow(dead_code)]
    #[derive(Debug, Deserialize)]
    struct AppCoinsResponse {
        coins: Vec<AppCoinRecord>,
    }

    let coins = serde_json::to_value(results::WalletCoinsResult {
        coins: vec![results::WalletCoinRecord {
            coin_id: "aa".repeat(32),
            asset: None,
            amount: 2_000_000_000_000,
            parent_coin_info: "bb".repeat(32),
            puzzle_hash: "cc".repeat(32),
            created_height: Some(5_000_000),
            spent_height: None,
        }],
        source: Some(results::WalletReadSource::Db),
        synced: true,
        peak_height: Some(5_000_000),
    })
    .unwrap();
    assert!(
        serde_json::from_value::<AppCoinsResponse>(coins).is_err(),
        "dig-app's frozen coin shape requires a non-null asset in control.wallet.coins"
    );
}

/// The wallet failure codes are the ones dig-node already emits, pinned by NUMBER and SYMBOL.
///
/// They live here so a client branches on the contract's constant instead of retyping the literal —
/// the drift dig-app's own review caught itself doing (dig-app#109), and which no fixture could
/// have caught, because the fixture would have retyped the same literal.
#[test]
fn the_wallet_failure_codes_match_the_nodes_catalogue() {
    for (code, number, symbol) in [
        (
            ControlErrorCode::WalletNoChainSource,
            -32040,
            "WALLET_NO_CHAIN_SOURCE",
        ),
        (
            ControlErrorCode::WalletNotSynced,
            -32041,
            "WALLET_NOT_SYNCED",
        ),
        (
            ControlErrorCode::WalletReadFailed,
            -32042,
            "WALLET_READ_FAILED",
        ),
        (
            ControlErrorCode::WalletRateLimited,
            -32043,
            "WALLET_RATE_LIMITED",
        ),
    ] {
        assert_eq!(code.code(), number, "{symbol} number drifted");
        assert_eq!(code.name(), symbol);
        assert_eq!(ControlErrorCode::from_code(number), Some(code));
        assert_eq!(
            code.origin(),
            "node",
            "a wallet read is served by the node's backend, not the shell"
        );
    }
}

// ---- control.wallet.arrivals (dig_ecosystem#2548) ------------------------------------------

/// **The arrival cursor's request and response shapes are pinned, in both node dialects.**
///
/// The node this contract describes already SERVES `control.wallet.arrivals`, so these vectors are
/// written against what it emits rather than against what would be tidy: `amount` is a decimal
/// STRING (the ledger stores the full `u64` range, which a JSON number cannot carry losslessly) and
/// `asset_id` is `null` for native XCH or the CAT's hex TAIL — never a ticker.
///
/// The empty page is a separate vector because it is the ordinary answer, not an edge case: it means
/// "the node consulted its own ledger and nothing has arrived since your cursor", and a client that
/// could not decode it would be blind exactly when nothing is wrong.
#[test]
fn the_arrival_cursor_wire_shapes_are_byte_stable() {
    assert_request(
        &WalletArrivalsParams {
            after_seq: 41,
            limit: Some(10),
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.arrivals","params":{"after_seq":41,"limit":10}}),
    );
    // An omitted `limit` is the node's default page size, so it is absent from the wire rather than
    // sent as a number this client invented.
    assert_request(
        &WalletArrivalsParams {
            after_seq: 0,
            limit: None,
        },
        json!({"jsonrpc":"2.0","id":1,"method":"control.wallet.arrivals","params":{"after_seq":0}}),
    );
    assert_result_round_trips::<results::WalletArrivalsResult>(json!({
        "arrivals": [{
            "seq": 7u64,
            "coin_id": "ab".repeat(32),
            "puzzle_hash": "cc".repeat(32),
            "amount": "18446744073709551615",
            "asset_id": null,
            "confirmed_height": 5_000_000u32
        }],
        "cursor": 7u64,
        "latest": 9u64
    }));
    assert_result_round_trips::<results::WalletArrivalsResult>(json!({
        "arrivals": [{
            "seq": 8u64,
            "coin_id": "ab".repeat(32),
            "puzzle_hash": "cc".repeat(32),
            "amount": "2500",
            "asset_id": "a406d3".to_string(),
            "confirmed_height": 5_000_001u32
        }],
        "cursor": 8u64,
        "latest": 8u64
    }));
    // The ordinary answer: nothing new. `cursor` echoes what the caller asked from, so a client
    // that stores it does not rewind.
    assert_result_round_trips::<results::WalletArrivalsResult>(json!({
        "arrivals": [], "cursor": 41u64, "latest": 41u64
    }));
}

/// **`latest` may run AHEAD of `cursor`, and the contract keeps that expressible.**
///
/// The node reads `latest` after materializing the page, so an arrival recorded in between sits
/// above the page and below `latest`. A client that resumed from `latest` would step over it. This
/// pins that the two are separate fields carrying separate facts — a shape that collapsed them, or
/// a result type that derived one from the other, fails here.
#[test]
fn the_arrival_page_cursor_is_the_last_row_handed_over_not_the_ledger_head() {
    let ahead: results::WalletArrivalsResult = serde_json::from_value(json!({
        "arrivals": [{
            "seq": 5u64, "coin_id": "ab".repeat(32), "puzzle_hash": "cc".repeat(32),
            "amount": "1", "asset_id": null, "confirmed_height": 100u32
        }],
        "cursor": 5u64,
        "latest": 12u64
    }))
    .expect("a page whose ledger has moved on is a valid answer");
    assert_eq!(
        ahead.cursor, 5,
        "the cursor must be the last row handed over"
    );
    assert_eq!(ahead.latest, 12, "the ledger head must survive the decode");
    assert_eq!(ahead.arrivals[0].amount, "1");
}

/// **The arrival cursor is TOKEN-GATED and reaches its own handler over the real dispatcher.**
///
/// The mock answers with a `seq` no neighbouring wallet handler produces, so an arm wired to the
/// wrong method is distinguishable rather than passing on a shape they happen to share.
#[test]
fn the_arrival_cursor_is_gated_and_routes_to_its_own_handler() {
    assert!(
        ControlMethod::WalletArrivals.requires_auth(),
        "the arrival cursor volunteers this node's own watched puzzle hashes, so it is gated \
         unlike the caller-addressed wallet reads"
    );
    let page = round_trip(&WalletArrivalsParams {
        after_seq: 0,
        limit: None,
    })
    .expect("arrivals must route");
    assert_eq!(page.arrivals[0].seq, 4_242);
    assert_eq!(page.cursor, 4_242);
    assert_eq!(page.latest, 4_243, "the ledger head must not be the cursor");
}

/// **An unknown phase token MUST NOT fail the parse.** This is the regression test for
/// dig_ecosystem#2609, and it is the whole reason [`results::WalletSyncPhase`] carries an
/// unrecognised arm.
///
/// The enum shipped as a closed three-variant `Deserialize`. When dig-node grew a fourth phase, the
/// unknown token did not degrade one field — serde aborted the WHOLE
/// [`results::WalletSyncStatusResult`], so dig-app's sync read returned `Err`, its chain-sync state
/// collapsed to `Unknown`, and the badge rendered nothing. A contract that fails closed on an
/// unrecognised token converts every future phase addition into a silent outage in every consumer
/// that has not been rebuilt yet.
#[test]
fn an_unknown_phase_token_deserializes_instead_of_erroring() {
    let parsed =
        serde_json::from_value::<results::WalletSyncPhase>(json!("a_phase_from_a_newer_node"))
            .expect("an unrecognised phase token must parse, not abort the response");

    assert_ne!(parsed, results::WalletSyncPhase::NotStarted);
    assert_ne!(parsed, results::WalletSyncPhase::Syncing);
    assert_ne!(
        parsed,
        results::WalletSyncPhase::Synced,
        "an unknown token coerced into a KNOWN phase is worse than the parse error it replaced: it \
         states a sync fact the node never sent"
    );
}

/// **One unknown token must not take the rest of the payload with it.** The height and the peer
/// count are still perfectly good observations, and a consumer that can read them renders a truthful
/// partial view instead of nothing at all.
#[test]
fn an_unknown_phase_token_does_not_kill_the_surrounding_result() {
    let parsed = serde_json::from_value::<results::WalletSyncStatusResult>(json!({
        "phase": "a_phase_from_a_newer_node",
        "peak_height": 5_000_000u32,
        "chia_peer_count": 3u32
    }))
    .expect("the unknown token must degrade the phase alone, not the whole result");

    assert_eq!(parsed.peak_height, Some(5_000_000));
    assert_eq!(parsed.chia_peer_count, Some(3));
}

/// **The unrecognised token is preserved verbatim, not normalised away.** Observability is the whole
/// point of the variant: a consumer that can name the token it did not understand turns a silent
/// mismatch into a one-line diagnosis, which is exactly what dig_ecosystem#2609 lacked — the break
/// was invisible until somebody built a probe against the published crate.
#[test]
fn an_unrecognized_phase_carries_the_token_it_did_not_understand() {
    let parsed =
        serde_json::from_value::<results::WalletSyncPhase>(json!("a_phase_from_a_newer_node"))
            .unwrap();

    assert_eq!(
        parsed.unrecognized_token(),
        Some("a_phase_from_a_newer_node")
    );
    assert!(!parsed.is_recognized());
    assert_eq!(parsed.as_wire(), "a_phase_from_a_newer_node");
    assert_eq!(
        serde_json::to_value(&parsed).unwrap(),
        json!("a_phase_from_a_newer_node"),
        "re-encoding must hand back the node's own token, never a placeholder"
    );

    // Every KNOWN phase reports no unrecognised token, so a consumer branching on the accessor
    // cannot mistake a phase it understands for one it does not.
    for phase in results::WalletSyncPhase::ALL {
        assert_eq!(phase.unrecognized_token(), None, "{phase:?}");
        assert!(phase.is_recognized(), "{phase:?}");
    }
}

/// **A phase is only ever a STRING.** Tolerating an unknown token must not slide into tolerating an
/// unknown SHAPE: a number, an object, or a null where a phase belongs is a malformed response, and
/// swallowing it as `Unrecognized` would let a genuinely broken payload read as a newer node.
#[test]
fn a_non_string_phase_is_still_a_type_error() {
    for malformed in [
        json!(3),
        json!(null),
        json!({"phase": "synced"}),
        json!(["synced"]),
    ] {
        assert!(
            serde_json::from_value::<results::WalletSyncPhase>(malformed.clone()).is_err(),
            "{malformed} is a malformed phase, not an unrecognised one"
        );
    }
}

/// **A payload from a node that predates `watched_addresses` still parses.** This is
/// dig_ecosystem#2609 in mirror image — a required new field would make every older node unreadable
/// to a client that has it, the same fail-closed break with the two sides swapped.
///
/// The absent field decodes to `None`, which means *the node did not report it* and NOT `Some(0)`.
/// Collapsing the two would have an old node silently assert that it watches no addresses, which is
/// the affirmative all-clear this whole family exists to stop being emitted by accident.
#[test]
fn a_payload_without_watched_addresses_parses_as_unreported() {
    let legacy = serde_json::from_value::<results::WalletSyncStatusResult>(json!({
        "phase": "synced", "peak_height": 5_000_000u32, "chia_peer_count": 5u32
    }))
    .expect("a node predating the field must stay readable");

    assert_eq!(
        legacy.watched_addresses, None,
        "absent means unreported; Some(0) would be a measurement the node never made"
    );
    assert_eq!(legacy.phase, results::WalletSyncPhase::Synced);
    assert_eq!(legacy.peak_height, Some(5_000_000));

    // An explicit null says the same thing as an absent key: the node cannot report the number.
    let explicit_null = serde_json::from_value::<results::WalletSyncStatusResult>(json!({
        "phase": "synced", "peak_height": 5_000_000u32, "chia_peer_count": 5u32,
        "watched_addresses": null
    }))
    .unwrap();
    assert_eq!(explicit_null, legacy);
}

/// **`phase` is the one structurally mandatory field; every count decodes absence as unreported.**
///
/// Pins the real serde behaviour rather than an assumed one. `Option` fields have ALWAYS tolerated a
/// missing key here — `watched_addresses` needed no attribute to gain the property, and
/// `peak_height` and `chia_peer_count` have had it since this type shipped. The test exists because
/// the opposite was assumed while adding the new field, and a doc-comment asserting the three
/// original fields were required would have been simply false.
///
/// The value of pinning it: an absent count MUST decode to `None`, never to `Some(0)`. A truncated
/// response that read as a measured zero would be an affirmative claim the node never made.
#[test]
fn phase_is_required_and_absent_counts_decode_as_unreported() {
    let mut without_phase = json!({
        "peak_height": 5_000_000u32, "chia_peer_count": 5u32, "watched_addresses": 12u32
    });
    assert!(
        serde_json::from_value::<results::WalletSyncStatusResult>(without_phase.take()).is_err(),
        "a response with no phase is malformed — there is no honest default for it"
    );

    for missing in ["peak_height", "chia_peer_count", "watched_addresses"] {
        let mut payload = json!({
            "phase": "synced", "peak_height": 5_000_000u32, "chia_peer_count": 5u32,
            "watched_addresses": 12u32
        });
        payload.as_object_mut().unwrap().remove(missing);

        let parsed = serde_json::from_value::<results::WalletSyncStatusResult>(payload)
            .unwrap_or_else(|e| panic!("`{missing}` absent must stay readable: {e}"));
        let decoded = serde_json::to_value(&parsed).unwrap();

        assert_eq!(
            decoded[missing],
            json!(null),
            "`{missing}` absent must decode as unreported, never as a measured zero"
        );
    }
}

/// **The two idle phases are different values, and the count cannot tell them apart.** The fixture
/// varies ONLY the phase, holding `watched_addresses` at the `0` both states share, so an
/// implementation that folded "no wallet" and "wallet not unlocked" into one nothing-to-watch token
/// — the exact conflation dig_ecosystem#2609's fix nearly shipped — cannot pass.
#[test]
fn no_wallet_enrolled_is_distinguishable_from_a_wallet_that_is_not_unlocked() {
    let no_wallet = results::WalletSyncStatusResult {
        phase: results::WalletSyncPhase::NoWalletEnrolled,
        peak_height: None,
        chia_peer_count: Some(2),
        watched_addresses: Some(0),
    };
    // Inherits `watched_addresses: Some(0)` from the fixture above: the two states genuinely SHARE
    // the count, and only the phase differs. Setting it again here would weaken the claim.
    let locked = results::WalletSyncStatusResult {
        phase: results::WalletSyncPhase::WalletNotUnlocked,
        ..no_wallet.clone()
    };

    assert_ne!(no_wallet, locked);
    assert_ne!(
        serde_json::to_value(&no_wallet).unwrap(),
        serde_json::to_value(&locked).unwrap(),
        "an enrolled-but-unwatched wallet must not wear the all-clear's wire shape"
    );
    assert_eq!(
        serde_json::to_value(&locked).unwrap()["phase"],
        json!("wallet_not_unlocked")
    );
}

/// **Only two phases may be rendered as settled, and the compiler decides which.**
///
/// `Synced` and `NoWalletEnrolled` are the complete pictures. Everything else has something
/// outstanding, and `WalletNotUnlocked` most of all — a wallet exists and nothing is following it,
/// which is the one idle state that must never wear a green tick.
///
/// Pinned against a literal table rather than by calling the method on itself, so an implementation
/// that widened the predicate to "any idle phase" — the nearest wrong one, and the conflation this
/// family exists to prevent — fails here.
#[test]
fn only_a_complete_picture_may_render_as_settled() {
    let expected = [
        (results::WalletSyncPhase::NotStarted, false),
        (results::WalletSyncPhase::Syncing, false),
        (results::WalletSyncPhase::Synced, true),
        (results::WalletSyncPhase::NoWalletEnrolled, true),
        (results::WalletSyncPhase::WalletNotUnlocked, false),
    ];
    for (phase, settled) in &expected {
        assert_eq!(
            phase.may_render_as_settled(),
            *settled,
            "{phase:?} is on the wrong side of the settled line"
        );
    }
    assert_eq!(
        expected.len(),
        results::WalletSyncPhase::ALL.len(),
        "every known phase must be classified here"
    );

    // A phase this build cannot interpret is never settled: it has no idea what the node meant.
    for unknown in ["a_newer_token", "", "settled", "no_addresses_to_watch"] {
        assert!(
            !results::WalletSyncPhase::from(unknown).may_render_as_settled(),
            "{unknown:?} must not be settled — this build cannot know what it means"
        );
    }
}

/// **A token cannot forge a log line or a label.** The raw accessor stays raw for relaying, and both
/// display paths escape.
///
/// The fixture is the concrete attack: `ESC [ 2 K` erases the current terminal line and `\r` returns
/// the cursor, so `format!("unknown phase: {token}")` rendered RAW prints a line reading `synced` —
/// the prefix that said it was unknown is gone. A right-to-left override does the same to a UI
/// label. Both are node-supplied, and this contract's whole subject is a consumer not asserting
/// something false about a wallet.
#[test]
fn a_token_cannot_forge_a_log_line() {
    let hostile = "\u{1b}[2K\rsynced\u{202e}";
    let phase = results::WalletSyncPhase::from(hostile);
    let token = phase
        .unrecognized_token_value()
        .expect("a hostile token is not a known phase");

    // The RAW accessor is deliberately unchanged: a relay must hand on the exact bytes.
    assert_eq!(token.as_str(), hostile);
    assert_eq!(phase.as_wire(), hostile, "the wire form stays verbatim");

    // Every DISPLAY path escapes. No bare ESC, CR or bidi override survives.
    for rendered in [token.to_string(), token.display_bounded(200)] {
        for forbidden in ['\u{1b}', '\r', '\u{202e}'] {
            assert!(
                !rendered.contains(forbidden),
                "{forbidden:?} survived into a display rendering: {rendered:?}"
            );
        }
        assert!(
            rendered.contains("synced"),
            "escaping must stay legible, not redact"
        );
    }
}

/// **A bounded rendering is bounded, and says when it dropped something.**
///
/// Nothing caps a token's length on the wire — the contract is transport-agnostic, and rejecting an
/// over-long token would put back the fail-closed parse this type exists to remove — so the bound
/// lives at the point of display. A truncated rendering that looked complete would be its own small
/// lie, hence the marker.
#[test]
fn a_bounded_rendering_is_bounded_and_marked() {
    let long = results::WalletSyncPhase::from("a".repeat(10_000).as_str());
    let token = long.unrecognized_token_value().unwrap();

    let rendered = token.display_bounded(32);
    assert!(
        rendered.trim_end_matches('').len() <= 32,
        "escaped content must respect the bound: {} bytes",
        rendered.len()
    );
    assert!(rendered.ends_with(''), "a truncated rendering must say so");

    // A token that FITS is not marked, so the marker means something.
    let short = results::WalletSyncPhase::from("a_newer_token");
    let short_token = short.unrecognized_token_value().unwrap();
    assert_eq!(short_token.display_bounded(64), "a_newer_token");
    assert!(!short_token.display_bounded(64).ends_with(''));

    // The pathological inputs, PINNED rather than proven once by hand. The bound is computed on the
    // ESCAPED bytes, and a control character expands about sixfold, so expansion is the case a naive
    // implementation overshoots on -- while slicing the raw string instead would panic on a char
    // boundary in the multi-byte rows below.
    for (raw, max) in [
        ("", 0usize),
        ("\u{1b}\u{1b}\u{1b}", 0),
        ("\u{1b}\u{1b}\u{1b}", 5),
        ("\u{1b}\u{1b}\u{1b}", 6),
        ("\u{1f600}\u{1f600}", 1),
        ("\u{1f600}\u{1f600}", 4),
        ("\u{202e}abc", 3),
        ("\u{7f}\u{9b}", 32),
    ] {
        let phase = results::WalletSyncPhase::from(raw);
        let Some(token) = phase.unrecognized_token_value() else {
            continue;
        };
        let rendered = token.display_bounded(max);

        assert!(
            rendered.trim_end_matches('').len() <= max,
            "{raw:?} at max={max} rendered {rendered:?}, over the bound"
        );
        for forbidden in ['\u{1b}', '\r', '\u{202e}', '\u{7f}', '\u{9b}'] {
            assert!(
                !rendered.contains(forbidden) && !token.to_string().contains(forbidden),
                "{forbidden:?} survived rendering of {raw:?}"
            );
        }
    }
}