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
//! # lipa-lightning-lib (aka 3L)
//!
//! This crate implements all the main business logic of the lipa wallet.
//!
//! Most functionality can be accessed by creating an instance of [`LightningNode`] and using its methods.

#![allow(clippy::let_unit_value)]

extern crate core;

mod activity;
mod amount;
mod analytics;
mod async_runtime;
mod auth;
mod backup;
mod callbacks;
mod config;
mod data_store;
mod errors;
mod event;
mod exchange_rate_provider;
mod invoice_details;
mod key_derivation;
mod limits;
mod lnurl;
mod locker;
mod logger;
mod migrations;
mod notification_handling;
mod offer;
mod payment;
mod phone_number;
mod random;
mod recovery;
mod reverse_swap;
mod sanitize_input;
mod secret;
mod swap;
mod symmetric_encryption;
mod task_manager;
mod util;

pub use crate::activity::{Activity, ChannelCloseInfo, ChannelCloseState, ListActivitiesResponse};
pub use crate::amount::{Amount, FiatValue};
use crate::amount::{AsSats, Msats, Permyriad, Sats, ToAmount};
use crate::analytics::{derive_analytics_keys, AnalyticsInterceptor};
pub use crate::analytics::{AnalyticsConfig, InvoiceCreationMetadata, PaymentMetadata};
use crate::async_runtime::AsyncRuntime;
use crate::auth::{build_async_auth, build_auth};
use crate::backup::BackupManager;
pub use crate::callbacks::EventsCallback;
use crate::config::WithTimezone;
pub use crate::config::{
    BreezSdkConfig, Config, MaxRoutingFeeConfig, ReceiveLimitsConfig, RemoteServicesConfig,
    TzConfig, TzTime,
};
use crate::data_store::CreatedInvoice;
use crate::errors::{
    map_lnurl_pay_error, map_lnurl_withdraw_error, map_send_payment_error, LnUrlWithdrawError,
    LnUrlWithdrawErrorCode, LnUrlWithdrawResult,
};
pub use crate::errors::{
    DecodeDataError, Error as LnError, LnUrlPayError, LnUrlPayErrorCode, LnUrlPayResult,
    MnemonicError, NotificationHandlingError, NotificationHandlingErrorCode, ParseError,
    ParsePhoneNumberError, ParsePhoneNumberPrefixError, PayError, PayErrorCode, PayResult, Result,
    RuntimeErrorCode, SimpleError, UnsupportedDataType,
};
use crate::event::LipaEventListener;
pub use crate::exchange_rate_provider::ExchangeRate;
use crate::exchange_rate_provider::ExchangeRateProviderImpl;
pub use crate::invoice_details::InvoiceDetails;
use crate::key_derivation::derive_persistence_encryption_key;
pub use crate::limits::{LiquidityLimit, PaymentAmountLimits};
pub use crate::lnurl::{LnUrlPayDetails, LnUrlWithdrawDetails};
use crate::locker::Locker;
pub use crate::notification_handling::{handle_notification, Notification, NotificationToggles};
pub use crate::offer::{OfferInfo, OfferKind, OfferStatus};
pub use crate::payment::{
    IncomingPaymentInfo, OutgoingPaymentInfo, PaymentInfo, PaymentState, Recipient,
};
pub use crate::phone_number::PhoneNumber;
use crate::phone_number::{lightning_address_to_phone_number, PhoneNumberPrefixParser};
pub use crate::recovery::recover_lightning_node;
pub use crate::reverse_swap::ReverseSwapInfo;
pub use crate::secret::{generate_secret, mnemonic_to_secret, words_by_prefix, Secret};
pub use crate::swap::{
    FailedSwapInfo, ResolveFailedSwapInfo, SwapAddressInfo, SwapInfo, SwapToLightningFees,
};
use crate::symmetric_encryption::{deterministic_encrypt, encrypt};
use crate::task_manager::TaskManager;
use crate::util::{
    replace_byte_arrays_by_hex_string, unix_timestamp_to_system_time, LogIgnoreError,
};

#[cfg(not(feature = "mock-deps"))]
#[allow(clippy::single_component_path_imports)]
use pocketclient;
#[cfg(feature = "mock-deps")]
use pocketclient_mock as pocketclient;

pub use crate::pocketclient::FiatTopupInfo;
use crate::pocketclient::PocketClient;

pub use breez_sdk_core::error::ReceiveOnchainError as SwapError;
pub use breez_sdk_core::error::RedeemOnchainError as SweepError;
use breez_sdk_core::error::{ReceiveOnchainError, RedeemOnchainError, SendPaymentError};
pub use breez_sdk_core::HealthCheckStatus as BreezHealthCheckStatus;
pub use breez_sdk_core::ReverseSwapStatus;
use breez_sdk_core::{
    parse, parse_invoice, BitcoinAddressData, BreezServices, ClosedChannelPaymentDetails,
    ConnectRequest, EnvironmentType, EventListener, GreenlightCredentials, GreenlightNodeConfig,
    InputType, ListPaymentsRequest, LnUrlPayRequest, LnUrlPayRequestData, LnUrlWithdrawRequest,
    LnUrlWithdrawRequestData, Network, NodeConfig, OpenChannelFeeRequest, OpeningFeeParams,
    PayOnchainRequest, PaymentDetails, PaymentStatus, PaymentTypeFilter,
    PrepareOnchainPaymentRequest, PrepareOnchainPaymentResponse, PrepareRedeemOnchainFundsRequest,
    PrepareRefundRequest, ReceiveOnchainRequest, RedeemOnchainFundsRequest, RefundRequest,
    ReportIssueRequest, ReportPaymentFailureDetails, SendPaymentRequest, SignMessageRequest,
    UnspentTransactionOutput,
};
use crow::{CountryCode, LanguageCode, OfferManager, TopupError, TopupInfo};
pub use crow::{PermanentFailureCode, TemporaryFailureCode};
use data_store::DataStore;
use email_address::EmailAddress;
use hex::FromHex;
use honeybadger::Auth;
pub use honeybadger::{TermsAndConditions, TermsAndConditionsStatus};
use iban::Iban;
use log::{debug, error, info, warn, Level};
use logger::init_logger_once;
use num_enum::TryFromPrimitive;
use parrot::AnalyticsClient;
pub use parrot::PaymentSource;
use perro::{
    ensure, invalid_input, permanent_failure, runtime_error, MapToError, OptionToError, ResultTrait,
};
use squirrel::RemoteBackupClient;
use std::cmp::{min, Reverse};
use std::collections::HashSet;
use std::ops::Not;
use std::path::Path;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
use std::{env, fs};
use uuid::Uuid;

const LOGS_DIR: &str = "logs";

const CLN_DUST_LIMIT_SAT: u64 = 546;

pub(crate) const DB_FILENAME: &str = "db2.db3";

/// Represent the result of comparision of a value with a given range.
pub enum RangeHit {
    /// The value is below the left side of the range.
    Below { min: Amount },
    /// The value is whithin the range.
    In,
    /// The value is above the right side of the range.
    Above { max: Amount },
}

/// The fee charged by the Lightning Service Provider (LSP) for opening a channel with the node.
/// This fee is being charged at the time of the channel creation.
/// The LSP simply subtracts this fee from an incoming payment (if this incoming payment leads to a channel creation).
pub struct LspFee {
    pub channel_minimum_fee: Amount,
    /// Parts per myriad (aka basis points) -> 100 is 1%
    pub channel_fee_permyriad: u64,
}

/// The type returned by [`LightningNode::calculate_lsp_fee`].
pub struct CalculateLspFeeResponse {
    /// Indicates the amount that will be charged.
    pub lsp_fee: Amount,
    /// An internal struct is not supposed to be inspected, but only passed to [`LightningNode::create_invoice`].
    pub lsp_fee_params: Option<OpeningFeeParams>,
}

/// Information about the Lightning node running in the background
pub struct NodeInfo {
    /// Lightning network public key of the node (also known as node id)
    pub node_pubkey: String,
    /// List of node ids of all the peers the node is connected to
    pub peers: Vec<String>,
    /// Amount of on-chain balance the node has
    pub onchain_balance: Amount,
    /// Information about the channels of the node
    pub channels_info: ChannelsInfo,
}

/// Information about the channels of the node
pub struct ChannelsInfo {
    /// The balance of the local node
    pub local_balance: Amount,
    /// The max amount that can be received in a single payment.
    /// Can be lower than `total_inbound_capacity` because MPP isn't allowed.
    pub max_receivable_single_payment: Amount,
    /// Capacity the node can actually receive.
    /// It excludes non usable channels, pending HTLCs, channels reserves, etc.
    pub total_inbound_capacity: Amount,
    /// Capacity the node can actually send.
    /// It excludes non usable channels, pending HTLCs, channels reserves, etc.
    pub outbound_capacity: Amount,
}

/// Indicates the max routing fee mode used to restrict fees of a payment of a given size
pub enum MaxRoutingFeeMode {
    /// `max_fee_permyriad` Parts per myriad (aka basis points) -> 100 is 1%
    Relative {
        max_fee_permyriad: u16,
    },
    Absolute {
        max_fee_amount: Amount,
    },
}

/// An error associated with a specific PocketOffer. Can be temporary, indicating there was an issue
/// with a previous withdrawal attempt and it can be retried, or it can be permanent.
///
/// More information on each specific error can be found on
/// [Pocket's Documentation Page](<https://pocketbitcoin.com/developers/docs/rest/v1/webhooks>).
pub type PocketOfferError = TopupError;

#[derive(Clone)]
pub struct SweepInfo {
    pub address: String,
    pub onchain_fee_rate: u32,
    pub onchain_fee_amount: Amount,
    pub amount: Amount,
}

#[derive(Clone, PartialEq, Debug)]
pub(crate) struct UserPreferences {
    fiat_currency: String,
    timezone_config: TzConfig,
}

/// Decoded data that can be obtained using [`LightningNode::decode_data`].
pub enum DecodedData {
    Bolt11Invoice {
        invoice_details: InvoiceDetails,
    },
    LnUrlPay {
        lnurl_pay_details: LnUrlPayDetails,
    },
    LnUrlWithdraw {
        lnurl_withdraw_details: LnUrlWithdrawDetails,
    },
    OnchainAddress {
        onchain_address_details: BitcoinAddressData,
    },
}

/// Invoice affordability returned by [`LightningNode::get_invoice_affordability`].
#[derive(Debug)]
pub enum InvoiceAffordability {
    /// Not enough funds available to pay the requested amount.
    NotEnoughFunds,
    /// Not enough funds available to pay the requested amount and the max routing fees.
    /// There might be a route that is affordable enough but it is unknown until tried.
    UnaffordableFees,
    /// Enough funds for the invoice and routing fees are available.
    Affordable,
}

/// Information about a wallet clearance operation as returned by
/// [`LightningNode::prepare_clear_wallet`].
pub struct ClearWalletInfo {
    /// The total amount available to be cleared. The amount sent will be smaller due to fees.
    pub clear_amount: Amount,
    /// Total fee estimate. Can differ from that fees that are charged when clearing the wallet.
    pub total_estimated_fees: Amount,
    /// Estimate for the total that will be paid in on-chain fees (lockup + claim txs).
    pub onchain_fee: Amount,
    /// Estimate for the fee paid to the swap service.
    pub swap_fee: Amount,
    prepare_response: PrepareOnchainPaymentResponse,
}

#[derive(PartialEq, Eq, Debug, TryFromPrimitive, Clone, Copy)]
#[repr(u8)]
pub(crate) enum EnableStatus {
    Enabled,
    FeatureDisabled,
}

pub enum FeatureFlag {
    LightningAddress,
    PhoneNumber,
}

/// The main class/struct of this library. Constructing an instance will initiate the Lightning node and
/// run it in the background. As long as an instance of `LightningNode` is held, the node will continue to run
/// in the background. Dropping the instance will start a deinit process.  
pub struct LightningNode {
    user_preferences: Arc<Mutex<UserPreferences>>,
    sdk: Arc<BreezServices>,
    auth: Arc<Auth>,
    async_auth: Arc<honeybadger::asynchronous::Auth>,
    fiat_topup_client: PocketClient,
    offer_manager: OfferManager,
    rt: AsyncRuntime,
    data_store: Arc<Mutex<DataStore>>,
    task_manager: Arc<Mutex<TaskManager>>,
    analytics_interceptor: Arc<AnalyticsInterceptor>,
    allowed_countries_country_iso_3166_1_alpha_2: Vec<String>,
    phone_number_prefix_parser: PhoneNumberPrefixParser,
    persistence_encryption_key: [u8; 32],
    config: Config,
}

/// Contains the fee information for the options to resolve funds that have moved on-chain.
///
/// This can occur due to channel closes, or swaps that failed to resolve in the available period.
pub struct OnchainResolvingFees {
    /// Fees to swap the funds back to lightning using [`LightningNode::swap_channel_close_funds_to_lightning`]
    /// or [`LightningNode::swap_failed_swap_funds_to_lightning`].
    /// Only available if enough funds are there to swap.
    pub swap_fees: Option<SwapToLightningFees>,
    /// Estimate of the fees for sending the funds on-chain using [`LightningNode::sweep_funds_from_channel_closes`]
    /// or [`LightningNode::resolve_failed_swap`].
    /// The exact fees will be known when calling [`LightningNode::prepare_sweep_funds_from_channel_closes`]
    /// or [`LightningNode::prepare_resolve_failed_swap`].
    pub sweep_onchain_fee_estimate: Amount,
    /// The fee rate used to compute `swaps_fees` and `sweep_onchain_fee_estimate`.
    /// It should be provided when swapping funds back to lightning or when sweeping funds
    /// to on-chain to ensure the same fee rate is used.
    pub sat_per_vbyte: u32,
}

#[allow(clippy::large_enum_variant)]
pub enum ActionRequiredItem {
    UncompletedOffer { offer: OfferInfo },
    UnresolvedFailedSwap { failed_swap: FailedSwapInfo },
    ChannelClosesFundsAvailable { available_funds: Amount },
}

impl From<OfferInfo> for ActionRequiredItem {
    fn from(value: OfferInfo) -> Self {
        ActionRequiredItem::UncompletedOffer { offer: value }
    }
}

impl From<FailedSwapInfo> for ActionRequiredItem {
    fn from(value: FailedSwapInfo) -> Self {
        ActionRequiredItem::UnresolvedFailedSwap { failed_swap: value }
    }
}

impl LightningNode {
    /// Create a new instance of [`LightningNode`].
    ///
    /// Parameters:
    /// * `config` - configuration parameters
    /// * `events_callback` - a callbacks interface for the consumer of this library to be notified
    ///   of certain events.
    ///
    /// Requires network: **yes**
    pub fn new(config: Config, events_callback: Box<dyn EventsCallback>) -> Result<Self> {
        enable_backtrace();
        fs::create_dir_all(&config.local_persistence_path).map_to_permanent_failure(format!(
            "Failed to create directory: {}",
            &config.local_persistence_path,
        ))?;
        if let Some(level) = config.file_logging_level {
            init_logger_once(
                level,
                &Path::new(&config.local_persistence_path).join(LOGS_DIR),
            )?;
        }
        info!("3L version: {}", env!("GITHUB_REF"));

        let rt = AsyncRuntime::new()?;

        let strong_typed_seed = sanitize_input::strong_type_seed(&config.seed)?;
        let auth = Arc::new(build_auth(
            &strong_typed_seed,
            &config.remote_services_config.backend_url,
        )?);
        let async_auth = Arc::new(build_async_auth(
            &strong_typed_seed,
            &config.remote_services_config.backend_url,
        )?);

        let user_preferences = Arc::new(Mutex::new(UserPreferences {
            fiat_currency: config.fiat_currency.clone(),
            timezone_config: config.timezone_config.clone(),
        }));

        let analytics_client = AnalyticsClient::new(
            config.remote_services_config.backend_url.clone(),
            derive_analytics_keys(&strong_typed_seed)?,
            Arc::clone(&async_auth),
        );

        let db_path = format!("{}/{DB_FILENAME}", config.local_persistence_path);
        let data_store = Arc::new(Mutex::new(DataStore::new(&db_path)?));

        let analytics_config = data_store.lock_unwrap().retrieve_analytics_config()?;
        let analytics_interceptor = Arc::new(AnalyticsInterceptor::new(
            analytics_client,
            Arc::clone(&user_preferences),
            rt.handle(),
            analytics_config,
        ));

        let events_callback = Arc::new(events_callback);
        let event_listener = Box::new(LipaEventListener::new(
            Arc::clone(&events_callback),
            Arc::clone(&analytics_interceptor),
        ));

        let sdk = rt.handle().block_on(async {
            let sdk = start_sdk(&config, event_listener).await?;
            if sdk
                .lsp_id()
                .await
                .map_to_runtime_error(
                    RuntimeErrorCode::NodeUnavailable,
                    "Failed to get current lsp id",
                )?
                .is_none()
            {
                let lsps = sdk.list_lsps().await.map_to_runtime_error(
                    RuntimeErrorCode::NodeUnavailable,
                    "Failed to list lsps",
                )?;
                let lsp = lsps
                    .into_iter()
                    .next()
                    .ok_or_runtime_error(RuntimeErrorCode::NodeUnavailable, "No lsp available")?;
                sdk.connect_lsp(lsp.id).await.map_to_runtime_error(
                    RuntimeErrorCode::NodeUnavailable,
                    "Failed to connect to lsp",
                )?;
            }
            Ok(sdk)
        })?;

        let exchange_rate_provider = Box::new(ExchangeRateProviderImpl::new(
            config.remote_services_config.backend_url.clone(),
            Arc::clone(&auth),
        ));

        let offer_manager = OfferManager::new(
            config.remote_services_config.backend_url.clone(),
            Arc::clone(&auth),
        );

        let fiat_topup_client = PocketClient::new(config.remote_services_config.pocket_url.clone())
            .map_to_runtime_error(
                RuntimeErrorCode::OfferServiceUnavailable,
                "Couldn't create a fiat topup client",
            )?;

        let persistence_encryption_key = derive_persistence_encryption_key(&strong_typed_seed)?;
        let backup_client = RemoteBackupClient::new(
            config.remote_services_config.backend_url.clone(),
            Arc::clone(&async_auth),
        );
        let backup_manager = BackupManager::new(backup_client, db_path, persistence_encryption_key);

        let task_manager = Arc::new(Mutex::new(TaskManager::new(
            rt.handle(),
            exchange_rate_provider,
            Arc::clone(&data_store),
            Arc::clone(&sdk),
            backup_manager,
            events_callback,
            config.breez_sdk_config.breez_sdk_api_key.clone(),
        )?));
        task_manager.lock_unwrap().foreground();

        register_webhook_url(&rt, &sdk, &auth, &config)?;

        let phone_number_prefix_parser =
            PhoneNumberPrefixParser::new(&config.phone_number_allowed_countries_iso_3166_1_alpha_2);

        Ok(LightningNode {
            user_preferences,
            sdk,
            auth,
            async_auth,
            fiat_topup_client,
            offer_manager,
            rt,
            data_store,
            task_manager,
            analytics_interceptor,
            allowed_countries_country_iso_3166_1_alpha_2: config
                .phone_number_allowed_countries_iso_3166_1_alpha_2
                .clone(),
            phone_number_prefix_parser,
            persistence_encryption_key,
            config,
        })
    }

    /// Request some basic info about the node
    ///
    /// Requires network: **no**
    pub fn get_node_info(&self) -> Result<NodeInfo> {
        let node_state = self.sdk.node_info().map_to_runtime_error(
            RuntimeErrorCode::NodeUnavailable,
            "Failed to read node info",
        )?;
        let rate = self.get_exchange_rate();

        Ok(NodeInfo {
            node_pubkey: node_state.id,
            peers: node_state.connected_peers,
            onchain_balance: node_state
                .onchain_balance_msat
                .as_msats()
                .to_amount_down(&rate),
            channels_info: ChannelsInfo {
                local_balance: node_state
                    .channels_balance_msat
                    .as_msats()
                    .to_amount_down(&rate),
                max_receivable_single_payment: node_state
                    .max_receivable_single_payment_amount_msat
                    .as_msats()
                    .to_amount_down(&rate),
                total_inbound_capacity: node_state
                    .total_inbound_liquidity_msats
                    .as_msats()
                    .to_amount_down(&rate),
                outbound_capacity: node_state.max_payable_msat.as_msats().to_amount_down(&rate),
            },
        })
    }

    /// When *receiving* payments, a new channel MAY be required. A fee will be charged to the user.
    /// This does NOT impact *sending* payments.
    /// Get information about the fee charged by the LSP for opening new channels
    ///
    /// Requires network: **no**
    pub fn query_lsp_fee(&self) -> Result<LspFee> {
        let exchange_rate = self.get_exchange_rate();
        let lsp_fee = self.task_manager.lock_unwrap().get_lsp_fee()?;
        Ok(LspFee {
            channel_minimum_fee: lsp_fee.min_msat.as_msats().to_amount_up(&exchange_rate),
            channel_fee_permyriad: lsp_fee.proportional as u64 / 100,
        })
    }

    /// Calculate the actual LSP fee for the given amount of an incoming payment.
    /// If the already existing inbound capacity is enough, no new channel is required.
    ///
    /// Parameters:
    /// * `amount_sat` - amount in sats to compute LSP fee for
    ///
    /// For the returned fees to be guaranteed to be accurate, the returned `lsp_fee_params` must be
    /// provided to [`LightningNode::create_invoice`]
    ///
    /// Requires network: **yes**
    pub fn calculate_lsp_fee(&self, amount_sat: u64) -> Result<CalculateLspFeeResponse> {
        let req = OpenChannelFeeRequest {
            amount_msat: Some(amount_sat.as_sats().msats),
            expiry: None,
        };
        let res = self
            .rt
            .handle()
            .block_on(self.sdk.open_channel_fee(req))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to compute opening channel fee",
            )?;
        Ok(CalculateLspFeeResponse {
            lsp_fee: res
                .fee_msat
                .ok_or_permanent_failure("Breez SDK open_channel_fee returned None lsp fee when provided with Some(amount_msat)")?
                .as_msats()
                .to_amount_up(&self.get_exchange_rate()),
            lsp_fee_params: Some(res.fee_params),
        })
    }

    /// Get the current limits for the amount that can be transferred in a single payment.
    /// Currently there are only limits for receiving payments.
    /// The limits (partly) depend on the channel situation of the node, so it should be called
    /// again every time the user is about to receive a payment.
    /// The limits stay the same regardless of what amount wants to receive (= no changes while
    /// he's typing the amount)
    ///
    /// Requires network: **no**
    pub fn get_payment_amount_limits(&self) -> Result<PaymentAmountLimits> {
        // TODO: try to move this logic inside the SDK
        let lsp_min_fee_amount = self.query_lsp_fee()?.channel_minimum_fee;
        let max_inbound_amount = self.get_node_info()?.channels_info.total_inbound_capacity;
        Ok(PaymentAmountLimits::calculate(
            max_inbound_amount.sats,
            lsp_min_fee_amount.sats,
            &self.get_exchange_rate(),
            &self.config.receive_limits_config,
        ))
    }

    /// Create an invoice to receive a payment with.
    ///
    /// Parameters:
    /// * `amount_sat` - the smallest amount of sats required for the node to accept the incoming
    ///   payment (sender will have to pay fees on top of that amount)
    /// * `lsp_fee_params` - the params that will be used to determine the lsp fee.
    ///    Can be obtained from [`LightningNode::calculate_lsp_fee`] to guarantee predicted fees
    ///    are the ones charged.
    /// * `description` - a description to be embedded into the created invoice
    /// * `metadata` - additional data about the invoice creation used for analytics purposes,
    ///    used to improve the user experience
    ///
    /// Requires network: **yes**
    pub fn create_invoice(
        &self,
        amount_sat: u64,
        lsp_fee_params: Option<OpeningFeeParams>,
        description: String,
        metadata: InvoiceCreationMetadata,
    ) -> Result<InvoiceDetails> {
        let response = self
            .rt
            .handle()
            .block_on(
                self.sdk
                    .receive_payment(breez_sdk_core::ReceivePaymentRequest {
                        amount_msat: amount_sat.as_sats().msats,
                        description,
                        preimage: None,
                        opening_fee_params: lsp_fee_params,
                        use_description_hash: None,
                        expiry: None,
                        cltv: None,
                    }),
            )
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to create an invoice",
            )?;

        self.store_payment_info(&response.ln_invoice.payment_hash, None);
        self.data_store
            .lock_unwrap()
            .store_created_invoice(
                &response.ln_invoice.payment_hash,
                &response.ln_invoice.bolt11,
                &response.opening_fee_msat,
                response.ln_invoice.timestamp + response.ln_invoice.expiry,
            )
            .map_to_permanent_failure("Failed to persist created invoice")?;

        self.analytics_interceptor.request_initiated(
            response.clone(),
            self.get_exchange_rate(),
            metadata,
        );
        Ok(InvoiceDetails::from_ln_invoice(
            response.ln_invoice,
            &self.get_exchange_rate(),
        ))
    }

    /// Parse a phone number prefix, check against the list of allowed countries
    /// (set in [`Config::phone_number_allowed_countries_iso_3166_1_alpha_2`]).
    /// The parser is not strict, it parses some invalid prefixes as valid.
    ///
    /// Requires network: **no**
    pub fn parse_phone_number_prefix(
        &self,
        phone_number_prefix: String,
    ) -> std::result::Result<(), ParsePhoneNumberPrefixError> {
        self.phone_number_prefix_parser.parse(&phone_number_prefix)
    }

    /// Parse a phone number, check against the list of allowed countries
    /// (set in [`Config::phone_number_allowed_countries_iso_3166_1_alpha_2`]).
    ///
    /// Returns a possible lightning address, which can be checked for existence
    /// with [`LightningNode::decode_data`].
    ///
    /// Requires network: **no**
    pub fn parse_phone_number_to_lightning_address(
        &self,
        phone_number: String,
    ) -> std::result::Result<String, ParsePhoneNumberError> {
        let phone_number = self.parse_phone_number(phone_number)?;
        Ok(phone_number
            .to_lightning_address(&self.config.remote_services_config.lipa_lightning_domain))
    }

    fn parse_phone_number(
        &self,
        phone_number: String,
    ) -> std::result::Result<PhoneNumber, ParsePhoneNumberError> {
        let phone_number = PhoneNumber::parse(&phone_number)?;
        ensure!(
            self.allowed_countries_country_iso_3166_1_alpha_2
                .contains(&phone_number.country_code.as_ref().to_string()),
            ParsePhoneNumberError::UnsupportedCountry
        );
        Ok(phone_number)
    }

    /// Decode a user-provided string (usually obtained from QR-code or pasted).
    ///
    /// Requires network: **yes**
    pub fn decode_data(&self, data: String) -> std::result::Result<DecodedData, DecodeDataError> {
        match self.rt.handle().block_on(parse(&data)) {
            Ok(InputType::Bolt11 { invoice }) => {
                ensure!(
                    invoice.network == Network::Bitcoin,
                    DecodeDataError::Unsupported {
                        typ: UnsupportedDataType::Network {
                            network: invoice.network.to_string(),
                        },
                    }
                );

                Ok(DecodedData::Bolt11Invoice {
                    invoice_details: InvoiceDetails::from_ln_invoice(
                        invoice,
                        &self.get_exchange_rate(),
                    ),
                })
            }
            Ok(InputType::LnUrlPay { data }) => Ok(DecodedData::LnUrlPay {
                lnurl_pay_details: LnUrlPayDetails::from_lnurl_pay_request_data(
                    data,
                    &self.get_exchange_rate(),
                )?,
            }),
            Ok(InputType::BitcoinAddress { address }) => Ok(DecodedData::OnchainAddress {
                onchain_address_details: address,
            }),
            Ok(InputType::LnUrlAuth { .. }) => Err(DecodeDataError::Unsupported {
                typ: UnsupportedDataType::LnUrlAuth,
            }),
            Ok(InputType::LnUrlError { data }) => {
                Err(DecodeDataError::LnUrlError { msg: data.reason })
            }
            Ok(InputType::LnUrlWithdraw { data }) => Ok(DecodedData::LnUrlWithdraw {
                lnurl_withdraw_details: LnUrlWithdrawDetails::from_lnurl_withdraw_request_data(
                    data,
                    &self.get_exchange_rate(),
                ),
            }),
            Ok(InputType::NodeId { .. }) => Err(DecodeDataError::Unsupported {
                typ: UnsupportedDataType::NodeId,
            }),
            Ok(InputType::Url { .. }) => Err(DecodeDataError::Unsupported {
                typ: UnsupportedDataType::Url,
            }),
            Err(e) => Err(DecodeDataError::Unrecognized { msg: e.to_string() }),
        }
    }

    /// Get the max routing fee mode that will be employed to restrict the fees for paying a given amount in sats
    ///
    /// Requires network: **no**
    pub fn get_payment_max_routing_fee_mode(&self, amount_sat: u64) -> MaxRoutingFeeMode {
        get_payment_max_routing_fee_mode(
            &self.config.max_routing_fee_config,
            amount_sat,
            &self.get_exchange_rate(),
        )
    }

    /// Checks if the given amount could be spent on an invoice.
    ///
    /// Parameters:
    /// * `amount` - The to be spent amount.
    ///
    /// Requires network: **no**
    pub fn get_invoice_affordability(&self, amount_sat: u64) -> Result<InvoiceAffordability> {
        let amount = amount_sat.as_sats();

        let routing_fee_mode = self.get_payment_max_routing_fee_mode(amount_sat);

        let max_fee_msats = match routing_fee_mode {
            MaxRoutingFeeMode::Relative { max_fee_permyriad } => {
                Permyriad(max_fee_permyriad).of(&amount).msats
            }
            MaxRoutingFeeMode::Absolute { max_fee_amount } => max_fee_amount.sats.as_sats().msats,
        };

        let node_state = self.sdk.node_info().map_to_runtime_error(
            RuntimeErrorCode::NodeUnavailable,
            "Failed to read node info",
        )?;

        if amount.msats > node_state.max_payable_msat {
            return Ok(InvoiceAffordability::NotEnoughFunds);
        }

        if amount.msats + max_fee_msats > node_state.max_payable_msat {
            return Ok(InvoiceAffordability::UnaffordableFees);
        }

        Ok(InvoiceAffordability::Affordable)
    }

    /// Start an attempt to pay an invoice. Can immediately fail, meaning that the payment couldn't be started.
    /// If successful, it doesn't mean that the payment itself was successful (funds received by the payee).
    /// After this method returns, the consumer of this library will learn about a successful/failed payment through the
    /// callbacks [`EventsCallback::payment_sent`] and [`EventsCallback::payment_failed`].
    ///
    /// Parameters:
    /// * `invoice_details` - details of an invoice decode by [`LightningNode::decode_data`]
    /// * `metadata` - additional meta information about the payment, used by analytics to improve the user experience.
    ///
    /// Requires network: **yes**
    pub fn pay_invoice(
        &self,
        invoice_details: InvoiceDetails,
        metadata: PaymentMetadata,
    ) -> PayResult<()> {
        self.pay_open_invoice(invoice_details, 0, metadata)
    }

    /// Similar to [`LightningNode::pay_invoice`] with the difference that the passed in invoice
    /// does not have any payment amount specified, and allows the caller of the method to
    /// specify an amount instead.
    ///
    /// Additional Parameters:
    /// * `amount_sat` - amount in sats to be paid
    ///
    /// Requires network: **yes**
    pub fn pay_open_invoice(
        &self,
        invoice_details: InvoiceDetails,
        amount_sat: u64,
        metadata: PaymentMetadata,
    ) -> PayResult<()> {
        let amount_msat = if amount_sat == 0 {
            None
        } else {
            Some(amount_sat.as_sats().msats)
        };
        self.store_payment_info(&invoice_details.payment_hash, None);
        let node_state = self
            .sdk
            .node_info()
            .map_to_runtime_error(PayErrorCode::NodeUnavailable, "Failed to read node info")?;
        ensure!(
            node_state.id != invoice_details.payee_pub_key,
            runtime_error(
                PayErrorCode::PayingToSelf,
                "A locally issued invoice tried to be paid"
            )
        );

        self.analytics_interceptor.pay_initiated(
            invoice_details.clone(),
            metadata,
            amount_msat,
            self.get_exchange_rate(),
        );

        let result = self
            .rt
            .handle()
            .block_on(self.sdk.send_payment(SendPaymentRequest {
                bolt11: invoice_details.invoice,
                use_trampoline: true,
                amount_msat,
                label: None,
            }));

        if matches!(
            result,
            Err(SendPaymentError::Generic { .. }
                | SendPaymentError::PaymentFailed { .. }
                | SendPaymentError::PaymentTimeout { .. }
                | SendPaymentError::RouteNotFound { .. }
                | SendPaymentError::RouteTooExpensive { .. }
                | SendPaymentError::ServiceConnectivity { .. })
        ) {
            self.report_send_payment_issue(invoice_details.payment_hash);
        }

        result.map_err(map_send_payment_error)?;
        Ok(())
    }

    /// Pay an LNURL-pay the provided amount.
    ///
    /// Parameters:
    /// * `lnurl_pay_request_data` - LNURL-pay request data as obtained from [`LightningNode::decode_data`]
    /// * `amount_sat` - amount to be paid
    /// * `comment` - optional comment to be sent to payee (`max_comment_length` in
    ///   [`LnUrlPayDetails`] must be respected)
    ///
    /// Returns the payment hash of the payment.
    ///
    /// Requires network: **yes**
    pub fn pay_lnurlp(
        &self,
        lnurl_pay_request_data: LnUrlPayRequestData,
        amount_sat: u64,
        comment: Option<String>,
    ) -> LnUrlPayResult<String> {
        let comment_allowed = lnurl_pay_request_data.comment_allowed;
        ensure!(
            !matches!(comment, Some(ref comment) if comment.len() > comment_allowed as usize),
            invalid_input(format!(
                "The provided comment is longer than the allowed {comment_allowed} characters"
            ))
        );

        let payment_hash = match self
            .rt
            .handle()
            .block_on(self.sdk.lnurl_pay(LnUrlPayRequest {
                data: lnurl_pay_request_data,
                amount_msat: amount_sat.as_sats().msats,
                use_trampoline: true,
                comment,
                payment_label: None,
                validate_success_action_url: Some(false),
            }))
            .map_err(map_lnurl_pay_error)?
        {
            breez_sdk_core::lnurl::pay::LnUrlPayResult::EndpointSuccess { data } => {
                Ok(data.payment.id)
            }
            breez_sdk_core::lnurl::pay::LnUrlPayResult::EndpointError { data } => runtime_error!(
                LnUrlPayErrorCode::LnUrlServerError,
                "LNURL server returned error: {}",
                data.reason
            ),
            breez_sdk_core::lnurl::pay::LnUrlPayResult::PayError { data } => {
                self.report_send_payment_issue(data.payment_hash);
                runtime_error!(
                    LnUrlPayErrorCode::PaymentFailed,
                    "Paying invoice for LNURL pay failed: {}",
                    data.reason
                )
            }
        }?;
        self.store_payment_info(&payment_hash, None);
        Ok(payment_hash)
    }

    /// List recipients from the most recent used.
    ///
    /// Returns a list of recipients (lightning addresses or phone numbers for now).
    ///
    /// Requires network: **no**
    pub fn list_recipients(&self) -> Result<Vec<Recipient>> {
        let list_payments_request = ListPaymentsRequest {
            filters: Some(vec![PaymentTypeFilter::Sent]),
            metadata_filters: None,
            from_timestamp: None,
            to_timestamp: None,
            include_failures: Some(true),
            limit: None,
            offset: None,
        };
        let to_lightning_address = |p: breez_sdk_core::Payment| match p.details {
            PaymentDetails::Ln { data } => match data.ln_address {
                Some(lightning_address) => Some((lightning_address, -p.payment_time)),
                None => None,
            },
            _ => None,
        };
        let mut lightning_addresses = self
            .rt
            .handle()
            .block_on(self.sdk.list_payments(list_payments_request))
            .map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Failed to list payments")?
            .into_iter()
            .flat_map(to_lightning_address)
            .collect::<Vec<_>>();
        lightning_addresses.sort();
        lightning_addresses.dedup_by_key(|p| p.0.clone());
        lightning_addresses.sort_by_key(|p| p.1);

        let recipients = lightning_addresses
            .into_iter()
            .map(|p| {
                Recipient::from_lightning_address(
                    &p.0,
                    &self.config.remote_services_config.lipa_lightning_domain,
                )
            })
            .collect();
        Ok(recipients)
    }

    /// Withdraw an LNURL-withdraw the provided amount.
    ///
    /// A successful return means the LNURL-withdraw service has started a payment.
    /// Only after the event [`EventsCallback::payment_received`] can the payment be considered
    /// received.
    ///
    /// Parameters:
    /// * `lnurl_withdraw_request_data` - LNURL-withdraw request data as obtained from [`LightningNode::decode_data`]
    /// * `amount_sat` - amount to be withdraw
    ///
    /// Returns the payment hash of the payment.
    ///
    /// Requires network: **yes**
    pub fn withdraw_lnurlw(
        &self,
        lnurl_withdraw_request_data: LnUrlWithdrawRequestData,
        amount_sat: u64,
    ) -> LnUrlWithdrawResult<String> {
        let payment_hash = match self
            .rt
            .handle()
            .block_on(self.sdk.lnurl_withdraw(LnUrlWithdrawRequest {
                data: lnurl_withdraw_request_data,
                amount_msat: amount_sat.as_sats().msats,
                description: None,
            }))
            .map_err(map_lnurl_withdraw_error)?
        {
            breez_sdk_core::LnUrlWithdrawResult::Ok { data } => Ok(data.invoice.payment_hash),
            breez_sdk_core::LnUrlWithdrawResult::Timeout { data } => {
                warn!("Tolerating timeout on submitting invoice to LNURL-w");
                Ok(data.invoice.payment_hash)
            }
            breez_sdk_core::LnUrlWithdrawResult::ErrorStatus { data } => runtime_error!(
                LnUrlWithdrawErrorCode::LnUrlServerError,
                "LNURL server returned error: {}",
                data.reason
            ),
        }?;
        self.store_payment_info(&payment_hash, None);
        Ok(payment_hash)
    }

    /// Get a list of the latest activities
    ///
    /// Parameters:
    /// * `number_of_completed_activities` - the maximum number of completed activities that will be returned
    ///
    /// Requires network: **no**
    pub fn get_latest_activities(
        &self,
        number_of_completed_activities: u32,
    ) -> Result<ListActivitiesResponse> {
        const LEEWAY_FOR_PENDING_PAYMENTS: u32 = 30;
        let list_payments_request = ListPaymentsRequest {
            filters: Some(vec![
                PaymentTypeFilter::Sent,
                PaymentTypeFilter::Received,
                PaymentTypeFilter::ClosedChannel,
            ]),
            metadata_filters: None,
            from_timestamp: None,
            to_timestamp: None,
            include_failures: Some(true),
            limit: Some(number_of_completed_activities + LEEWAY_FOR_PENDING_PAYMENTS),
            offset: None,
        };
        let breez_activities = self
            .rt
            .handle()
            .block_on(self.sdk.list_payments(list_payments_request))
            .map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Failed to list payments")?
            .into_iter()
            .map(|p| self.activity_from_breez_payment(p))
            .filter_map(filter_out_and_log_corrupted_activities)
            .collect::<Vec<_>>();

        // Query created invoices, filter out ones which are in the breez db.
        let created_invoices = self
            .data_store
            .lock_unwrap()
            .retrieve_created_invoices(number_of_completed_activities)?;

        let number_of_created_invoices = created_invoices.len();
        let mut activities = self.multiplex_activities(breez_activities, created_invoices);
        activities.sort_by_cached_key(|m| Reverse(m.get_time()));

        // To produce stable output we look for pending activities only in the
        // first `look_for_pending` latest activities.
        // Yes, we risk to omit old pending ones.
        let look_for_pending = LEEWAY_FOR_PENDING_PAYMENTS as usize + number_of_created_invoices;
        let mut tail_activities = activities.split_off(min(look_for_pending, activities.len()));
        let head_activities = activities;
        let (mut pending_activities, mut completed_activities): (Vec<_>, Vec<_>) =
            head_activities.into_iter().partition(Activity::is_pending);
        tail_activities.retain(|m| !m.is_pending());
        completed_activities.append(&mut tail_activities);
        completed_activities.truncate(number_of_completed_activities as usize);

        if let Some(in_progress_swap) = self
            .rt
            .handle()
            .block_on(self.sdk.in_progress_swap())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to get in-progress swap",
            )?
        {
            let created_at = unix_timestamp_to_system_time(in_progress_swap.created_at as u64)
                .with_timezone(self.user_preferences.lock_unwrap().clone().timezone_config);

            pending_activities.push(Activity::Swap {
                incoming_payment_info: None,
                swap_info: SwapInfo {
                    bitcoin_address: in_progress_swap.bitcoin_address,
                    created_at,
                    // Multiple txs can be sent to swap address and they aren't guaranteed to
                    // confirm all at the same time. Our best guess of the amount that will be
                    // received once the entire swap confirms is given by confirmed sats added to
                    // any unconfirmed sats waiting to be confirmed.
                    paid_amount: (in_progress_swap.unconfirmed_sats
                        + in_progress_swap.confirmed_sats)
                        .as_sats()
                        .to_amount_down(&self.get_exchange_rate()),
                    txid: in_progress_swap
                        .unconfirmed_tx_ids
                        .first()
                        .or(in_progress_swap.confirmed_tx_ids.first())
                        .ok_or(permanent_failure("In-progress swap doesn't have any txids"))?
                        .clone(),
                },
            })
        }
        pending_activities.sort_by_cached_key(|m| Reverse(m.get_time()));

        Ok(ListActivitiesResponse {
            pending_activities,
            completed_activities,
        })
    }

    /// Combines a list of activities with a list of locally created invoices
    /// into a single activity list.
    ///
    /// Duplicates are removed.
    fn multiplex_activities(
        &self,
        breez_activities: Vec<Activity>,
        local_created_invoices: Vec<CreatedInvoice>,
    ) -> Vec<Activity> {
        let breez_payment_hashes: HashSet<_> = breez_activities
            .iter()
            .filter_map(|m| m.get_payment_info().map(|p| p.hash.clone()))
            .collect();
        let mut activities = local_created_invoices
            .into_iter()
            .filter(|i| !breez_payment_hashes.contains(i.hash.as_str()))
            .map(|i| self.payment_from_created_invoice(&i))
            .filter_map(filter_out_and_log_corrupted_payments)
            .map(|p| Activity::IncomingPayment {
                incoming_payment_info: p,
            })
            .collect::<Vec<_>>();
        activities.extend(breez_activities);
        activities
    }

    /// Get an incoming payment by its payment hash.
    ///
    /// Parameters:
    /// * `hash` - hex representation of payment hash
    ///
    /// Requires network: **no**
    pub fn get_incoming_payment(&self, hash: String) -> Result<IncomingPaymentInfo> {
        if let Some(breez_payment) = self
            .rt
            .handle()
            .block_on(self.sdk.payment_by_hash(hash.clone()))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to get payment by hash",
            )?
        {
            return match self.activity_from_breez_ln_payment(breez_payment)? {
                Activity::IncomingPayment {
                    incoming_payment_info,
                } => Ok(incoming_payment_info),
                Activity::OutgoingPayment { .. } => invalid_input!("OutgoingPayment was found"),
                Activity::OfferClaim {
                    incoming_payment_info,
                    ..
                } => Ok(incoming_payment_info),
                Activity::Swap {
                    incoming_payment_info: Some(incoming_payment_info),
                    ..
                } => Ok(incoming_payment_info),
                Activity::Swap {
                    incoming_payment_info: None,
                    ..
                } => invalid_input!("Pending swap was found"),
                Activity::ReverseSwap { .. } => invalid_input!("ReverseSwap was found"),
                Activity::ChannelClose { .. } => invalid_input!("ChannelClose was found"),
            };
        }
        let invoice = self
            .data_store
            .lock_unwrap()
            .retrieve_created_invoice_by_hash(&hash)?
            .ok_or_invalid_input("No payment with provided hash was found")?;
        self.payment_from_created_invoice(&invoice)
    }

    /// Get an outgoing payment by its payment hash.
    ///
    /// Parameters:
    /// * `hash` - hex representation of payment hash
    ///
    /// Requires network: **no**
    pub fn get_outgoing_payment(&self, hash: String) -> Result<OutgoingPaymentInfo> {
        let breez_payment = self
            .rt
            .handle()
            .block_on(self.sdk.payment_by_hash(hash))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to get payment by hash",
            )?
            .ok_or_invalid_input("No payment with provided hash was found")?;

        match self.activity_from_breez_ln_payment(breez_payment)? {
            Activity::IncomingPayment { .. } => invalid_input!("IncomingPayment was found"),
            Activity::OutgoingPayment {
                outgoing_payment_info,
            } => Ok(outgoing_payment_info),
            Activity::OfferClaim { .. } => invalid_input!("OfferClaim was found"),
            Activity::Swap { .. } => invalid_input!("Swap was found"),
            Activity::ReverseSwap {
                outgoing_payment_info,
                ..
            } => Ok(outgoing_payment_info),
            Activity::ChannelClose { .. } => invalid_input!("ChannelClose was found"),
        }
    }

    /// Get an activity by its payment hash.
    ///
    /// Parameters:
    /// * `hash` - hex representation of payment hash
    ///
    /// Requires network: **no**
    pub fn get_activity(&self, hash: String) -> Result<Activity> {
        let payment = self
            .rt
            .handle()
            .block_on(self.sdk.payment_by_hash(hash))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to get payment by hash",
            )?
            .ok_or_invalid_input("No activity with provided hash was found")?;

        self.activity_from_breez_ln_payment(payment)
    }

    /// Set a personal note on a specific payment.
    ///
    /// Parameters:
    /// * `payment_hash` - The hash of the payment for which a personal note will be set.
    /// * `note` - The personal note.
    ///
    /// Requires network: **no**
    pub fn set_payment_personal_note(&self, payment_hash: String, note: String) -> Result<()> {
        let note = Some(note.trim().to_string()).filter(|s| !s.is_empty());

        self.data_store
            .lock_unwrap()
            .update_personal_note(&payment_hash, note.as_deref())
    }

    fn activity_from_breez_payment(
        &self,
        breez_payment: breez_sdk_core::Payment,
    ) -> Result<Activity> {
        match &breez_payment.details {
            PaymentDetails::Ln { .. } => self.activity_from_breez_ln_payment(breez_payment),
            PaymentDetails::ClosedChannel { data } => {
                self.activity_from_breez_closed_channel_payment(&breez_payment, data)
            }
        }
    }

    fn activity_from_breez_ln_payment(
        &self,
        breez_payment: breez_sdk_core::Payment,
    ) -> Result<Activity> {
        let payment_details = match breez_payment.details {
            PaymentDetails::Ln { ref data } => data,
            PaymentDetails::ClosedChannel { .. } => {
                invalid_input!("PaymentInfo cannot be created from channel close")
            }
        };
        let local_payment_data = self
            .data_store
            .lock_unwrap()
            .retrieve_payment_info(&payment_details.payment_hash)?;
        let (exchange_rate, tz_config, personal_note, offer, received_on, received_lnurl_comment) =
            match local_payment_data {
                Some(data) => (
                    Some(data.exchange_rate),
                    data.user_preferences.timezone_config,
                    data.personal_note,
                    data.offer,
                    data.received_on,
                    data.received_lnurl_comment,
                ),
                None => (
                    self.get_exchange_rate(),
                    self.user_preferences.lock_unwrap().timezone_config.clone(),
                    None,
                    None,
                    None,
                    None,
                ),
            };

        if let Some(offer) = offer {
            let incoming_payment_info = IncomingPaymentInfo::new(
                breez_payment,
                &exchange_rate,
                tz_config,
                personal_note,
                received_on,
                received_lnurl_comment,
                &self.config.remote_services_config.lipa_lightning_domain,
            )?;
            let offer_kind = fill_payout_fee(
                offer,
                incoming_payment_info.requested_amount.sats.as_msats(),
                &exchange_rate,
            );
            Ok(Activity::OfferClaim {
                incoming_payment_info,
                offer_kind,
            })
        } else if let Some(ref s) = payment_details.swap_info {
            let swap_info = SwapInfo {
                bitcoin_address: s.bitcoin_address.clone(),
                // TODO: Persist SwapInfo in local db on state change, requires https://github.com/breez/breez-sdk/issues/518
                created_at: unix_timestamp_to_system_time(s.created_at as u64)
                    .with_timezone(tz_config.clone()),
                paid_amount: s.paid_msat.as_msats().to_amount_down(&exchange_rate),
                txid: s
                    .confirmed_tx_ids
                    .first()
                    .ok_or(permanent_failure("Confirmed swap has no confirmed txid"))?
                    .clone(),
            };
            let incoming_payment_info = IncomingPaymentInfo::new(
                breez_payment,
                &exchange_rate,
                tz_config,
                personal_note,
                received_on,
                received_lnurl_comment,
                &self.config.remote_services_config.lipa_lightning_domain,
            )?;
            Ok(Activity::Swap {
                incoming_payment_info: Some(incoming_payment_info),
                swap_info,
            })
        } else if let Some(ref s) = payment_details.reverse_swap_info {
            let reverse_swap_info = ReverseSwapInfo {
                paid_onchain_amount: s.onchain_amount_sat.as_sats().to_amount_up(&exchange_rate),
                swap_fees_amount: (breez_payment.amount_msat
                    - s.onchain_amount_sat.as_sats().msats)
                    .as_msats()
                    .to_amount_up(&exchange_rate),
                claim_txid: s.claim_txid.clone(),
                status: s.status,
            };
            let outgoing_payment_info = OutgoingPaymentInfo::new(
                breez_payment,
                &exchange_rate,
                tz_config,
                personal_note,
                &self.config.remote_services_config.lipa_lightning_domain,
            )?;
            Ok(Activity::ReverseSwap {
                outgoing_payment_info,
                reverse_swap_info,
            })
        } else if breez_payment.payment_type == breez_sdk_core::PaymentType::Received {
            let incoming_payment_info = IncomingPaymentInfo::new(
                breez_payment,
                &exchange_rate,
                tz_config,
                personal_note,
                received_on,
                received_lnurl_comment,
                &self.config.remote_services_config.lipa_lightning_domain,
            )?;
            Ok(Activity::IncomingPayment {
                incoming_payment_info,
            })
        } else if breez_payment.payment_type == breez_sdk_core::PaymentType::Sent {
            let outgoing_payment_info = OutgoingPaymentInfo::new(
                breez_payment,
                &exchange_rate,
                tz_config,
                personal_note,
                &self.config.remote_services_config.lipa_lightning_domain,
            )?;
            Ok(Activity::OutgoingPayment {
                outgoing_payment_info,
            })
        } else {
            permanent_failure!("Unreachable code")
        }
    }

    fn activity_from_breez_closed_channel_payment(
        &self,
        breez_payment: &breez_sdk_core::Payment,
        details: &ClosedChannelPaymentDetails,
    ) -> Result<Activity> {
        let amount = breez_payment
            .amount_msat
            .as_msats()
            .to_amount_up(&self.get_exchange_rate());

        let user_preferences = self.user_preferences.lock_unwrap();

        let time = unix_timestamp_to_system_time(breez_payment.payment_time as u64)
            .with_timezone(user_preferences.timezone_config.clone());

        let (closed_at, state) = match breez_payment.status {
            PaymentStatus::Pending => (None, ChannelCloseState::Pending),
            PaymentStatus::Complete => (Some(time), ChannelCloseState::Confirmed),
            PaymentStatus::Failed => {
                permanent_failure!("A channel close Breez Payment has status *Failed*");
            }
        };

        // According to the docs, it can only be empty for older closed channels.
        let closing_tx_id = details.closing_txid.clone().unwrap_or_default();

        Ok(Activity::ChannelClose {
            channel_close_info: ChannelCloseInfo {
                amount,
                state,
                closed_at,
                closing_tx_id,
            },
        })
    }

    fn payment_from_created_invoice(
        &self,
        created_invoice: &CreatedInvoice,
    ) -> Result<IncomingPaymentInfo> {
        let invoice =
            parse_invoice(created_invoice.invoice.as_str()).map_to_permanent_failure(format!(
                "Invalid invoice obtained from local db: {}",
                created_invoice.invoice
            ))?;
        let invoice_details = InvoiceDetails::from_ln_invoice(invoice.clone(), &None);

        let payment_state = if SystemTime::now() > invoice_details.expiry_timestamp {
            PaymentState::InvoiceExpired
        } else {
            PaymentState::Created
        };

        let local_payment_data = self
            .data_store
            .lock_unwrap()
            .retrieve_payment_info(&invoice_details.payment_hash)?
            .ok_or_permanent_failure("Locally created invoice doesn't have local payment data")?;
        let exchange_rate = Some(local_payment_data.exchange_rate);
        let invoice_details = InvoiceDetails::from_ln_invoice(invoice, &exchange_rate);
        // For receiving payments, we use the invoice timestamp.
        let time = invoice_details
            .creation_timestamp
            .with_timezone(local_payment_data.user_preferences.timezone_config);
        let lsp_fees = created_invoice
            .channel_opening_fees
            .unwrap_or_default()
            .as_msats()
            .to_amount_up(&exchange_rate);
        let requested_amount = invoice_details
            .amount
            .clone()
            .ok_or_permanent_failure("Locally created invoice doesn't include an amount")?
            .sats
            .as_sats()
            .to_amount_down(&exchange_rate);

        let amount = requested_amount.clone().sats - lsp_fees.sats;
        let amount = amount.as_sats().to_amount_down(&exchange_rate);

        let personal_note = local_payment_data.personal_note;

        let payment_info = PaymentInfo {
            payment_state,
            hash: invoice_details.payment_hash.clone(),
            amount,
            invoice_details: invoice_details.clone(),
            created_at: time,
            description: invoice_details.description,
            preimage: None,
            personal_note,
        };
        let incoming_payment_info = IncomingPaymentInfo {
            payment_info,
            requested_amount,
            lsp_fees,
            received_on: None,
            received_lnurl_comment: None,
        };
        Ok(incoming_payment_info)
    }

    /// Call the method when the app goes to foreground, such that the user can interact with it.
    /// The library starts running the background tasks more frequently to improve user experience.
    ///
    /// Requires network: **no**
    pub fn foreground(&self) {
        self.task_manager.lock_unwrap().foreground();
    }

    /// Call the method when the app goes to background, such that the user can not interact with it.
    /// The library stops running some unnecessary tasks and runs necessary tasks less frequently.
    /// It should save battery and internet traffic.
    ///
    /// Requires network: **no**
    pub fn background(&self) {
        self.task_manager.lock_unwrap().background();
    }

    /// List codes of supported fiat currencies.
    /// Please keep in mind that this method doesn't make any network calls. It simply retrieves
    /// previously fetched values that are frequently updated by a background task.
    ///
    /// The fetched list will be persisted across restarts to alleviate the consequences of a
    /// slow or unresponsive exchange rate service.
    /// The method will return an empty list if there is nothing persisted yet and
    /// the values are not yet fetched from the service.
    ///
    /// Requires network: **no**
    pub fn list_currency_codes(&self) -> Vec<String> {
        let rates = self.task_manager.lock_unwrap().get_exchange_rates();
        rates.iter().map(|r| r.currency_code.clone()).collect()
    }

    /// Get exchange rate on the BTC/default currency pair
    /// Please keep in mind that this method doesn't make any network calls. It simply retrieves
    /// previously fetched values that are frequently updated by a background task.
    ///
    /// The fetched exchange rates will be persisted across restarts to alleviate the consequences of a
    /// slow or unresponsive exchange rate service.
    ///
    /// The return value is an optional to deal with the possibility
    /// of no exchange rate values being known.
    ///
    /// Requires network: **no**
    pub fn get_exchange_rate(&self) -> Option<ExchangeRate> {
        let rates = self.task_manager.lock_unwrap().get_exchange_rates();
        let currency_code = self.user_preferences.lock_unwrap().fiat_currency.clone();
        rates
            .iter()
            .find(|r| r.currency_code == currency_code)
            .cloned()
    }

    /// Change the fiat currency (ISO 4217 currency code) - not all are supported
    /// The method [`LightningNode::list_currency_codes`] can used to list supported codes.
    ///
    /// Requires network: **no**
    pub fn change_fiat_currency(&self, fiat_currency: String) {
        self.user_preferences.lock_unwrap().fiat_currency = fiat_currency;
    }

    /// Change the timezone config.
    ///
    /// Parameters:
    /// * `timezone_config` - the user's current timezone
    ///
    /// Requires network: **no**
    pub fn change_timezone_config(&self, timezone_config: TzConfig) {
        self.user_preferences.lock_unwrap().timezone_config = timezone_config;
    }

    /// Accepts Pocket's T&C.
    ///
    /// Parameters:
    /// * `version` - the version number being accepted.
    /// * `fingerprint` - the fingerprint of the version being accepted.
    ///
    /// Requires network: **yes**
    pub fn accept_pocket_terms_and_conditions(
        &self,
        version: i64,
        fingerprint: String,
    ) -> Result<()> {
        self.auth
            .accept_terms_and_conditions(TermsAndConditions::Pocket, version, fingerprint)
            .map_runtime_error_to(RuntimeErrorCode::AuthServiceUnavailable)
    }

    /// Similar to [`get_terms_and_conditions_status`] with the difference that this method is pre-filling
    /// the environment and seed based on the node configuration.
    ///
    /// Requires network: **yes**
    pub fn get_terms_and_conditions_status(
        &self,
        terms_and_conditions: TermsAndConditions,
    ) -> Result<TermsAndConditionsStatus> {
        self.auth
            .get_terms_and_conditions_status(terms_and_conditions)
            .map_runtime_error_to(RuntimeErrorCode::AuthServiceUnavailable)
    }

    /// Register for fiat topups. Returns information that can be used by the user to transfer fiat
    /// to the 3rd party exchange service. Once the 3rd party exchange receives funds, the user will
    /// be able to withdraw sats using LNURL-w.
    ///
    /// Parameters:
    /// * `email` - this email will be used to send status information about different topups
    /// * `user_iban` - the user will send fiat from this iban
    /// * `user_currency` - the fiat currency (ISO 4217 currency code) that will be sent for
    ///    exchange. Not all are supported. A consumer of this library should find out about available
    ///    ones using other sources.
    ///
    /// Requires network: **yes**
    pub fn register_fiat_topup(
        &self,
        email: Option<String>,
        user_iban: String,
        user_currency: String,
    ) -> Result<FiatTopupInfo> {
        debug!("register_fiat_topup() - called with - email: {email:?} - user_iban: {user_iban} - user_currency: {user_currency:?}");
        user_iban
            .parse::<Iban>()
            .map_to_invalid_input("Invalid user_iban")?;

        if let Some(email) = email.as_ref() {
            EmailAddress::from_str(email).map_to_invalid_input("Invalid email")?;
        }

        let sdk = Arc::clone(&self.sdk);
        let sign_message = |message| async move {
            sdk.sign_message(SignMessageRequest { message })
                .await
                .ok()
                .map(|r| r.signature)
        };
        let topup_info = self
            .rt
            .handle()
            .block_on(self.fiat_topup_client.register_pocket_fiat_topup(
                &user_iban,
                user_currency,
                self.get_node_info()?.node_pubkey,
                sign_message,
            ))
            .map_to_runtime_error(
                RuntimeErrorCode::OfferServiceUnavailable,
                "Failed to register pocket fiat topup",
            )?;

        self.data_store
            .lock_unwrap()
            .store_fiat_topup_info(topup_info.clone())?;

        self.offer_manager
            .register_topup(topup_info.order_id.clone(), email)
            .map_runtime_error_to(RuntimeErrorCode::OfferServiceUnavailable)?;

        Ok(topup_info)
    }

    /// Resets a previous fiat topups registration.
    ///
    /// Requires network: **no**
    pub fn reset_fiat_topup(&self) -> Result<()> {
        self.data_store.lock_unwrap().clear_fiat_topup_info()
    }

    /// Hides the topup with the given id. Can be called on expired topups so that they stop being returned
    /// by [`LightningNode::query_uncompleted_offers`].
    ///
    /// Topup id can be obtained from [`OfferKind::Pocket`].
    ///
    /// Requires network: **yes**
    pub fn hide_topup(&self, id: String) -> Result<()> {
        self.offer_manager
            .hide_topup(id)
            .map_runtime_error_to(RuntimeErrorCode::OfferServiceUnavailable)
    }

    /// List action required items.
    ///
    /// Returns a list of actionable items. They can be:
    /// * Uncompleted offers (either available for collection or failed).
    /// * Unresolved failed swaps.
    /// * Available funds resulting from channel closes.
    ///
    /// Requires network: **yes**
    pub fn list_action_required_items(&self) -> Result<Vec<ActionRequiredItem>> {
        let uncompleted_offers = self.query_uncompleted_offers()?;

        let sat_per_vbyte = self.query_onchain_fee_rate()?;
        let hidden_failed_swap_addresses = self
            .data_store
            .lock_unwrap()
            .retrieve_hidden_unresolved_failed_swaps()?;
        let failed_swaps: Vec<_> = self
            .get_unresolved_failed_swaps()?
            .into_iter()
            .filter(|s| {
                hidden_failed_swap_addresses.contains(&s.address).not()
                    || self
                        .prepare_resolve_failed_swap(
                            s.clone(),
                            "1BitcoinEaterAddressDontSendf59kuE".to_string(),
                            sat_per_vbyte * 2,
                        )
                        .is_ok()
            })
            .collect();

        let available_channel_closes_funds = self.get_node_info()?.onchain_balance;

        let mut action_required_items: Vec<ActionRequiredItem> = uncompleted_offers
            .into_iter()
            .map(Into::into)
            .chain(failed_swaps.into_iter().map(Into::into))
            .collect();

        // CLN currently forces a min-emergency onchain balance of 546 (the dust limit)
        // TODO: Replace CLN_DUST_LIMIT_SAT with 0 if/when
        //      https://github.com/ElementsProject/lightning/issues/7131 is addressed
        if available_channel_closes_funds.sats > CLN_DUST_LIMIT_SAT {
            let utxos = self.get_node_utxos()?;

            // If we already have a 546 sat UTXO, then we hide from the total amount available
            let available_funds_sats = if utxos
                .iter()
                .any(|u| u.amount_millisatoshi == CLN_DUST_LIMIT_SAT * 1_000)
            {
                available_channel_closes_funds.sats
            } else {
                available_channel_closes_funds.sats - CLN_DUST_LIMIT_SAT
            };

            let optional_hidden_amount_sat = self
                .data_store
                .lock_unwrap()
                .retrieve_hidden_channel_close_onchain_funds_amount_sat()?;

            let include_item_in_list = match optional_hidden_amount_sat {
                Some(amount) if amount == available_channel_closes_funds.sats => {
                    self.get_channel_close_resolving_fees()?.is_some()
                }
                _ => true,
            };

            if include_item_in_list {
                action_required_items.push(ActionRequiredItem::ChannelClosesFundsAvailable {
                    available_funds: available_funds_sats
                        .as_sats()
                        .to_amount_down(&self.get_exchange_rate()),
                });
            }
        }

        // TODO: improve ordering of items in the returned vec
        Ok(action_required_items)
    }

    /// Hides the channel close action required item in case the amount cannot be recovered due
    /// to it being too small. The item will reappear once the amount of funds changes or
    /// onchain-fees go down enough to make the amount recoverable.
    ///
    /// Requires network: **no**
    pub fn hide_channel_closes_funds_available_action_required_item(&self) -> Result<()> {
        let onchain_balance_sat = self.get_node_info()?.onchain_balance.sats;
        self.data_store
            .lock_unwrap()
            .store_hidden_channel_close_onchain_funds_amount_sat(onchain_balance_sat)?;
        Ok(())
    }

    /// Hides the unresolved failed swap action required item in case the amount cannot be
    /// recovered due to it being too small. The item will reappear once the onchain-fees go
    /// down enough to make the amount recoverable.
    ///
    /// Requires network: **no**
    pub fn hide_unresolved_failed_swap_action_required_item(
        &self,
        failed_swap_info: FailedSwapInfo,
    ) -> Result<()> {
        self.data_store
            .lock_unwrap()
            .store_hidden_unresolved_failed_swap(&failed_swap_info.address)?;
        Ok(())
    }

    /// Get a list of unclaimed fund offers
    ///
    /// Requires network: **yes**
    pub fn query_uncompleted_offers(&self) -> Result<Vec<OfferInfo>> {
        let topup_infos = self
            .offer_manager
            .query_uncompleted_topups()
            .map_runtime_error_to(RuntimeErrorCode::OfferServiceUnavailable)?;
        let rate = self.get_exchange_rate();

        let list_payments_request = ListPaymentsRequest {
            filters: Some(vec![PaymentTypeFilter::Received]),
            metadata_filters: None,
            from_timestamp: None,
            to_timestamp: None,
            include_failures: Some(false),
            limit: Some(5),
            offset: None,
        };
        let latest_activities = self
            .rt
            .handle()
            .block_on(self.sdk.list_payments(list_payments_request))
            .map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Failed to list payments")?
            .into_iter()
            .filter(|p| p.status == PaymentStatus::Complete)
            .map(|p| self.activity_from_breez_payment(p))
            .filter_map(filter_out_and_log_corrupted_activities)
            .collect::<Vec<_>>();

        Ok(
            filter_out_recently_claimed_topups(topup_infos, latest_activities)
                .into_iter()
                .map(|topup_info| OfferInfo::from(topup_info, &rate))
                .collect(),
        )
    }

    /// Calculates the lightning payout fee for an uncompleted offer.
    ///
    /// Parameters:
    /// * `offer` - An uncompleted offer for which the lightning payout fee should get calculated.
    ///
    /// Requires network: **yes**
    pub fn calculate_lightning_payout_fee(&self, offer: OfferInfo) -> Result<Amount> {
        ensure!(
            offer.status != OfferStatus::REFUNDED && offer.status != OfferStatus::SETTLED,
            invalid_input(format!("Provided offer is already completed: {offer:?}"))
        );

        let max_withdrawable_msats = match self.rt.handle().block_on(parse(
            &offer
                .lnurlw
                .ok_or_permanent_failure("Uncompleted offer didn't include an lnurlw")?,
        )) {
            Ok(InputType::LnUrlWithdraw { data }) => data,
            Ok(input_type) => {
                permanent_failure!("Invalid input type LNURLw in uncompleted offer: {input_type:?}")
            }
            Err(err) => {
                permanent_failure!("Invalid LNURLw in uncompleted offer: {err}")
            }
        }
        .max_withdrawable;

        ensure!(
            max_withdrawable_msats <= offer.amount.sats.as_sats().msats,
            permanent_failure("LNURLw provides more")
        );

        let exchange_rate = self.get_exchange_rate();

        Ok((offer.amount.sats.as_sats().msats - max_withdrawable_msats)
            .as_msats()
            .to_amount_up(&exchange_rate))
    }

    /// Request to collect the offer (e.g. a Pocket topup).
    /// A payment hash will be returned to track incoming payment.
    /// The offer collection might be considered successful once
    /// [`EventsCallback::payment_received`] is called,
    /// or the [`PaymentState`] of the respective payment becomes [`PaymentState::Succeeded`].
    ///
    /// Parameters:
    /// * `offer` - An offer that is still valid for collection. Must have its `lnurlw` field
    ///   filled in.
    ///
    /// Requires network: **yes**
    pub fn request_offer_collection(&self, offer: OfferInfo) -> Result<String> {
        let lnurlw_data = match self.rt.handle().block_on(parse(
            &offer
                .lnurlw
                .ok_or_invalid_input("The provided offer didn't include an lnurlw")?,
        )) {
            Ok(InputType::LnUrlWithdraw { data }) => data,
            Ok(input_type) => {
                permanent_failure!("Invalid input type LNURLw in offer: {input_type:?}")
            }
            Err(err) => permanent_failure!("Invalid LNURLw in offer: {err}"),
        };
        let collectable_amount = lnurlw_data.max_withdrawable;
        let hash = match self
            .rt
            .handle()
            .block_on(self.sdk.lnurl_withdraw(LnUrlWithdrawRequest {
                data: lnurlw_data,
                amount_msat: collectable_amount,
                description: None,
            })) {
            Ok(breez_sdk_core::LnUrlWithdrawResult::Ok { data }) => data.invoice.payment_hash,
            Ok(breez_sdk_core::LnUrlWithdrawResult::Timeout { .. }) => runtime_error!(
                RuntimeErrorCode::OfferServiceUnavailable,
                "Failed to withdraw offer due to timeout on submitting invoice"
            ),
            Ok(breez_sdk_core::LnUrlWithdrawResult::ErrorStatus { data }) => runtime_error!(
                RuntimeErrorCode::OfferServiceUnavailable,
                "Failed to withdraw offer due to: {}",
                data.reason
            ),
            Err(breez_sdk_core::LnUrlWithdrawError::Generic { err }) => runtime_error!(
                RuntimeErrorCode::OfferServiceUnavailable,
                "Failed to withdraw offer due to: {err}"
            ),
            Err(breez_sdk_core::LnUrlWithdrawError::InvalidAmount { err }) => {
                permanent_failure!("Invalid amount in invoice for LNURL withdraw: {err}")
            }
            Err(breez_sdk_core::LnUrlWithdrawError::InvalidInvoice { err }) => {
                permanent_failure!("Invalid invoice for LNURL withdraw: {err}")
            }
            Err(breez_sdk_core::LnUrlWithdrawError::InvalidUri { err }) => {
                permanent_failure!("Invalid URL in LNURL withdraw: {err}")
            }
            Err(breez_sdk_core::LnUrlWithdrawError::ServiceConnectivity { err }) => {
                runtime_error!(
                    RuntimeErrorCode::OfferServiceUnavailable,
                    "Failed to withdraw offer due to: {err}"
                )
            }
            Err(breez_sdk_core::LnUrlWithdrawError::InvoiceNoRoutingHints { err }) => {
                permanent_failure!(
                    "A locally created invoice doesn't have any routing hints: {err}"
                )
            }
        };

        // MOCK: We need to simulate the backend receiving an update from Pocket that the offer has been settled.
        #[allow(irrefutable_let_patterns)]
        #[cfg(feature = "mock-deps")]
        if let OfferKind::Pocket { id, .. } = offer.offer_kind.clone() {
            self.offer_manager.hide_topup(id).unwrap();
        }

        self.store_payment_info(&hash, Some(offer.offer_kind));

        Ok(hash)
    }

    /// Registers a new notification token. If a token has already been registered, it will be updated.
    ///
    /// Requires network: **yes**
    pub fn register_notification_token(
        &self,
        notification_token: String,
        language_iso_639_1: String,
        country_iso_3166_1_alpha_2: String,
    ) -> Result<()> {
        let language = LanguageCode::from_str(&language_iso_639_1.to_lowercase())
            .map_to_invalid_input("Invalid language code")?;
        let country = CountryCode::for_alpha2(&country_iso_3166_1_alpha_2.to_uppercase())
            .map_to_invalid_input("Invalid country code")?;

        self.offer_manager
            .register_notification_token(notification_token, language, country)
            .map_runtime_error_to(RuntimeErrorCode::OfferServiceUnavailable)
    }

    /// Get the wallet UUID v5 from the wallet pubkey
    ///
    /// If the auth flow has never succeeded in this Auth instance, this method will require network
    /// access.
    ///
    /// Requires network: **yes**
    pub fn get_wallet_pubkey_id(&self) -> Result<String> {
        self.auth.get_wallet_pubkey_id().map_to_runtime_error(
            RuntimeErrorCode::AuthServiceUnavailable,
            "Failed to authenticate in order to get the wallet pubkey id",
        )
    }

    /// Get the payment UUID v5 from the payment hash
    ///
    /// Returns a UUID v5 derived from the payment hash. This will always return the same output
    /// given the same input.
    ///
    /// Parameters:
    /// * `payment_hash` - a payment hash represented in hex
    ///
    /// Requires network: **no**
    pub fn get_payment_uuid(&self, payment_hash: String) -> Result<String> {
        get_payment_uuid(payment_hash)
    }

    fn store_payment_info(&self, hash: &str, offer: Option<OfferKind>) {
        let user_preferences = self.user_preferences.lock_unwrap().clone();
        let exchange_rates = self.task_manager.lock_unwrap().get_exchange_rates();
        self.data_store
            .lock_unwrap()
            .store_payment_info(hash, user_preferences, exchange_rates, offer, None, None)
            .log_ignore_error(Level::Error, "Failed to persist payment info")
    }

    /// Query the current recommended on-chain fee rate.
    ///
    /// This is useful to obtain a fee rate to be used for [`LightningNode::sweep_funds_from_channel_closes`].
    ///
    /// Requires network: **yes**
    pub fn query_onchain_fee_rate(&self) -> Result<u32> {
        let recommended_fees = self
            .rt
            .handle()
            .block_on(self.sdk.recommended_fees())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Couldn't fetch recommended fees",
            )?;

        Ok(recommended_fees.half_hour_fee as u32)
    }

    /// Prepares a sweep of all available on-chain funds to the provided on-chain address.
    ///
    /// Parameters:
    /// * `address` - the funds will be sweeped to this address
    /// * `onchain_fee_rate` - the fee rate that should be applied for the transaction.
    ///   The recommended on-chain fee rate can be queried using [`LightningNode::query_onchain_fee_rate`]
    ///
    /// Returns information on the prepared sweep, including the exact fee that results from
    /// using the provided fee rate. The method [`LightningNode::sweep_funds_from_channel_closes`] can be used to broadcast
    /// the sweep transaction.
    ///
    /// Requires network: **yes**
    pub fn prepare_sweep_funds_from_channel_closes(
        &self,
        address: String,
        onchain_fee_rate: u32,
    ) -> std::result::Result<SweepInfo, RedeemOnchainError> {
        let res =
            self.rt
                .handle()
                .block_on(self.sdk.prepare_redeem_onchain_funds(
                    PrepareRedeemOnchainFundsRequest {
                        to_address: address.clone(),
                        sat_per_vbyte: onchain_fee_rate,
                    },
                ))?;

        let onchain_balance_sat = self
            .sdk
            .node_info()
            .map_err(|e| RedeemOnchainError::ServiceConnectivity {
                err: format!("Failed to fetch on-chain balance: {e}"),
            })?
            .onchain_balance_msat
            .as_msats()
            .to_amount_down(&None)
            .sats;

        let rate = self.get_exchange_rate();

        // Add the amount that won't be possible to be swept due to CLN's min-emergency limit (546 sats)
        // TODO: remove CLN_DUST_LIMIT_SAT addition if/when
        //      https://github.com/ElementsProject/lightning/issues/7131 is addressed
        let utxos = self
            .get_node_utxos()
            .map_err(|e| RedeemOnchainError::Generic { err: e.to_string() })?;
        let onchain_fee_sat = if utxos
            .iter()
            .any(|u| u.amount_millisatoshi == CLN_DUST_LIMIT_SAT * 1_000)
        {
            res.tx_fee_sat
        } else {
            res.tx_fee_sat + CLN_DUST_LIMIT_SAT
        };

        let onchain_fee_amount = onchain_fee_sat.as_sats().to_amount_up(&rate);

        Ok(SweepInfo {
            address,
            onchain_fee_rate,
            onchain_fee_amount,
            amount: (onchain_balance_sat - res.tx_fee_sat)
                .as_sats()
                .to_amount_up(&rate),
        })
    }

    /// Sweeps all available on-chain funds to the specified on-chain address.
    ///
    /// Parameters:
    /// * `sweep_info` - a prepared sweep info that can be obtained using
    ///     [`LightningNode::prepare_sweep_funds_from_channel_closes`]
    ///
    /// Returns the txid of the sweep transaction.
    ///
    /// Requires network: **yes**
    pub fn sweep_funds_from_channel_closes(&self, sweep_info: SweepInfo) -> Result<String> {
        let txid = self
            .rt
            .handle()
            .block_on(self.sdk.redeem_onchain_funds(RedeemOnchainFundsRequest {
                to_address: sweep_info.address,
                sat_per_vbyte: sweep_info.onchain_fee_rate,
            }))
            .map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Failed to sweep funds")?
            .txid;
        Ok(hex::encode(txid))
    }

    /// Generates a Bitcoin on-chain address that can be used to topup the local LN wallet from an
    /// external on-chain wallet.
    ///
    /// Funds sent to this address should conform to the min and max values provided within
    /// [`SwapAddressInfo`].
    ///
    /// If a swap is in progress, this method will return an error.
    ///
    /// Parameters:
    /// * `lsp_fee_params` - the lsp fee parameters to be used if a new channel needs to
    ///   be opened. Can be obtained using [`LightningNode::calculate_lsp_fee`].
    ///
    /// Requires network: **yes**
    pub fn generate_swap_address(
        &self,
        lsp_fee_params: Option<OpeningFeeParams>,
    ) -> std::result::Result<SwapAddressInfo, ReceiveOnchainError> {
        let swap_info =
            self.rt
                .handle()
                .block_on(self.sdk.receive_onchain(ReceiveOnchainRequest {
                    opening_fee_params: lsp_fee_params,
                }))?;
        let rate = self.get_exchange_rate();

        Ok(SwapAddressInfo {
            address: swap_info.bitcoin_address,
            min_deposit: (swap_info.min_allowed_deposit as u64)
                .as_sats()
                .to_amount_up(&rate),
            max_deposit: (swap_info.max_allowed_deposit as u64)
                .as_sats()
                .to_amount_down(&rate),
            swap_fee: 0_u64.as_sats().to_amount_up(&rate),
        })
    }

    /// Lists all unresolved failed swaps. Each individual failed swap can be recovered
    /// using [`LightningNode::resolve_failed_swap`].
    ///
    /// Requires network: **yes**
    pub fn get_unresolved_failed_swaps(&self) -> Result<Vec<FailedSwapInfo>> {
        Ok(self
            .rt
            .handle()
            .block_on(self.sdk.list_refundables())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to list refundable failed swaps",
            )?
            .into_iter()
            .map(|s| FailedSwapInfo {
                address: s.bitcoin_address,
                amount: s
                    .confirmed_sats
                    .as_sats()
                    .to_amount_down(&self.get_exchange_rate()),
                created_at: unix_timestamp_to_system_time(s.created_at as u64),
            })
            .collect())
    }

    /// Returns the fees for resolving a failed swap if there are enough funds to pay for fees.
    ///
    /// Must only be called when the failed swap is unresolved.
    ///
    /// Returns the fee information for the available resolving options.
    ///
    /// Requires network: *yes*
    pub fn get_failed_swap_resolving_fees(
        &self,
        failed_swap_info: FailedSwapInfo,
    ) -> Result<Option<OnchainResolvingFees>> {
        let sdk = Arc::clone(&self.sdk);
        let handle = self.rt.handle();
        let swap_address = failed_swap_info.address;
        let prepare_onchain_tx =
            move |to_address: String, sat_per_vbyte: u32| -> Result<(Sats, Sats)> {
                let prepare_refund_response = handle
                    .block_on(sdk.prepare_refund(PrepareRefundRequest {
                        swap_address,
                        to_address,
                        sat_per_vbyte,
                    }))
                    .map_to_runtime_error(
                        RuntimeErrorCode::NodeUnavailable,
                        "Failed to prepare refund",
                    )?;
                let sent_amount = (failed_swap_info.amount.sats
                    - prepare_refund_response.refund_tx_fee_sat)
                    .as_sats();
                let onchain_fee = prepare_refund_response.refund_tx_fee_sat.as_sats();

                Ok((sent_amount, onchain_fee))
            };
        self.get_onchain_resolving_fees(failed_swap_info.amount.sats.as_msats(), prepare_onchain_tx)
    }

    fn get_onchain_resolving_fees<F>(
        &self,
        amount: Msats,
        prepare_onchain_tx: F,
    ) -> Result<Option<OnchainResolvingFees>>
    where
        F: FnOnce(String, u32) -> Result<(Sats, Sats)>,
    {
        let rate = self.get_exchange_rate();
        let lsp_fees = self.calculate_lsp_fee(amount.msats)?;

        let swap_info = self
            .rt
            .handle()
            .block_on(self.sdk.receive_onchain(ReceiveOnchainRequest {
                opening_fee_params: lsp_fees.lsp_fee_params,
            }))
            .ok();

        let sat_per_vbyte = self.query_onchain_fee_rate()?;

        let (sent_amount, onchain_fee) = match prepare_onchain_tx(
            swap_info
                .clone()
                .map(|s| s.bitcoin_address)
                .unwrap_or("1BitcoinEaterAddressDontSendf59kuE".to_string()),
            sat_per_vbyte,
        ) {
            Ok(t) => t,
            // TODO: expose distinction between insufficient funds failure and other failures
            //  -> requires that the SDK exposes an error when preparing for resolving failed swaps
            //  for now, it only does for preparing to resolve onchain funds from channel closes.
            Err(e) => {
                error!("Failed to prepare onchain tx due to {e}");
                return Ok(None);
            }
        };

        // Require onchain fees to be less than half of the onchain balance to leave some leeway
        //  (for now, the onchain fee is just an estimation because the destination address is unknown)
        if onchain_fee.sats * 2 > amount.sats_round_down().sats {
            return Ok(None);
        }

        let lsp_fees = self.calculate_lsp_fee(sent_amount.sats)?;

        if swap_info.is_none()
            || sent_amount.sats < (swap_info.clone().unwrap().min_allowed_deposit as u64)
            || sent_amount.sats > (swap_info.clone().unwrap().max_allowed_deposit as u64)
            || sent_amount.sats <= lsp_fees.lsp_fee.sats
        {
            return Ok(Some(OnchainResolvingFees {
                swap_fees: None,
                sweep_onchain_fee_estimate: onchain_fee.to_amount_up(&rate),
                sat_per_vbyte,
            }));
        }

        let swap_fee = 0_u64.as_sats();
        let swap_to_lightning_fees = SwapToLightningFees {
            swap_fee: swap_fee.sats.as_sats().to_amount_up(&rate),
            onchain_fee: onchain_fee.to_amount_up(&rate),
            channel_opening_fee: lsp_fees.lsp_fee.clone(),
            total_fees: (swap_fee.sats + onchain_fee.sats + lsp_fees.lsp_fee.sats)
                .as_sats()
                .to_amount_up(&rate),
            lsp_fee_params: lsp_fees.lsp_fee_params,
        };

        Ok(Some(OnchainResolvingFees {
            swap_fees: Some(swap_to_lightning_fees),
            sweep_onchain_fee_estimate: onchain_fee.to_amount_up(&rate),
            sat_per_vbyte,
        }))
    }

    /// Prepares the resolution of a failed swap in order to know how much will be recovered and how much
    /// will be paid in on-chain fees.
    ///
    /// Parameters:
    /// * `failed_swap_info` - the failed swap that will be prepared
    /// * `to_address` - the destination address to which funds will be sent
    /// * `onchain_fee_rate` - the fee rate that will be applied. The recommended one can be fetched
    ///   using [`LightningNode::query_onchain_fee_rate`]
    ///
    /// Requires network: **yes**
    pub fn prepare_resolve_failed_swap(
        &self,
        failed_swap_info: FailedSwapInfo,
        to_address: String,
        onchain_fee_rate: u32,
    ) -> Result<ResolveFailedSwapInfo> {
        let response = self
            .rt
            .handle()
            .block_on(self.sdk.prepare_refund(PrepareRefundRequest {
                swap_address: failed_swap_info.address.clone(),
                to_address: to_address.clone(),
                sat_per_vbyte: onchain_fee_rate,
            }))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to prepare a failed swap refund transaction",
            )?;

        let rate = self.get_exchange_rate();
        let onchain_fee = response.refund_tx_fee_sat.as_sats().to_amount_up(&rate);
        let recovered_amount = (failed_swap_info.amount.sats - onchain_fee.sats)
            .as_sats()
            .to_amount_down(&rate);

        Ok(ResolveFailedSwapInfo {
            swap_address: failed_swap_info.address,
            recovered_amount,
            onchain_fee,
            to_address,
            onchain_fee_rate,
        })
    }

    /// Creates and broadcasts a resolving transaction to recover funds from a failed swap. Existing
    /// failed swaps can be listed using [`LightningNode::get_unresolved_failed_swaps`] and preparing
    /// the resolution of a failed swap can be done using [`LightningNode::prepare_resolve_failed_swap`].
    ///
    /// Parameters:
    /// * `resolve_failed_swap_info` - Information needed to resolve the failed swap. Can be obtained
    ///   using [`LightningNode::prepare_resolve_failed_swap`].
    ///
    /// Returns the txid of the resolving transaction.
    ///
    /// Paid on-chain fees can be known in advance using [`LightningNode::prepare_resolve_failed_swap`].
    ///
    /// Requires network: **yes**
    pub fn resolve_failed_swap(
        &self,
        resolve_failed_swap_info: ResolveFailedSwapInfo,
    ) -> Result<String> {
        Ok(self
            .rt
            .handle()
            .block_on(self.sdk.refund(RefundRequest {
                swap_address: resolve_failed_swap_info.swap_address,
                to_address: resolve_failed_swap_info.to_address,
                sat_per_vbyte: resolve_failed_swap_info.onchain_fee_rate,
            }))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to create and broadcast failed swap refund transaction",
            )?
            .refund_tx_id)
    }

    pub fn swap_failed_swap_funds_to_lightning(
        &self,
        failed_swap_info: FailedSwapInfo,
        sat_per_vbyte: u32,
        lsp_fee_param: Option<OpeningFeeParams>,
    ) -> Result<String> {
        let swap_address_info = self
            .generate_swap_address(lsp_fee_param.clone())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Couldn't generate swap address",
            )?;

        let prepare_response = self
            .rt
            .handle()
            .block_on(self.sdk.prepare_refund(PrepareRefundRequest {
                swap_address: failed_swap_info.address.clone(),
                to_address: swap_address_info.address.clone(),
                sat_per_vbyte,
            }))
            .map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Coudln't prepare refund")?;

        let send_amount_sats = failed_swap_info.amount.sats - prepare_response.refund_tx_fee_sat;

        ensure!(
            swap_address_info.min_deposit.sats <= send_amount_sats,
            runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed swap amount isn't enough for creating new swap"
            )
        );

        ensure!(
            swap_address_info.max_deposit.sats >= send_amount_sats,
            runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed swap amount is too big for creating new swap"
            )
        );

        let lsp_fees = self.calculate_lsp_fee(send_amount_sats)?.lsp_fee.sats;
        ensure!(
            lsp_fees < send_amount_sats,
            runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "A new channel is needed and the failed swap amount is not enough to pay for fees"
            )
        );

        let refund_response = self
            .rt
            .handle()
            .block_on(self.sdk.refund(RefundRequest {
                swap_address: failed_swap_info.address,
                to_address: swap_address_info.address,
                sat_per_vbyte,
            }))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Couldn't broadcast swap refund transaction",
            )?;

        Ok(refund_response.refund_tx_id)
    }

    /// Returns the fees for resolving channel closes if there are enough funds to pay for fees.
    ///
    /// Must only be called when there are onchain funds to resolve.
    ///
    /// Returns the fee information for the available resolving options.
    ///
    /// Requires network: **yes**
    pub fn get_channel_close_resolving_fees(&self) -> Result<Option<OnchainResolvingFees>> {
        let onchain_balance = self
            .sdk
            .node_info()
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Couldn't fetch on-chain balance",
            )?
            .onchain_balance_msat
            .as_msats();
        ensure!(
            onchain_balance.msats != 0,
            invalid_input("No on-chain funds to resolve")
        );

        let prepare_onchain_tx =
            move |to_address: String, sat_per_vbyte: u32| -> Result<(Sats, Sats)> {
                let sweep_info = self
                    .prepare_sweep_funds_from_channel_closes(to_address, sat_per_vbyte)
                    .map_to_runtime_error(
                        RuntimeErrorCode::NodeUnavailable,
                        "Failed to prepare sweep funds from channel closes",
                    )?;

                Ok((
                    sweep_info.amount.sats.as_sats(),
                    sweep_info.onchain_fee_amount.sats.as_sats(),
                ))
            };

        self.get_onchain_resolving_fees(onchain_balance, prepare_onchain_tx)
    }

    /// Automatically swaps on-chain funds back to lightning.
    ///
    /// If a swap is in progress, this method will return an error.
    ///
    /// If the current balance doesn't fulfill the limits, this method will return an error.
    /// Before using this method use [`LightningNode::get_channel_close_resolving_fees`] to validate a swap is available.
    ///
    /// Parameters:
    /// * `sat_per_vbyte` - the fee rate to use for the on-chain transaction.
    ///   Can be obtained with [`LightningNode::get_channel_close_resolving_fees`].
    /// * `lsp_fee_params` - the lsp fee params for opening a new channel if necessary.
    ///   Can be obtained with [`LightningNode::get_channel_close_resolving_fees`].
    ///
    /// Returns the txid of the sweeping tx.
    ///
    /// Requires network: **yes**
    pub fn swap_channel_close_funds_to_lightning(
        &self,
        sat_per_vbyte: u32,
        lsp_fee_params: Option<OpeningFeeParams>,
    ) -> std::result::Result<String, RedeemOnchainError> {
        let onchain_balance = self.sdk.node_info()?.onchain_balance_msat.as_msats();

        let swap_address_info =
            self.generate_swap_address(lsp_fee_params.clone())
                .map_err(|e| RedeemOnchainError::Generic {
                    err: format!("Couldn't generate swap address: {}", e),
                })?;

        let prepare_response =
            self.rt
                .handle()
                .block_on(self.sdk.prepare_redeem_onchain_funds(
                    PrepareRedeemOnchainFundsRequest {
                        to_address: swap_address_info.address.clone(),
                        sat_per_vbyte,
                    },
                ))?;
        // TODO: remove CLN_DUST_LIMIT_SAT component if/when
        //      https://github.com/ElementsProject/lightning/issues/7131 is addressed
        let send_amount_sats = onchain_balance.sats_round_down().sats
            - CLN_DUST_LIMIT_SAT
            - prepare_response.tx_fee_sat;

        if swap_address_info.min_deposit.sats > send_amount_sats {
            return Err(RedeemOnchainError::InsufficientFunds {
                err: format!(
                    "Not enough funds ({} sats after onchain fees) available for min swap amount({} sats)",
                    send_amount_sats,
                    swap_address_info.min_deposit.sats,
                ),
            });
        }

        if swap_address_info.max_deposit.sats < send_amount_sats {
            return Err(RedeemOnchainError::Generic {
                err: format!(
                    "Available funds ({} sats after onchain fees) exceed limit for swap ({} sats)",
                    send_amount_sats, swap_address_info.max_deposit.sats,
                ),
            });
        }

        let lsp_fees = self
            .calculate_lsp_fee(send_amount_sats)
            .map_err(|_| RedeemOnchainError::ServiceConnectivity {
                err: "Could not get lsp fees".to_string(),
            })?
            .lsp_fee
            .sats;
        if lsp_fees >= send_amount_sats {
            return Err(RedeemOnchainError::InsufficientFunds {
                err: format!(
                    "Available funds ({} sats after onchain fees) are not enough for lsp fees ({} sats)",
                    send_amount_sats, lsp_fees,
                ),
            });
        }

        let sweep_result = self.rt.handle().block_on(self.sdk.redeem_onchain_funds(
            RedeemOnchainFundsRequest {
                to_address: swap_address_info.address,
                sat_per_vbyte,
            },
        ))?;

        Ok(hex::encode(sweep_result.txid))
    }

    /// Prints additional debug information to the logs.
    ///
    /// Throws an error in case that the necessary information can't be retrieved.
    ///
    /// Requires network: **yes**
    pub fn log_debug_info(&self) -> Result<()> {
        self.rt
            .handle()
            .block_on(self.sdk.sync())
            .log_ignore_error(Level::Error, "Failed to sync node");

        let available_lsps = self
            .rt
            .handle()
            .block_on(self.sdk.list_lsps())
            .map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Couldn't list lsps")?;

        let connected_lsp = self
            .rt
            .handle()
            .block_on(self.sdk.lsp_id())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to get current lsp id",
            )?
            .unwrap_or("<no connection>".to_string());

        let node_state = self.sdk.node_info().map_to_runtime_error(
            RuntimeErrorCode::NodeUnavailable,
            "Failed to read node info",
        )?;

        let channels = self
            .rt
            .handle()
            .block_on(self.sdk.execute_dev_command("listpeerchannels".to_string()))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Couldn't execute `listpeerchannels` command",
            )?;

        let payments = self
            .rt
            .handle()
            .block_on(self.sdk.execute_dev_command("listpayments".to_string()))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Couldn't execute `listpayments` command",
            )?;

        let diagnostics = self
            .rt
            .handle()
            .block_on(self.sdk.generate_diagnostic_data())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Couldn't call generate_diagnostic_data",
            )?;

        info!("3L version: {}", env!("GITHUB_REF"));
        info!("Wallet pubkey id: {:?}", self.get_wallet_pubkey_id());
        // Print connected peers, balances, inbound/outbound capacities, on-chain funds.
        info!("Node state:\n{node_state:?}");
        info!(
            "List of available lsps:\n{}",
            replace_byte_arrays_by_hex_string(&format!("{available_lsps:?}"))
        );
        info!("Connected lsp id: {connected_lsp}");
        info!(
            "List of peer channels:\n{}",
            replace_byte_arrays_by_hex_string(&channels)
        );
        info!(
            "List of payments:\n{}",
            replace_byte_arrays_by_hex_string(&payments)
        );
        info!("Diagnostic data:\n{diagnostics}");
        Ok(())
    }

    /// Returns the latest [`FiatTopupInfo`] if the user has registered for the fiat topup.
    ///
    /// Requires network: **no**
    pub fn retrieve_latest_fiat_topup_info(&self) -> Result<Option<FiatTopupInfo>> {
        self.data_store
            .lock_unwrap()
            .retrieve_latest_fiat_topup_info()
    }

    /// Returns the health check status of Breez and Greenlight services.
    ///
    /// Requires network: **yes**
    pub fn get_health_status(&self) -> Result<BreezHealthCheckStatus> {
        Ok(self
            .rt
            .handle()
            .block_on(BreezServices::service_health_check(
                self.config.breez_sdk_config.breez_sdk_api_key.clone(),
            ))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to get health status",
            )?
            .status)
    }

    /// Check if clearing the wallet is feasible.
    ///
    /// Meaning that the balance is within the range of what can be reverse-swapped.
    ///
    /// Requires network: **yes**
    pub fn check_clear_wallet_feasibility(&self) -> Result<RangeHit> {
        let limits = self
            .rt
            .handle()
            .block_on(self.sdk.onchain_payment_limits())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to get on-chain payment limits",
            )?;
        let balance_sat = self
            .sdk
            .node_info()
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to read node info",
            )?
            .channels_balance_msat
            .as_msats()
            .sats_round_down()
            .sats;
        let exchange_rate = self.get_exchange_rate();

        // Accomodating lightning network routing fees.
        let routing_fee = Permyriad(self.config.max_routing_fee_config.max_routing_fee_permyriad)
            .of(&limits.min_sat.as_sats())
            .sats_round_up();
        let min = limits.min_sat + routing_fee.sats;
        let range_hit = match balance_sat {
            balance_sat if balance_sat < min => RangeHit::Below {
                min: min.as_sats().to_amount_up(&exchange_rate),
            },
            balance_sat if balance_sat <= limits.max_sat => RangeHit::In,
            balance_sat if limits.max_sat < balance_sat => RangeHit::Above {
                max: limits.max_sat.as_sats().to_amount_down(&exchange_rate),
            },
            _ => permanent_failure!("Unreachable code in check_clear_wallet_feasibility()"),
        };
        Ok(range_hit)
    }

    /// Prepares a reverse swap that sends all funds in LN channels. This is possible because the
    /// route to the swap service is known, so fees can be known in advance.
    ///
    /// This can fail if the balance is either too low or too high for it to be reverse-swapped.
    /// The method [`LightningNode::check_clear_wallet_feasibility`] can be used to check if the balance
    /// is within the required range.
    ///
    /// Requires network: **yes**
    pub fn prepare_clear_wallet(&self) -> Result<ClearWalletInfo> {
        let claim_tx_feerate = self.query_onchain_fee_rate()?;
        let limits = self
            .rt
            .handle()
            .block_on(self.sdk.onchain_payment_limits())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to get on-chain payment limits",
            )?;
        let prepare_response = self
            .rt
            .handle()
            .block_on(
                self.sdk
                    .prepare_onchain_payment(PrepareOnchainPaymentRequest {
                        amount_sat: limits.max_payable_sat,
                        amount_type: breez_sdk_core::SwapAmountType::Send,
                        claim_tx_feerate,
                    }),
            )
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to prepare on-chain payment",
            )?;

        let total_fees_sat = prepare_response.total_fees;
        let onchain_fee_sat = prepare_response.fees_claim + prepare_response.fees_lockup;
        let swap_fee_sat = total_fees_sat - onchain_fee_sat;
        let exchange_rate = self.get_exchange_rate();

        Ok(ClearWalletInfo {
            clear_amount: prepare_response
                .sender_amount_sat
                .as_sats()
                .to_amount_up(&exchange_rate),
            total_estimated_fees: total_fees_sat.as_sats().to_amount_up(&exchange_rate),
            onchain_fee: onchain_fee_sat.as_sats().to_amount_up(&exchange_rate),
            swap_fee: swap_fee_sat.as_sats().to_amount_up(&exchange_rate),
            prepare_response,
        })
    }

    /// Starts a reverse swap that sends all funds in LN channels to the provided on-chain address.
    ///
    /// Parameters:
    /// * `clear_wallet_info` - An instance of [`ClearWalletInfo`] obtained using
    ///   [`LightningNode::prepare_clear_wallet`].
    /// * `destination_onchain_address_data` - An on-chain address data instance. Can be obtained
    ///   using [`LightningNode::decode_data`].
    ///
    /// Requires network: **yes**
    pub fn clear_wallet(
        &self,
        clear_wallet_info: ClearWalletInfo,
        destination_onchain_address_data: BitcoinAddressData,
    ) -> Result<()> {
        self.rt
            .handle()
            .block_on(self.sdk.pay_onchain(PayOnchainRequest {
                recipient_address: destination_onchain_address_data.address,
                prepare_res: clear_wallet_info.prepare_response,
            }))
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to start reverse swap",
            )?;
        Ok(())
    }

    /// Set the analytics configuration.
    ///
    /// This can be used to completely prevent any analytics data from being reported.
    ///
    /// Requires network: **no**
    pub fn set_analytics_config(&self, config: AnalyticsConfig) -> Result<()> {
        *self.analytics_interceptor.config.lock_unwrap() = config.clone();
        self.data_store
            .lock_unwrap()
            .append_analytics_config(config)
    }

    /// Get the currently configured analytics configuration.
    ///
    /// Requires network: **no**
    pub fn get_analytics_config(&self) -> Result<AnalyticsConfig> {
        self.data_store.lock_unwrap().retrieve_analytics_config()
    }

    /// Register a human-readable lightning address or return the previously
    /// registered one.
    ///
    /// Requires network: **yes**
    pub fn register_lightning_address(&self) -> Result<String> {
        let address = self
            .rt
            .handle()
            .block_on(pigeon::assign_lightning_address(
                &self.config.remote_services_config.backend_url,
                &self.async_auth,
            ))
            .map_to_runtime_error(
                RuntimeErrorCode::AuthServiceUnavailable,
                "Failed to register a lightning address",
            )?;
        self.data_store
            .lock_unwrap()
            .store_lightning_address(&address)?;
        Ok(address)
    }

    /// Query the registered lightning address.
    ///
    /// Requires network: **no**
    pub fn query_lightning_address(&self) -> Result<Option<String>> {
        Ok(self
            .data_store
            .lock_unwrap()
            .retrieve_lightning_addresses()?
            .into_iter()
            .filter_map(with_status(EnableStatus::Enabled))
            .find(|a| !a.starts_with('-')))
    }

    /// Query for a previously verified phone number.
    ///
    /// Requires network: **no**
    pub fn query_verified_phone_number(&self) -> Result<Option<String>> {
        Ok(self
            .data_store
            .lock_unwrap()
            .retrieve_lightning_addresses()?
            .into_iter()
            .filter_map(with_status(EnableStatus::Enabled))
            .find(|a| a.starts_with('-'))
            .and_then(|a| {
                lightning_address_to_phone_number(
                    &a,
                    &self.config.remote_services_config.lipa_lightning_domain,
                )
            }))
    }

    /// Start the verification process for a new phone number. This will trigger an SMS containing
    /// an OTP to be sent to the provided `phone_number`. To conclude the verification process,
    /// the method [`LightningNode::verify_phone_number`] should be called next.
    ///
    /// Parameters:
    /// * `phone_number` - the phone number to be registered. Needs to be checked for validity using
    ///   [LightningNode::parse_phone_number_to_lightning_address].
    ///
    /// Requires network: **yes**
    pub fn request_phone_number_verification(&self, phone_number: String) -> Result<()> {
        let phone_number = self
            .parse_phone_number(phone_number)
            .map_to_invalid_input("Invalid phone number")?;

        let encrypted_number = encrypt(
            phone_number.e164.as_bytes(),
            &self.persistence_encryption_key,
        )?;
        let encrypted_number = hex::encode(encrypted_number);

        self.rt
            .handle()
            .block_on(pigeon::request_phone_number_verification(
                &self.config.remote_services_config.backend_url,
                &self.async_auth,
                phone_number.e164,
                encrypted_number,
            ))
            .map_to_runtime_error(
                RuntimeErrorCode::AuthServiceUnavailable,
                "Failed to register phone number",
            )
    }

    /// Finish the verification process for a new phone number.
    ///
    /// Parameters:
    /// * `phone_number` - the phone number to be verified.
    /// * `otp` - the OTP code sent as an SMS to the phone number.
    ///
    /// Requires network: **yes**
    pub fn verify_phone_number(&self, phone_number: String, otp: String) -> Result<()> {
        let phone_number = self
            .parse_phone_number(phone_number)
            .map_to_invalid_input("Invalid phone number")?;

        self.rt
            .handle()
            .block_on(pigeon::verify_phone_number(
                &self.config.remote_services_config.backend_url,
                &self.async_auth,
                phone_number.e164.clone(),
                otp,
            ))
            .map_to_runtime_error(
                RuntimeErrorCode::AuthServiceUnavailable,
                "Failed to submit phone number registration otp",
            )?;
        let address = phone_number
            .to_lightning_address(&self.config.remote_services_config.lipa_lightning_domain);
        self.data_store
            .lock_unwrap()
            .store_lightning_address(&address)
    }

    /// Set value of a feature flag.
    /// The method will report the change to the backend and update the local database.
    ///
    /// Parameters:
    /// * `feature` - feature flag to be set.
    /// * `enable` - enable or disable the feature.
    ///
    /// Requires network: **yes**
    pub fn set_feature_flag(&self, feature: FeatureFlag, flag_enabled: bool) -> Result<()> {
        let kind_of_address = match feature {
            FeatureFlag::LightningAddress => |a: &String| !a.starts_with('-'),
            FeatureFlag::PhoneNumber => |a: &String| a.starts_with('-'),
        };
        let (from_status, to_status) = match flag_enabled {
            true => (EnableStatus::FeatureDisabled, EnableStatus::Enabled),
            false => (EnableStatus::Enabled, EnableStatus::FeatureDisabled),
        };

        let addresses = self
            .data_store
            .lock_unwrap()
            .retrieve_lightning_addresses()?
            .into_iter()
            .filter_map(with_status(from_status))
            .filter(kind_of_address)
            .collect::<Vec<_>>();

        if addresses.is_empty() {
            info!("No lightning addresses to change the status");
            return Ok(());
        }

        let doing = match flag_enabled {
            true => "Enabling",
            false => "Disabling",
        };
        info!("{doing} {addresses:?} on the backend");

        self.rt
            .handle()
            .block_on(async {
                if flag_enabled {
                    pigeon::enable_lightning_addresses(
                        &self.config.remote_services_config.backend_url,
                        &self.async_auth,
                        addresses.clone(),
                    )
                    .await
                } else {
                    pigeon::disable_lightning_addresses(
                        &self.config.remote_services_config.backend_url,
                        &self.async_auth,
                        addresses.clone(),
                    )
                    .await
                }
            })
            .map_to_runtime_error(
                RuntimeErrorCode::AuthServiceUnavailable,
                "Failed to enable/disable a lightning address",
            )?;
        let mut data_store = self.data_store.lock_unwrap();
        addresses
            .into_iter()
            .try_for_each(|a| data_store.update_lightning_address(&a, to_status))
    }

    fn report_send_payment_issue(&self, payment_hash: String) {
        debug!("Reporting failure of payment: {payment_hash}");
        let data = ReportPaymentFailureDetails {
            payment_hash,
            comment: None,
        };
        let request = ReportIssueRequest::PaymentFailure { data };
        self.rt
            .handle()
            .block_on(self.sdk.report_issue(request))
            .log_ignore_error(Level::Warn, "Failed to report issue");
    }

    fn get_node_utxos(&self) -> Result<Vec<UnspentTransactionOutput>> {
        let node_state = self
            .sdk
            .node_info()
            .map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Couldn't get node info")?;

        Ok(node_state.utxos)
    }

    // Only meant for example CLI use
    #[doc(hidden)]
    pub fn close_all_channels_with_current_lsp(&self) -> Result<()> {
        self.rt
            .handle()
            .block_on(self.sdk.close_lsp_channels())
            .map_to_runtime_error(
                RuntimeErrorCode::NodeUnavailable,
                "Failed to close channels",
            )?;
        Ok(())
    }
}

pub(crate) async fn start_sdk(
    config: &Config,
    event_listener: Box<dyn EventListener>,
) -> Result<Arc<BreezServices>> {
    let developer_cert = config
        .breez_sdk_config
        .breez_sdk_partner_certificate
        .as_bytes()
        .to_vec();
    let developer_key = config
        .breez_sdk_config
        .breez_sdk_partner_key
        .as_bytes()
        .to_vec();
    let partner_credentials = GreenlightCredentials {
        developer_cert,
        developer_key,
    };

    let mut breez_config = BreezServices::default_config(
        EnvironmentType::Production,
        config.breez_sdk_config.breez_sdk_api_key.clone(),
        NodeConfig::Greenlight {
            config: GreenlightNodeConfig {
                partner_credentials: Some(partner_credentials),
                invite_code: None,
            },
        },
    );

    breez_config
        .working_dir
        .clone_from(&config.local_persistence_path);
    breez_config.exemptfee_msat = config
        .max_routing_fee_config
        .max_routing_fee_exempt_fee_sats
        .as_sats()
        .msats;
    breez_config.maxfee_percent =
        Permyriad(config.max_routing_fee_config.max_routing_fee_permyriad).to_percentage();
    let connect_request = ConnectRequest {
        config: breez_config,
        seed: config.seed.clone(),
        restore_only: None,
    };
    BreezServices::connect(connect_request, event_listener)
        .await
        .map_to_runtime_error(
            RuntimeErrorCode::NodeUnavailable,
            "Failed to initialize a breez sdk instance",
        )
}

/// Accept lipa's terms and conditions. Should be called before instantiating a [`LightningNode`]
/// for the first time.
///
/// Parameters:
/// * `backend_url`
/// * `seed` - the seed from the wallet for which the T&C will be accepted.
/// * `version` - the version number being accepted.
/// * `fingerprint` - the fingerprint of the version being accepted.
///
/// Requires network: **yes**
pub fn accept_terms_and_conditions(
    backend_url: String,
    seed: Vec<u8>,
    version: i64,
    fingerprint: String,
) -> Result<()> {
    enable_backtrace();
    let seed = sanitize_input::strong_type_seed(&seed)?;
    let auth = build_auth(&seed, &backend_url)?;
    auth.accept_terms_and_conditions(TermsAndConditions::Lipa, version, fingerprint)
        .map_runtime_error_to(RuntimeErrorCode::AuthServiceUnavailable)
}

/// Try to parse the provided string as a lightning address, return [`ParseError`]
/// precisely indicating why parsing failed.
///
/// Requires network: **no**
pub fn parse_lightning_address(address: &str) -> std::result::Result<(), ParseError> {
    parser::parse_lightning_address(address).map_err(ParseError::from)
}

/// Allows checking if certain terms and conditions have been accepted by the user.
///
/// Parameters:
/// * `environment` - Which environment should be used.
/// * `seed` - The seed of the wallet.
/// * `terms_and_conditions` - [`TermsAndConditions`] for which the status should be requested.
///
/// Returns the status of the requested [`TermsAndConditions`].
///
/// Requires network: **yes**
pub fn get_terms_and_conditions_status(
    backend_url: String,
    seed: Vec<u8>,
    terms_and_conditions: TermsAndConditions,
) -> Result<TermsAndConditionsStatus> {
    enable_backtrace();
    let seed = sanitize_input::strong_type_seed(&seed)?;
    let auth = build_auth(&seed, &backend_url)?;
    auth.get_terms_and_conditions_status(terms_and_conditions)
        .map_runtime_error_to(RuntimeErrorCode::AuthServiceUnavailable)
}

fn get_payment_uuid(payment_hash: String) -> Result<String> {
    let hash = hex::decode(payment_hash).map_to_invalid_input("Invalid payment hash encoding")?;

    Ok(Uuid::new_v5(&Uuid::NAMESPACE_OID, &hash)
        .hyphenated()
        .to_string())
}

pub(crate) fn enable_backtrace() {
    env::set_var("RUST_BACKTRACE", "1");
}

fn get_payment_max_routing_fee_mode(
    config: &MaxRoutingFeeConfig,
    amount_sat: u64,
    exchange_rate: &Option<ExchangeRate>,
) -> MaxRoutingFeeMode {
    let max_fee_permyriad = Permyriad(config.max_routing_fee_permyriad);
    let relative_fee = max_fee_permyriad.of(&amount_sat.as_sats());
    if relative_fee.msats < config.max_routing_fee_exempt_fee_sats.as_sats().msats {
        MaxRoutingFeeMode::Absolute {
            max_fee_amount: config
                .max_routing_fee_exempt_fee_sats
                .as_sats()
                .to_amount_up(exchange_rate),
        }
    } else {
        MaxRoutingFeeMode::Relative {
            max_fee_permyriad: max_fee_permyriad.0,
        }
    }
}

fn filter_out_recently_claimed_topups(
    topups: Vec<TopupInfo>,
    latest_activities: Vec<Activity>,
) -> Vec<TopupInfo> {
    let pocket_id = |a: Activity| match a {
        Activity::OfferClaim {
            incoming_payment_info: _,
            offer_kind: OfferKind::Pocket { id, .. },
        } => Some(id),
        _ => None,
    };
    let latest_succeeded_payment_offer_ids: HashSet<String> = latest_activities
        .into_iter()
        .filter(|a| a.get_payment_info().map(|p| p.payment_state) == Some(PaymentState::Succeeded))
        .filter_map(pocket_id)
        .collect();
    topups
        .into_iter()
        .filter(|o| !latest_succeeded_payment_offer_ids.contains(&o.id))
        .collect()
}

fn fill_payout_fee(
    offer: OfferKind,
    requested_amount: Msats,
    rate: &Option<ExchangeRate>,
) -> OfferKind {
    match offer {
        OfferKind::Pocket {
            id,
            exchange_rate,
            topup_value_minor_units,
            topup_value_sats,
            exchange_fee_minor_units,
            exchange_fee_rate_permyriad,
            lightning_payout_fee: _,
            error,
        } => {
            let lightning_payout_fee = topup_value_sats.map(|v| {
                (v.as_sats().msats - requested_amount.msats)
                    .as_msats()
                    .to_amount_up(rate)
            });

            OfferKind::Pocket {
                id,
                exchange_rate,
                topup_value_minor_units,
                topup_value_sats,
                exchange_fee_minor_units,
                exchange_fee_rate_permyriad,
                lightning_payout_fee,
                error,
            }
        }
    }
}

// TODO provide corrupted acticity information partially instead of hiding it
fn filter_out_and_log_corrupted_activities(r: Result<Activity>) -> Option<Activity> {
    if r.is_ok() {
        r.ok()
    } else {
        error!(
            "Corrupted activity data, ignoring activity: {}",
            r.expect_err("Expected error, received ok")
        );
        None
    }
}

// TODO provide corrupted payment information partially instead of hiding it
fn filter_out_and_log_corrupted_payments(
    r: Result<IncomingPaymentInfo>,
) -> Option<IncomingPaymentInfo> {
    if r.is_ok() {
        r.ok()
    } else {
        error!(
            "Corrupted payment data, ignoring payment: {}",
            r.expect_err("Expected error, received ok")
        );
        None
    }
}

pub(crate) fn register_webhook_url(
    rt: &AsyncRuntime,
    sdk: &BreezServices,
    auth: &Auth,
    config: &Config,
) -> Result<()> {
    let id = auth.get_wallet_pubkey_id().map_to_runtime_error(
        RuntimeErrorCode::AuthServiceUnavailable,
        "Failed to authenticate in order to get wallet pubkey id",
    )?;
    let encrypted_id = deterministic_encrypt(
        id.as_bytes(),
        &<[u8; 32]>::from_hex(
            &config
                .remote_services_config
                .notification_webhook_secret_hex,
        )
        .map_to_invalid_input("Invalid notification_webhook_secret_hex")?,
    )
    .map_to_permanent_failure("Failed to encrypt wallet pubkey id")?;
    let encrypted_id = hex::encode(encrypted_id);
    let webhook_url = config
        .remote_services_config
        .notification_webhook_base_url
        .replacen("{id}", &encrypted_id, 1);
    rt.handle()
        .block_on(sdk.register_webhook(webhook_url.clone()))
        .map_to_runtime_error(
            RuntimeErrorCode::NodeUnavailable,
            "Failed to register notification webhook",
        )?;
    debug!("Successfully registered notification webhook with Breez SDK. URL: {webhook_url}");
    Ok(())
}

fn with_status(status: EnableStatus) -> impl Fn((String, EnableStatus)) -> Option<String> {
    move |(v, s)| if s == status { Some(v) } else { None }
}

include!(concat!(env!("OUT_DIR"), "/lipalightninglib.uniffi.rs"));

#[cfg(test)]
mod tests {
    use super::*;
    use crate::amount::Sats;
    use crow::TopupStatus;
    use perro::Error;

    const PAYMENT_HASH: &str = "0b78877a596f18d5f6effde3dda1df25a5cf20439ff1ac91478d7e518211040f";
    const PAYMENT_UUID: &str = "c6e597bd-0a98-5b46-8e74-f6098f5d16a3";

    #[test]
    fn test_payment_uuid() {
        let payment_uuid = get_payment_uuid(PAYMENT_HASH.to_string());

        assert_eq!(payment_uuid, Ok(PAYMENT_UUID.to_string()));
    }

    #[test]
    fn test_payment_uuid_invalid_input() {
        let invalid_hash_encoding = get_payment_uuid("INVALID_HEX_STRING".to_string());

        assert!(matches!(
            invalid_hash_encoding,
            Err(Error::InvalidInput { .. })
        ));

        assert_eq!(
            &invalid_hash_encoding.unwrap_err().to_string()[0..43],
            "InvalidInput: Invalid payment hash encoding"
        );
    }

    const MAX_FEE_PERMYRIAD: Permyriad = Permyriad(150);
    const EXEMPT_FEE: Sats = Sats::new(21);

    #[test]
    fn test_get_payment_max_routing_fee_mode_absolute() {
        let max_routing_mode = get_payment_max_routing_fee_mode(
            &MaxRoutingFeeConfig {
                max_routing_fee_permyriad: MAX_FEE_PERMYRIAD.0,
                max_routing_fee_exempt_fee_sats: EXEMPT_FEE.sats,
            },
            EXEMPT_FEE.msats / ((MAX_FEE_PERMYRIAD.0 as u64) / 10) - 1,
            &None,
        );

        match max_routing_mode {
            MaxRoutingFeeMode::Absolute { max_fee_amount } => {
                assert_eq!(max_fee_amount.sats, EXEMPT_FEE.sats);
            }
            _ => {
                panic!("Unexpected variant");
            }
        }
    }

    #[test]
    fn test_get_payment_max_routing_fee_mode_relative() {
        let max_routing_mode = get_payment_max_routing_fee_mode(
            &MaxRoutingFeeConfig {
                max_routing_fee_permyriad: MAX_FEE_PERMYRIAD.0,
                max_routing_fee_exempt_fee_sats: EXEMPT_FEE.sats,
            },
            EXEMPT_FEE.msats / ((MAX_FEE_PERMYRIAD.0 as u64) / 10),
            &None,
        );

        match max_routing_mode {
            MaxRoutingFeeMode::Relative { max_fee_permyriad } => {
                assert_eq!(max_fee_permyriad, MAX_FEE_PERMYRIAD.0);
            }
            _ => {
                panic!("Unexpected variant");
            }
        }
    }

    #[test]
    fn test_filter_out_recently_claimed_topups() {
        let topups = vec![
            TopupInfo {
                id: "123".to_string(),
                status: TopupStatus::READY,
                amount_sat: 0,
                topup_value_minor_units: 0,
                exchange_fee_rate_permyriad: 0,
                exchange_fee_minor_units: 0,
                exchange_rate: graphql::ExchangeRate {
                    currency_code: "eur".to_string(),
                    sats_per_unit: 0,
                    updated_at: SystemTime::now(),
                },
                expires_at: None,
                lnurlw: None,
                error: None,
            },
            TopupInfo {
                id: "234".to_string(),
                status: TopupStatus::READY,
                amount_sat: 0,
                topup_value_minor_units: 0,
                exchange_fee_rate_permyriad: 0,
                exchange_fee_minor_units: 0,
                exchange_rate: graphql::ExchangeRate {
                    currency_code: "eur".to_string(),
                    sats_per_unit: 0,
                    updated_at: SystemTime::now(),
                },
                expires_at: None,
                lnurlw: None,
                error: None,
            },
        ];

        let mut payment_info = PaymentInfo {
            payment_state: PaymentState::Succeeded,
            hash: "hash".to_string(),
            amount: Amount::default(),
            invoice_details: InvoiceDetails {
                invoice: "bca".to_string(),
                amount: None,
                description: "".to_string(),
                payment_hash: "".to_string(),
                payee_pub_key: "".to_string(),
                creation_timestamp: SystemTime::now(),
                expiry_interval: Default::default(),
                expiry_timestamp: SystemTime::now(),
            },
            created_at: SystemTime::now().with_timezone(TzConfig::default()),
            description: "".to_string(),
            preimage: None,
            personal_note: None,
        };

        let incoming_payment = Activity::IncomingPayment {
            incoming_payment_info: IncomingPaymentInfo {
                payment_info: payment_info.clone(),
                requested_amount: Amount::default(),
                lsp_fees: Amount::default(),
                received_on: None,
                received_lnurl_comment: None,
            },
        };

        payment_info.hash = "hash2".to_string();
        let topup = Activity::OfferClaim {
            incoming_payment_info: IncomingPaymentInfo {
                payment_info: payment_info.clone(),
                requested_amount: Amount::default(),
                lsp_fees: Amount::default(),
                received_on: None,
                received_lnurl_comment: None,
            },
            offer_kind: OfferKind::Pocket {
                id: "123".to_string(),
                exchange_rate: ExchangeRate {
                    currency_code: "".to_string(),
                    rate: 0,
                    updated_at: SystemTime::now(),
                },
                topup_value_minor_units: 0,
                topup_value_sats: Some(0),
                exchange_fee_minor_units: 0,
                exchange_fee_rate_permyriad: 0,
                lightning_payout_fee: None,
                error: None,
            },
        };

        payment_info.hash = "hash3".to_string();
        payment_info.payment_state = PaymentState::Failed;
        let failed_topup = Activity::OfferClaim {
            incoming_payment_info: IncomingPaymentInfo {
                payment_info,
                requested_amount: Amount::default(),
                lsp_fees: Amount::default(),
                received_on: None,
                received_lnurl_comment: None,
            },
            offer_kind: OfferKind::Pocket {
                id: "234".to_string(),
                exchange_rate: ExchangeRate {
                    currency_code: "".to_string(),
                    rate: 0,
                    updated_at: SystemTime::now(),
                },
                topup_value_minor_units: 0,
                topup_value_sats: Some(0),
                exchange_fee_minor_units: 0,
                exchange_fee_rate_permyriad: 0,
                lightning_payout_fee: None,
                error: None,
            },
        };
        let latest_payments = vec![incoming_payment, topup, failed_topup];

        let filtered_topups = filter_out_recently_claimed_topups(topups, latest_payments);

        assert_eq!(filtered_topups.len(), 1);
        assert_eq!(filtered_topups.first().unwrap().id, "234");
    }
}