bsv-wallet-cli 0.2.2

Self-hosted BSV wallet CLI and BRC-100 server, wire-compatible with MetaNet Client
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
//! Integration tests for all 28 WalletInterface HTTP endpoints.
//!
//! These tests spin up a real HTTP server with a fresh wallet backed by
//! a temporary SQLite database. They exercise every endpoint and verify
//! the response shape.

use bsv_sdk::primitives::PrivateKey;
use bsv_wallet_cli::server::{self, ServerConfig};
use bsv_wallet_toolbox::{
    Chain, Services, ServicesOptions, StorageSqlx, Wallet, WalletStorageWriter,
};
use reqwest::Client;
use serde_json::{json, Value};
use std::net::SocketAddr;
use tempfile::TempDir;

/// Spin up a server on a random port, return the base URL and a reqwest client.
async fn setup() -> (String, Client, TempDir) {
    let tmp = TempDir::new().expect("temp dir");
    let db_path = tmp.path().join("test.db");

    let storage = StorageSqlx::open(db_path.to_str().unwrap())
        .await
        .expect("open db");

    let key = PrivateKey::random();
    let identity_key = key.public_key().to_hex();
    storage
        .migrate("bsv-wallet-test", &identity_key)
        .await
        .expect("migrate db");
    storage.make_available().await.expect("make available");

    let services = {
        let mut opts = ServicesOptions::mainnet();
        if let Ok(url) = std::env::var("CHAINTRACKS_URL") {
            opts = opts.with_chaintracks_url(url);
        }
        Services::with_options(Chain::Main, opts).expect("services")
    };
    let wallet = Wallet::new(Some(key), storage, services)
        .await
        .expect("wallet");

    let state = server::make_wallet_state(wallet);
    let app = server::make_router(state, ServerConfig::default());

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind");
    let addr: SocketAddr = listener.local_addr().expect("local addr");
    tokio::spawn(async move {
        axum::serve(listener, app).await.ok();
    });

    let base = format!("http://{}", addr);
    let client = Client::new();
    (base, client, tmp)
}

/// Helper: POST JSON with Origin header
async fn post_json(client: &Client, url: &str, body: Value) -> reqwest::Response {
    client
        .post(url)
        .header("Origin", "http://test.local")
        .json(&body)
        .send()
        .await
        .expect("request failed")
}

/// Helper: POST and assert 200, printing error body on failure
async fn post_json_ok(client: &Client, url: &str, body: Value) -> Value {
    let resp = post_json(client, url, body).await;
    let status = resp.status();
    let body: Value = resp.json().await.unwrap();
    assert_eq!(status, 200, "endpoint returned {}: {:?}", status, body);
    body
}

// =============================================================================
// Batch 1: Status (GET)
// =============================================================================

#[tokio::test]
async fn test_is_authenticated() {
    let (base, client, _tmp) = setup().await;
    let resp = client
        .get(format!("{base}/isAuthenticated"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["authenticated"], true);
}

#[tokio::test]
async fn test_get_height() {
    let (base, client, _tmp) = setup().await;
    let resp = client
        .get(format!("{base}/getHeight"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert!(body["height"].is_number(), "height should be a number");
}

#[tokio::test]
async fn test_get_network() {
    let (base, client, _tmp) = setup().await;
    let resp = client
        .get(format!("{base}/getNetwork"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["network"], "mainnet");
}

#[tokio::test]
async fn test_get_version() {
    let (base, client, _tmp) = setup().await;
    let resp = client
        .get(format!("{base}/getVersion"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert!(body["version"].is_string(), "version should be a string");
}

#[tokio::test]
async fn test_wait_for_authentication() {
    let (base, client, _tmp) = setup().await;
    let resp = client
        .get(format!("{base}/waitForAuthentication"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["authenticated"], true);
}

// =============================================================================
// Batch 2: Header
// =============================================================================

#[tokio::test]
async fn test_get_header_for_height() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/getHeaderForHeight"),
        json!({"height": 1}),
    )
    .await;
    let status = resp.status().as_u16();
    if std::env::var("CHAINTRACKS_URL").is_ok() {
        // With Chaintracks configured, expect 200 and a hex header
        assert_eq!(status, 200, "expected 200 with CHAINTRACKS_URL set");
        let body: Value = resp.json().await.unwrap();
        let header = body["header"].as_str().expect("header should be string");
        assert_eq!(header.len(), 160, "80-byte header = 160 hex chars");
    } else {
        // Without Chaintracks, the endpoint may return 400 or 502 (service error)
        assert!(
            status == 200 || status == 400 || status == 502,
            "unexpected status: {}",
            status
        );
    }
}

// =============================================================================
// Batch 3: Crypto
// =============================================================================

#[tokio::test]
async fn test_get_public_key_identity() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/getPublicKey"),
        json!({"identityKey": true}),
    )
    .await;
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["publicKey"].is_string(),
        "publicKey should be a hex string"
    );
}

#[tokio::test]
async fn test_encrypt_decrypt_roundtrip() {
    let (base, client, _tmp) = setup().await;
    let plaintext: Vec<u8> = b"hello world".to_vec();

    // Encrypt
    let body = post_json_ok(
        &client,
        &format!("{base}/encrypt"),
        json!({
            "plaintext": plaintext,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let ciphertext = body["ciphertext"].as_array().expect("ciphertext array");
    assert!(!ciphertext.is_empty(), "ciphertext should not be empty");

    // Decrypt
    let body = post_json_ok(
        &client,
        &format!("{base}/decrypt"),
        json!({
            "ciphertext": ciphertext,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let decrypted: Vec<u8> = body["plaintext"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_u64().unwrap() as u8)
        .collect();
    assert_eq!(decrypted, plaintext);
}

#[tokio::test]
async fn test_create_verify_signature_roundtrip() {
    let (base, client, _tmp) = setup().await;
    let data: Vec<u8> = b"sign this".to_vec();

    // Create signature
    let body = post_json_ok(
        &client,
        &format!("{base}/createSignature"),
        json!({
            "data": data,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let signature = body["signature"].as_array().expect("signature array");

    // Verify signature
    let body = post_json_ok(
        &client,
        &format!("{base}/verifySignature"),
        json!({
            "data": data,
            "signature": signature,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone",
            "forSelf": true
        }),
    )
    .await;
    assert_eq!(body["valid"], true);
}

#[tokio::test]
async fn test_create_verify_hmac_roundtrip() {
    let (base, client, _tmp) = setup().await;
    let data: Vec<u8> = b"hmac this".to_vec();

    // Create HMAC
    let body = post_json_ok(
        &client,
        &format!("{base}/createHmac"),
        json!({
            "data": data,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let hmac = body["hmac"].as_array().expect("hmac array");
    assert_eq!(hmac.len(), 32, "HMAC should be 32 bytes");

    // Verify HMAC
    let body = post_json_ok(
        &client,
        &format!("{base}/verifyHmac"),
        json!({
            "data": data,
            "hmac": hmac,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    assert_eq!(body["valid"], true);
}

// =============================================================================
// Batch 4: Transaction Workflow
// =============================================================================

#[tokio::test]
async fn test_list_actions_empty() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/listActions"),
        json!({"labels": ["test"]}),
    )
    .await;
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["totalActions"], 0);
    assert!(body["actions"].is_array());
}

#[tokio::test]
async fn test_list_outputs_empty() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/listOutputs"),
        json!({"basket": "default"}),
    )
    .await;
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["totalOutputs"], 0);
    assert!(body["outputs"].is_array());
}

// =============================================================================
// Batch 5: Certificates
// =============================================================================

#[tokio::test]
async fn test_list_certificates_empty() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/listCertificates"),
        json!({"certifiers": [], "types": []}),
    )
    .await;
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["totalCertificates"], 0);
    assert!(body["certificates"].is_array());
}

// =============================================================================
// Batch 6: Discovery
// =============================================================================

#[tokio::test]
async fn test_discover_by_identity_key() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/discoverByIdentityKey"),
        json!({"identityKey": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"}),
    )
    .await;
    assert_eq!(
        body["totalCertificates"], 0,
        "fresh wallet should have 0 certificates"
    );
    assert!(
        body["certificates"].as_array().unwrap().is_empty(),
        "certificates should be empty"
    );
}

/// Discovery with invalid identity key still returns 200 with empty results (endpoint is lenient).
#[tokio::test]
async fn test_discover_by_identity_key_invalid() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/discoverByIdentityKey"),
        json!({"identityKey": "not-a-valid-pubkey"}),
    )
    .await;
    assert_eq!(
        body["totalCertificates"], 0,
        "invalid key should return 0 certificates"
    );
    assert!(body["certificates"].as_array().unwrap().is_empty());
}

#[tokio::test]
async fn test_discover_by_attributes() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/discoverByAttributes"),
        json!({"attributes": {"name": "test"}}),
    )
    .await;
    assert_eq!(
        body["totalCertificates"], 0,
        "fresh wallet should have 0 certificates"
    );
    assert!(
        body["certificates"].as_array().unwrap().is_empty(),
        "certificates should be empty"
    );
}

#[tokio::test]
async fn test_discover_by_attributes_empty() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/discoverByAttributes"),
        json!({"attributes": {}}),
    )
    .await;
    assert_eq!(body["totalCertificates"], 0);
    assert!(body["certificates"].as_array().unwrap().is_empty());
}

// =============================================================================
// Batch 7: Edge-case tests for production confidence
// =============================================================================

/// Encrypt with counterparty "self" and decrypt with counterparty "self".
/// This is the most common production pattern: a user storing their own encrypted data.
#[tokio::test]
async fn test_encrypt_decrypt_self_counterparty() {
    let (base, client, _tmp) = setup().await;
    let plaintext: Vec<u8> = b"my secret vault data".to_vec();

    // Encrypt with counterparty "self"
    let body = post_json_ok(
        &client,
        &format!("{base}/encrypt"),
        json!({
            "plaintext": plaintext,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "self"
        }),
    )
    .await;
    let ciphertext = body["ciphertext"].as_array().expect("ciphertext array");
    assert!(!ciphertext.is_empty(), "ciphertext should not be empty");

    // Decrypt with counterparty "self"
    let body = post_json_ok(
        &client,
        &format!("{base}/decrypt"),
        json!({
            "ciphertext": ciphertext,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "self"
        }),
    )
    .await;
    let decrypted: Vec<u8> = body["plaintext"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_u64().unwrap() as u8)
        .collect();
    assert_eq!(
        decrypted, plaintext,
        "self-encrypted data should round-trip"
    );
}

/// Encrypt and decrypt a 10KB payload to verify large data handling.
#[tokio::test]
async fn test_encrypt_decrypt_large_payload() {
    let (base, client, _tmp) = setup().await;
    // 10KB of repeating pattern bytes
    let plaintext: Vec<u8> = (0..10240).map(|i| (i % 256) as u8).collect();

    // Encrypt
    let body = post_json_ok(
        &client,
        &format!("{base}/encrypt"),
        json!({
            "plaintext": plaintext,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let ciphertext = body["ciphertext"].as_array().expect("ciphertext array");
    assert!(
        ciphertext.len() >= plaintext.len(),
        "ciphertext should be at least as large as plaintext"
    );

    // Decrypt
    let body = post_json_ok(
        &client,
        &format!("{base}/decrypt"),
        json!({
            "ciphertext": ciphertext,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let decrypted: Vec<u8> = body["plaintext"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_u64().unwrap() as u8)
        .collect();
    assert_eq!(decrypted.len(), 10240, "decrypted length should be 10KB");
    assert_eq!(
        decrypted, plaintext,
        "large payload should round-trip exactly"
    );
}

/// Send garbage ciphertext to /decrypt and verify it returns 400, not a panic/500.
#[tokio::test]
async fn test_encrypt_bad_ciphertext_returns_error() {
    let (base, client, _tmp) = setup().await;
    let garbage: Vec<u8> = vec![0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02, 0x03, 0x04];

    let resp = post_json(
        &client,
        &format!("{base}/decrypt"),
        json!({
            "ciphertext": garbage,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    assert_eq!(
        resp.status(),
        400,
        "garbage ciphertext should return 400, got {}",
        resp.status()
    );
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["message"].is_string(),
        "error response should have a message field"
    );
}

/// Create a signature for data A, then verify against data B.
/// The wallet returns 400 with an error message indicating the signature is not valid.
#[tokio::test]
async fn test_verify_signature_wrong_data_returns_invalid() {
    let (base, client, _tmp) = setup().await;
    let data_a: Vec<u8> = b"original data".to_vec();
    let data_b: Vec<u8> = b"different data".to_vec();

    // Create signature over data_a
    let body = post_json_ok(
        &client,
        &format!("{base}/createSignature"),
        json!({
            "data": data_a,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let signature = body["signature"].as_array().expect("signature array");

    // Verify signature against data_b — should fail (400 with error message)
    let resp = post_json(
        &client,
        &format!("{base}/verifySignature"),
        json!({
            "data": data_b,
            "signature": signature,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone",
            "forSelf": true
        }),
    )
    .await;
    assert_eq!(
        resp.status(),
        400,
        "signature verified against wrong data should return 400"
    );
    let body: Value = resp.json().await.unwrap();
    let message = body["message"].as_str().unwrap_or("");
    assert!(
        message.to_lowercase().contains("not valid") || message.to_lowercase().contains("invalid"),
        "error should indicate invalid signature, got: {message}"
    );
}

/// Create an HMAC for data A, then verify against data B.
/// The wallet returns 400 with an error message indicating the HMAC is not valid.
#[tokio::test]
async fn test_verify_hmac_wrong_data_returns_invalid() {
    let (base, client, _tmp) = setup().await;
    let data_a: Vec<u8> = b"original hmac data".to_vec();
    let data_b: Vec<u8> = b"different hmac data".to_vec();

    // Create HMAC over data_a
    let body = post_json_ok(
        &client,
        &format!("{base}/createHmac"),
        json!({
            "data": data_a,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let hmac = body["hmac"].as_array().expect("hmac array");

    // Verify HMAC against data_b — should fail (400 with error message)
    let resp = post_json(
        &client,
        &format!("{base}/verifyHmac"),
        json!({
            "data": data_b,
            "hmac": hmac,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    assert_eq!(
        resp.status(),
        400,
        "HMAC verified against wrong data should return 400"
    );
    let body: Value = resp.json().await.unwrap();
    let message = body["message"].as_str().unwrap_or("");
    assert!(
        message.to_lowercase().contains("not valid") || message.to_lowercase().contains("invalid"),
        "error should indicate invalid HMAC, got: {message}"
    );
}

/// POST to /encrypt WITHOUT an Origin header. Should return 400 with "Origin header required".
#[tokio::test]
async fn test_encrypt_missing_origin_returns_400() {
    let (base, client, _tmp) = setup().await;
    let plaintext: Vec<u8> = b"test".to_vec();

    // Send request WITHOUT Origin header (do not use post_json helper which adds it)
    let resp = client
        .post(format!("{base}/encrypt"))
        .json(&json!({
            "plaintext": plaintext,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }))
        .send()
        .await
        .expect("request failed");

    assert_eq!(
        resp.status(),
        400,
        "missing Origin should return 400, got {}",
        resp.status()
    );
    let body: Value = resp.json().await.unwrap();
    let message = body["message"].as_str().unwrap_or("");
    assert!(
        message.contains("Origin header required"),
        "error message should mention Origin header, got: {message}"
    );
}

// =============================================================================
// Batch 8: Transaction workflow — createAction, signAction, abortAction,
//          relinquishOutput, internalizeAction
// =============================================================================

/// POST /createAction with outputs but no funding — should return 400.
#[tokio::test]
async fn test_create_action_insufficient_funds() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "test unfunded action",
            "outputs": [{
                "lockingScript": "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac",
                "satoshis": 1000,
                "outputDescription": "test output"
            }]
        }),
    )
    .await;
    let status = resp.status().as_u16();
    let body: Value = resp.json().await.unwrap();
    // Insufficient funds → 402, other wallet errors → 400
    assert!(
        status == 402 || status == 400,
        "unfunded wallet creating action with outputs should return 402 or 400, got {}: {:?}",
        status,
        body
    );
    assert!(
        body["message"].is_string(),
        "error should have message field"
    );
}

/// POST /signAction with invalid reference — should return 400.
#[tokio::test]
async fn test_sign_action_invalid_reference() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/signAction"),
        json!({
            "spends": {},
            "reference": "nonexistent-reference-abc123"
        }),
    )
    .await;
    assert_eq!(
        resp.status(),
        400,
        "invalid signAction reference should return 400"
    );
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["message"].is_string(),
        "error should have message field"
    );
}

/// POST /abortAction with invalid reference — should return 400.
#[tokio::test]
async fn test_abort_action_invalid_reference() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/abortAction"),
        json!({
            "reference": "nonexistent-reference-abc123"
        }),
    )
    .await;
    let status = resp.status().as_u16();
    let body: Value = resp.json().await.unwrap();
    // Invalid reference → 404 (not found) or 400 depending on error message
    assert!(
        status == 400 || status == 404,
        "invalid abortAction reference should return 400 or 404, got {}: {:?}",
        status,
        body
    );
    assert!(
        body["message"].is_string(),
        "error should have message field"
    );
}

/// POST /relinquishOutput with nonexistent output — wallet returns 200 with relinquished: false.
#[tokio::test]
async fn test_relinquish_output_nonexistent() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/relinquishOutput"),
        json!({
            "basket": "default",
            "output": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef.0"
        }),
    )
    .await;
    // Nonexistent output: wallet may return relinquished: false or true (no-op)
    assert!(
        body["relinquished"].is_boolean(),
        "response should have relinquished boolean, got: {:?}",
        body
    );
}

/// POST /internalizeAction with garbage tx — should return 400.
#[tokio::test]
async fn test_internalize_action_invalid_tx() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/internalizeAction"),
        json!({
            "tx": [0xDE, 0xAD, 0xBE, 0xEF],
            "outputs": [{
                "outputIndex": 0,
                "protocol": "wallet payment",
                "paymentRemittance": {
                    "derivationPrefix": "test",
                    "derivationSuffix": "test",
                    "senderIdentityKey": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
                }
            }],
            "description": "test invalid internalize"
        }),
    )
    .await;
    assert_eq!(resp.status(), 400, "garbage tx should return 400");
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["message"].is_string(),
        "error should have message field"
    );
}

// =============================================================================
// Batch 9: Certificates — acquireCertificate, proveCertificate,
//          relinquishCertificate
// =============================================================================

/// Full certificate lifecycle: acquire → list (find it) → relinquish → list (verify gone).
/// All operations are DB-only — no chain interaction or funding needed.
#[tokio::test]
async fn test_certificate_full_lifecycle() {
    let (base, client, _tmp) = setup().await;
    let cert_type = "dGVzdA=="; // base64("test")
    let certifier = "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";

    // Step 1: Acquire certificate (direct protocol)
    let cert = post_json_ok(
        &client,
        &format!("{base}/acquireCertificate"),
        json!({
            "certificateType": cert_type,
            "certifier": certifier,
            "acquisitionProtocol": "direct",
            "fields": {"name": "test"},
            "serialNumber": "AQID",
            "revocationOutpoint": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef.0",
            "signature": "deadbeef",
            "keyringRevealer": "certifier",
            "keyringForSubject": {}
        }),
    )
    .await;
    assert!(
        cert["certificateType"].is_string(),
        "should have certificateType"
    );
    assert!(cert["certifier"].is_string(), "should have certifier");
    assert!(cert["subject"].is_string(), "should have subject");
    let serial = cert["serialNumber"]
        .as_str()
        .expect("cert should have serialNumber");

    // Step 2: List certificates — should find our cert
    let list = post_json_ok(
        &client,
        &format!("{base}/listCertificates"),
        json!({
            "certifiers": [certifier],
            "types": [cert_type]
        }),
    )
    .await;
    assert!(
        list["totalCertificates"].as_u64().unwrap() >= 1,
        "should find at least 1 certificate after acquisition"
    );
    let certs = list["certificates"].as_array().expect("certificates array");
    // Each entry has { certificate: { serialNumber, ... }, verifier: "..." }
    assert!(
        certs
            .iter()
            .any(|c| c["certificate"]["serialNumber"].as_str() == Some(serial)),
        "listed certificates should include our acquired cert (serial={})",
        serial
    );

    // Step 3: Relinquish the certificate
    let relinquish = post_json_ok(
        &client,
        &format!("{base}/relinquishCertificate"),
        json!({
            "certificateType": cert_type,
            "serialNumber": serial,
            "certifier": certifier
        }),
    )
    .await;
    assert_eq!(
        relinquish["relinquished"], true,
        "certificate should be relinquished successfully"
    );

    // Step 4: List again — cert should be gone
    let list2 = post_json_ok(
        &client,
        &format!("{base}/listCertificates"),
        json!({
            "certifiers": [certifier],
            "types": [cert_type]
        }),
    )
    .await;
    assert_eq!(
        list2["totalCertificates"].as_u64().unwrap(),
        0,
        "certificate count should be 0 after relinquishing"
    );
}

/// POST /proveCertificate with a made-up certificate — should return 400.
#[tokio::test]
async fn test_prove_certificate_not_found() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/proveCertificate"),
        json!({
            "certificate": {
                "certificateType": "dGVzdA==",
                "subject": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
                "serialNumber": "AQID",
                "certifier": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
                "revocationOutpoint": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef.0",
                "signature": "deadbeef",
                "fields": {"name": "test"}
            },
            "fieldsToReveal": ["name"],
            "verifier": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
        }),
    )
    .await;
    assert_eq!(
        resp.status(),
        400,
        "proving nonexistent cert should return 400"
    );
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["message"].is_string(),
        "error should have message field"
    );
}

/// POST /relinquishCertificate with nonexistent cert — wallet returns 200 with relinquished: false.
#[tokio::test]
async fn test_relinquish_certificate_not_found() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/relinquishCertificate"),
        json!({
            "certificateType": "dGVzdA==",
            "serialNumber": "AQID",
            "certifier": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
        }),
    )
    .await;
    assert!(
        body["relinquished"].is_boolean(),
        "response should have relinquished boolean, got: {:?}",
        body
    );
}

// =============================================================================
// Batch 10: Key Linkage — revealCounterpartyKeyLinkage,
//           revealSpecificKeyLinkage
// =============================================================================

/// POST /revealCounterpartyKeyLinkage with valid pubkeys — returns 200 with linkage object.
#[tokio::test]
async fn test_reveal_counterparty_key_linkage() {
    let (base, client, _tmp) = setup().await;
    let test_key = "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
    let body = post_json_ok(
        &client,
        &format!("{base}/revealCounterpartyKeyLinkage"),
        json!({
            "counterparty": test_key,
            "verifier": test_key
        }),
    )
    .await;
    let linkage = body
        .get("linkage")
        .expect("response should have linkage object");
    assert!(
        linkage["encryptedLinkage"].is_string(),
        "linkage should have encryptedLinkage"
    );
    assert!(
        linkage["encryptedLinkageProof"].is_string(),
        "linkage should have encryptedLinkageProof"
    );
    assert!(linkage["prover"].is_string(), "linkage should have prover");
    assert!(
        linkage["verifier"].is_string(),
        "linkage should have verifier"
    );
    assert!(
        linkage["counterparty"].is_string(),
        "linkage should have counterparty"
    );
    assert!(
        body["revelationTime"].is_string(),
        "response should have revelationTime"
    );
}

/// POST /revealCounterpartyKeyLinkage with invalid pubkey — returns 400.
#[tokio::test]
async fn test_reveal_counterparty_key_linkage_invalid_key() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/revealCounterpartyKeyLinkage"),
        json!({
            "counterparty": "not-a-valid-pubkey",
            "verifier": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
        }),
    )
    .await;
    assert_eq!(
        resp.status(),
        400,
        "invalid counterparty key should return 400"
    );
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["message"].is_string(),
        "error should have message field"
    );
}

/// POST /revealSpecificKeyLinkage with valid pubkeys and protocol — returns 200.
#[tokio::test]
async fn test_reveal_specific_key_linkage() {
    let (base, client, _tmp) = setup().await;
    let test_key = "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
    let body = post_json_ok(
        &client,
        &format!("{base}/revealSpecificKeyLinkage"),
        json!({
            "counterparty": test_key,
            "verifier": test_key,
            "protocolID": [2, "tests"],
            "keyID": "1"
        }),
    )
    .await;
    let linkage = body
        .get("linkage")
        .expect("response should have linkage object");
    assert!(
        linkage["encryptedLinkage"].is_string(),
        "linkage should have encryptedLinkage"
    );
    assert!(
        linkage["encryptedLinkageProof"].is_string(),
        "linkage should have encryptedLinkageProof"
    );
    assert!(linkage["prover"].is_string(), "linkage should have prover");
    assert!(
        linkage["verifier"].is_string(),
        "linkage should have verifier"
    );
    assert!(
        body.get("protocol").is_some(),
        "response should have protocol"
    );
}

/// POST /revealSpecificKeyLinkage with invalid pubkey — returns 400.
#[tokio::test]
async fn test_reveal_specific_key_linkage_invalid_key() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/revealSpecificKeyLinkage"),
        json!({
            "counterparty": "not-a-valid-pubkey",
            "verifier": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
            "protocolID": [2, "tests"],
            "keyID": "1"
        }),
    )
    .await;
    assert_eq!(
        resp.status(),
        400,
        "invalid counterparty key should return 400"
    );
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["message"].is_string(),
        "error should have message field"
    );
}

// =============================================================================
// Batch 11: Edge-case tests for production confidence
// =============================================================================

/// Get a derived public key (with protocolID, keyID, counterparty) and verify
/// it differs from the identity key.
#[tokio::test]
async fn test_get_public_key_derived() {
    let (base, client, _tmp) = setup().await;

    // Get identity key
    let identity_body = post_json_ok(
        &client,
        &format!("{base}/getPublicKey"),
        json!({"identityKey": true}),
    )
    .await;
    let identity_key = identity_body["publicKey"]
        .as_str()
        .expect("identity publicKey should be a string");

    // Get derived key with protocol, keyID, and counterparty
    let derived_body = post_json_ok(
        &client,
        &format!("{base}/getPublicKey"),
        json!({
            "identityKey": false,
            "protocolID": [2, "tests"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let derived_key = derived_body["publicKey"]
        .as_str()
        .expect("derived publicKey should be a string");

    // The derived key must be a valid compressed public key (66 hex chars starting with 02 or 03)
    assert_eq!(
        derived_key.len(),
        66,
        "derived key should be 66 hex characters (compressed pubkey)"
    );
    assert!(
        derived_key.starts_with("02") || derived_key.starts_with("03"),
        "derived key should start with 02 or 03, got: {}",
        &derived_key[..4]
    );

    // The derived key should differ from the identity key
    assert_ne!(
        identity_key, derived_key,
        "derived key should differ from identity key"
    );
}

// =============================================================================
// Batch 12: Additional coverage — non-default baskets, pagination,
//           labelQueryMode, createAction options passthrough
// =============================================================================

/// listOutputs with a non-default basket that doesn't exist — returns 200 with empty results (#17).
#[tokio::test]
async fn test_list_outputs_nondefault_basket() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/listOutputs"),
        json!({
            "basket": "worm-proofs",
            "include": "locking scripts",
            "limit": 10,
            "offset": 0
        }),
    )
    .await;
    assert_eq!(
        body["totalOutputs"], 0,
        "non-existent basket should have 0 outputs"
    );
    assert!(
        body["outputs"].as_array().unwrap().is_empty(),
        "outputs should be empty"
    );
}

/// listActions with offset beyond available data — returns 200 with empty results (#18).
/// Note: totalActions includes offset (server quirk), but the actions array is correctly empty.
#[tokio::test]
async fn test_list_actions_pagination() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/listActions"),
        json!({
            "labels": [],
            "labelQueryMode": "any",
            "includeLabels": false,
            "includeInputs": false,
            "includeOutputs": false,
            "limit": 10,
            "offset": 100
        }),
    )
    .await;
    assert!(
        body["totalActions"].is_number(),
        "totalActions should be a number"
    );
    assert!(
        body["actions"].as_array().unwrap().is_empty(),
        "actions should be empty at high offset"
    );
}

/// listOutputs with offset beyond available data — returns 200 with empty results (#18).
/// Note: totalOutputs includes offset (server quirk), but the outputs array is correctly empty.
#[tokio::test]
async fn test_list_outputs_pagination() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/listOutputs"),
        json!({
            "basket": "default",
            "include": "locking scripts",
            "limit": 10,
            "offset": 100
        }),
    )
    .await;
    assert!(
        body["totalOutputs"].is_number(),
        "totalOutputs should be a number"
    );
    assert!(
        body["outputs"].as_array().unwrap().is_empty(),
        "outputs should be empty at high offset"
    );
}

/// listActions with labelQueryMode "all" — accepted and returns well-shaped response (#19).
#[tokio::test]
async fn test_list_actions_label_query_mode_all() {
    let (base, client, _tmp) = setup().await;
    let body = post_json_ok(
        &client,
        &format!("{base}/listActions"),
        json!({
            "labels": ["send", "receive"],
            "labelQueryMode": "all",
            "includeLabels": true,
            "includeInputs": false,
            "includeOutputs": false,
            "limit": 10,
            "offset": 0
        }),
    )
    .await;
    assert_eq!(body["totalActions"], 0);
    assert!(body["actions"].as_array().unwrap().is_empty());
}

/// createAction with noSend option — deserializes correctly (402 not 500) (#20).
#[tokio::test]
async fn test_create_action_with_no_send_option() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "noSend test",
            "outputs": [{
                "lockingScript": "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac",
                "satoshis": 1000,
                "outputDescription": "test"
            }],
            "options": {
                "signAndProcess": true,
                "noSend": true,
                "acceptDelayedBroadcast": false,
                "randomizeOutputs": false
            }
        }),
    )
    .await;
    let status = resp.status().as_u16();
    assert!(
        status == 402 || status == 400,
        "noSend option should deserialize correctly, got {} (500 = deserialization bug)",
        status
    );
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["message"].is_string(),
        "error should have message field"
    );
}

/// createAction with randomizeOutputs option — deserializes correctly (#20).
#[tokio::test]
async fn test_create_action_with_randomize_outputs() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "randomizeOutputs test",
            "outputs": [{
                "lockingScript": "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac",
                "satoshis": 1000,
                "outputDescription": "test"
            }],
            "options": {
                "signAndProcess": true,
                "randomizeOutputs": true
            }
        }),
    )
    .await;
    let status = resp.status().as_u16();
    assert!(
        status == 402 || status == 400,
        "randomizeOutputs option should deserialize correctly, got {}",
        status
    );
}

/// createAction with acceptDelayedBroadcast option — deserializes correctly (#20).
#[tokio::test]
async fn test_create_action_with_accept_delayed_broadcast() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "acceptDelayedBroadcast test",
            "outputs": [{
                "lockingScript": "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac",
                "satoshis": 1000,
                "outputDescription": "test"
            }],
            "options": {
                "signAndProcess": true,
                "acceptDelayedBroadcast": true
            }
        }),
    )
    .await;
    let status = resp.status().as_u16();
    assert!(
        status == 402 || status == 400,
        "acceptDelayedBroadcast option should deserialize correctly, got {}",
        status
    );
}

/// createAction output with customInstructions, basket, and tags — deserializes correctly (#20).
#[tokio::test]
async fn test_create_action_output_custom_instructions() {
    let (base, client, _tmp) = setup().await;
    let resp = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "custom_instructions test",
            "outputs": [{
                "lockingScript": "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac",
                "satoshis": 1000,
                "outputDescription": "test",
                "basket": "worm-proofs",
                "tags": ["test-tag"],
                "customInstructions": "some-instruction-string"
            }]
        }),
    )
    .await;
    let status = resp.status().as_u16();
    assert!(
        status == 402 || status == 400,
        "output fields should deserialize correctly, got {}",
        status
    );
}

// =============================================================================
// E2E tests against a RUNNING real wallet (gated behind WALLET_URL env var).
//
// These tests hit a live `bsv-wallet serve` instance with real chain data
// and a funded wallet. They are safe: deferred-signing actions are always
// aborted, so no sats are spent.
//
// Run:  WALLET_URL=http://localhost:3322 cargo test --test integration e2e_
// =============================================================================

/// Helper: connect to a running wallet server. Returns None if WALLET_URL not set.
fn e2e_setup() -> Option<(String, Client)> {
    let url = std::env::var("WALLET_URL").ok()?;
    Some((url, Client::new()))
}

/// E2E: createAction (signAndProcess:false) → verify signableTransaction → abortAction → listActions.
/// Tests the full deferred signing HTTP flow with a funded wallet without spending any sats.
#[tokio::test]
async fn e2e_create_and_abort_action() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // Step 1: Create an unsigned action with a tiny output (signAndProcess: false)
    let resp = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "e2e test unsigned action",
            "outputs": [{
                "lockingScript": "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac",
                "satoshis": 1,
                "outputDescription": "e2e test output"
            }],
            "labels": ["e2e-test-abort"],
            "options": {
                "signAndProcess": false
            }
        }),
    )
    .await;
    let status = resp.status().as_u16();
    let body: Value = resp.json().await.unwrap();
    assert_eq!(
        status, 200,
        "createAction should succeed on funded wallet: {:?}",
        body
    );

    // Step 2: Verify signableTransaction is present with reference
    let st = body
        .get("signableTransaction")
        .expect("response should have signableTransaction");
    let reference = st["reference"]
        .as_str()
        .expect("signableTransaction should have reference string");
    assert!(!reference.is_empty(), "reference should not be empty");
    assert!(
        st["tx"].is_array(),
        "signableTransaction.tx should be a byte array"
    );

    // Step 3: Abort the unsigned action to release locked UTXOs
    let abort = post_json_ok(
        &client,
        &format!("{base}/abortAction"),
        json!({ "reference": reference }),
    )
    .await;
    assert_eq!(abort["aborted"], true, "abortAction should succeed");

    // Step 4: List actions — the aborted action should appear with failed status
    let list = post_json_ok(
        &client,
        &format!("{base}/listActions"),
        json!({"labels": ["e2e-test-abort"]}),
    )
    .await;
    assert!(
        list["totalActions"].is_number(),
        "listActions should return totalActions"
    );
}

/// E2E: Full crypto round-trip against the real wallet.
/// Proves the production wallet handles encrypt→decrypt and sign→verify correctly.
#[tokio::test]
async fn e2e_crypto_roundtrip() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // Get identity key
    let identity = post_json_ok(
        &client,
        &format!("{base}/getPublicKey"),
        json!({"identityKey": true}),
    )
    .await;
    let identity_key = identity["publicKey"].as_str().expect("identity key");
    assert_eq!(
        identity_key.len(),
        66,
        "identity key should be 66 hex chars"
    );

    // Encrypt with counterparty "self" (most common production pattern)
    let plaintext: Vec<u8> = b"e2e test secret data".to_vec();
    let enc = post_json_ok(
        &client,
        &format!("{base}/encrypt"),
        json!({
            "plaintext": plaintext,
            "protocolID": [2, "e2e test"],
            "keyID": "1",
            "counterparty": "self"
        }),
    )
    .await;
    let ciphertext = enc["ciphertext"].as_array().expect("ciphertext");
    assert!(!ciphertext.is_empty(), "ciphertext should not be empty");

    // Decrypt
    let dec = post_json_ok(
        &client,
        &format!("{base}/decrypt"),
        json!({
            "ciphertext": ciphertext,
            "protocolID": [2, "e2e test"],
            "keyID": "1",
            "counterparty": "self"
        }),
    )
    .await;
    let decrypted: Vec<u8> = dec["plaintext"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_u64().unwrap() as u8)
        .collect();
    assert_eq!(decrypted, plaintext, "decrypt should round-trip");

    // Sign
    let data: Vec<u8> = b"e2e test signature data".to_vec();
    let sig = post_json_ok(
        &client,
        &format!("{base}/createSignature"),
        json!({
            "data": data,
            "protocolID": [2, "e2e test"],
            "keyID": "1",
            "counterparty": "anyone"
        }),
    )
    .await;
    let signature = sig["signature"].as_array().expect("signature");

    // Verify
    let verify = post_json_ok(
        &client,
        &format!("{base}/verifySignature"),
        json!({
            "data": data,
            "signature": signature,
            "protocolID": [2, "e2e test"],
            "keyID": "1",
            "counterparty": "anyone",
            "forSelf": true
        }),
    )
    .await;
    assert_eq!(verify["valid"], true, "signature should verify");
}

/// E2E: Certificate lifecycle against the real wallet.
/// acquire → list → relinquish → list (verify gone).
#[tokio::test]
async fn e2e_certificate_lifecycle() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    let cert_type = "ZTJlLXRlc3Q="; // base64("e2e test")
    let certifier = "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
    // Use a unique serial per run (timestamp-based) to avoid UNIQUE constraint from previous runs.
    // relinquishCertificate soft-deletes, so the DB row persists and blocks re-insertion.
    use std::time::{SystemTime, UNIX_EPOCH};
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let serial_input = format!("e2e-{}", ts);

    // Acquire
    let cert = post_json_ok(
        &client,
        &format!("{base}/acquireCertificate"),
        json!({
            "certificateType": cert_type,
            "certifier": certifier,
            "acquisitionProtocol": "direct",
            "fields": {"email": "test@example.com"},
            "serialNumber": serial_input,
            "revocationOutpoint": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef.0",
            "signature": "deadbeef",
            "keyringRevealer": "certifier",
            "keyringForSubject": {}
        }),
    )
    .await;
    let serial = cert["serialNumber"].as_str().expect("serialNumber");

    // List — should find it
    let list = post_json_ok(
        &client,
        &format!("{base}/listCertificates"),
        json!({"certifiers": [certifier], "types": [cert_type]}),
    )
    .await;
    assert!(
        list["totalCertificates"].as_u64().unwrap() >= 1,
        "should find the acquired certificate"
    );

    // Relinquish
    let rel = post_json_ok(
        &client,
        &format!("{base}/relinquishCertificate"),
        json!({
            "certificateType": cert_type,
            "serialNumber": serial,
            "certifier": certifier
        }),
    )
    .await;
    assert_eq!(rel["relinquished"], true, "should relinquish successfully");

    // List again — should be gone
    let list2 = post_json_ok(
        &client,
        &format!("{base}/listCertificates"),
        json!({"certifiers": [certifier], "types": [cert_type]}),
    )
    .await;
    assert_eq!(
        list2["totalCertificates"].as_u64().unwrap(),
        0,
        "certificate should be gone after relinquishing"
    );
}

/// E2E: Key linkage with the wallet's real identity key.
#[tokio::test]
async fn e2e_key_linkage() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // Get the wallet's identity key
    let identity = post_json_ok(
        &client,
        &format!("{base}/getPublicKey"),
        json!({"identityKey": true}),
    )
    .await;
    let identity_key = identity["publicKey"].as_str().expect("identity key");

    // Use a different key as counterparty
    let counterparty = "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";

    // Reveal counterparty key linkage
    let resp = post_json(
        &client,
        &format!("{base}/revealCounterpartyKeyLinkage"),
        json!({
            "counterparty": counterparty,
            "verifier": identity_key
        }),
    )
    .await;
    let status = resp.status().as_u16();
    let body: Value = resp.json().await.unwrap();
    assert!(
        status == 200 || status == 400,
        "counterparty linkage should return 200 or 400, got {}: {:?}",
        status,
        body
    );

    // Reveal specific key linkage
    let resp = post_json(
        &client,
        &format!("{base}/revealSpecificKeyLinkage"),
        json!({
            "counterparty": counterparty,
            "verifier": identity_key,
            "protocolID": [2, "e2e test"],
            "keyID": "1"
        }),
    )
    .await;
    let status = resp.status().as_u16();
    assert!(
        status == 200 || status == 400,
        "specific linkage should return 200 or 400, got {}",
        status
    );
}

/// E2E: All status endpoints against the real wallet.
#[tokio::test]
async fn e2e_status_endpoints() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // isAuthenticated
    let resp = client
        .get(format!("{base}/isAuthenticated"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["authenticated"], true);

    // getHeight — should return real chain height
    let resp = client
        .get(format!("{base}/getHeight"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    let height = body["height"].as_u64().expect("height");
    assert!(
        height > 800000,
        "mainnet height should be > 800000, got {}",
        height
    );

    // getNetwork
    let resp = client
        .get(format!("{base}/getNetwork"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["network"], "mainnet");

    // getVersion
    let resp = client
        .get(format!("{base}/getVersion"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: Value = resp.json().await.unwrap();
    assert!(body["version"].is_string());

    // getHeaderForHeight — real header for genesis block
    let body = post_json_ok(
        &client,
        &format!("{base}/getHeaderForHeight"),
        json!({"height": 1}),
    )
    .await;
    let header = body["header"].as_str().expect("header");
    assert_eq!(header.len(), 160, "80-byte header = 160 hex chars");
}

/// E2E: signAction happy path — create unsigned tx, sign it, verify signed result.
/// Tests the full deferred-signing flow: createAction(signAndProcess:false) → signAction.
/// The signed tx is NOT auto-broadcast (caller would need to use sendWithResults).
#[tokio::test]
async fn e2e_sign_action_happy_path() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // Step 1: Create an unsigned action (signAndProcess: false) with a 1-sat output
    let create = post_json_ok(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "e2e sign action test",
            "outputs": [{
                "lockingScript": "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac",
                "satoshis": 1,
                "outputDescription": "e2e sign test output"
            }],
            "labels": ["e2e-test-sign"],
            "options": {
                "signAndProcess": false
            }
        }),
    )
    .await;

    // Step 2: Verify signableTransaction is present with reference
    let st = create
        .get("signableTransaction")
        .expect("response should have signableTransaction");
    let reference = st["reference"]
        .as_str()
        .expect("signableTransaction should have reference string");
    assert!(!reference.is_empty(), "reference should not be empty");
    assert!(
        st["tx"].is_array(),
        "signableTransaction.tx should be a byte array"
    );

    // Step 3: Sign the action with empty spends (wallet signs all inputs itself)
    let sign = post_json_ok(
        &client,
        &format!("{base}/signAction"),
        json!({
            "spends": {},
            "reference": reference
        }),
    )
    .await;

    // Step 4: Verify the signed result contains txid or tx
    let has_txid = sign.get("txid").map(|v| !v.is_null()).unwrap_or(false);
    let has_tx = sign.get("tx").map(|v| !v.is_null()).unwrap_or(false);
    assert!(
        has_txid || has_tx,
        "signAction should return txid or tx: {:?}",
        sign
    );
}

/// E2E: internalizeAction with real BEEF from WoC.
/// Fetches a real BEEF tx, converts to AtomicBEEF, and verifies the wallet
/// gets past BEEF parsing (error should be about ownership, not parsing).
#[tokio::test]
async fn e2e_internalize_action_real_beef() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // Find a real txid by querying WoC for the wallet address history.
    // Set E2E_WALLET_ADDRESS to a funded address, or this test will be skipped.
    let Some(addr) = std::env::var("E2E_WALLET_ADDRESS").ok() else {
        eprintln!("Skipping e2e_internalize: E2E_WALLET_ADDRESS not set");
        return;
    };
    let addr = addr.as_str();
    let history_resp = client
        .get(format!(
            "https://api.whatsonchain.com/v1/bsv/main/address/{addr}/history"
        ))
        .send()
        .await;
    let Ok(resp) = history_resp else {
        eprintln!("Skipping e2e_internalize: WoC address history request failed");
        return;
    };
    if resp.status() != 200 {
        eprintln!("Skipping e2e_internalize: WoC returned {}", resp.status());
        return;
    }
    let history: Value = resp.json().await.unwrap();
    let Some(txid) = history
        .as_array()
        .and_then(|a| a.first())
        .and_then(|t| t["tx_hash"].as_str())
    else {
        eprintln!("Skipping e2e_internalize: no txs found for wallet address");
        return;
    };
    let txid = txid.to_string(); // own the string before resp is dropped

    // Fetch BEEF from WoC
    let beef_resp = client
        .get(format!(
            "https://api.whatsonchain.com/v1/bsv/main/tx/{txid}/beef"
        ))
        .send()
        .await;
    let Ok(resp) = beef_resp else {
        eprintln!("Skipping e2e_internalize: WoC BEEF fetch failed");
        return;
    };
    if resp.status() != 200 {
        eprintln!(
            "Skipping e2e_internalize: WoC BEEF returned {}",
            resp.status()
        );
        return;
    }
    let raw = resp.bytes().await.unwrap().to_vec();

    // WoC may return BEEF as hex string or raw binary
    let beef_bytes = if let Ok(text) = std::str::from_utf8(&raw) {
        let clean = text.trim().trim_matches('"');
        hex::decode(clean).unwrap_or(raw)
    } else {
        raw
    };
    assert!(
        beef_bytes.len() > 36,
        "BEEF data too short: {} bytes",
        beef_bytes.len()
    );

    // Convert to AtomicBEEF: [01,01,01,01] + reversed_txid(32) + standard_beef
    let txid_bytes = hex::decode(&txid).expect("valid hex txid");
    assert_eq!(txid_bytes.len(), 32, "txid should be 32 bytes");
    let mut reversed_txid = txid_bytes;
    reversed_txid.reverse();

    let mut atomic_beef: Vec<u8> = vec![0x01, 0x01, 0x01, 0x01];
    atomic_beef.extend_from_slice(&reversed_txid);
    atomic_beef.extend_from_slice(&beef_bytes);

    // Call internalizeAction with the AtomicBEEF
    let resp = post_json(
        &client,
        &format!("{base}/internalizeAction"),
        json!({
            "tx": atomic_beef,
            "outputs": [{
                "outputIndex": 0,
                "protocol": "wallet payment",
                "paymentRemittance": {
                    "derivationPrefix": "test",
                    "derivationSuffix": "test",
                    "senderIdentityKey": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
                }
            }],
            "description": "e2e internalize real BEEF test"
        }),
    )
    .await;

    // Should get past BEEF parsing — error should be about ownership, not parsing
    let status = resp.status().as_u16();
    let body: Value = resp.json().await.unwrap();
    assert_eq!(
        status, 400,
        "should return 400 (output isn't ours): {:?}",
        body
    );
    let message = body["message"].as_str().unwrap_or("");
    let msg_lower = message.to_lowercase();
    // Error should NOT be about BEEF parsing/version — should be past that stage
    assert!(
        !msg_lower.contains("not a valid beef")
            && !msg_lower.contains("beef version")
            && !msg_lower.contains("unexpected version"),
        "error should be past BEEF parsing (about ownership), got: {message}"
    );
}

/// E2E: createAction with noSend:true — signed but not broadcast.
/// Verifies the response contains tx bytes, txid hex string, and noSendChange outpoints.
/// NOTE: noSend locks UTXOs. Run e2e tests with --test-threads=1 to avoid contention.
#[tokio::test]
async fn e2e_nosend_flow() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // Create a signed-but-not-broadcast action (signAndProcess:true, noSend:true)
    let body = post_json_ok(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "e2e noSend test",
            "outputs": [{
                "lockingScript": "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac",
                "satoshis": 1,
                "outputDescription": "e2e noSend test output"
            }],
            "labels": ["e2e-test-nosend"],
            "options": {
                "signAndProcess": true,
                "noSend": true
            }
        }),
    )
    .await;

    // Verify txid is a 64-char hex string
    let txid = body["txid"]
        .as_str()
        .expect("noSend response should have txid as hex string");
    assert_eq!(
        txid.len(),
        64,
        "txid should be 64 hex chars, got len={}",
        txid.len()
    );

    // Verify tx is present as a non-empty byte array
    let tx = body["tx"]
        .as_array()
        .expect("noSend response should have tx as byte array");
    assert!(!tx.is_empty(), "tx byte array should not be empty");

    // signableTransaction should NOT be present (tx is already signed)
    assert!(
        body.get("signableTransaction").is_none() || body["signableTransaction"].is_null(),
        "noSend should not have signableTransaction (tx is already signed)"
    );

    // Verify noSendChange is present (change outpoints for the noSend tx)
    assert!(
        body.get("noSendChange").is_some() && !body["noSendChange"].is_null(),
        "noSend response should have noSendChange: {:?}",
        body
    );

    // Clean up: abort the noSend transaction so its UTXOs don't pollute the pool
    // for subsequent tests (e.g. e2e_sign_action_happy_path)
    let _abort = post_json_ok(
        &client,
        &format!("{base}/abortAction"),
        json!({ "reference": txid }),
    )
    .await;
}

// =============================================================================
// Auth token enforcement test
// =============================================================================

/// Spin up a server WITH auth token, verify 401 without token and 200 with token.
#[tokio::test]
async fn test_auth_token_enforcement() {
    let tmp = TempDir::new().expect("temp dir");
    let db_path = tmp.path().join("test_auth.db");

    let storage = StorageSqlx::open(db_path.to_str().unwrap())
        .await
        .expect("open db");

    let key = PrivateKey::random();
    let identity_key = key.public_key().to_hex();
    storage
        .migrate("bsv-wallet-test", &identity_key)
        .await
        .expect("migrate db");
    storage.make_available().await.expect("make available");

    let services = {
        let mut opts = ServicesOptions::mainnet();
        if let Ok(url) = std::env::var("CHAINTRACKS_URL") {
            opts = opts.with_chaintracks_url(url);
        }
        Services::with_options(Chain::Main, opts).expect("services")
    };
    let wallet = Wallet::new(Some(key), storage, services)
        .await
        .expect("wallet");

    let state = server::make_wallet_state(wallet);
    let config = ServerConfig {
        auth_token: Some("test-secret-token".to_string()),
        tls: None,
    };
    let app = server::make_router(state, config);

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind");
    let addr: SocketAddr = listener.local_addr().expect("local addr");
    tokio::spawn(async move {
        axum::serve(listener, app).await.ok();
    });

    let base = format!("http://{}", addr);
    let client = Client::new();

    // Without token → 401
    let resp = client
        .get(format!("{base}/isAuthenticated"))
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        401,
        "request without token should return 401"
    );

    // With wrong token → 401
    let resp = client
        .get(format!("{base}/isAuthenticated"))
        .header("Authorization", "Bearer wrong-token")
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        401,
        "request with wrong token should return 401"
    );

    // With correct token → 200
    let resp = client
        .get(format!("{base}/isAuthenticated"))
        .header("Authorization", "Bearer test-secret-token")
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        200,
        "request with correct token should return 200"
    );
    let body: Value = resp.json().await.unwrap();
    assert_eq!(body["authenticated"], true);
}

// =============================================================================
// E2E: BEEF broadcast test — createAction with OP_RETURN (real broadcast)
// =============================================================================

/// E2E: createAction with a 0-sat OP_RETURN output — verifies real broadcast succeeds.
///
/// This test actually broadcasts a transaction to the BSV network (~200 sats mining fee).
/// It validates the full BEEF serialization → signing → broadcast pipeline.
///
/// Run:  WALLET_URL=http://localhost:3322 cargo test --test integration e2e_create_action_broadcast_beef -- --test-threads=1
#[tokio::test]
async fn e2e_create_action_broadcast_beef() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // OP_RETURN script: OP_0 OP_RETURN <"beef-broadcast-test">
    // 00 6a 13 626565662d62726f6164636173742d74657374
    let op_return_script = "006a13626565662d62726f6164636173742d74657374";

    // Step 1: Create a broadcast action with OP_RETURN (signAndProcess:true, default)
    let resp = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "e2e BEEF broadcast test",
            "outputs": [{
                "lockingScript": op_return_script,
                "satoshis": 0,
                "outputDescription": "BEEF broadcast verification"
            }],
            "labels": ["e2e-test-broadcast"]
        }),
    )
    .await;

    let status = resp.status().as_u16();
    let body: Value = resp.json().await.unwrap();

    // Must succeed — if BEEF serialization or broadcast is broken, this fails
    assert_eq!(
        status, 200,
        "createAction broadcast should succeed (status {}): {:?}",
        status, body
    );

    // Step 2: Verify txid is a valid 64-char hex string
    let txid = body["txid"]
        .as_str()
        .expect("broadcast response should have txid");
    assert_eq!(txid.len(), 64, "txid should be 64 hex chars, got: {}", txid);
    assert!(
        txid.chars().all(|c| c.is_ascii_hexdigit()),
        "txid should be hex, got: {}",
        txid
    );

    // Step 3: Verify no signableTransaction (tx was signed and broadcast)
    assert!(
        body.get("signableTransaction").is_none() || body["signableTransaction"].is_null(),
        "broadcast response should not have signableTransaction"
    );

    // Step 4: Verify no error fields
    assert!(
        body.get("error").is_none() || body["error"].is_null(),
        "broadcast response should not have error: {:?}",
        body
    );

    eprintln!("BEEF broadcast succeeded! txid: {}", txid);

    // Step 5: Verify the action appears in listActions
    let actions_body = post_json_ok(
        &client,
        &format!("{base}/listActions"),
        json!({
            "labels": ["e2e-test-broadcast"],
            "includeLabels": true,
            "includeOutputs": true
        }),
    )
    .await;

    let total = actions_body["totalActions"]
        .as_u64()
        .expect("totalActions should be a number");
    assert!(
        total >= 1,
        "should have at least 1 action with e2e-test-broadcast label, got {}",
        total
    );

    // Step 6: Verify the action's txid matches
    let actions = actions_body["actions"]
        .as_array()
        .expect("actions should be an array");
    let found = actions.iter().any(|a| a["txid"].as_str() == Some(txid));
    assert!(
        found,
        "broadcast txid {} should appear in listActions results",
        txid
    );

    eprintln!(
        "BEEF broadcast E2E complete: txid={}, found in listActions=true",
        txid
    );
}

// =============================================================================
// E2E: EF broadcast tests — PushDrop-style large scripts and UTXO chaining
// =============================================================================

/// E2E: createAction with PushDrop-style script — verifies EF broadcast handles large scripts.
///
/// Tests that the BEEF->EF conversion correctly embeds parent UTXO data even when
/// the transaction has large locking scripts (PushDrop pattern used by bsv-worm proofs).
///
/// The script is: OP_FALSE OP_RETURN OP_PUSHDATA2 <512 bytes of 0xaa>
/// Total script: 517 bytes (1034 hex chars).
///
/// Run: WALLET_URL=http://localhost:3322 cargo test --test integration e2e_create_action_broadcast_pushdata -- --test-threads=1
#[tokio::test]
async fn e2e_create_action_broadcast_pushdata() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // Build PushDrop-style OP_RETURN script:
    // 00       = OP_FALSE
    // 6a       = OP_RETURN
    // 4d       = OP_PUSHDATA2
    // 0002     = 512 in little-endian u16
    // aa * 512 = 512 bytes of data
    let data_hex = "aa".repeat(512); // 1024 hex chars = 512 bytes
    let op_return_script = format!("006a4d0002{}", data_hex);
    assert_eq!(
        op_return_script.len(),
        1034,
        "PushDrop script should be 1034 hex chars (517 bytes)"
    );

    // Step 1: Create a broadcast action with the large OP_RETURN (signAndProcess:true)
    let resp = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "e2e EF broadcast PushDrop test",
            "outputs": [{
                "lockingScript": op_return_script,
                "satoshis": 0,
                "outputDescription": "PushDrop-style large OP_RETURN for EF broadcast verification"
            }],
            "labels": ["e2e-test-pushdata"]
        }),
    )
    .await;

    let status = resp.status().as_u16();
    let body: Value = resp.json().await.unwrap();

    // Must succeed — if BEEF->EF conversion breaks on large scripts, this fails
    assert_eq!(
        status, 200,
        "createAction broadcast should succeed with large PushDrop script (status {}): {:?}",
        status, body
    );

    // Step 2: Verify txid is a valid 64-char hex string
    let txid = body["txid"]
        .as_str()
        .expect("broadcast response should have txid");
    assert_eq!(txid.len(), 64, "txid should be 64 hex chars, got: {}", txid);
    assert!(
        txid.chars().all(|c| c.is_ascii_hexdigit()),
        "txid should be hex, got: {}",
        txid
    );

    // Step 3: Verify no signableTransaction (tx was signed and broadcast)
    assert!(
        body.get("signableTransaction").is_none() || body["signableTransaction"].is_null(),
        "broadcast response should not have signableTransaction"
    );

    // Step 4: Verify no error fields
    assert!(
        body.get("error").is_none() || body["error"].is_null(),
        "broadcast response should not have error: {:?}",
        body
    );

    eprintln!(
        "EF broadcast with PushDrop script succeeded! txid: {}",
        txid
    );

    // Step 5: Verify the action appears in listActions
    let actions_body = post_json_ok(
        &client,
        &format!("{base}/listActions"),
        json!({
            "labels": ["e2e-test-pushdata"],
            "includeLabels": true,
            "includeOutputs": true
        }),
    )
    .await;

    let total = actions_body["totalActions"]
        .as_u64()
        .expect("totalActions should be a number");
    assert!(
        total >= 1,
        "should have at least 1 action with e2e-test-pushdata label, got {}",
        total
    );

    // Step 6: Verify the action's txid matches
    let actions = actions_body["actions"]
        .as_array()
        .expect("actions should be an array");
    let found = actions.iter().any(|a| a["txid"].as_str() == Some(txid));
    assert!(
        found,
        "broadcast txid {} should appear in listActions results",
        txid
    );

    eprintln!(
        "EF broadcast PushDrop E2E complete: txid={}, script_len=517 bytes, found in listActions=true",
        txid
    );
}

/// E2E: Two sequential createActions — verifies UTXO chaining works with EF broadcast.
///
/// The second transaction must use the change output from the first. This tests
/// that the wallet correctly manages UTXOs between consecutive broadcasts and
/// that EF format works for chained transactions.
///
/// Run: WALLET_URL=http://localhost:3322 cargo test --test integration e2e_sequential_broadcasts -- --test-threads=1
#[tokio::test]
async fn e2e_sequential_broadcasts() {
    let Some((base, client)) = e2e_setup() else {
        eprintln!("Skipping e2e test: WALLET_URL not set");
        return;
    };

    // --- First broadcast ---

    // OP_RETURN script: OP_0 OP_RETURN <"seq-broadcast-1">
    // 00 6a 0f 7365712d62726f6164636173742d31
    let script_1 = "006a0f7365712d62726f6164636173742d31";

    let resp1 = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "e2e sequential broadcast 1",
            "outputs": [{
                "lockingScript": script_1,
                "satoshis": 0,
                "outputDescription": "sequential broadcast test 1"
            }],
            "labels": ["e2e-test-sequential"]
        }),
    )
    .await;

    let status1 = resp1.status().as_u16();
    let body1: Value = resp1.json().await.unwrap();
    assert_eq!(
        status1, 200,
        "first sequential broadcast should succeed (status {}): {:?}",
        status1, body1
    );

    let txid1 = body1["txid"]
        .as_str()
        .expect("first broadcast should have txid");
    assert_eq!(
        txid1.len(),
        64,
        "first txid should be 64 hex chars, got: {}",
        txid1
    );
    assert!(
        txid1.chars().all(|c| c.is_ascii_hexdigit()),
        "first txid should be hex, got: {}",
        txid1
    );
    assert!(
        body1.get("error").is_none() || body1["error"].is_null(),
        "first broadcast should not have error: {:?}",
        body1
    );

    eprintln!("Sequential broadcast 1 succeeded: txid={}", txid1);

    // --- Second broadcast (immediately after first) ---

    // OP_RETURN script: OP_0 OP_RETURN <"seq-broadcast-2">
    // 00 6a 0f 7365712d62726f6164636173742d32
    let script_2 = "006a0f7365712d62726f6164636173742d32";

    let resp2 = post_json(
        &client,
        &format!("{base}/createAction"),
        json!({
            "description": "e2e sequential broadcast 2",
            "outputs": [{
                "lockingScript": script_2,
                "satoshis": 0,
                "outputDescription": "sequential broadcast test 2"
            }],
            "labels": ["e2e-test-sequential"]
        }),
    )
    .await;

    let status2 = resp2.status().as_u16();
    let body2: Value = resp2.json().await.unwrap();
    assert_eq!(
        status2, 200,
        "second sequential broadcast should succeed (status {}): {:?}",
        status2, body2
    );

    let txid2 = body2["txid"]
        .as_str()
        .expect("second broadcast should have txid");
    assert_eq!(
        txid2.len(),
        64,
        "second txid should be 64 hex chars, got: {}",
        txid2
    );
    assert!(
        txid2.chars().all(|c| c.is_ascii_hexdigit()),
        "second txid should be hex, got: {}",
        txid2
    );
    assert!(
        body2.get("error").is_none() || body2["error"].is_null(),
        "second broadcast should not have error: {:?}",
        body2
    );

    // Verify the two txids are different (distinct transactions)
    assert_ne!(
        txid1, txid2,
        "sequential broadcasts should produce different txids"
    );

    eprintln!("Sequential broadcast 2 succeeded: txid={}", txid2);

    // Verify both actions appear in listActions
    let actions_body = post_json_ok(
        &client,
        &format!("{base}/listActions"),
        json!({
            "labels": ["e2e-test-sequential"],
            "includeLabels": true,
            "includeOutputs": true
        }),
    )
    .await;

    let total = actions_body["totalActions"]
        .as_u64()
        .expect("totalActions should be a number");
    assert!(
        total >= 2,
        "should have at least 2 actions with e2e-test-sequential label, got {}",
        total
    );

    let actions = actions_body["actions"]
        .as_array()
        .expect("actions should be an array");
    let found1 = actions.iter().any(|a| a["txid"].as_str() == Some(txid1));
    let found2 = actions.iter().any(|a| a["txid"].as_str() == Some(txid2));
    assert!(found1, "first txid {} should appear in listActions", txid1);
    assert!(found2, "second txid {} should appear in listActions", txid2);

    eprintln!(
        "Sequential broadcasts E2E complete: txid1={}, txid2={}, both found in listActions",
        txid1, txid2
    );
}