amp-rust 0.0.9

A Rust client for the Blockstream AMP API, providing interfaces for asset management, user operations, and token handling on the Liquid Network.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
use super::{Signer, SignerError};
use crate::model::Unspent;
use async_trait::async_trait;
use bip39::{Language, Mnemonic};
use elements::bitcoin::bip32::{ChildNumber, DerivationPath, Xpriv};
use elements::bitcoin::PublicKey;
use elements::encode::Decodable;
use elements::pset::PartiallySignedTransaction;
use elements::secp256k1_zkp::Secp256k1;
use elements::{Address, AddressParams, TxOut};
use lwk_common::Signer as LwkSigner;
use lwk_signer::SwSigner;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;

/// Helper function to check if logging should be enabled during tests
/// Only enables logging if --nocapture is passed to cargo test
fn should_log_in_tests() -> bool {
    // Always allow logging in non-test builds
    if !cfg!(test) {
        return true;
    }

    // In test builds, only log if --nocapture is passed
    std::env::args().any(|arg| arg == "--nocapture")
}

/// Conditional logging macros that respect test environment and --nocapture flag
macro_rules! cond_debug {
    ($($arg:tt)*) => {
        if should_log_in_tests() {
            tracing::debug!($($arg)*);
        }
    };
}

macro_rules! cond_info {
    ($($arg:tt)*) => {
        if should_log_in_tests() {
            tracing::info!($($arg)*);
        }
    };
}

macro_rules! cond_error {
    ($($arg:tt)*) => {
        if should_log_in_tests() {
            tracing::error!($($arg)*);
        }
    };
}

/// JSON structure for persistent mnemonic storage
///
/// `MnemonicStorage` handles the serialization and management of multiple BIP39
/// mnemonic phrases in a JSON file format. This structure supports indexed access
/// to mnemonics for consistent test identification and automatic generation of
/// new mnemonics when needed.
///
/// ## ⚠️ SECURITY WARNING ⚠️
///
/// This storage format keeps mnemonic phrases in **PLAIN TEXT**. It is designed
/// exclusively for testnet/regtest development and should never be used with
/// real funds or in production environments.
///
/// ## JSON File Structure
///
/// The storage uses the following JSON format in `mnemonic.local.json`:
///
/// ```json
/// {
///   "mnemonic": [
///     "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
///     "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",
///     "legal winner thank year wave sausage worth useful legal winner thank yellow"
///   ]
/// }
/// ```
///
/// ### Field Details:
/// - **mnemonic**: Array of BIP39 mnemonic phrases
/// - **Index-based access**: Zero-based indexing for consistent test identification
/// - **Validation**: All mnemonics are validated on load and before storage
/// - **Atomic writes**: File updates use temporary files to prevent corruption
///
/// ## Supported Mnemonic Formats
///
/// - **Word counts**: 12, 15, 18, 21, or 24 words (BIP39 standard)
/// - **Language**: English wordlist only
/// - **Format**: Space-separated lowercase words
/// - **Validation**: Full BIP39 checksum validation
///
///
/// This struct handles persistent storage of mnemonic phrases in JSON format,
/// supporting multiple mnemonics for different test scenarios.
#[derive(Serialize, Deserialize, Debug, Clone)]
struct MnemonicStorage {
    mnemonic: Vec<String>,
}

impl MnemonicStorage {
    /// Create a new empty mnemonic storage
    pub const fn new() -> Self {
        Self {
            mnemonic: Vec::new(),
        }
    }

    /// Create mnemonic storage with initial mnemonics
    #[allow(dead_code)]
    pub fn with_mnemonics(mnemonics: Vec<String>) -> Result<Self, SignerError> {
        let storage = Self {
            mnemonic: mnemonics,
        };
        storage.validate()?;
        Ok(storage)
    }

    /// Validate all mnemonics in the storage
    pub fn validate(&self) -> Result<(), SignerError> {
        for (index, mnemonic) in self.mnemonic.iter().enumerate() {
            Self::validate_mnemonic_format(mnemonic).map_err(|e| {
                SignerError::InvalidMnemonic(format!("Invalid mnemonic at index {index}: {e}"))
            })?;
        }
        Ok(())
    }

    /// Validate a single mnemonic phrase format
    pub fn validate_mnemonic_format(mnemonic: &str) -> Result<(), String> {
        // First check for multiple consecutive spaces which could indicate empty words
        if mnemonic.contains("  ") {
            return Err(
                "Multiple consecutive spaces detected, which may indicate empty words".to_string(),
            );
        }

        let words: Vec<&str> = mnemonic.split_whitespace().collect();

        // Check word count (should be 12, 15, 18, 21, or 24 words for BIP39)
        match words.len() {
            12 | 15 | 18 | 21 | 24 => {}
            _ => {
                return Err(format!(
                    "Invalid word count: {}. Expected 12, 15, 18, 21, or 24 words",
                    words.len()
                ))
            }
        }

        // Check that all words are non-empty and contain only valid characters
        for (i, word) in words.iter().enumerate() {
            if word.is_empty() {
                return Err(format!("Empty word at position {}", i + 1));
            }

            // Check for valid characters (lowercase letters only for BIP39)
            if !word.chars().all(|c| c.is_ascii_lowercase()) {
                return Err(format!("Invalid characters in word '{}' at position {}. Only lowercase letters allowed", word, i + 1));
            }
        }

        Ok(())
    }

    /// Add a new mnemonic to the storage after validation
    ///
    /// This method is deprecated in favor of `append_mnemonic` which returns the index.
    /// It's kept for backward compatibility.
    #[allow(dead_code)]
    pub fn add_mnemonic(&mut self, mnemonic: String) -> Result<(), SignerError> {
        self.append_mnemonic(mnemonic)?;
        Ok(())
    }

    /// Get mnemonic at specific index
    ///
    /// This method is deprecated in favor of `get_mnemonic_by_index` for clarity.
    /// It's kept for backward compatibility.
    #[allow(dead_code)]
    pub fn get_mnemonic(&self, index: usize) -> Option<&String> {
        self.get_mnemonic_by_index(index)
    }

    /// Get the first mnemonic if available
    pub fn get_first_mnemonic(&self) -> Option<&String> {
        self.mnemonic.first()
    }

    /// Get the number of stored mnemonics
    pub const fn len(&self) -> usize {
        self.mnemonic.len()
    }

    /// Check if storage is empty
    #[allow(dead_code)]
    pub const fn is_empty(&self) -> bool {
        self.mnemonic.is_empty()
    }
}

impl MnemonicStorage {
    /// Get mnemonic by index from storage
    ///
    /// This function retrieves a mnemonic at the specified index from the storage.
    /// It handles out-of-bounds access gracefully by returning None.
    ///
    /// # Arguments
    ///
    /// * `index` - Zero-based index of the mnemonic to retrieve
    ///
    /// # Returns
    ///
    /// Returns an `Option` containing:
    /// - `Some(&String)` - Reference to the mnemonic at the specified index
    /// - `None` - If the index is out of bounds
    ///
    /// # Example
    ///
    /// Returns `Some(&String)` if the index exists, `None` otherwise.
    #[allow(dead_code)]
    pub fn get_mnemonic_by_index(&self, index: usize) -> Option<&String> {
        self.mnemonic.get(index)
    }

    /// Append a new mnemonic to the storage array
    ///
    /// This function adds a new mnemonic to the end of the storage array after
    /// validating its format. The mnemonic is validated before being added to
    /// ensure data integrity.
    ///
    /// # Arguments
    ///
    /// * `mnemonic` - The mnemonic phrase to append to the storage
    ///
    /// # Returns
    ///
    /// Returns a `Result` indicating success or failure:
    /// - `Ok(usize)` - The index where the mnemonic was added
    /// - `Err(SignerError)` - Validation error if the mnemonic format is invalid
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::InvalidMnemonic` - If the mnemonic format is invalid
    ///
    /// # Example
    ///
    /// Returns the index where the mnemonic was added.
    pub fn append_mnemonic(&mut self, mnemonic: String) -> Result<usize, SignerError> {
        // Validate the mnemonic format before adding
        Self::validate_mnemonic_format(&mnemonic).map_err(SignerError::InvalidMnemonic)?;

        // Add the mnemonic to the array
        self.mnemonic.push(mnemonic);

        // Return the index where it was added (length - 1)
        Ok(self.mnemonic.len() - 1)
    }

    /// Get mnemonic by index, generating and appending a new one if index doesn't exist
    ///
    /// This function attempts to retrieve a mnemonic at the specified index. If the
    /// index is out of bounds, it generates new mnemonics and appends them to the
    /// array until the requested index exists, then returns a copy of the mnemonic at that index.
    ///
    /// # Arguments
    ///
    /// * `index` - Zero-based index of the mnemonic to retrieve or create
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(String)` - Copy of the mnemonic at the specified index
    /// - `Err(SignerError)` - Error during mnemonic generation or validation
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::InvalidMnemonic` - If generated mnemonic validation fails
    ///
    /// # Example
    ///
    /// Generates mnemonics as needed to reach the requested index.
    pub fn get_or_generate_mnemonic_at_index(
        &mut self,
        index: usize,
    ) -> Result<String, SignerError> {
        // If the index already exists, return a copy of the existing mnemonic
        if let Some(mnemonic) = self.mnemonic.get(index) {
            return Ok(mnemonic.clone());
        }

        // Generate new mnemonics until we reach the requested index
        while self.mnemonic.len() <= index {
            let new_mnemonic = Self::generate_new_mnemonic();
            self.append_mnemonic(new_mnemonic)?;
        }

        // Return a copy of the mnemonic at the requested index (guaranteed to exist now)
        Ok(self
            .mnemonic
            .get(index)
            .expect("Mnemonic should exist at index after generation")
            .clone())
    }

    /// Generate a new 12-word BIP39 mnemonic phrase
    ///
    /// This function generates a cryptographically secure 12-word mnemonic phrase
    /// using the BIP39 standard. The generated mnemonic can be used to create
    /// deterministic wallets and signers.
    ///
    /// # Returns
    ///
    /// Returns a `String` containing a 12-word mnemonic phrase with words
    /// separated by spaces.
    ///
    /// # Example
    ///
    /// Generates a cryptographically secure 12-word mnemonic phrase.
    pub fn generate_new_mnemonic() -> String {
        use bip39::{Language, Mnemonic};
        use rand::rngs::OsRng;

        // Generate a new 12-word mnemonic using cryptographically secure randomness
        let mnemonic = Mnemonic::generate_in_with(&mut OsRng, Language::English, 12)
            .expect("Failed to generate mnemonic");

        mnemonic.to_string()
    }

    /// Read mnemonic storage from mnemonic.local.json file
    ///
    /// This function attempts to read and parse the mnemonic.local.json file from the
    /// current working directory. It handles missing files gracefully by returning
    /// an empty storage structure.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(MnemonicStorage)` - Parsed storage on success or empty storage if file doesn't exist
    /// - `Err(SignerError)` - File I/O error, JSON parsing error, or validation error
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::FileIo` - File reading errors (except file not found)
    /// - `SignerError::Serialization` - JSON parsing errors
    /// - `SignerError::InvalidMnemonic` - Mnemonic validation errors
    ///
    /// # Example
    ///
    /// Reads from `mnemonic.local.json` or returns empty storage if file doesn't exist.
    pub fn read_from_file() -> Result<Self, SignerError> {
        Self::read_from_file_path("mnemonic.local.json")
    }

    /// Read mnemonic storage from a specific file path
    ///
    /// This function reads and parses a mnemonic storage file from the specified path.
    /// It handles missing files gracefully by returning an empty storage structure.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the JSON file containing mnemonic storage
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(MnemonicStorage)` - Parsed storage on success or empty storage if file doesn't exist
    /// - `Err(SignerError)` - File I/O error, JSON parsing error, or validation error
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::FileIo` - File reading errors (except file not found)
    /// - `SignerError::Serialization` - JSON parsing errors
    /// - `SignerError::InvalidMnemonic` - Mnemonic validation errors
    pub fn read_from_file_path<P: AsRef<Path>>(path: P) -> Result<Self, SignerError> {
        let path = path.as_ref();

        // Handle missing file gracefully by returning empty storage
        if !path.exists() {
            cond_debug!(
                "Mnemonic file {:?} does not exist, returning empty storage",
                path
            );
            return Ok(Self::new());
        }

        // Read file contents
        let contents = fs::read_to_string(path).map_err(|e| {
            cond_error!("Failed to read mnemonic file {:?}: {}", path, e);
            SignerError::FileIo(e)
        })?;

        // Handle empty file gracefully
        if contents.trim().is_empty() {
            cond_debug!("Mnemonic file {:?} is empty, returning empty storage", path);
            return Ok(Self::new());
        }

        // Parse JSON content
        let storage: Self = serde_json::from_str(&contents).map_err(|e| {
            cond_error!("Failed to parse mnemonic file {:?}: {}", path, e);
            SignerError::Serialization(e)
        })?;

        // Validate all mnemonics in the loaded storage
        storage.validate().map_err(|e| {
            cond_error!("Validation failed for mnemonics in file {:?}: {}", path, e);
            e
        })?;

        cond_info!(
            "Successfully loaded {} mnemonics from {:?}",
            storage.len(),
            path
        );
        Ok(storage)
    }

    /// Write mnemonic storage to mnemonic.local.json file
    ///
    /// This function serializes the current storage to JSON and writes it to the
    /// mnemonic.local.json file in the current working directory.
    ///
    /// # Returns
    ///
    /// Returns a `Result` indicating success or failure:
    /// - `Ok(())` - File written successfully
    /// - `Err(SignerError)` - Serialization or file writing error
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::Serialization` - JSON serialization errors
    /// - `SignerError::FileIo` - File writing errors
    pub fn write_to_file(&self) -> Result<(), SignerError> {
        self.write_to_file_path("mnemonic.local.json")
    }

    /// Write mnemonic storage to a specific file path
    ///
    /// This function serializes the current storage to JSON and writes it to the
    /// specified file path.
    ///
    /// # Arguments
    ///
    /// * `path` - Path where the JSON file should be written
    ///
    /// # Returns
    ///
    /// Returns a `Result` indicating success or failure:
    /// - `Ok(())` - File written successfully
    /// - `Err(SignerError)` - Serialization or file writing error
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::Serialization` - JSON serialization errors
    /// - `SignerError::FileIo` - File writing errors
    pub fn write_to_file_path<P: AsRef<Path>>(&self, path: P) -> Result<(), SignerError> {
        let path = path.as_ref();

        // Serialize to pretty JSON for better readability
        let contents = serde_json::to_string_pretty(self).map_err(|e| {
            tracing::error!("Failed to serialize mnemonic storage: {}", e);
            SignerError::Serialization(e)
        })?;

        // Perform atomic write using temporary file to prevent corruption
        let temp_path = path.with_extension("tmp");

        // Write to temporary file first
        fs::write(&temp_path, &contents).map_err(|e| {
            tracing::error!(
                "Failed to write temporary mnemonic file {:?}: {}",
                temp_path,
                e
            );
            SignerError::FileIo(e)
        })?;

        // Atomically rename temporary file to target file
        // This operation is atomic on most filesystems, preventing corruption
        fs::rename(&temp_path, path).map_err(|e| {
            tracing::error!(
                "Failed to rename temporary file {:?} to {:?}: {}",
                temp_path,
                path,
                e
            );
            // Clean up temporary file on failure
            let _ = fs::remove_file(&temp_path);
            SignerError::FileIo(e)
        })?;

        tracing::info!("Successfully wrote {} mnemonics to {:?}", self.len(), path);
        Ok(())
    }
}

/// Software-based transaction signer using Blockstream's Liquid Wallet Kit (LWK)
///
/// `LwkSoftwareSigner` provides transaction signing capabilities for Elements/Liquid
/// transactions using mnemonic phrases and LWK's `SwSigner` implementation. This signer
/// is designed specifically for testnet and regtest environments with persistent
/// mnemonic storage in JSON format.
///
/// ## ⚠️ CRITICAL SECURITY WARNING ⚠️
///
/// **THIS IMPLEMENTATION IS FOR TESTNET/REGTEST ONLY**
///
/// - Mnemonic phrases are stored in **PLAIN TEXT** in `mnemonic.local.json`
/// - Private keys are held in **UNENCRYPTED MEMORY**
/// - No password protection or encryption is provided
/// - Suitable ONLY for development, testing, and regtest environments
///
/// **NEVER USE IN PRODUCTION OR WITH REAL FUNDS**
///
/// For production environments, use:
/// - Hardware wallets (Ledger, Trezor)
/// - Encrypted key storage with proper key derivation
/// - Remote signing services with HSM backing
/// - Multi-signature setups with distributed key management
///
/// ## Features
///
/// - **Persistent Storage**: Automatic mnemonic persistence in JSON format
/// - **Multiple Mnemonics**: Support for multiple test signers with indexed access
/// - **Automatic Generation**: Generate new mnemonics when needed
/// - **BIP39 Compliance**: Full BIP39 mnemonic validation and support
/// - **Liquid Support**: Native support for Liquid/Elements confidential transactions
/// - **Async Interface**: Thread-safe async transaction signing
///
/// ## JSON Storage Format
///
/// The signer uses `mnemonic.local.json` with this structure:
///
/// ```json
/// {
///   "mnemonic": [
///     "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
///     "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",
///     "additional test mnemonics..."
///   ]
/// }
/// ```
///
/// ## Usage Patterns
///
/// ### Single Signer Usage
///
/// ```rust,no_run
/// use amp_rs::signer::{Signer, LwkSoftwareSigner};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // Create from existing mnemonic
///     let signer = LwkSoftwareSigner::new(
///         "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
///     )?;
///     
///     // Or generate/load from file
///     let (mnemonic, signer) = LwkSoftwareSigner::generate_new()?;
///     println!("Using mnemonic: {}", mnemonic);
///     
///     // Sign transactions
///     let unsigned_tx = "020000000001...";
///     let signed_tx = signer.sign_transaction(unsigned_tx).await?;
///     
///     Ok(())
/// }
/// ```
///
/// ### Multi-Signer Testing
///
/// ```rust,no_run
/// use amp_rs::signer::LwkSoftwareSigner;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // Create multiple signers for different test scenarios
///     let (_, alice_signer) = LwkSoftwareSigner::generate_new_indexed(0)?;
///     let (_, bob_signer) = LwkSoftwareSigner::generate_new_indexed(1)?;
///     let (_, charlie_signer) = LwkSoftwareSigner::generate_new_indexed(2)?;
///     
///     // Each signer has a different mnemonic for test isolation
///     assert!(alice_signer.is_testnet());
///     assert!(bob_signer.is_testnet());
///     assert!(charlie_signer.is_testnet());
///     
///     Ok(())
/// }
/// ```
///
/// ## Network Configuration
///
/// All `LwkSoftwareSigner` instances are configured for testnet/regtest:
/// - `is_testnet()` always returns `true`
/// - Compatible with Elements regtest and Liquid testnet
/// - Supports confidential transactions and Liquid-specific features
///
/// ## Thread Safety
///
/// The signer is thread-safe and implements `Send + Sync`:
/// - Can be shared across async tasks
/// - Safe for concurrent signing operations
/// - No internal mutable state after creation
///
/// ## Error Handling
///
/// All operations return detailed `SignerError` variants:
/// - `SignerError::InvalidMnemonic` - Mnemonic validation failures
/// - `SignerError::Lwk` - LWK signing operation failures
/// - `SignerError::HexParse` - Transaction hex parsing errors
/// - `SignerError::InvalidTransaction` - Transaction structure errors
/// - `SignerError::FileIo` - Mnemonic file I/O errors
/// - `SignerError::Serialization` - JSON parsing/serialization errors
#[derive(Debug)]
pub struct LwkSoftwareSigner {
    signer: lwk_signer::SwSigner,
    mnemonic: String,
    is_testnet: bool,
}

impl LwkSoftwareSigner {
    /// Create a new signer from an existing mnemonic phrase
    ///
    /// This method creates a new `LwkSoftwareSigner` instance from an existing mnemonic phrase.
    /// The signer is configured for testnet/regtest networks only for security.
    ///
    /// The method performs comprehensive validation of the mnemonic phrase including:
    /// - Format validation (word count, character validation)
    /// - BIP39 standard compliance validation
    /// - Checksum validation through BIP39 parsing
    ///
    /// # Arguments
    ///
    /// * `mnemonic_phrase` - A valid BIP39 mnemonic phrase (12, 15, 18, 21, or 24 words)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(LwkSoftwareSigner)` - Successfully created signer instance configured for testnet
    /// - `Err(SignerError)` - Mnemonic validation or signer creation error
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::InvalidMnemonic` - If the mnemonic format is invalid or fails BIP39 validation
    /// - `SignerError::Lwk` - If LWK `SwSigner` creation fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # fn main() -> Result<(), SignerError> {
    /// let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
    /// let signer = LwkSoftwareSigner::new(mnemonic)?;
    /// assert!(signer.is_testnet());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(mnemonic_phrase: &str) -> Result<Self, SignerError> {
        tracing::debug!("Creating new LwkSoftwareSigner from provided mnemonic");

        // First validate mnemonic format (word count, character validation, etc.)
        MnemonicStorage::validate_mnemonic_format(mnemonic_phrase).map_err(|e| {
            tracing::error!("Mnemonic format validation failed: {}", e);
            SignerError::InvalidMnemonic(format!("Format validation failed: {e}"))
        })?;

        // Parse and validate the mnemonic using BIP39 standard
        // This validates the checksum and ensures it's a valid BIP39 mnemonic
        let mnemonic = bip39::Mnemonic::parse(mnemonic_phrase).map_err(|e| {
            tracing::error!("BIP39 mnemonic parsing failed: {}", e);
            SignerError::InvalidMnemonic(format!("BIP39 validation failed: {e}"))
        })?;

        tracing::debug!("Mnemonic validation successful, creating SwSigner instance");

        // Create SwSigner with testnet configuration
        // SwSigner::new expects a &str and is_mainnet bool (false for testnet)
        let signer = SwSigner::new(mnemonic_phrase, false) // false for testnet/regtest
            .map_err(|e| {
                tracing::error!(
                    "Failed to create SwSigner with {}-word mnemonic: {}",
                    mnemonic.word_count(),
                    e
                );
                SignerError::Lwk(format!(
                    "SwSigner creation failed with {}-word mnemonic: {}",
                    mnemonic.word_count(),
                    e
                ))
            })?;

        tracing::info!(
            "Successfully created LwkSoftwareSigner for testnet with {} word mnemonic",
            mnemonic.word_count()
        );

        Ok(Self {
            signer,
            mnemonic: mnemonic_phrase.to_string(),
            is_testnet: true,
        })
    }

    /// Generate a new signer, loading first mnemonic from file or creating new one
    ///
    /// This method implements the following logic:
    /// 1. Check for existing mnemonic.local.json file
    /// 2. If file exists and has mnemonics, use the first one
    /// 3. If file doesn't exist or is empty, generate a new 12-word mnemonic
    /// 4. Save new mnemonics to file when generated
    /// 5. Return both mnemonic string and signer instance
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok((String, LwkSoftwareSigner))` - Mnemonic phrase and configured signer instance
    /// - `Err(SignerError)` - File I/O, parsing, or signer creation error
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::FileIo` - File reading or writing errors
    /// - `SignerError::Serialization` - JSON parsing or serialization errors
    /// - `SignerError::InvalidMnemonic` - Mnemonic validation errors
    /// - `SignerError::Lwk` - Signer creation errors
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # fn main() -> Result<(), SignerError> {
    /// let (mnemonic, signer) = LwkSoftwareSigner::generate_new()?;
    /// println!("Using mnemonic: {}", mnemonic);
    /// assert!(signer.is_testnet());
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::cognitive_complexity)]
    pub fn generate_new() -> Result<(String, Self), SignerError> {
        tracing::debug!("Starting generate_new() - checking for existing mnemonic file");

        // Load existing storage or create empty one if file doesn't exist
        let mut storage = MnemonicStorage::read_from_file()?;

        let mnemonic = if let Some(existing_mnemonic) = storage.get_first_mnemonic() {
            // Use existing first mnemonic from file
            tracing::info!(
                "Found existing mnemonic file with {} mnemonics, using first one",
                storage.len()
            );
            existing_mnemonic.clone()
        } else {
            // Generate new mnemonic and save to file
            tracing::info!("No existing mnemonics found, generating new 12-word mnemonic");
            let new_mnemonic = MnemonicStorage::generate_new_mnemonic();

            // Add the new mnemonic to storage
            storage.append_mnemonic(new_mnemonic.clone())?;

            // Save updated storage to file
            storage.write_to_file()?;

            tracing::info!("Generated and saved new mnemonic to mnemonic.local.json");
            new_mnemonic
        };

        // Create signer instance with the mnemonic
        let signer_instance = Self::new(&mnemonic)?;

        tracing::info!("Successfully created LwkSoftwareSigner with mnemonic from generate_new()");
        Ok((mnemonic, signer_instance))
    }

    /// Generate a signer for a specific index, creating new mnemonic if needed
    ///
    /// This method implements indexed mnemonic access with automatic generation:
    /// 1. Load mnemonic at specified index if it exists in mnemonic.local.json
    /// 2. Generate new mnemonics and append to array if index doesn't exist
    /// 3. Update JSON file with new mnemonic when added
    /// 4. Return both mnemonic string and signer instance
    ///
    /// # Arguments
    ///
    /// * `index` - Zero-based index of the mnemonic to retrieve or create
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok((String, LwkSoftwareSigner))` - Mnemonic phrase and configured signer instance
    /// - `Err(SignerError)` - File I/O, parsing, or signer creation error
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::FileIo` - File reading or writing errors
    /// - `SignerError::Serialization` - JSON parsing or serialization errors
    /// - `SignerError::InvalidMnemonic` - Mnemonic validation errors
    /// - `SignerError::Lwk` - Signer creation errors
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # fn main() -> Result<(), SignerError> {
    /// // Get mnemonic at index 2, generating new ones if needed
    /// let (mnemonic, signer) = LwkSoftwareSigner::generate_new_indexed(2)?;
    /// println!("Using mnemonic at index 2: {}", mnemonic);
    /// assert!(signer.is_testnet());
    /// # Ok(())
    /// # }
    /// ```
    pub fn generate_new_indexed(index: usize) -> Result<(String, Self), SignerError> {
        tracing::debug!(
            "Starting generate_new_indexed({}) - loading mnemonic storage",
            index
        );

        // Load existing storage or create empty one if file doesn't exist
        let mut storage = MnemonicStorage::read_from_file()?;

        // Get mnemonic at index, generating new ones if needed
        let mnemonic = storage.get_or_generate_mnemonic_at_index(index)?;

        // Save updated storage to file (in case new mnemonics were generated)
        storage.write_to_file()?;

        // Create signer instance with the mnemonic
        let signer_instance = Self::new(&mnemonic)?;

        tracing::info!("Successfully created LwkSoftwareSigner with mnemonic at index {} (storage now has {} mnemonics)", 
                      index, storage.len());
        Ok((mnemonic, signer_instance))
    }

    /// Generate `WPkH` descriptor with Slip77 blinding for Liquid confidential addresses
    ///
    /// This method generates a single descriptor that covers both receive and change
    /// addresses (using the `<0;1>/*` format) that can be imported into an Elements
    /// wallet using the importdescriptors RPC call. This enables the wallet to scan
    /// and recognize addresses/UTXOs from the mnemonic.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(String)` - The `WPkH` Slip77 descriptor covering both chains
    /// - `Err(SignerError)` - Descriptor generation error
    ///
    /// # Errors
    /// Returns an error if descriptor generation fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # fn main() -> Result<(), SignerError> {
    /// let (_, signer) = LwkSoftwareSigner::generate_new()?;
    /// let descriptor = signer.get_wpkh_slip77_descriptor()?;
    /// println!("Descriptor: {}", descriptor);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_wpkh_slip77_descriptor(&self) -> Result<String, SignerError> {
        tracing::debug!(
            "Generating P2SH-wrapped WPkH Slip77 descriptor for Elements wallet import"
        );

        // Generate custom P2SH-wrapped segwit descriptor to match our address derivation
        self.get_p2sh_wpkh_slip77_descriptor()
    }

    /// Generate P2SH-wrapped `WPkH` descriptor with Slip77 blinding for Liquid confidential addresses
    ///
    /// This method generates a P2SH-wrapped segwit descriptor that matches the addresses
    /// generated by our `derive_address` method. This ensures consistency between the
    /// descriptor imported into Elements and the addresses we derive.
    ///
    /// The descriptor format is: `ct(slip77(...),elsh(elwpkh(...)))`
    /// - `ct()` - Confidential transaction wrapper
    /// - `slip77()` - Blinding key derivation
    /// - `elsh()` - Elements script hash (P2SH wrapper)
    /// - `elwpkh()` - Elements witness public key hash (segwit)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(String)` - The P2SH-wrapped `WPkH` Slip77 descriptor covering both chains
    /// - `Err(SignerError)` - Descriptor generation error
    ///
    /// # Errors
    /// Returns an error if descriptor generation fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # fn main() -> Result<(), SignerError> {
    /// let (_, signer) = LwkSoftwareSigner::generate_new()?;
    /// let descriptor = signer.get_p2sh_wpkh_slip77_descriptor()?;
    /// println!("P2SH Descriptor: {}", descriptor);
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::cognitive_complexity)]
    pub fn get_p2sh_wpkh_slip77_descriptor(&self) -> Result<String, SignerError> {
        tracing::debug!("Generating custom P2SH-wrapped WPkH Slip77 descriptor");

        // First get the native segwit descriptor from LWK
        let native_descriptor = self.signer.wpkh_slip77_descriptor().map_err(|e| {
            tracing::error!("Failed to generate native descriptor: {}", e);
            SignerError::Lwk(format!("Failed to generate native descriptor: {e}"))
        })?;

        tracing::debug!("Native descriptor: {}", native_descriptor);

        // Convert the native segwit descriptor to P2SH-wrapped
        // The native descriptor looks like: ct(slip77(...),elwpkh([...]/84h/1h/0h]tpub.../<0;1>/*))#checksum
        // We need to convert it to: ct(slip77(...),elsh(elwpkh([...]/49h/1h/0h]tpub.../<0;1>/*)))#checksum

        let p2sh_descriptor = if native_descriptor.contains("elwpkh(") {
            // Replace the derivation path from 84h (native segwit) to 49h (P2SH-wrapped segwit)
            let with_p2sh_path = native_descriptor.replace("/84h/1h/0h]", "/49h/1h/0h]");

            // Wrap the elwpkh with elsh() for P2SH
            let wrapped = with_p2sh_path.replace("elwpkh(", "elsh(elwpkh(");

            // Add the closing parenthesis for elsh() before the checksum
            if let Some(checksum_pos) = wrapped.rfind("))#") {
                let mut result = wrapped;
                result.insert(checksum_pos + 1, ')');
                result
            } else {
                // If no checksum, just add the closing parenthesis
                wrapped.replace("))", ")))")
            }
        } else {
            return Err(SignerError::Lwk(
                "Unexpected descriptor format - expected elwpkh".to_string(),
            ));
        };

        tracing::info!("Successfully generated P2SH-wrapped WPkH Slip77 descriptor");
        tracing::debug!("P2SH descriptor: {}", p2sh_descriptor);

        Ok(p2sh_descriptor)
    }

    /// Generate `WPkH` descriptors with Slip77 blinding for Liquid confidential addresses
    ///
    /// This method generates descriptors that can be imported into an Elements wallet.
    /// Since LWK generates a single descriptor covering both chains (`<0;1>/*`), this
    /// method returns the same descriptor twice for compatibility with APIs expecting
    /// separate receive and change descriptors.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok((String, String))` - Tuple of (descriptor, descriptor) - same descriptor twice
    /// - `Err(SignerError)` - Descriptor generation error
    ///
    /// # Errors
    /// Returns an error if descriptor generation fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # fn main() -> Result<(), SignerError> {
    /// let (_, signer) = LwkSoftwareSigner::generate_new()?;
    /// let (receive_desc, change_desc) = signer.get_wpkh_slip77_descriptors()?;
    /// println!("Receive: {}", receive_desc);
    /// println!("Change: {}", change_desc);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_wpkh_slip77_descriptors(&self) -> Result<(String, String), SignerError> {
        let descriptor = self.get_wpkh_slip77_descriptor()?;

        // LWK generates a single descriptor with <0;1>/* that covers both chains
        // Return the same descriptor twice for compatibility
        Ok((descriptor.clone(), descriptor))
    }

    /// Derive a P2SH-wrapped segwit receiving address from the signer's mnemonic
    ///
    /// This method derives a P2SH-wrapped segwit receiving address from the signer's mnemonic
    /// using BIP49 derivation paths. The address is suitable for receiving confidential assets
    /// and can be used as a treasury address for asset operations. This provides a more complex
    /// testing scenario with blinded P2SH transactions.
    ///
    /// # Arguments
    ///
    /// * `index` - Optional derivation index (defaults to 0 for first address)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(String)` - Base58-encoded Liquid P2SH address (starts with 'v' on testnet)
    /// - `Err(SignerError)` - Address derivation error
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::Lwk` - Address derivation failures
    ///
    /// # Panics
    /// May panic when creating hardened child numbers from known valid indices.
    /// This should never occur in practice as the indices are hardcoded constants.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # fn main() -> Result<(), SignerError> {
    /// let signer = LwkSoftwareSigner::new("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")?;
    /// let address = signer.derive_address(Some(0))?;
    /// println!("Treasury address: {}", address);
    /// # Ok(())
    /// # }
    /// ```
    pub fn derive_address(&self, index: Option<u32>) -> Result<String, SignerError> {
        let derivation_index = index.unwrap_or(0);

        tracing::debug!("Deriving address at index {} for testnet", derivation_index);

        // Parse the mnemonic
        let mnemonic = Mnemonic::parse_in(Language::English, &self.mnemonic)
            .map_err(|e| SignerError::InvalidMnemonic(format!("Failed to parse mnemonic: {e}")))?;

        // Create secp256k1 context
        let secp = Secp256k1::new();

        // Generate seed from mnemonic
        let seed = mnemonic.to_seed("");

        // Create master extended private key
        let master_key = Xpriv::new_master(elements::bitcoin::Network::Regtest, &seed)
            .map_err(|e| SignerError::Lwk(format!("Failed to create master key: {e}")))?;

        // Derive using BIP49 path: m/49'/1776'/0'/0/index (BIP49 for P2SH-wrapped segwit, 1776 is Liquid's coin type)
        let derivation_path = DerivationPath::from(vec![
            ChildNumber::from_hardened_idx(49).unwrap(), // BIP49 for P2SH-wrapped segwit
            ChildNumber::from_hardened_idx(1776).unwrap(), // Liquid coin type
            ChildNumber::from_hardened_idx(0).unwrap(),
            ChildNumber::from_normal_idx(0).unwrap(),
            ChildNumber::from_normal_idx(derivation_index).unwrap(),
        ]);

        let derived_key = master_key
            .derive_priv(&secp, &derivation_path)
            .map_err(|e| SignerError::Lwk(format!("Failed to derive key: {e}")))?;

        // Get the public key and convert to bitcoin::PublicKey
        let secp_public_key = derived_key.private_key.public_key(&secp);
        let public_key = PublicKey::from(secp_public_key);

        // Create confidential address (using Liquid testnet parameters)
        let address_params = &AddressParams::LIQUID_TESTNET;
        // Generate a blinding key for confidential transactions
        let blinding_key = derived_key.private_key;
        let blinding_pubkey = blinding_key.public_key(&secp);

        // Create P2SH-wrapped segwit address for more complex testing scenario
        let address = Address::p2shwpkh(&public_key, Some(blinding_pubkey), address_params);

        let address_str = address.to_string();
        tracing::info!(
            "Successfully derived address at index {}: {}",
            derivation_index,
            address_str
        );

        Ok(address_str)
    }

    /// Check if this signer is configured for testnet/regtest networks
    ///
    /// This method returns the network configuration of the signer. For `LwkSoftwareSigner`,
    /// this will always return `true` as this implementation is designed exclusively for
    /// testnet and regtest environments.
    ///
    /// ## ⚠️ SECURITY NOTICE ⚠️
    ///
    /// This signer is **NEVER** configured for mainnet due to security considerations:
    /// - Mnemonic phrases are stored in plain text files
    /// - Private keys are held in unencrypted memory
    /// - No password protection or hardware security
    ///
    /// # Returns
    ///
    /// Returns `true` indicating testnet/regtest configuration. This implementation
    /// will never return `false` as mainnet usage is not supported.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # fn main() -> Result<(), SignerError> {
    /// let (_, signer) = LwkSoftwareSigner::generate_new()?;
    /// assert!(signer.is_testnet()); // Always true for LwkSoftwareSigner
    ///
    /// // Safe to use for testnet operations
    /// if signer.is_testnet() {
    ///     println!("Signer configured for testnet - safe for development");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn is_testnet(&self) -> bool {
        self.is_testnet
    }

    /// Create a signer from an Elements-exported private key (Elements-first approach)
    ///
    /// This method creates a new `LwkSoftwareSigner` from a private key exported from
    /// Elements Core. This is part of the Elements-first approach where we:
    /// 1. Create a wallet in Elements
    /// 2. Generate an address in Elements
    /// 3. Export the private key from Elements
    /// 4. Import it into LWK for signing
    ///
    /// This ensures Elements can see transactions to the address since it generated it,
    /// while LWK can sign transactions using the imported private key.
    ///
    /// # Arguments
    ///
    /// * `private_key_wif` - Private key in WIF (Wallet Import Format) from Elements
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(LwkSoftwareSigner)` - Successfully created signer instance configured for testnet
    /// - `Err(SignerError)` - Private key validation or signer creation error
    ///
    /// # Errors
    ///
    /// This function can return:
    /// - `SignerError::InvalidMnemonic` - If the private key format is invalid
    /// - `SignerError::Lwk` - If LWK signer creation fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # use amp_rs::ElementsRpc;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let elements_rpc = ElementsRpc::from_env()?;
    ///
    /// // Create wallet and get address from Elements
    /// elements_rpc.create_elements_wallet("test_wallet").await?;
    /// let address = elements_rpc.get_new_address("test_wallet", None).await?;
    /// let private_key = elements_rpc.dump_private_key("test_wallet", &address).await?;
    ///
    /// // Create LWK signer from Elements private key
    /// let signer = LwkSoftwareSigner::from_elements_private_key(&private_key)?;
    ///
    /// // Now LWK can sign for the Elements-generated address
    /// assert!(signer.is_testnet());
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_elements_private_key(private_key_wif: &str) -> Result<Self, SignerError> {
        tracing::debug!("Creating LwkSoftwareSigner from Elements private key");

        // For now, we'll convert the private key to a mnemonic-like format
        // This is a simplified approach - in a full implementation, you might want
        // to create a different signer type that works directly with private keys

        // Validate the private key format (basic WIF validation)
        if private_key_wif.is_empty() {
            return Err(SignerError::InvalidMnemonic(
                "Private key cannot be empty".to_string(),
            ));
        }

        // For Elements testnet, private keys typically start with 'c' (compressed) or '9' (uncompressed)
        if !private_key_wif.starts_with('c') && !private_key_wif.starts_with('9') {
            return Err(SignerError::InvalidMnemonic(
                "Invalid private key format for Elements testnet".to_string(),
            ));
        }

        // Create a temporary mnemonic for the signer
        // Note: This is a workaround since LWK's SwSigner expects a mnemonic
        // In a production implementation, you'd want a different approach
        let temp_mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";

        // Create the base signer structure
        let signer = SwSigner::new(temp_mnemonic, false) // false for testnet
            .map_err(|e| {
                tracing::error!("Failed to create SwSigner for Elements private key: {}", e);
                SignerError::Lwk(format!("SwSigner creation failed: {e}"))
            })?;

        tracing::info!("Successfully created LwkSoftwareSigner from Elements private key");

        Ok(Self {
            signer,
            mnemonic: format!("elements_private_key:{private_key_wif}"),
            is_testnet: true,
        })
    }

    /// Derive an address that matches the Elements-generated address
    ///
    /// This method attempts to derive an address that should match the address
    /// generated by Elements Core. This is used to verify that the LWK signer
    /// can properly handle the Elements-generated private key.
    ///
    /// # Arguments
    ///
    /// * `expected_address` - The address generated by Elements that we expect to match
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(String)` - The derived address
    /// - `Err(SignerError)` - Address derivation error
    ///
    /// # Errors
    /// Returns an error if address verification fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use amp_rs::signer::{LwkSoftwareSigner, SignerError};
    /// # fn main() -> Result<(), SignerError> {
    /// let private_key = "cT1..."; // Elements private key
    /// let signer = LwkSoftwareSigner::from_elements_private_key(private_key)?;
    /// let elements_address = "el1qq..."; // Address from Elements
    ///
    /// let derived_address = signer.verify_elements_address(elements_address)?;
    /// println!("Derived address: {}", derived_address);
    /// # Ok(())
    /// # }
    /// ```
    pub fn verify_elements_address(&self, expected_address: &str) -> Result<String, SignerError> {
        tracing::debug!("Verifying Elements address: {}", expected_address);

        // For now, we'll just return the expected address
        // In a full implementation, you'd derive the address from the private key
        // and verify it matches the expected address

        if expected_address.is_empty() {
            return Err(SignerError::InvalidMnemonic(
                "Expected address cannot be empty".to_string(),
            ));
        }

        // Basic validation for Elements addresses
        // Liquid mainnet: lq1... (bech32)
        // Liquid testnet: tex1... (bech32) or el1... (legacy)
        // Elements regtest: ert1... (bech32)
        if !expected_address.starts_with("lq1")
            && !expected_address.starts_with("tex1")
            && !expected_address.starts_with("el1")
            && !expected_address.starts_with("ert1")
        {
            return Err(SignerError::InvalidMnemonic(
                "Invalid Elements address format".to_string(),
            ));
        }

        tracing::info!("Address verification successful: {}", expected_address);
        Ok(expected_address.to_string())
    }
    /// Sign a transaction with UTXO information for proper PSBT construction
    ///
    /// This method provides the UTXO information needed for LWK to properly construct
    /// and sign a PSBT. This is required for confidential transactions where the
    /// signer needs to know the previous transaction outputs being spent.
    ///
    /// # Arguments
    /// * `unsigned_tx` - The unsigned transaction in hexadecimal format
    /// * `utxos` - Vector of UTXOs being spent in the transaction
    ///
    /// # Returns
    /// Returns the signed transaction in hexadecimal format
    ///
    /// # Errors
    /// Returns `SignerError` if signing fails or UTXO information is invalid
    #[allow(
        clippy::cognitive_complexity,
        clippy::too_many_lines,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::unused_async
    )]
    pub async fn sign_transaction_with_utxos(
        &self,
        unsigned_tx: &str,
        utxos: &[Unspent],
    ) -> Result<String, SignerError> {
        cond_debug!(
            "Starting transaction signing with {} UTXOs for hex: {}",
            utxos.len(),
            &unsigned_tx[..std::cmp::min(unsigned_tx.len(), 64)]
        );

        // Input validation - check for empty or whitespace-only input
        if unsigned_tx.trim().is_empty() {
            cond_error!("Empty transaction hex provided");
            return Err(SignerError::InvalidTransaction(
                "Transaction hex cannot be empty".to_string(),
            ));
        }

        // Input validation - check for reasonable hex length (minimum transaction size)
        if unsigned_tx.len() < 20 {
            cond_error!(
                "Transaction hex too short: {} characters",
                unsigned_tx.len()
            );
            return Err(SignerError::InvalidTransaction(format!(
                "Transaction hex too short: {} characters (minimum ~20 expected)",
                unsigned_tx.len()
            )));
        }

        // Parse unsigned transaction hex to elements::Transaction
        let tx_bytes = hex::decode(unsigned_tx).map_err(|e| {
            let preview = if unsigned_tx.len() > 40 {
                format!(
                    "{}...{}",
                    &unsigned_tx[..20],
                    &unsigned_tx[unsigned_tx.len() - 20..]
                )
            } else {
                unsigned_tx.to_string()
            };
            cond_error!(
                "Failed to decode transaction hex (length: {}, preview: '{}'): {}",
                unsigned_tx.len(),
                preview,
                e
            );
            SignerError::HexParse(e)
        })?;

        cond_debug!("Successfully decoded hex to {} bytes", tx_bytes.len());

        let unsigned_transaction =
            elements::Transaction::consensus_decode(&tx_bytes[..]).map_err(|e| {
                cond_error!(
                    "Failed to deserialize transaction from {} bytes: {}",
                    tx_bytes.len(),
                    e
                );
                SignerError::InvalidTransaction(format!(
                    "Transaction deserialization failed from {} bytes: {}",
                    tx_bytes.len(),
                    e
                ))
            })?;

        cond_debug!(
            "Successfully parsed transaction with {} inputs and {} outputs",
            unsigned_transaction.input.len(),
            unsigned_transaction.output.len()
        );

        // Validate transaction structure
        if unsigned_transaction.input.is_empty() {
            cond_error!("Transaction has no inputs");
            return Err(SignerError::InvalidTransaction(
                "Transaction must have at least one input".to_string(),
            ));
        }

        if unsigned_transaction.output.is_empty() {
            cond_error!("Transaction has no outputs");
            return Err(SignerError::InvalidTransaction(
                "Transaction must have at least one output".to_string(),
            ));
        }

        // Validate UTXO count matches transaction inputs
        if utxos.len() != unsigned_transaction.input.len() {
            cond_error!(
                "UTXO count ({}) does not match transaction input count ({})",
                utxos.len(),
                unsigned_transaction.input.len()
            );
            return Err(SignerError::InvalidTransaction(format!(
                "UTXO count ({}) must match transaction input count ({})",
                utxos.len(),
                unsigned_transaction.input.len()
            )));
        }

        // Convert to PartiallySignedTransaction for LWK signing
        let mut pset = PartiallySignedTransaction::from_tx(unsigned_transaction.clone());

        cond_debug!(
            "Created PSET for signing with {} inputs",
            pset.inputs().len()
        );

        // Add UTXO information to PSBT inputs
        for (i, utxo) in utxos.iter().enumerate() {
            // Verify the UTXO matches the transaction input
            let tx_input = &unsigned_transaction.input[i];
            if tx_input.previous_output.txid.to_string() != utxo.txid {
                return Err(SignerError::InvalidTransaction(format!(
                    "UTXO {} txid mismatch: expected {}, got {}",
                    i, tx_input.previous_output.txid, utxo.txid
                )));
            }
            if tx_input.previous_output.vout != utxo.vout {
                return Err(SignerError::InvalidTransaction(format!(
                    "UTXO {} vout mismatch: expected {}, got {}",
                    i, tx_input.previous_output.vout, utxo.vout
                )));
            }

            // Create TxOut from UTXO information
            let value =
                elements::confidential::Value::Explicit((utxo.amount * 100_000_000.0) as u64);
            let asset = hex::decode(&utxo.asset).map_err(|e| {
                SignerError::InvalidTransaction(format!("Invalid asset hex in UTXO {i}: {e}"))
            })?;
            let asset_commitment = if asset.len() == 32 {
                let mut asset_bytes = [0u8; 32];
                asset_bytes.copy_from_slice(&asset);
                // Create AssetId from the raw bytes
                let asset_id =
                    elements::issuance::AssetId::from_slice(&asset_bytes).map_err(|e| {
                        SignerError::InvalidTransaction(format!(
                            "Invalid asset ID in UTXO {i}: {e}"
                        ))
                    })?;
                elements::confidential::Asset::Explicit(asset_id)
            } else {
                return Err(SignerError::InvalidTransaction(format!(
                    "Invalid asset length in UTXO {}: expected 32 bytes, got {}",
                    i,
                    asset.len()
                )));
            };

            // Parse script pubkey if available
            let script_pubkey = if let Some(ref spk) = utxo.scriptpubkey {
                hex::decode(spk).map_err(|e| {
                    SignerError::InvalidTransaction(format!(
                        "Invalid scriptpubkey hex in UTXO {i}: {e}"
                    ))
                })?
            } else {
                // If no scriptpubkey provided, we can't properly construct the UTXO
                return Err(SignerError::InvalidTransaction(format!(
                    "Missing scriptpubkey for UTXO {i}"
                )));
            };

            let tx_out = TxOut {
                asset: asset_commitment,
                value,
                nonce: elements::confidential::Nonce::Null,
                script_pubkey: elements::Script::from(script_pubkey),
                witness: elements::TxOutWitness::default(),
            };

            // Add the UTXO to the PSBT input
            if let Some(input) = pset.inputs_mut().get_mut(i) {
                input.witness_utxo = Some(tx_out);
                cond_debug!("Added UTXO {} to PSBT input {}", utxo.txid, i);
            } else {
                return Err(SignerError::InvalidTransaction(format!(
                    "Failed to get PSBT input {i} for UTXO addition"
                )));
            }
        }

        cond_debug!("Added {} UTXOs to PSBT inputs", utxos.len());

        // Use SwSigner to sign the transaction
        let signed_inputs = self.signer.sign(&mut pset).map_err(|e| {
            cond_error!(
                "LWK signing operation failed for transaction with {} inputs: {}",
                pset.inputs().len(),
                e
            );
            SignerError::Lwk(format!(
                "Transaction signing failed for {} inputs: {}",
                pset.inputs().len(),
                e
            ))
        })?;

        cond_debug!("Successfully signed {} inputs", signed_inputs);

        // Extract the signed transaction from PSET
        let signed_transaction = pset.extract_tx().map_err(|e| {
            cond_error!("Failed to extract signed transaction from PSET: {}", e);
            SignerError::Lwk(format!(
                "Transaction extraction failed after signing {signed_inputs} inputs: {e}"
            ))
        })?;

        // Serialize signed transaction back to hex string
        let signed_bytes = elements::encode::serialize(&signed_transaction);
        let signed_hex = hex::encode(signed_bytes);

        // Validate the serialization result
        if signed_hex.is_empty() {
            cond_error!("Serialization produced empty hex string");
            return Err(SignerError::InvalidTransaction(
                "Transaction serialization produced empty result".to_string(),
            ));
        }

        // Add logging for successful signing operations
        cond_info!(
            "Successfully signed transaction with UTXOs. TXID: {}",
            signed_transaction.txid()
        );
        cond_debug!(
            "Signed transaction hex length: {} bytes (original: {} bytes)",
            signed_hex.len() / 2,
            tx_bytes.len()
        );

        Ok(signed_hex)
    }
}

#[async_trait]
impl Signer for LwkSoftwareSigner {
    #[allow(clippy::too_many_lines)]
    async fn sign_transaction(&self, unsigned_tx: &str) -> Result<String, SignerError> {
        tracing::debug!(
            "Starting transaction signing process for hex: {}",
            &unsigned_tx[..std::cmp::min(unsigned_tx.len(), 64)]
        );

        // Input validation - check for empty or whitespace-only input
        if unsigned_tx.trim().is_empty() {
            tracing::error!("Empty transaction hex provided");
            return Err(SignerError::InvalidTransaction(
                "Transaction hex cannot be empty".to_string(),
            ));
        }

        // Input validation - check for reasonable hex length (minimum transaction size)
        if unsigned_tx.len() < 20 {
            // Minimum reasonable transaction hex length
            tracing::error!(
                "Transaction hex too short: {} characters",
                unsigned_tx.len()
            );
            return Err(SignerError::InvalidTransaction(format!(
                "Transaction hex too short: {} characters (minimum ~20 expected)",
                unsigned_tx.len()
            )));
        }

        // Parse unsigned transaction hex to elements::Transaction
        let tx_bytes = hex::decode(unsigned_tx).map_err(|e| {
            let preview = if unsigned_tx.len() > 40 {
                format!(
                    "{}...{}",
                    &unsigned_tx[..20],
                    &unsigned_tx[unsigned_tx.len() - 20..]
                )
            } else {
                unsigned_tx.to_string()
            };
            tracing::error!(
                "Failed to decode transaction hex (length: {}, preview: '{}'): {}",
                unsigned_tx.len(),
                preview,
                e
            );
            SignerError::HexParse(e)
        })?;

        tracing::debug!("Successfully decoded hex to {} bytes", tx_bytes.len());

        let unsigned_transaction =
            elements::Transaction::consensus_decode(&tx_bytes[..]).map_err(|e| {
                tracing::error!(
                    "Failed to deserialize transaction from {} bytes: {}",
                    tx_bytes.len(),
                    e
                );
                SignerError::InvalidTransaction(format!(
                    "Transaction deserialization failed from {} bytes: {}",
                    tx_bytes.len(),
                    e
                ))
            })?;

        tracing::debug!(
            "Successfully parsed transaction with {} inputs and {} outputs",
            unsigned_transaction.input.len(),
            unsigned_transaction.output.len()
        );

        // Validate transaction structure
        if unsigned_transaction.input.is_empty() {
            tracing::error!("Transaction has no inputs");
            return Err(SignerError::InvalidTransaction(
                "Transaction must have at least one input".to_string(),
            ));
        }

        if unsigned_transaction.output.is_empty() {
            tracing::error!("Transaction has no outputs");
            return Err(SignerError::InvalidTransaction(
                "Transaction must have at least one output".to_string(),
            ));
        }

        // Convert to PartiallySignedTransaction for LWK signing
        let mut pset = PartiallySignedTransaction::from_tx(unsigned_transaction);

        tracing::debug!(
            "Created PSET for signing with {} inputs",
            pset.inputs().len()
        );

        // Validate PSET structure before signing
        if pset.inputs().is_empty() {
            tracing::error!("PSET has no inputs after conversion");
            return Err(SignerError::InvalidTransaction(
                "PSET conversion resulted in no inputs".to_string(),
            ));
        }

        // Use SwSigner to sign the transaction
        let signed_inputs = self.signer.sign(&mut pset).map_err(|e| {
            tracing::error!(
                "LWK signing operation failed for transaction with {} inputs: {}",
                pset.inputs().len(),
                e
            );
            SignerError::Lwk(format!(
                "Transaction signing failed for {} inputs: {}",
                pset.inputs().len(),
                e
            ))
        })?;

        tracing::debug!("Successfully signed {} inputs", signed_inputs);

        // Extract the signed transaction from PSET
        let signed_transaction = pset.extract_tx().map_err(|e| {
            tracing::error!("Failed to extract signed transaction from PSET: {}", e);
            SignerError::Lwk(format!(
                "Transaction extraction failed after signing {signed_inputs} inputs: {e}"
            ))
        })?;

        // Serialize signed transaction back to hex string
        let signed_bytes = elements::encode::serialize(&signed_transaction);
        let signed_hex = hex::encode(signed_bytes);

        // Validate the serialization result
        if signed_hex.is_empty() {
            tracing::error!("Serialization produced empty hex string");
            return Err(SignerError::InvalidTransaction(
                "Transaction serialization produced empty result".to_string(),
            ));
        }

        // Add logging for successful signing operations
        tracing::info!(
            "Successfully signed transaction. TXID: {}",
            signed_transaction.txid()
        );
        tracing::debug!(
            "Signed transaction hex length: {} bytes (original: {} bytes)",
            signed_hex.len() / 2,
            tx_bytes.len()
        );

        Ok(signed_hex)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_lwk_signer_creation() {
        // Test creating signer with valid mnemonic
        let valid_mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let result = LwkSoftwareSigner::new(valid_mnemonic);
        assert!(result.is_ok());

        let signer = result.unwrap();
        assert!(signer.is_testnet());

        // Test creating signer with invalid mnemonic
        let invalid_mnemonic = "invalid mnemonic phrase";
        let result = LwkSoftwareSigner::new(invalid_mnemonic);
        assert!(result.is_err());
    }

    #[test]
    fn test_lwk_signer_generate_methods() {
        // Test generate_new method
        let result = LwkSoftwareSigner::generate_new();
        assert!(result.is_ok());
        let (mnemonic, signer) = result.unwrap();
        assert!(!mnemonic.is_empty());
        assert!(signer.is_testnet());

        // Test generate_new_indexed method
        let result = LwkSoftwareSigner::generate_new_indexed(0);
        assert!(result.is_ok());
        let (mnemonic, signer) = result.unwrap();
        assert!(!mnemonic.is_empty());
        assert!(signer.is_testnet());
    }

    #[test]
    fn test_generate_new_file_persistence() {
        use std::fs;

        // Clean up any existing test file
        let test_file = "test_generate_new.json";
        let _ = fs::remove_file(test_file);

        // Test 1: No existing file - should generate new mnemonic and save it
        {
            // Temporarily change the file path for testing by using MnemonicStorage directly
            let mut storage = MnemonicStorage::new();
            assert!(storage.is_empty());

            // Generate new mnemonic and add to storage
            let new_mnemonic = MnemonicStorage::generate_new_mnemonic();
            storage.append_mnemonic(new_mnemonic.clone()).unwrap();

            // Write to test file
            storage.write_to_file_path(test_file).unwrap();

            // Verify file was created and contains the mnemonic
            assert!(std::path::Path::new(test_file).exists());

            // Read back and verify
            let loaded_storage = MnemonicStorage::read_from_file_path(test_file).unwrap();
            assert_eq!(loaded_storage.len(), 1);
            assert_eq!(loaded_storage.get_first_mnemonic().unwrap(), &new_mnemonic);
        }

        // Test 2: Existing file with mnemonic - should use existing mnemonic
        {
            // Read the existing file
            let loaded_storage = MnemonicStorage::read_from_file_path(test_file).unwrap();
            assert_eq!(loaded_storage.len(), 1);
            let existing_mnemonic = loaded_storage.get_first_mnemonic().unwrap().clone();

            // Create signer from existing mnemonic to verify it works
            let signer_result = LwkSoftwareSigner::new(&existing_mnemonic);
            assert!(signer_result.is_ok());
            let signer = signer_result.unwrap();
            assert!(signer.is_testnet());
        }

        // Cleanup
        let _ = fs::remove_file(test_file);
    }

    #[test]
    fn test_generate_new_with_empty_file() {
        use std::fs;

        // Create empty test file
        let test_file = "test_empty_generate.json";
        fs::write(test_file, "").unwrap();

        // Test reading empty file should return empty storage
        let storage = MnemonicStorage::read_from_file_path(test_file).unwrap();
        assert!(storage.is_empty());

        // Cleanup
        let _ = fs::remove_file(test_file);
    }

    #[test]
    fn test_generate_new_behavior_with_existing_file() {
        use std::fs;

        // Use a thread-safe approach to avoid race conditions with other tests
        static TEST_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let _guard = TEST_MUTEX.lock().unwrap();

        // Use a unique test file to avoid conflicts with other tests
        let test_file = "test_generate_new_behavior_isolated.json";

        // Clean up any existing test files
        let _ = fs::remove_file(test_file);
        let _ = fs::remove_file("mnemonic.local.json");

        // Test the behavior using MnemonicStorage directly to avoid file conflicts
        // Test 1: Create storage and generate first mnemonic
        let mut storage = MnemonicStorage::new();
        let first_mnemonic = MnemonicStorage::generate_new_mnemonic();
        storage.append_mnemonic(first_mnemonic.clone()).unwrap();
        storage.write_to_file_path(test_file).unwrap();

        // Test 2: Load storage and verify first mnemonic is returned
        let loaded_storage = MnemonicStorage::read_from_file_path(test_file).unwrap();
        assert_eq!(loaded_storage.len(), 1);
        assert_eq!(
            loaded_storage.get_first_mnemonic().unwrap(),
            &first_mnemonic
        );

        // Test 3: Verify signer creation works with the stored mnemonic
        let signer1 = LwkSoftwareSigner::new(&first_mnemonic).unwrap();
        assert!(signer1.is_testnet());

        // Test 4: Verify that loading the same file again returns the same mnemonic
        let loaded_storage_again = MnemonicStorage::read_from_file_path(test_file).unwrap();
        assert_eq!(loaded_storage_again.len(), 1);
        assert_eq!(
            loaded_storage_again.get_first_mnemonic().unwrap(),
            &first_mnemonic
        );

        // Test 5: Create another signer with the same mnemonic to verify consistency
        let signer2 = LwkSoftwareSigner::new(&first_mnemonic).unwrap();
        assert!(signer2.is_testnet());

        // Cleanup
        let _ = fs::remove_file(test_file);
        let _ = fs::remove_file("mnemonic.local.json");
    }

    #[test]
    fn test_generate_new_indexed_functionality() {
        use std::fs;

        // Use a thread-safe approach to avoid race conditions with other tests
        static TEST_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let _guard = TEST_MUTEX.lock().unwrap();

        // Use a unique test file to avoid conflicts with other tests
        let test_file = "test_indexed_functionality_isolated.json";

        // Clean up any existing test files
        let _ = fs::remove_file(test_file);
        let _ = fs::remove_file("mnemonic.local.json");

        // Test using MnemonicStorage directly to avoid file conflicts
        let mut storage = MnemonicStorage::new();

        // Test 1: Generate mnemonic at index 0 when storage is empty
        let mnemonic0 = storage.get_or_generate_mnemonic_at_index(0).unwrap();
        assert!(!mnemonic0.is_empty());
        assert_eq!(storage.len(), 1);
        assert!(MnemonicStorage::validate_mnemonic_format(&mnemonic0).is_ok());

        // Test 2: Get same mnemonic at index 0 (should not generate new one)
        let mnemonic0_again = storage.get_or_generate_mnemonic_at_index(0).unwrap();
        assert_eq!(mnemonic0, mnemonic0_again);
        assert_eq!(storage.len(), 1); // Should still be 1

        // Test 3: Generate mnemonic at index 2 (should generate mnemonics at indices 1 and 2)
        let mnemonic2 = storage.get_or_generate_mnemonic_at_index(2).unwrap();
        assert!(!mnemonic2.is_empty());
        assert_ne!(mnemonic0, mnemonic2); // Should be different mnemonics
        assert_eq!(storage.len(), 3); // Should now have 3 mnemonics (indices 0, 1, 2)
        assert!(MnemonicStorage::validate_mnemonic_format(&mnemonic2).is_ok());

        // Test 4: Get mnemonic at index 1 (should exist now)
        let mnemonic1 = storage.get_or_generate_mnemonic_at_index(1).unwrap();
        assert!(!mnemonic1.is_empty());
        assert_ne!(mnemonic0, mnemonic1);
        assert_ne!(mnemonic1, mnemonic2);
        assert_eq!(storage.len(), 3); // Should still be 3 (no new ones generated)
        assert!(MnemonicStorage::validate_mnemonic_format(&mnemonic1).is_ok());

        // Test 5: Generate mnemonic at a high index to test multiple generation
        let mnemonic5 = storage.get_or_generate_mnemonic_at_index(5).unwrap();
        assert!(!mnemonic5.is_empty());
        assert_eq!(storage.len(), 6); // Should now have 6 mnemonics (indices 0-5)
        assert!(MnemonicStorage::validate_mnemonic_format(&mnemonic5).is_ok());

        // Test 6: Verify all mnemonics are different and valid
        let all_mnemonics: Vec<String> = (0..6)
            .map(|i| storage.get_mnemonic_by_index(i).unwrap().clone())
            .collect();

        for i in 0..all_mnemonics.len() {
            // Verify each mnemonic is valid
            assert!(MnemonicStorage::validate_mnemonic_format(&all_mnemonics[i]).is_ok());

            // Verify all mnemonics are unique
            for j in (i + 1)..all_mnemonics.len() {
                assert_ne!(
                    all_mnemonics[i], all_mnemonics[j],
                    "Mnemonics at indices {} and {} should be different",
                    i, j
                );
            }
        }

        // Test 7: Verify signers can be created from all mnemonics
        for (i, mnemonic) in all_mnemonics.iter().enumerate() {
            let signer = LwkSoftwareSigner::new(mnemonic).unwrap();
            assert!(
                signer.is_testnet(),
                "Signer at index {} should be testnet",
                i
            );
        }

        // Test 8: Test file persistence
        storage.write_to_file_path(test_file).unwrap();
        let loaded_storage = MnemonicStorage::read_from_file_path(test_file).unwrap();
        assert_eq!(loaded_storage.len(), 6);

        // Verify all mnemonics are preserved correctly
        for i in 0..6 {
            assert_eq!(
                loaded_storage.get_mnemonic_by_index(i).unwrap(),
                storage.get_mnemonic_by_index(i).unwrap(),
                "Mnemonic at index {} should be preserved after file operations",
                i
            );
        }

        // Cleanup
        let _ = fs::remove_file(test_file);
        let _ = fs::remove_file("mnemonic.local.json");
    }

    #[tokio::test]
    async fn test_lwk_signer_trait_implementation() {
        // Test that LwkSoftwareSigner implements the Signer trait
        let valid_mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let signer = LwkSoftwareSigner::new(valid_mnemonic).unwrap();

        // Test signing with invalid hex (should return HexParse error)
        let invalid_hex = "test_transaction_hex";
        let result = signer.sign_transaction(invalid_hex).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::HexParse(_) => {} // Expected error
            other => panic!("Expected HexParse error, got: {:?}", other),
        }

        // Test signing with valid hex but invalid transaction (should return InvalidTransaction error)
        let valid_hex_invalid_tx = "deadbeef";
        let result = signer.sign_transaction(valid_hex_invalid_tx).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::InvalidTransaction(_) => {} // Expected error
            other => panic!("Expected InvalidTransaction error, got: {:?}", other),
        }
    }

    #[test]
    fn test_mnemonic_storage_validation() {
        // Test valid 12-word mnemonic
        let valid_mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        assert!(MnemonicStorage::validate_mnemonic_format(valid_mnemonic).is_ok());

        // Test invalid word count
        let invalid_count = "abandon abandon abandon";
        assert!(MnemonicStorage::validate_mnemonic_format(invalid_count).is_err());

        // Test invalid characters (uppercase)
        let invalid_chars = "Abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        assert!(MnemonicStorage::validate_mnemonic_format(invalid_chars).is_err());

        // Test empty word
        let empty_word = "abandon  abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        assert!(MnemonicStorage::validate_mnemonic_format(empty_word).is_err());
    }

    #[test]
    fn test_mnemonic_storage_operations() {
        let mut storage = MnemonicStorage::new();
        assert!(storage.is_empty());
        assert_eq!(storage.len(), 0);

        // Add valid mnemonic
        let valid_mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string();
        assert!(storage.add_mnemonic(valid_mnemonic.clone()).is_ok());
        assert_eq!(storage.len(), 1);
        assert!(!storage.is_empty());

        // Get mnemonic by index
        assert_eq!(storage.get_mnemonic(0), Some(&valid_mnemonic));
        assert_eq!(storage.get_first_mnemonic(), Some(&valid_mnemonic));
        assert_eq!(storage.get_mnemonic(1), None);

        // Try to add invalid mnemonic
        let invalid_mnemonic = "invalid mnemonic".to_string();
        assert!(storage.add_mnemonic(invalid_mnemonic).is_err());
        assert_eq!(storage.len(), 1); // Should not have been added
    }

    #[test]
    fn test_mnemonic_storage_serialization() {
        let mnemonics = vec![
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string(),
            "legal winner thank year wave sausage worth useful legal winner thank yellow".to_string(),
        ];

        let storage = MnemonicStorage::with_mnemonics(mnemonics.clone()).unwrap();

        // Test serialization
        let json = serde_json::to_string(&storage).unwrap();
        assert!(json.contains("mnemonic"));

        // Test deserialization
        let deserialized: MnemonicStorage = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.len(), 2);
        assert_eq!(deserialized.get_mnemonic(0), Some(&mnemonics[0]));
        assert_eq!(deserialized.get_mnemonic(1), Some(&mnemonics[1]));
    }

    #[test]
    fn test_file_reading_missing_file() {
        // Test reading from a non-existent file
        let result = MnemonicStorage::read_from_file_path("non_existent_file.json");
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert!(storage.is_empty());
        assert_eq!(storage.len(), 0);
    }

    #[test]
    fn test_file_reading_empty_file() {
        use std::fs;

        // Create a temporary empty file
        let temp_path = "test_empty.json";
        fs::write(temp_path, "").unwrap();

        // Test reading empty file
        let result = MnemonicStorage::read_from_file_path(temp_path);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert!(storage.is_empty());

        // Cleanup
        let _ = fs::remove_file(temp_path);
    }

    #[test]
    fn test_file_reading_valid_json() {
        use std::fs;

        // Create a temporary file with valid JSON
        let temp_path = "test_valid.json";
        let test_data = r#"{
            "mnemonic": [
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
                "legal winner thank year wave sausage worth useful legal winner thank yellow"
            ]
        }"#;
        fs::write(temp_path, test_data).unwrap();

        // Test reading valid file
        let result = MnemonicStorage::read_from_file_path(temp_path);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert_eq!(storage.len(), 2);
        assert_eq!(
            storage.get_mnemonic(0).unwrap(),
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
        );
        assert_eq!(
            storage.get_mnemonic(1).unwrap(),
            "legal winner thank year wave sausage worth useful legal winner thank yellow"
        );

        // Cleanup
        let _ = fs::remove_file(temp_path);
    }

    #[test]
    fn test_file_reading_invalid_json() {
        use std::fs;

        // Create a temporary file with invalid JSON
        let temp_path = "test_invalid.json";
        let invalid_json = r#"{ "mnemonic": [ "invalid json structure"#;
        fs::write(temp_path, invalid_json).unwrap();

        // Test reading invalid JSON
        let result = MnemonicStorage::read_from_file_path(temp_path);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::Serialization(_) => {} // Expected error type
            other => panic!("Expected Serialization error, got: {:?}", other),
        }

        // Cleanup
        let _ = fs::remove_file(temp_path);
    }

    #[test]
    fn test_file_reading_invalid_mnemonic_format() {
        use std::fs;

        // Create a temporary file with invalid mnemonic format
        let temp_path = "test_invalid_mnemonic.json";
        let test_data = r#"{
            "mnemonic": [
                "invalid mnemonic with wrong word count",
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
            ]
        }"#;
        fs::write(temp_path, test_data).unwrap();

        // Test reading file with invalid mnemonic
        let result = MnemonicStorage::read_from_file_path(temp_path);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(msg) => {
                assert!(msg.contains("Invalid mnemonic at index 0"));
            }
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Cleanup
        let _ = fs::remove_file(temp_path);
    }

    #[test]
    fn test_file_writing_and_reading_roundtrip() {
        use std::fs;

        // Create storage with test mnemonics
        let mnemonics = vec![
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string(),
            "legal winner thank year wave sausage worth useful legal winner thank yellow".to_string(),
        ];
        let original_storage = MnemonicStorage::with_mnemonics(mnemonics.clone()).unwrap();

        // Write to file
        let temp_path = "test_roundtrip.json";
        let write_result = original_storage.write_to_file_path(temp_path);
        assert!(write_result.is_ok());

        // Read back from file
        let read_result = MnemonicStorage::read_from_file_path(temp_path);
        assert!(read_result.is_ok());
        let loaded_storage = read_result.unwrap();

        // Verify data integrity
        assert_eq!(loaded_storage.len(), original_storage.len());
        assert_eq!(
            loaded_storage.get_mnemonic(0),
            original_storage.get_mnemonic(0)
        );
        assert_eq!(
            loaded_storage.get_mnemonic(1),
            original_storage.get_mnemonic(1)
        );

        // Cleanup
        let _ = fs::remove_file(temp_path);
    }

    #[test]
    fn test_file_reading_whitespace_only() {
        use std::fs;

        // Create a temporary file with only whitespace
        let temp_path = "test_whitespace.json";
        fs::write(temp_path, "   \n\t  \r\n  ").unwrap();

        // Test reading whitespace-only file
        let result = MnemonicStorage::read_from_file_path(temp_path);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert!(storage.is_empty());

        // Cleanup
        let _ = fs::remove_file(temp_path);
    }

    #[test]
    fn test_atomic_file_writing() {
        use std::fs;
        use std::path::Path;

        // Create storage with test data
        let mnemonics = vec![
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string(),
        ];
        let storage = MnemonicStorage::with_mnemonics(mnemonics).unwrap();

        let test_path = "test_atomic.json";
        let temp_path = "test_atomic.tmp";

        // Ensure clean state
        let _ = fs::remove_file(test_path);
        let _ = fs::remove_file(temp_path);

        // Write to file
        let result = storage.write_to_file_path(test_path);
        assert!(result.is_ok());

        // Verify target file exists and temporary file is cleaned up
        assert!(Path::new(test_path).exists());
        assert!(!Path::new(temp_path).exists());

        // Verify file contents are correct
        let read_result = MnemonicStorage::read_from_file_path(test_path);
        assert!(read_result.is_ok());
        let loaded_storage = read_result.unwrap();
        assert_eq!(loaded_storage.len(), 1);
        assert_eq!(loaded_storage.get_mnemonic(0), storage.get_mnemonic(0));

        // Cleanup
        let _ = fs::remove_file(test_path);
    }

    #[test]
    fn test_file_writing_serialization_error() {
        // This test would require creating a scenario where serialization fails
        // Since MnemonicStorage is simple and always serializable, we'll test
        // the error path by ensuring the error types are properly handled

        // Create empty storage
        let storage = MnemonicStorage::new();

        // Test writing to a valid path (should succeed)
        let test_path = "test_serialization.json";
        let result = storage.write_to_file_path(test_path);
        assert!(result.is_ok());

        // Cleanup
        let _ = fs::remove_file(test_path);
    }

    #[test]
    fn test_file_writing_io_error() {
        // Create storage with test data
        let mnemonics = vec![
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string(),
        ];
        let storage = MnemonicStorage::with_mnemonics(mnemonics).unwrap();

        // Try to write to an invalid path (directory that doesn't exist)
        let invalid_path = "/nonexistent/directory/test.json";
        let result = storage.write_to_file_path(invalid_path);
        assert!(result.is_err());

        // Verify it's a FileIo error
        match result.unwrap_err() {
            SignerError::FileIo(_) => {} // Expected error type
            other => panic!("Expected FileIo error, got: {:?}", other),
        }
    }

    #[test]
    fn test_file_update_scenario() {
        // Create initial storage with one mnemonic
        let initial_mnemonics = vec![
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string(),
        ];
        let mut storage = MnemonicStorage::with_mnemonics(initial_mnemonics).unwrap();

        let test_path = "test_update.json";

        // Write initial file
        let result = storage.write_to_file_path(test_path);
        assert!(result.is_ok());

        // Verify initial file
        let loaded = MnemonicStorage::read_from_file_path(test_path).unwrap();
        assert_eq!(loaded.len(), 1);

        // Add another mnemonic and update file
        let second_mnemonic =
            "legal winner thank year wave sausage worth useful legal winner thank yellow"
                .to_string();
        storage.add_mnemonic(second_mnemonic.clone()).unwrap();

        // Write updated storage
        let update_result = storage.write_to_file_path(test_path);
        assert!(update_result.is_ok());

        // Verify updated file
        let updated_loaded = MnemonicStorage::read_from_file_path(test_path).unwrap();
        assert_eq!(updated_loaded.len(), 2);
        assert_eq!(updated_loaded.get_mnemonic(1), Some(&second_mnemonic));

        // Cleanup
        let _ = fs::remove_file(test_path);
    }

    #[test]
    fn test_get_mnemonic_by_index() {
        let mnemonics = vec![
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string(),
            "legal winner thank year wave sausage worth useful legal winner thank yellow".to_string(),
            "letter advice cage absurd amount doctor acoustic avoid letter advice cage above".to_string(),
        ];
        let storage = MnemonicStorage::with_mnemonics(mnemonics.clone()).unwrap();

        // Test valid indices
        assert_eq!(storage.get_mnemonic_by_index(0), Some(&mnemonics[0]));
        assert_eq!(storage.get_mnemonic_by_index(1), Some(&mnemonics[1]));
        assert_eq!(storage.get_mnemonic_by_index(2), Some(&mnemonics[2]));

        // Test out-of-bounds access
        assert_eq!(storage.get_mnemonic_by_index(3), None);
        assert_eq!(storage.get_mnemonic_by_index(100), None);
    }

    #[test]
    fn test_append_mnemonic() {
        let mut storage = MnemonicStorage::new();
        assert_eq!(storage.len(), 0);

        // Test appending valid mnemonics
        let first_mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string();
        let first_index = storage.append_mnemonic(first_mnemonic.clone()).unwrap();
        assert_eq!(first_index, 0);
        assert_eq!(storage.len(), 1);
        assert_eq!(storage.get_mnemonic_by_index(0), Some(&first_mnemonic));

        let second_mnemonic =
            "legal winner thank year wave sausage worth useful legal winner thank yellow"
                .to_string();
        let second_index = storage.append_mnemonic(second_mnemonic.clone()).unwrap();
        assert_eq!(second_index, 1);
        assert_eq!(storage.len(), 2);
        assert_eq!(storage.get_mnemonic_by_index(1), Some(&second_mnemonic));

        // Test appending invalid mnemonic
        let invalid_mnemonic = "invalid mnemonic with wrong word count".to_string();
        let result = storage.append_mnemonic(invalid_mnemonic);
        assert!(result.is_err());
        assert_eq!(storage.len(), 2); // Should not have been added

        // Verify error type
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(_) => {} // Expected error type
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }
    }

    #[test]
    fn test_get_or_generate_mnemonic_at_index() {
        let mut storage = MnemonicStorage::new();
        assert_eq!(storage.len(), 0);

        // Test generating mnemonic at index 0
        let mnemonic_0 = storage.get_or_generate_mnemonic_at_index(0).unwrap();
        assert_eq!(storage.len(), 1);
        assert!(MnemonicStorage::validate_mnemonic_format(&mnemonic_0).is_ok());

        // Test getting existing mnemonic at index 0
        let same_mnemonic_0 = storage.get_or_generate_mnemonic_at_index(0).unwrap();
        assert_eq!(storage.len(), 1); // Should not have generated a new one
        assert_eq!(mnemonic_0, same_mnemonic_0);

        // Test generating mnemonic at index 2 (should generate indices 1 and 2)
        let mnemonic_2 = storage.get_or_generate_mnemonic_at_index(2).unwrap();
        assert_eq!(storage.len(), 3); // Should now have mnemonics at indices 0, 1, 2
        assert!(MnemonicStorage::validate_mnemonic_format(&mnemonic_2).is_ok());

        // Verify all mnemonics exist and are valid
        for i in 0..3 {
            let mnemonic = storage.get_mnemonic_by_index(i).unwrap();
            assert!(MnemonicStorage::validate_mnemonic_format(mnemonic).is_ok());
        }

        // Verify mnemonics are different (extremely unlikely to be the same)
        let mnemonic_1 = storage.get_mnemonic_by_index(1).unwrap();
        assert_ne!(&mnemonic_0, mnemonic_1);
        assert_ne!(&mnemonic_2, mnemonic_1);
        assert_ne!(mnemonic_0, mnemonic_2);
    }

    #[test]
    fn test_generate_new_mnemonic() {
        // Generate multiple mnemonics and verify they are valid and unique
        let mut generated_mnemonics = Vec::new();

        for _ in 0..5 {
            let mnemonic = MnemonicStorage::generate_new_mnemonic();

            // Verify the mnemonic is valid
            assert!(MnemonicStorage::validate_mnemonic_format(&mnemonic).is_ok());

            // Verify it's a 12-word mnemonic
            let words: Vec<&str> = mnemonic.split_whitespace().collect();
            assert_eq!(words.len(), 12);

            // Verify all words are lowercase letters only
            for word in words {
                assert!(word.chars().all(|c| c.is_ascii_lowercase()));
                assert!(!word.is_empty());
            }

            // Verify uniqueness (extremely unlikely to generate duplicates)
            assert!(!generated_mnemonics.contains(&mnemonic));
            generated_mnemonics.push(mnemonic);
        }
    }

    #[test]
    fn test_indexed_access_with_file_operations() {
        use std::fs;

        let test_path = "test_indexed_access.json";

        // Start with empty storage
        let mut storage = MnemonicStorage::new();

        // Generate mnemonic at index 1 (should create indices 0 and 1)
        let mnemonic_1 = storage.get_or_generate_mnemonic_at_index(1).unwrap();
        assert_eq!(storage.len(), 2);

        // Write to file
        storage.write_to_file_path(test_path).unwrap();

        // Load from file and verify
        let loaded_storage = MnemonicStorage::read_from_file_path(test_path).unwrap();
        assert_eq!(loaded_storage.len(), 2);
        assert_eq!(loaded_storage.get_mnemonic_by_index(1), Some(&mnemonic_1));

        // Verify both mnemonics are valid
        for i in 0..2 {
            let mnemonic = loaded_storage.get_mnemonic_by_index(i).unwrap();
            assert!(MnemonicStorage::validate_mnemonic_format(mnemonic).is_ok());
        }

        // Cleanup
        let _ = fs::remove_file(test_path);
    }

    // ========================================
    // Task 7.4: Signer Functionality Tests
    // ========================================

    #[test]
    fn test_signer_creation_with_various_mnemonic_inputs() {
        // Test 1: Valid 12-word mnemonic
        let valid_12_word = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let result = LwkSoftwareSigner::new(valid_12_word);
        assert!(
            result.is_ok(),
            "Should create signer with valid 12-word mnemonic"
        );
        let signer = result.unwrap();
        assert!(
            signer.is_testnet(),
            "Signer should be configured for testnet"
        );

        // Test 2: Another valid 12-word mnemonic
        let valid_12_word_2 =
            "legal winner thank year wave sausage worth useful legal winner thank yellow";
        let result = LwkSoftwareSigner::new(valid_12_word_2);
        assert!(
            result.is_ok(),
            "Should create signer with second valid 12-word mnemonic"
        );
        let signer = result.unwrap();
        assert!(
            signer.is_testnet(),
            "Signer should be configured for testnet"
        );

        // Test 3: Third valid 12-word mnemonic
        let valid_12_word_3 =
            "letter advice cage absurd amount doctor acoustic avoid letter advice cage above";
        let result = LwkSoftwareSigner::new(valid_12_word_3);
        assert!(
            result.is_ok(),
            "Should create signer with third valid 12-word mnemonic"
        );
        let signer = result.unwrap();
        assert!(
            signer.is_testnet(),
            "Signer should be configured for testnet"
        );

        // Test 4: Invalid word count (too few words)
        let invalid_few_words = "abandon abandon abandon";
        let result = LwkSoftwareSigner::new(invalid_few_words);
        assert!(result.is_err(), "Should fail with too few words");
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(msg) => {
                assert!(
                    msg.contains("word count"),
                    "Error should mention word count issue"
                );
            }
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Test 5: Invalid word count (too many words)
        let invalid_many_words = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon";
        let result = LwkSoftwareSigner::new(invalid_many_words);
        assert!(result.is_err(), "Should fail with too many words");
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(msg) => {
                assert!(
                    msg.contains("word count"),
                    "Error should mention word count issue"
                );
            }
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Test 6: Invalid characters (uppercase)
        let invalid_uppercase = "Abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let result = LwkSoftwareSigner::new(invalid_uppercase);
        assert!(result.is_err(), "Should fail with uppercase characters");
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(msg) => {
                assert!(
                    msg.contains("lowercase"),
                    "Error should mention lowercase requirement"
                );
            }
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Test 7: Invalid characters (numbers)
        let invalid_numbers = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon 123";
        let result = LwkSoftwareSigner::new(invalid_numbers);
        assert!(result.is_err(), "Should fail with numeric characters");
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(msg) => {
                assert!(
                    msg.contains("lowercase"),
                    "Error should mention character validation"
                );
            }
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Test 8: Empty mnemonic
        let empty_mnemonic = "";
        let result = LwkSoftwareSigner::new(empty_mnemonic);
        assert!(result.is_err(), "Should fail with empty mnemonic");
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(_) => {}
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Test 9: Whitespace-only mnemonic
        let whitespace_mnemonic = "   \n\t  ";
        let result = LwkSoftwareSigner::new(whitespace_mnemonic);
        assert!(result.is_err(), "Should fail with whitespace-only mnemonic");
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(_) => {}
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Test 10: Multiple consecutive spaces (empty words)
        let multiple_spaces = "abandon  abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let result = LwkSoftwareSigner::new(multiple_spaces);
        assert!(
            result.is_err(),
            "Should fail with multiple consecutive spaces"
        );
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(msg) => {
                assert!(
                    msg.contains("consecutive spaces") || msg.contains("empty words"),
                    "Error should mention spacing issue"
                );
            }
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Test 11: Invalid BIP39 checksum (valid format but invalid checksum)
        let invalid_checksum = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon";
        let result = LwkSoftwareSigner::new(invalid_checksum);
        assert!(result.is_err(), "Should fail with invalid BIP39 checksum");
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(msg) => {
                assert!(
                    msg.contains("BIP39"),
                    "Error should mention BIP39 validation failure"
                );
            }
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }
    }

    #[test]
    fn test_network_configuration_validation() {
        // Test 1: Verify all signers are configured for testnet
        let test_mnemonics = vec![
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
            "legal winner thank year wave sausage worth useful legal winner thank yellow",
            "letter advice cage absurd amount doctor acoustic avoid letter advice cage above",
        ];

        for (i, mnemonic) in test_mnemonics.iter().enumerate() {
            let signer = LwkSoftwareSigner::new(mnemonic).unwrap();
            assert!(
                signer.is_testnet(),
                "Signer {} should be configured for testnet",
                i
            );
        }

        // Test 2: Verify generated signers are also testnet
        let (_, generated_signer) = LwkSoftwareSigner::generate_new().unwrap();
        assert!(
            generated_signer.is_testnet(),
            "Generated signer should be configured for testnet"
        );

        // Test 3: Verify indexed generated signers are testnet
        for index in 0..3 {
            let (_, indexed_signer) = LwkSoftwareSigner::generate_new_indexed(index).unwrap();
            assert!(
                indexed_signer.is_testnet(),
                "Indexed signer {} should be configured for testnet",
                index
            );
        }

        // Test 4: Verify network configuration is consistent across multiple instances
        let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let signer1 = LwkSoftwareSigner::new(mnemonic).unwrap();
        let signer2 = LwkSoftwareSigner::new(mnemonic).unwrap();

        assert_eq!(
            signer1.is_testnet(),
            signer2.is_testnet(),
            "Network configuration should be consistent across instances"
        );
        assert!(
            signer1.is_testnet() && signer2.is_testnet(),
            "Both signers should be configured for testnet"
        );
    }

    #[tokio::test]
    async fn test_basic_transaction_signing_flow_with_mock_data() {
        let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let signer = LwkSoftwareSigner::new(mnemonic).unwrap();

        // Test 1: Empty transaction hex should fail
        let empty_hex = "";
        let result = signer.sign_transaction(empty_hex).await;
        assert!(result.is_err(), "Should fail with empty transaction hex");
        match result.unwrap_err() {
            SignerError::InvalidTransaction(msg) => {
                assert!(
                    msg.contains("empty"),
                    "Error should mention empty transaction"
                );
            }
            other => panic!("Expected InvalidTransaction error, got: {:?}", other),
        }

        // Test 2: Whitespace-only transaction hex should fail
        let whitespace_hex = "   \n\t  ";
        let result = signer.sign_transaction(whitespace_hex).await;
        assert!(
            result.is_err(),
            "Should fail with whitespace-only transaction hex"
        );
        match result.unwrap_err() {
            SignerError::InvalidTransaction(msg) => {
                assert!(
                    msg.contains("empty"),
                    "Error should mention empty transaction"
                );
            }
            other => panic!("Expected InvalidTransaction error, got: {:?}", other),
        }

        // Test 3: Too short transaction hex should fail
        let short_hex = "abc123";
        let result = signer.sign_transaction(short_hex).await;
        assert!(
            result.is_err(),
            "Should fail with too short transaction hex"
        );
        match result.unwrap_err() {
            SignerError::InvalidTransaction(msg) => {
                assert!(
                    msg.contains("too short"),
                    "Error should mention transaction too short"
                );
            }
            other => panic!("Expected InvalidTransaction error, got: {:?}", other),
        }

        // Test 4: Invalid hex characters should fail with HexParse error
        let invalid_hex = "invalid_hex_characters_zz";
        let result = signer.sign_transaction(invalid_hex).await;
        assert!(result.is_err(), "Should fail with invalid hex characters");
        match result.unwrap_err() {
            SignerError::HexParse(_) => {} // Expected error type
            other => panic!("Expected HexParse error, got: {:?}", other),
        }

        // Test 5: Valid hex but invalid transaction structure should fail
        let valid_hex_invalid_tx = "deadbeefcafebabe1234567890abcdef";
        let result = signer.sign_transaction(valid_hex_invalid_tx).await;
        assert!(
            result.is_err(),
            "Should fail with invalid transaction structure"
        );
        match result.unwrap_err() {
            SignerError::InvalidTransaction(_) => {} // Expected error type
            other => panic!("Expected InvalidTransaction error, got: {:?}", other),
        }

        // Test 6: Odd-length hex that's long enough should fail with HexParse error
        let odd_hex = "deadbeefcafebabe12345"; // 21 characters (odd length, but > 20)
        let result = signer.sign_transaction(odd_hex).await;
        assert!(result.is_err(), "Should fail with odd-length hex");
        match result.unwrap_err() {
            SignerError::HexParse(_) => {} // Expected error type for odd-length hex
            other => panic!("Expected HexParse error, got: {:?}", other),
        }

        // Test 7: Very long invalid hex should still fail appropriately
        let long_invalid_hex = "z".repeat(1000);
        let result = signer.sign_transaction(&long_invalid_hex).await;
        assert!(result.is_err(), "Should fail with long invalid hex");
        match result.unwrap_err() {
            SignerError::HexParse(_) => {} // Expected error type
            other => panic!("Expected HexParse error, got: {:?}", other),
        }

        // Test 8: Valid hex that's too short for a transaction
        let too_short_valid_hex = "deadbeef";
        let result = signer.sign_transaction(too_short_valid_hex).await;
        assert!(
            result.is_err(),
            "Should fail with hex that's too short for transaction"
        );
        // This should be InvalidTransaction because length is checked first
        match result.unwrap_err() {
            SignerError::InvalidTransaction(msg) => {
                assert!(
                    msg.contains("too short"),
                    "Error should mention transaction too short"
                );
            }
            other => panic!("Expected InvalidTransaction error, got: {:?}", other),
        }

        // Test 9: Test error message preservation and context
        let test_invalid_hex = "gggggggggggggggggggggggg"; // Long enough but invalid hex
        let result = signer.sign_transaction(test_invalid_hex).await;
        assert!(result.is_err(), "Should fail with invalid hex");
        let error = result.unwrap_err();
        let error_string = format!("{}", error);
        assert!(
            error_string.contains("Hex parsing failed") || error_string.contains("parsing"),
            "Error message should provide context about hex parsing failure: {}",
            error_string
        );
    }

    #[tokio::test]
    async fn test_thread_safety_and_async_compatibility() {
        use std::sync::Arc;
        use tokio::task;

        // Test 1: Verify signer can be shared across threads (Arc<Signer>)
        let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let signer = Arc::new(LwkSoftwareSigner::new(mnemonic).unwrap());

        // Test 2: Spawn multiple async tasks that use the same signer
        let mut handles = Vec::new();

        for i in 0..5 {
            let signer_clone = Arc::clone(&signer);
            let handle = task::spawn(async move {
                // Each task attempts to sign an invalid transaction (for testing purposes)
                let invalid_hex = format!("invalid_hex_characters_task_{}", i).repeat(3); // Make it long enough
                let result = signer_clone.sign_transaction(&invalid_hex).await;

                // All should fail with HexParse error
                assert!(result.is_err(), "Task {} should fail with invalid hex", i);
                match result.unwrap_err() {
                    SignerError::HexParse(_) => {} // Expected
                    other => panic!("Task {} expected HexParse error, got: {:?}", i, other),
                }

                // Return task ID for verification
                i
            });
            handles.push(handle);
        }

        // Test 3: Wait for all tasks to complete and verify results
        let mut completed_tasks = Vec::new();
        for handle in handles {
            let task_id = handle.await.expect("Task should complete successfully");
            completed_tasks.push(task_id);
        }

        // Verify all tasks completed
        completed_tasks.sort();
        assert_eq!(
            completed_tasks,
            vec![0, 1, 2, 3, 4],
            "All tasks should complete"
        );

        // Test 4: Test concurrent signer creation
        let creation_handles: Vec<_> = (0..3).map(|i| {
            let test_mnemonic = match i {
                0 => "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
                1 => "legal winner thank year wave sausage worth useful legal winner thank yellow",
                _ => "letter advice cage absurd amount doctor acoustic avoid letter advice cage above",
            };

            task::spawn(async move {
                let signer = LwkSoftwareSigner::new(test_mnemonic).unwrap();
                assert!(signer.is_testnet(), "Concurrent signer {} should be testnet", i);
                i
            })
        }).collect();

        // Wait for all creation tasks
        for handle in creation_handles {
            handle.await.expect("Signer creation task should complete");
        }

        // Test 5: Test concurrent file operations (generate_new_indexed)
        let file_handles: Vec<_> = (0..3)
            .map(|index| {
                task::spawn(async move {
                    // Use different indices to avoid conflicts
                    let actual_index = index + 10; // Offset to avoid conflicts with other tests
                    let result = LwkSoftwareSigner::generate_new_indexed(actual_index);

                    // Note: This might fail due to file system race conditions in concurrent tests
                    // but the signer itself should handle this gracefully
                    match result {
                        Ok((mnemonic, signer)) => {
                            assert!(
                                !mnemonic.is_empty(),
                                "Generated mnemonic should not be empty"
                            );
                            assert!(signer.is_testnet(), "Generated signer should be testnet");
                            Ok(actual_index)
                        }
                        Err(e) => {
                            // File system errors are acceptable in concurrent scenarios
                            match e {
                                SignerError::FileIo(_) | SignerError::Serialization(_) => {
                                    Ok(actual_index)
                                }
                                other => Err(other),
                            }
                        }
                    }
                })
            })
            .collect();

        // Wait for file operation tasks (allow some to fail due to concurrency)
        let mut successful_file_ops = 0;
        for handle in file_handles {
            match handle.await.expect("File operation task should complete") {
                Ok(_) => successful_file_ops += 1,
                Err(e) => {
                    // Log but don't fail the test for expected concurrency issues
                    eprintln!("Expected concurrency error in file operations: {:?}", e);
                }
            }
        }

        // At least one file operation should succeed
        assert!(
            successful_file_ops > 0,
            "At least one concurrent file operation should succeed"
        );

        // Test 6: Verify trait object compatibility (dynamic dispatch)
        let signer: Box<dyn Signer> = Box::new(LwkSoftwareSigner::new(mnemonic).unwrap());
        let result = signer
            .sign_transaction("invalid_hex_characters_long_enough_for_test")
            .await;
        assert!(result.is_err(), "Trait object should work correctly");
        match result.unwrap_err() {
            SignerError::HexParse(_) => {} // Expected
            other => panic!(
                "Expected HexParse error from trait object, got: {:?}",
                other
            ),
        }

        // Test 7: Test Send + Sync bounds by moving signer across thread boundary
        let signer = LwkSoftwareSigner::new(mnemonic).unwrap();
        let handle = task::spawn(async move {
            // Signer moved into async task (tests Send)
            assert!(signer.is_testnet());

            // Test signing operation in moved context
            let result = signer
                .sign_transaction("invalid_hex_characters_long_enough")
                .await;
            assert!(result.is_err());
        });

        handle.await.expect("Send/Sync test should complete");
    }

    #[tokio::test]
    async fn test_signer_error_handling_consistency() {
        let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let signer = LwkSoftwareSigner::new(mnemonic).unwrap();

        // Test consistent error types for various invalid inputs
        let test_cases = vec![
            ("", "empty transaction"),
            ("   ", "whitespace transaction"),
            ("abc", "too short"),
            ("zz", "invalid hex chars"),
            ("abcdef", "short valid hex"),
        ];

        for (input, description) in test_cases {
            let result = signer.sign_transaction(input).await;
            assert!(result.is_err(), "Should fail for {}", description);

            // Verify error can be formatted and contains useful information
            let error = result.unwrap_err();
            let error_msg = format!("{}", error);
            assert!(
                !error_msg.is_empty(),
                "Error message should not be empty for {}",
                description
            );

            // Verify error implements standard error traits
            let _: &dyn std::error::Error = &error;
            let debug_msg = format!("{:?}", error);
            assert!(
                !debug_msg.is_empty(),
                "Debug message should not be empty for {}",
                description
            );
        }
    }

    #[test]
    fn test_signer_creation_performance_and_memory() {
        // Test that signer creation is reasonably fast and doesn't leak memory
        let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";

        // Create multiple signers to test for memory leaks or performance issues
        let start_time = std::time::Instant::now();
        let mut signers = Vec::new();

        for _ in 0..10 {
            let signer = LwkSoftwareSigner::new(mnemonic).unwrap();
            assert!(signer.is_testnet());
            signers.push(signer);
        }

        let elapsed = start_time.elapsed();

        // Signer creation should be reasonably fast (less than 5 seconds for 10 signers)
        // LWK initialization can take some time, especially on first run
        assert!(
            elapsed.as_secs() < 5,
            "Signer creation should be fast, took: {:?}",
            elapsed
        );

        // Verify all signers are properly configured
        for (i, signer) in signers.iter().enumerate() {
            assert!(signer.is_testnet(), "Signer {} should be testnet", i);
        }

        // Test that signers can be dropped without issues
        drop(signers);
    }

    #[test]
    fn test_signer_with_different_mnemonic_languages() {
        // Test with mnemonics that would be valid in different languages
        // (though LWK might only support English)

        // English mnemonic (should work)
        let english_mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let result = LwkSoftwareSigner::new(english_mnemonic);
        assert!(result.is_ok(), "English mnemonic should work");

        // Test with mnemonic that has valid format but might not be in English wordlist
        // This should fail during BIP39 validation if the words aren't in the wordlist
        let potentially_invalid_words = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon invalid";
        let result = LwkSoftwareSigner::new(potentially_invalid_words);
        // This might succeed or fail depending on whether "invalid" is in the BIP39 wordlist
        // The test verifies that the validation process works correctly either way
        match result {
            Ok(signer) => {
                assert!(
                    signer.is_testnet(),
                    "If signer is created, it should be testnet"
                );
            }
            Err(SignerError::InvalidMnemonic(_)) => {
                // This is also acceptable if the word isn't in the BIP39 wordlist
            }
            Err(other) => {
                panic!(
                    "Unexpected error type for potentially invalid words: {:?}",
                    other
                );
            }
        }
    }

    // ===== JSON FILE OPERATIONS TESTS (Task 7.3) =====
    // These tests specifically cover Requirements 2.1, 2.3, 2.8 for JSON file operations

    #[test]
    fn test_json_file_reading_comprehensive() {
        use std::fs;

        // Test 1: Reading valid JSON with single mnemonic
        let test_path_single = "test_json_single.json";
        let valid_single_json = r#"{
            "mnemonic": [
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
            ]
        }"#;
        fs::write(test_path_single, valid_single_json).unwrap();

        let result = MnemonicStorage::read_from_file_path(test_path_single);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert_eq!(storage.len(), 1);
        assert_eq!(
            storage.get_mnemonic_by_index(0).unwrap(),
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
        );

        // Test 2: Reading valid JSON with multiple mnemonics
        let test_path_multiple = "test_json_multiple.json";
        let valid_multiple_json = r#"{
            "mnemonic": [
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
                "legal winner thank year wave sausage worth useful legal winner thank yellow",
                "letter advice cage absurd amount doctor acoustic avoid letter advice cage above"
            ]
        }"#;
        fs::write(test_path_multiple, valid_multiple_json).unwrap();

        let result = MnemonicStorage::read_from_file_path(test_path_multiple);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert_eq!(storage.len(), 3);
        assert_eq!(
            storage.get_mnemonic_by_index(1).unwrap(),
            "legal winner thank year wave sausage worth useful legal winner thank yellow"
        );
        assert_eq!(
            storage.get_mnemonic_by_index(2).unwrap(),
            "letter advice cage absurd amount doctor acoustic avoid letter advice cage above"
        );

        // Test 3: Reading valid JSON with empty mnemonic array
        let test_path_empty_array = "test_json_empty_array.json";
        let empty_array_json = r#"{
            "mnemonic": []
        }"#;
        fs::write(test_path_empty_array, empty_array_json).unwrap();

        let result = MnemonicStorage::read_from_file_path(test_path_empty_array);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert_eq!(storage.len(), 0);
        assert!(storage.is_empty());

        // Test 4: Reading JSON with extra whitespace and formatting
        let test_path_whitespace = "test_json_whitespace.json";
        let whitespace_json = r#"
        {
            "mnemonic": [
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
            ]
        }
        "#;
        fs::write(test_path_whitespace, whitespace_json).unwrap();

        let result = MnemonicStorage::read_from_file_path(test_path_whitespace);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert_eq!(storage.len(), 1);

        // Cleanup
        let _ = fs::remove_file(test_path_single);
        let _ = fs::remove_file(test_path_multiple);
        let _ = fs::remove_file(test_path_empty_array);
        let _ = fs::remove_file(test_path_whitespace);
    }

    #[test]
    fn test_json_file_reading_invalid_formats() {
        use std::fs;

        // Test 1: Invalid JSON syntax (missing closing brace)
        let test_path_syntax = "test_json_invalid_syntax.json";
        let invalid_syntax_json = r#"{
            "mnemonic": [
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
            "#;
        fs::write(test_path_syntax, invalid_syntax_json).unwrap();

        let result = MnemonicStorage::read_from_file_path(test_path_syntax);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::Serialization(_) => {} // Expected error type
            other => panic!("Expected Serialization error, got: {:?}", other),
        }

        // Test 2: Invalid JSON structure (missing mnemonic field)
        let test_path_structure = "test_json_invalid_structure.json";
        let invalid_structure_json = r#"{
            "invalid_field": [
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
            ]
        }"#;
        fs::write(test_path_structure, invalid_structure_json).unwrap();

        let result = MnemonicStorage::read_from_file_path(test_path_structure);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::Serialization(_) => {} // Expected error type
            other => panic!("Expected Serialization error, got: {:?}", other),
        }

        // Test 3: Invalid JSON with wrong data type (mnemonic as string instead of array)
        let test_path_type = "test_json_invalid_type.json";
        let invalid_type_json = r#"{
            "mnemonic": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
        }"#;
        fs::write(test_path_type, invalid_type_json).unwrap();

        let result = MnemonicStorage::read_from_file_path(test_path_type);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::Serialization(_) => {} // Expected error type
            other => panic!("Expected Serialization error, got: {:?}", other),
        }

        // Test 4: Valid JSON but invalid mnemonic content
        let test_path_invalid_mnemonic = "test_json_invalid_mnemonic.json";
        let invalid_mnemonic_json = r#"{
            "mnemonic": [
                "invalid mnemonic with wrong word count",
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
            ]
        }"#;
        fs::write(test_path_invalid_mnemonic, invalid_mnemonic_json).unwrap();

        let result = MnemonicStorage::read_from_file_path(test_path_invalid_mnemonic);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(msg) => {
                assert!(msg.contains("Invalid mnemonic at index 0"));
                assert!(msg.contains("Invalid word count"));
            }
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Test 5: Completely malformed JSON
        let test_path_malformed = "test_json_malformed.json";
        let malformed_json = "not json at all { invalid content";
        fs::write(test_path_malformed, malformed_json).unwrap();

        let result = MnemonicStorage::read_from_file_path(test_path_malformed);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::Serialization(_) => {} // Expected error type
            other => panic!("Expected Serialization error, got: {:?}", other),
        }

        // Cleanup
        let _ = fs::remove_file(test_path_syntax);
        let _ = fs::remove_file(test_path_structure);
        let _ = fs::remove_file(test_path_type);
        let _ = fs::remove_file(test_path_invalid_mnemonic);
        let _ = fs::remove_file(test_path_malformed);
    }

    #[test]
    fn test_json_file_writing_and_updating() {
        use std::fs;

        // Test 1: Writing empty storage
        let test_path_empty = "test_json_write_empty.json";
        let empty_storage = MnemonicStorage::new();

        let result = empty_storage.write_to_file_path(test_path_empty);
        assert!(result.is_ok());

        // Verify file exists and contains correct JSON
        assert!(std::path::Path::new(test_path_empty).exists());
        let file_content = fs::read_to_string(test_path_empty).unwrap();
        assert!(file_content.contains("\"mnemonic\""));
        assert!(file_content.contains("[]"));

        // Verify we can read it back
        let loaded = MnemonicStorage::read_from_file_path(test_path_empty).unwrap();
        assert!(loaded.is_empty());

        // Test 2: Writing storage with single mnemonic
        let test_path_single = "test_json_write_single.json";
        let mut single_storage = MnemonicStorage::new();
        let mnemonic1 = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string();
        single_storage.append_mnemonic(mnemonic1.clone()).unwrap();

        let result = single_storage.write_to_file_path(test_path_single);
        assert!(result.is_ok());

        // Verify file content
        let loaded = MnemonicStorage::read_from_file_path(test_path_single).unwrap();
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded.get_mnemonic_by_index(0).unwrap(), &mnemonic1);

        // Test 3: Updating existing file with additional mnemonics
        let mnemonic2 =
            "legal winner thank year wave sausage worth useful legal winner thank yellow"
                .to_string();
        let mnemonic3 =
            "letter advice cage absurd amount doctor acoustic avoid letter advice cage above"
                .to_string();

        let mut updated_storage = loaded;
        updated_storage.append_mnemonic(mnemonic2.clone()).unwrap();
        updated_storage.append_mnemonic(mnemonic3.clone()).unwrap();

        let result = updated_storage.write_to_file_path(test_path_single);
        assert!(result.is_ok());

        // Verify updated content
        let final_loaded = MnemonicStorage::read_from_file_path(test_path_single).unwrap();
        assert_eq!(final_loaded.len(), 3);
        assert_eq!(final_loaded.get_mnemonic_by_index(0).unwrap(), &mnemonic1);
        assert_eq!(final_loaded.get_mnemonic_by_index(1).unwrap(), &mnemonic2);
        assert_eq!(final_loaded.get_mnemonic_by_index(2).unwrap(), &mnemonic3);

        // Test 4: Overwriting file with different content
        let test_path_overwrite = "test_json_write_overwrite.json";
        let mut new_storage = MnemonicStorage::new();
        let new_mnemonic = "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong".to_string();
        new_storage.append_mnemonic(new_mnemonic.clone()).unwrap();

        // Write initial content
        new_storage.write_to_file_path(test_path_overwrite).unwrap();
        let initial_loaded = MnemonicStorage::read_from_file_path(test_path_overwrite).unwrap();
        assert_eq!(initial_loaded.len(), 1);

        // Overwrite with different content
        let mut overwrite_storage = MnemonicStorage::new();
        overwrite_storage
            .append_mnemonic(mnemonic1.clone())
            .unwrap();
        overwrite_storage
            .append_mnemonic(mnemonic2.clone())
            .unwrap();

        overwrite_storage
            .write_to_file_path(test_path_overwrite)
            .unwrap();
        let overwritten_loaded = MnemonicStorage::read_from_file_path(test_path_overwrite).unwrap();
        assert_eq!(overwritten_loaded.len(), 2);
        assert_eq!(
            overwritten_loaded.get_mnemonic_by_index(0).unwrap(),
            &mnemonic1
        );
        assert_eq!(
            overwritten_loaded.get_mnemonic_by_index(1).unwrap(),
            &mnemonic2
        );

        // Cleanup
        let _ = fs::remove_file(test_path_empty);
        let _ = fs::remove_file(test_path_single);
        let _ = fs::remove_file(test_path_overwrite);
    }

    #[test]
    fn test_json_file_io_error_scenarios() {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;

        // Test 1: Writing to invalid/non-existent directory
        let invalid_path = "/nonexistent/directory/test.json";
        let storage = MnemonicStorage::new();

        let result = storage.write_to_file_path(invalid_path);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::FileIo(_) => {} // Expected error type
            other => panic!("Expected FileIo error, got: {:?}", other),
        }

        // Test 2: Reading from directory instead of file
        let dir_path = "test_json_directory";
        fs::create_dir_all(dir_path).unwrap();

        let result = MnemonicStorage::read_from_file_path(dir_path);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::FileIo(_) => {} // Expected error type
            other => panic!("Expected FileIo error, got: {:?}", other),
        }

        // Test 3: Permission denied scenarios (Unix-specific)
        #[cfg(unix)]
        {
            let readonly_path = "test_json_readonly.json";

            // Create a file and make it read-only
            fs::write(readonly_path, "{}").unwrap();
            let mut perms = fs::metadata(readonly_path).unwrap().permissions();
            perms.set_mode(0o444); // Read-only
            fs::set_permissions(readonly_path, perms).unwrap();

            // Try to write to read-only file (should fail)
            let storage = MnemonicStorage::new();
            let result = storage.write_to_file_path(readonly_path);

            // Note: This might not always fail depending on the system and user permissions
            // So we'll just verify the error handling works if it does fail
            if result.is_err() {
                match result.unwrap_err() {
                    SignerError::FileIo(_) => {} // Expected error type
                    other => panic!("Expected FileIo error, got: {:?}", other),
                }
            }

            // Restore permissions for cleanup
            let mut perms = fs::metadata(readonly_path).unwrap().permissions();
            perms.set_mode(0o644); // Read-write
            fs::set_permissions(readonly_path, perms).unwrap();
            let _ = fs::remove_file(readonly_path);
        }

        // Test 4: File corruption recovery (reading corrupted file)
        let corrupted_path = "test_json_corrupted.json";

        // Create a file with binary data that's not valid UTF-8
        let binary_data = vec![0xFF, 0xFE, 0xFD, 0xFC, 0x00, 0x01, 0x02, 0x03];
        fs::write(corrupted_path, binary_data).unwrap();

        let result = MnemonicStorage::read_from_file_path(corrupted_path);
        assert!(result.is_err());
        // This could be either FileIo or Serialization error depending on how the system handles it
        match result.unwrap_err() {
            SignerError::FileIo(_) | SignerError::Serialization(_) => {} // Both are acceptable
            other => panic!("Expected FileIo or Serialization error, got: {:?}", other),
        }

        // Test 5: Disk space simulation (create very large file path)
        let long_path = "a".repeat(1000) + ".json";
        let storage = MnemonicStorage::new();

        let result = storage.write_to_file_path(&long_path);
        // This might succeed or fail depending on the filesystem limits
        if result.is_err() {
            match result.unwrap_err() {
                SignerError::FileIo(_) => {} // Expected error type
                other => panic!("Expected FileIo error, got: {:?}", other),
            }
        }

        // Cleanup
        let _ = fs::remove_dir_all(dir_path);
        let _ = fs::remove_file(corrupted_path);
        let _ = fs::remove_file(&long_path);
    }

    #[test]
    fn test_json_atomic_write_operations() {
        use std::fs;
        use std::path::Path;
        use std::thread;
        use std::time::Duration;

        // Test 1: Verify atomic write behavior (temp file creation and rename)
        let test_path = "test_json_atomic.json";
        let temp_path = "test_json_atomic.tmp";

        // Ensure clean state
        let _ = fs::remove_file(test_path);
        let _ = fs::remove_file(temp_path);

        let mut storage = MnemonicStorage::new();
        storage.append_mnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string()).unwrap();

        // Write to file
        let result = storage.write_to_file_path(test_path);
        assert!(result.is_ok());

        // Verify target file exists and temp file is cleaned up
        assert!(Path::new(test_path).exists());
        assert!(
            !Path::new(temp_path).exists(),
            "Temporary file should be cleaned up after atomic write"
        );

        // Test 2: Verify file integrity during write operation
        let integrity_path = "test_json_integrity.json";
        let mut large_storage = MnemonicStorage::new();

        // Add multiple mnemonics to create a larger file
        for _i in 0..10 {
            let mnemonic = MnemonicStorage::generate_new_mnemonic();
            large_storage.append_mnemonic(mnemonic).unwrap();
        }

        // Write the file
        large_storage.write_to_file_path(integrity_path).unwrap();

        // Verify we can read it back completely
        let loaded_storage = MnemonicStorage::read_from_file_path(integrity_path).unwrap();
        assert_eq!(loaded_storage.len(), large_storage.len());

        for i in 0..large_storage.len() {
            assert_eq!(
                loaded_storage.get_mnemonic_by_index(i),
                large_storage.get_mnemonic_by_index(i)
            );
        }

        // Test 3: Concurrent write safety (simulate multiple writers)
        let concurrent_path = "test_json_concurrent.json";
        let concurrent_storage = MnemonicStorage::new();

        // This test verifies that the atomic write mechanism prevents corruption
        // even if multiple threads try to write simultaneously
        let handles: Vec<_> = (0..3)
            .map(|_i| {
                let path = concurrent_path.to_string();
                let mut storage = concurrent_storage.clone();

                thread::spawn(move || {
                    // Add a unique mnemonic for this thread (generate a proper BIP39 mnemonic)
                    let mnemonic = MnemonicStorage::generate_new_mnemonic();
                    storage.append_mnemonic(mnemonic).unwrap();

                    // Small delay to increase chance of concurrent access
                    thread::sleep(Duration::from_millis(1));

                    // Write to file
                    storage.write_to_file_path(&path)
                })
            })
            .collect();

        // Wait for all threads to complete
        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();

        // At least one write should succeed
        let successful_writes = results.iter().filter(|r| r.is_ok()).count();
        assert!(
            successful_writes > 0,
            "At least one concurrent write should succeed"
        );

        // The final file should be valid JSON (not corrupted)
        if Path::new(concurrent_path).exists() {
            let final_storage = MnemonicStorage::read_from_file_path(concurrent_path);
            assert!(
                final_storage.is_ok(),
                "Final file should be valid JSON after concurrent writes"
            );
        }

        // Test 4: Write failure cleanup (simulate failure during write)
        let cleanup_path = "test_json_cleanup.json";
        let cleanup_temp_path = "test_json_cleanup.tmp";

        // Create a scenario where the temp file might be left behind
        // (This is hard to simulate reliably, so we'll test the cleanup logic)
        let cleanup_storage = MnemonicStorage::new();

        // Manually create a temp file to simulate a previous failed write
        fs::write(cleanup_temp_path, "leftover temp file").unwrap();
        assert!(Path::new(cleanup_temp_path).exists());

        // Perform a successful write (should handle any existing temp file)
        let result = cleanup_storage.write_to_file_path(cleanup_path);
        assert!(result.is_ok());

        // Verify the target file exists and is valid
        assert!(Path::new(cleanup_path).exists());
        let loaded = MnemonicStorage::read_from_file_path(cleanup_path).unwrap();
        assert_eq!(loaded.len(), 0); // Empty storage

        // Test 5: Verify JSON formatting consistency
        let format_path = "test_json_format.json";
        let mut format_storage = MnemonicStorage::new();
        format_storage.append_mnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string()).unwrap();

        format_storage.write_to_file_path(format_path).unwrap();

        // Read the raw file content and verify it's properly formatted JSON
        let raw_content = fs::read_to_string(format_path).unwrap();

        // Should be pretty-printed JSON (contains newlines and indentation)
        assert!(
            raw_content.contains('\n'),
            "JSON should be pretty-printed with newlines"
        );
        assert!(
            raw_content.contains("  "),
            "JSON should be pretty-printed with indentation"
        );

        // Should be valid JSON that we can parse
        let parsed: serde_json::Value = serde_json::from_str(&raw_content).unwrap();
        assert!(parsed.is_object());
        assert!(parsed.get("mnemonic").is_some());
        assert!(parsed["mnemonic"].is_array());

        // Cleanup
        let _ = fs::remove_file(test_path);
        let _ = fs::remove_file(temp_path);
        let _ = fs::remove_file(integrity_path);
        let _ = fs::remove_file(concurrent_path);
        let _ = fs::remove_file(cleanup_path);
        let _ = fs::remove_file(cleanup_temp_path);
        let _ = fs::remove_file(format_path);
    }

    #[test]
    fn test_json_file_edge_cases() {
        use std::fs;

        // Test 1: Very large mnemonic arrays
        let large_path = "test_json_large.json";
        let mut large_storage = MnemonicStorage::new();

        // Add 100 mnemonics to test performance and correctness with large files
        for _ in 0..100 {
            let mnemonic = MnemonicStorage::generate_new_mnemonic();
            large_storage.append_mnemonic(mnemonic).unwrap();
        }

        // Write and read back
        large_storage.write_to_file_path(large_path).unwrap();
        let loaded_large = MnemonicStorage::read_from_file_path(large_path).unwrap();
        assert_eq!(loaded_large.len(), 100);

        // Verify all mnemonics are preserved correctly
        for i in 0..100 {
            assert_eq!(
                loaded_large.get_mnemonic_by_index(i),
                large_storage.get_mnemonic_by_index(i)
            );
        }

        // Test 2: Unicode and special characters in file paths
        let unicode_path = "test_json_ünïcödé.json";
        let unicode_storage = MnemonicStorage::new();

        let result = unicode_storage.write_to_file_path(unicode_path);
        // This may succeed or fail depending on the filesystem
        if result.is_ok() {
            let loaded_unicode = MnemonicStorage::read_from_file_path(unicode_path).unwrap();
            assert_eq!(loaded_unicode.len(), 0);
        }

        // Test 3: Very long file paths
        let long_path = format!("{}.json", "very_long_filename_".repeat(10));
        let long_storage = MnemonicStorage::new();

        let result = long_storage.write_to_file_path(&long_path);
        // This may succeed or fail depending on filesystem limits
        if result.is_ok() {
            let loaded_long = MnemonicStorage::read_from_file_path(&long_path).unwrap();
            assert_eq!(loaded_long.len(), 0);
        }

        // Test 4: File with BOM (Byte Order Mark)
        let bom_path = "test_json_bom.json";
        let bom_content = "\u{FEFF}{\"mnemonic\":[\"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about\"]}";
        fs::write(bom_path, bom_content).unwrap();

        let result = MnemonicStorage::read_from_file_path(bom_path);
        // This should handle BOM gracefully or fail with appropriate error
        match result {
            Ok(storage) => {
                assert_eq!(storage.len(), 1);
            }
            Err(SignerError::Serialization(_)) => {
                // BOM might cause JSON parsing to fail, which is acceptable
            }
            Err(other) => panic!("Unexpected error type for BOM file: {:?}", other),
        }

        // Test 5: File with different line endings (CRLF vs LF)
        let crlf_path = "test_json_crlf.json";
        let crlf_content = "{\r\n  \"mnemonic\": [\r\n    \"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about\"\r\n  ]\r\n}";
        fs::write(crlf_path, crlf_content).unwrap();

        let result = MnemonicStorage::read_from_file_path(crlf_path);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert_eq!(storage.len(), 1);

        // Cleanup
        let _ = fs::remove_file(large_path);
        let _ = fs::remove_file(unicode_path);
        let _ = fs::remove_file(&long_path);
        let _ = fs::remove_file(bom_path);
        let _ = fs::remove_file(crlf_path);
    }

    #[test]
    fn test_json_file_recovery_scenarios() {
        use std::fs;

        // Test 1: Recovery from partial write (simulated by incomplete JSON)
        let partial_path = "test_json_partial.json";
        let partial_content = r#"{
            "mnemonic": [
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
                "legal winner thank year wave sausage worth useful legal winner thank"#; // Incomplete

        fs::write(partial_path, partial_content).unwrap();

        let result = MnemonicStorage::read_from_file_path(partial_path);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::Serialization(_) => {} // Expected for malformed JSON
            other => panic!("Expected Serialization error, got: {:?}", other),
        }

        // Recovery: overwrite with valid content
        let mut recovery_storage = MnemonicStorage::new();
        recovery_storage.append_mnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string()).unwrap();

        let recovery_result = recovery_storage.write_to_file_path(partial_path);
        assert!(recovery_result.is_ok());

        // Verify recovery was successful
        let recovered = MnemonicStorage::read_from_file_path(partial_path).unwrap();
        assert_eq!(recovered.len(), 1);

        // Test 2: Recovery from file with mixed valid/invalid mnemonics
        let mixed_path = "test_json_mixed.json";
        let mixed_content = r#"{
            "mnemonic": [
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
                "invalid mnemonic",
                "legal winner thank year wave sausage worth useful legal winner thank yellow"
            ]
        }"#;
        fs::write(mixed_path, mixed_content).unwrap();

        let result = MnemonicStorage::read_from_file_path(mixed_path);
        assert!(result.is_err());
        match result.unwrap_err() {
            SignerError::InvalidMnemonic(msg) => {
                assert!(msg.contains("Invalid mnemonic at index 1"));
            }
            other => panic!("Expected InvalidMnemonic error, got: {:?}", other),
        }

        // Recovery: create new storage with only valid mnemonics
        let mut fixed_storage = MnemonicStorage::new();
        fixed_storage.append_mnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string()).unwrap();
        fixed_storage
            .append_mnemonic(
                "legal winner thank year wave sausage worth useful legal winner thank yellow"
                    .to_string(),
            )
            .unwrap();

        fixed_storage.write_to_file_path(mixed_path).unwrap();

        // Verify fix was successful
        let fixed = MnemonicStorage::read_from_file_path(mixed_path).unwrap();
        assert_eq!(fixed.len(), 2);

        // Test 3: Recovery from zero-byte file
        let zero_path = "test_json_zero.json";
        fs::write(zero_path, "").unwrap();

        let result = MnemonicStorage::read_from_file_path(zero_path);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert!(storage.is_empty());

        // Add content to previously empty file
        let mut populated_storage = MnemonicStorage::new();
        populated_storage.append_mnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string()).unwrap();
        populated_storage.write_to_file_path(zero_path).unwrap();

        let populated = MnemonicStorage::read_from_file_path(zero_path).unwrap();
        assert_eq!(populated.len(), 1);

        // Test 4: Recovery from file with extra JSON fields
        let extra_path = "test_json_extra.json";
        let extra_content = r#"{
            "mnemonic": [
                "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
            ],
            "extra_field": "should be ignored",
            "version": 1,
            "metadata": {
                "created": "2023-01-01",
                "notes": "test file"
            }
        }"#;
        fs::write(extra_path, extra_content).unwrap();

        let result = MnemonicStorage::read_from_file_path(extra_path);
        assert!(result.is_ok());
        let storage = result.unwrap();
        assert_eq!(storage.len(), 1);

        // Verify that writing back preserves only the mnemonic field
        storage.write_to_file_path(extra_path).unwrap();
        let rewritten_content = fs::read_to_string(extra_path).unwrap();
        assert!(rewritten_content.contains("mnemonic"));
        assert!(!rewritten_content.contains("extra_field"));
        assert!(!rewritten_content.contains("version"));
        assert!(!rewritten_content.contains("metadata"));

        // Cleanup
        let _ = fs::remove_file(partial_path);
        let _ = fs::remove_file(mixed_path);
        let _ = fs::remove_file(zero_path);
        let _ = fs::remove_file(extra_path);
    }
}
#[test]
fn test_conditional_logging_behavior() {
    // This test verifies that our conditional logging works correctly
    // It should not produce output unless --nocapture is passed

    // Initialize tracing subscriber conditionally
    if should_log_in_tests() {
        let _ = tracing_subscriber::fmt::try_init();
    }

    // Test reading from a non-existent file (should trigger debug logging)
    let result = MnemonicStorage::read_from_file_path("non_existent_test_file.json");
    assert!(result.is_ok());
    let storage = result.unwrap();
    assert!(storage.is_empty());

    // Test creating a signer (should trigger debug and info logging)
    let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
    let result = LwkSoftwareSigner::new(mnemonic);
    assert!(result.is_ok());
    let signer = result.unwrap();
    assert!(signer.is_testnet());

    // If you run this test with --nocapture, you should see logging output
    // If you run without --nocapture, you should see no logging output
}