ldk-node 0.7.0

A ready-to-go node implementation built using LDK.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

mod common;

use std::collections::HashSet;
use std::str::FromStr;
use std::sync::Arc;

use bitcoin::address::NetworkUnchecked;
use bitcoin::hashes::sha256::Hash as Sha256Hash;
use bitcoin::hashes::Hash;
use bitcoin::{Address, Amount, ScriptBuf};
use common::logging::{init_log_logger, validate_log_entry, MultiNodeLogger, TestLogWriter};
use common::{
	bump_fee_and_broadcast, distribute_funds_unconfirmed, do_channel_full_cycle,
	expect_channel_pending_event, expect_channel_ready_event, expect_event,
	expect_payment_claimable_event, expect_payment_received_event, expect_payment_successful_event,
	expect_splice_pending_event, generate_blocks_and_wait, open_channel, open_channel_push_amt,
	premine_and_distribute_funds, premine_blocks, prepare_rbf, random_config,
	random_listening_addresses, setup_bitcoind_and_electrsd, setup_builder, setup_node,
	setup_node_for_async_payments, setup_two_nodes, wait_for_tx, TestChainSource, TestSyncStore,
};
use ldk_node::config::{AsyncPaymentsRole, EsploraSyncConfig};
use ldk_node::liquidity::LSPS2ServiceConfig;
use ldk_node::payment::{
	ConfirmationStatus, PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus,
	QrPaymentResult,
};
use ldk_node::{Builder, DynStore, Event, NodeError};
use lightning::ln::channelmanager::PaymentId;
use lightning::routing::gossip::{NodeAlias, NodeId};
use lightning::routing::router::RouteParametersConfig;
use lightning_invoice::{Bolt11InvoiceDescription, Description};
use lightning_types::payment::{PaymentHash, PaymentPreimage};
use log::LevelFilter;

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn channel_full_cycle() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);
	do_channel_full_cycle(node_a, node_b, &bitcoind.client, &electrsd.client, false, true, false)
		.await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn channel_full_cycle_electrum() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Electrum(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);
	do_channel_full_cycle(node_a, node_b, &bitcoind.client, &electrsd.client, false, true, false)
		.await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn channel_full_cycle_bitcoind_rpc_sync() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::BitcoindRpcSync(&bitcoind);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);
	do_channel_full_cycle(node_a, node_b, &bitcoind.client, &electrsd.client, false, true, false)
		.await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn channel_full_cycle_bitcoind_rest_sync() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::BitcoindRestSync(&bitcoind);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);
	do_channel_full_cycle(node_a, node_b, &bitcoind.client, &electrsd.client, false, true, false)
		.await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn channel_full_cycle_force_close() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);
	do_channel_full_cycle(node_a, node_b, &bitcoind.client, &electrsd.client, false, true, true)
		.await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn channel_full_cycle_force_close_trusted_no_reserve() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, true);
	do_channel_full_cycle(node_a, node_b, &bitcoind.client, &electrsd.client, false, true, true)
		.await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn channel_full_cycle_0conf() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, true, true, false);
	do_channel_full_cycle(node_a, node_b, &bitcoind.client, &electrsd.client, true, true, false)
		.await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn channel_full_cycle_legacy_staticremotekey() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);
	do_channel_full_cycle(node_a, node_b, &bitcoind.client, &electrsd.client, false, false, false)
		.await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn channel_open_fails_when_funds_insufficient() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);

	let addr_a = node_a.onchain_payment().new_address().unwrap();
	let addr_b = node_b.onchain_payment().new_address().unwrap();

	let premine_amount_sat = 100_000;

	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![addr_a, addr_b],
		Amount::from_sat(premine_amount_sat),
	)
	.await;
	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();
	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, premine_amount_sat);
	assert_eq!(node_b.list_balances().spendable_onchain_balance_sats, premine_amount_sat);

	println!("\nA -- open_channel -> B");
	assert_eq!(
		Err(NodeError::InsufficientFunds),
		node_a.open_channel(
			node_b.node_id(),
			node_b.listening_addresses().unwrap().first().unwrap().clone(),
			120000,
			None,
			None,
		)
	);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn multi_hop_sending() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());

	// Setup and fund 5 nodes
	let mut nodes = Vec::new();
	for _ in 0..5 {
		let config = random_config(true);
		let sync_config = EsploraSyncConfig { background_sync_config: None };
		setup_builder!(builder, config.node_config);
		builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
		let node = builder.build().unwrap();
		node.start().unwrap();
		nodes.push(node);
	}

	let addresses = nodes.iter().map(|n| n.onchain_payment().new_address().unwrap()).collect();
	let premine_amount_sat = 5_000_000;
	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		addresses,
		Amount::from_sat(premine_amount_sat),
	)
	.await;

	for n in &nodes {
		n.sync_wallets().unwrap();
		assert_eq!(n.list_balances().spendable_onchain_balance_sats, premine_amount_sat);
		assert_eq!(n.next_event(), None);
	}

	// Setup channel topology:
	//                    (1M:0)- N2 -(1M:0)
	//                   /                  \
	//  N0 -(100k:0)-> N1                    N4
	//                   \                  /
	//                    (1M:0)- N3 -(1M:0)

	open_channel(&nodes[0], &nodes[1], 100_000, true, &electrsd).await;
	open_channel(&nodes[1], &nodes[2], 1_000_000, true, &electrsd).await;
	// We need to sync wallets in-between back-to-back channel opens from the same node so BDK
	// wallet picks up on the broadcast funding tx and doesn't double-spend itself.
	//
	// TODO: Remove once fixed in BDK.
	nodes[1].sync_wallets().unwrap();
	open_channel(&nodes[1], &nodes[3], 1_000_000, true, &electrsd).await;
	open_channel(&nodes[2], &nodes[4], 1_000_000, true, &electrsd).await;
	open_channel(&nodes[3], &nodes[4], 1_000_000, true, &electrsd).await;

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	for n in &nodes {
		n.sync_wallets().unwrap();
	}

	expect_event!(nodes[0], ChannelReady);
	expect_event!(nodes[1], ChannelReady);
	expect_event!(nodes[1], ChannelReady);
	expect_event!(nodes[1], ChannelReady);
	expect_event!(nodes[2], ChannelReady);
	expect_event!(nodes[2], ChannelReady);
	expect_event!(nodes[3], ChannelReady);
	expect_event!(nodes[3], ChannelReady);
	expect_event!(nodes[4], ChannelReady);
	expect_event!(nodes[4], ChannelReady);

	// Sleep a bit for gossip to propagate.
	tokio::time::sleep(std::time::Duration::from_secs(1)).await;

	let route_params = RouteParametersConfig {
		max_total_routing_fee_msat: Some(75_000),
		max_total_cltv_expiry_delta: 1000,
		max_path_count: 10,
		max_channel_saturation_power_of_half: 2,
	};

	let invoice_description =
		Bolt11InvoiceDescription::Direct(Description::new(String::from("asdf")).unwrap());
	let invoice = nodes[4]
		.bolt11_payment()
		.receive(2_500_000, &invoice_description.clone().into(), 9217)
		.unwrap();
	nodes[0].bolt11_payment().send(&invoice, Some(route_params)).unwrap();

	expect_event!(nodes[1], PaymentForwarded);

	// We expect that the payment goes through N2 or N3, so we check both for the PaymentForwarded event.
	let node_2_fwd_event = matches!(nodes[2].next_event(), Some(Event::PaymentForwarded { .. }));
	let node_3_fwd_event = matches!(nodes[3].next_event(), Some(Event::PaymentForwarded { .. }));
	assert!(node_2_fwd_event || node_3_fwd_event);

	let payment_id = expect_payment_received_event!(&nodes[4], 2_500_000);
	let fee_paid_msat = Some(2000);
	expect_payment_successful_event!(nodes[0], payment_id, Some(fee_paid_msat));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn start_stop_reinit() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let config = random_config(true);

	let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());

	let test_sync_store: Arc<DynStore> =
		Arc::new(TestSyncStore::new(config.node_config.storage_dir_path.clone().into()));

	let sync_config = EsploraSyncConfig { background_sync_config: None };
	setup_builder!(builder, config.node_config);
	builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));

	let node = builder.build_with_store(Arc::clone(&test_sync_store)).unwrap();
	node.start().unwrap();

	let expected_node_id = node.node_id();
	assert_eq!(node.start(), Err(NodeError::AlreadyRunning));

	let funding_address = node.onchain_payment().new_address().unwrap();

	assert_eq!(node.list_balances().total_onchain_balance_sats, 0);

	let expected_amount = Amount::from_sat(100000);
	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![funding_address],
		expected_amount,
	)
	.await;

	node.sync_wallets().unwrap();
	assert_eq!(node.list_balances().spendable_onchain_balance_sats, expected_amount.to_sat());

	let log_file = format!("{}/ldk_node.log", config.node_config.clone().storage_dir_path);
	assert!(std::path::Path::new(&log_file).exists());

	node.stop().unwrap();
	assert_eq!(node.stop(), Err(NodeError::NotRunning));

	node.start().unwrap();
	assert_eq!(node.start(), Err(NodeError::AlreadyRunning));

	node.stop().unwrap();
	assert_eq!(node.stop(), Err(NodeError::NotRunning));
	drop(node);

	setup_builder!(builder, config.node_config);
	builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));

	let reinitialized_node = builder.build_with_store(Arc::clone(&test_sync_store)).unwrap();
	reinitialized_node.start().unwrap();
	assert_eq!(reinitialized_node.node_id(), expected_node_id);

	assert_eq!(
		reinitialized_node.list_balances().spendable_onchain_balance_sats,
		expected_amount.to_sat()
	);

	reinitialized_node.sync_wallets().unwrap();
	assert_eq!(
		reinitialized_node.list_balances().spendable_onchain_balance_sats,
		expected_amount.to_sat()
	);

	reinitialized_node.stop().unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn onchain_send_receive() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);

	let addr_a = node_a.onchain_payment().new_address().unwrap();
	let addr_b = node_b.onchain_payment().new_address().unwrap();
	// This is a Bitcoin Testnet address. Sending funds to this address from the Regtest network will fail
	let static_address = "tb1q0d40e5rta4fty63z64gztf8c3v20cvet6v2jdh";
	let unchecked_address = Address::<NetworkUnchecked>::from_str(static_address).unwrap();
	let addr_c = unchecked_address.assume_checked();

	let premine_amount_sat = 1_100_000;
	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![addr_a.clone(), addr_b.clone()],
		Amount::from_sat(premine_amount_sat),
	)
	.await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();
	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, premine_amount_sat);
	assert_eq!(node_b.list_balances().spendable_onchain_balance_sats, premine_amount_sat);

	let node_a_payments = node_a.list_payments();
	let node_b_payments = node_b.list_payments();
	for payments in [&node_a_payments, &node_b_payments] {
		assert_eq!(payments.len(), 1)
	}
	for p in [node_a_payments.first().unwrap(), node_b_payments.first().unwrap()] {
		assert_eq!(p.amount_msat, Some(premine_amount_sat * 1000));
		assert_eq!(p.direction, PaymentDirection::Inbound);
		// We got only 1-conf here, so we're only pending for now.
		assert_eq!(p.status, PaymentStatus::Pending);
		match p.kind {
			PaymentKind::Onchain { status, .. } => {
				assert!(matches!(status, ConfirmationStatus::Confirmed { .. }));
			},
			_ => panic!("Unexpected payment kind"),
		}
	}

	let channel_amount_sat = 1_000_000;
	let reserve_amount_sat = 25_000;
	open_channel(&node_b, &node_a, channel_amount_sat, true, &electrsd).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();
	expect_channel_ready_event!(node_a, node_b.node_id());
	expect_channel_ready_event!(node_b, node_a.node_id());

	let node_a_payments =
		node_a.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Onchain { .. }));
	assert_eq!(node_a_payments.len(), 1);
	let node_b_payments =
		node_b.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Onchain { .. }));
	assert_eq!(node_b_payments.len(), 2);

	let onchain_fee_buffer_sat = 1000;
	let expected_node_a_balance = premine_amount_sat - reserve_amount_sat;
	let expected_node_b_balance_lower =
		premine_amount_sat - channel_amount_sat - reserve_amount_sat - onchain_fee_buffer_sat;
	let expected_node_b_balance_upper =
		premine_amount_sat - channel_amount_sat - reserve_amount_sat;
	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, expected_node_a_balance);
	assert!(node_b.list_balances().spendable_onchain_balance_sats > expected_node_b_balance_lower);
	assert!(node_b.list_balances().spendable_onchain_balance_sats < expected_node_b_balance_upper);

	assert_eq!(
		Err(NodeError::InsufficientFunds),
		node_a.onchain_payment().send_to_address(&addr_b, expected_node_a_balance + 1, None)
	);

	assert_eq!(
		Err(NodeError::InvalidAddress),
		node_a.onchain_payment().send_to_address(&addr_c, expected_node_a_balance + 1, None)
	);

	assert_eq!(
		Err(NodeError::InvalidAddress),
		node_a.onchain_payment().send_all_to_address(&addr_c, true, None)
	);

	let amount_to_send_sats = 54321;
	let txid =
		node_b.onchain_payment().send_to_address(&addr_a, amount_to_send_sats, None).unwrap();
	wait_for_tx(&electrsd.client, txid).await;
	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	let payment_id = PaymentId(txid.to_byte_array());
	let payment_a = node_a.payment(&payment_id).unwrap();
	assert_eq!(payment_a.status, PaymentStatus::Pending);
	match payment_a.kind {
		PaymentKind::Onchain { status, .. } => {
			assert!(matches!(status, ConfirmationStatus::Unconfirmed));
		},
		_ => panic!("Unexpected payment kind"),
	}
	assert!(payment_a.fee_paid_msat > Some(0));
	let payment_b = node_b.payment(&payment_id).unwrap();
	assert_eq!(payment_b.status, PaymentStatus::Pending);
	match payment_a.kind {
		PaymentKind::Onchain { status, .. } => {
			assert!(matches!(status, ConfirmationStatus::Unconfirmed));
		},
		_ => panic!("Unexpected payment kind"),
	}
	assert!(payment_b.fee_paid_msat > Some(0));
	assert_eq!(payment_a.amount_msat, Some(amount_to_send_sats * 1000));
	assert_eq!(payment_a.amount_msat, payment_b.amount_msat);
	assert_eq!(payment_a.fee_paid_msat, payment_b.fee_paid_msat);

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	let expected_node_a_balance = expected_node_a_balance + amount_to_send_sats;
	let expected_node_b_balance_lower = expected_node_b_balance_lower - amount_to_send_sats;
	let expected_node_b_balance_upper = expected_node_b_balance_upper - amount_to_send_sats;
	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, expected_node_a_balance);
	assert!(node_b.list_balances().spendable_onchain_balance_sats > expected_node_b_balance_lower);
	assert!(node_b.list_balances().spendable_onchain_balance_sats < expected_node_b_balance_upper);

	let node_a_payments =
		node_a.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Onchain { .. }));
	assert_eq!(node_a_payments.len(), 2);
	let node_b_payments =
		node_b.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Onchain { .. }));
	assert_eq!(node_b_payments.len(), 3);

	let payment_a = node_a.payment(&payment_id).unwrap();
	match payment_a.kind {
		PaymentKind::Onchain { txid: _txid, status } => {
			assert_eq!(_txid, txid);
			assert!(matches!(status, ConfirmationStatus::Confirmed { .. }));
		},
		_ => panic!("Unexpected payment kind"),
	}

	let payment_b = node_a.payment(&payment_id).unwrap();
	match payment_b.kind {
		PaymentKind::Onchain { txid: _txid, status } => {
			assert_eq!(_txid, txid);
			assert!(matches!(status, ConfirmationStatus::Confirmed { .. }));
		},
		_ => panic!("Unexpected payment kind"),
	}

	let addr_b = node_b.onchain_payment().new_address().unwrap();
	let txid = node_a.onchain_payment().send_all_to_address(&addr_b, true, None).unwrap();
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	wait_for_tx(&electrsd.client, txid).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	let expected_node_b_balance_lower = expected_node_b_balance_lower + expected_node_a_balance;
	let expected_node_b_balance_upper = expected_node_b_balance_upper + expected_node_a_balance;
	let expected_node_a_balance = 0;
	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, expected_node_a_balance);
	assert_eq!(node_a.list_balances().total_onchain_balance_sats, reserve_amount_sat);
	assert!(node_b.list_balances().spendable_onchain_balance_sats > expected_node_b_balance_lower);
	assert!(node_b.list_balances().spendable_onchain_balance_sats < expected_node_b_balance_upper);

	let node_a_payments =
		node_a.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Onchain { .. }));
	assert_eq!(node_a_payments.len(), 3);
	let node_b_payments =
		node_b.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Onchain { .. }));
	assert_eq!(node_b_payments.len(), 4);

	let addr_b = node_b.onchain_payment().new_address().unwrap();
	let txid = node_a.onchain_payment().send_all_to_address(&addr_b, false, None).unwrap();
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	wait_for_tx(&electrsd.client, txid).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	let expected_node_b_balance_lower = expected_node_b_balance_lower + reserve_amount_sat;
	let expected_node_b_balance_upper = expected_node_b_balance_upper + reserve_amount_sat;
	let expected_node_a_balance = 0;

	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, expected_node_a_balance);
	assert_eq!(node_a.list_balances().total_onchain_balance_sats, expected_node_a_balance);
	assert!(node_b.list_balances().spendable_onchain_balance_sats > expected_node_b_balance_lower);
	assert!(node_b.list_balances().spendable_onchain_balance_sats < expected_node_b_balance_upper);

	let node_a_payments =
		node_a.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Onchain { .. }));
	assert_eq!(node_a_payments.len(), 4);
	let node_b_payments =
		node_b.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Onchain { .. }));
	assert_eq!(node_b_payments.len(), 5);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn onchain_send_all_retains_reserve() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);

	// Setup nodes
	let addr_a = node_a.onchain_payment().new_address().unwrap();
	let addr_b = node_b.onchain_payment().new_address().unwrap();

	let premine_amount_sat = 1_000_000;
	let reserve_amount_sat = 25_000;
	let onchain_fee_buffer_sat = 1000;
	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![addr_a.clone(), addr_b.clone()],
		Amount::from_sat(premine_amount_sat),
	)
	.await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();
	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, premine_amount_sat);
	assert_eq!(node_b.list_balances().spendable_onchain_balance_sats, premine_amount_sat);

	// Send all over, with 0 reserve as we don't have any channels open.
	let txid = node_a.onchain_payment().send_all_to_address(&addr_b, true, None).unwrap();

	wait_for_tx(&electrsd.client, txid).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();
	// Check node a sent all and node b received it
	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, 0);
	assert!(((premine_amount_sat * 2 - onchain_fee_buffer_sat)..=(premine_amount_sat * 2))
		.contains(&node_b.list_balances().spendable_onchain_balance_sats));

	// Refill to make sure we have enough reserve for the channel open.
	let txid = bitcoind
		.client
		.send_to_address(&addr_a, Amount::from_sat(reserve_amount_sat))
		.unwrap()
		.0
		.parse()
		.unwrap();
	wait_for_tx(&electrsd.client, txid).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();
	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, reserve_amount_sat);

	// Open a channel.
	open_channel(&node_b, &node_a, premine_amount_sat, false, &electrsd).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();
	expect_channel_ready_event!(node_a, node_b.node_id());
	expect_channel_ready_event!(node_b, node_a.node_id());

	// Check node a sent all and node b received it
	assert_eq!(node_a.list_balances().spendable_onchain_balance_sats, 0);
	assert!(((premine_amount_sat - reserve_amount_sat - onchain_fee_buffer_sat)
		..=premine_amount_sat)
		.contains(&node_b.list_balances().spendable_onchain_balance_sats));

	// Send all over again, this time ensuring the reserve is accounted for
	let txid = node_b.onchain_payment().send_all_to_address(&addr_a, true, None).unwrap();

	wait_for_tx(&electrsd.client, txid).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	// Check node b sent all and node a received it
	assert_eq!(node_b.list_balances().total_onchain_balance_sats, reserve_amount_sat);
	assert_eq!(node_b.list_balances().spendable_onchain_balance_sats, 0);
	assert!(((premine_amount_sat - reserve_amount_sat - onchain_fee_buffer_sat)
		..=premine_amount_sat)
		.contains(&node_a.list_balances().spendable_onchain_balance_sats));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn onchain_wallet_recovery() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();

	let chain_source = TestChainSource::Esplora(&electrsd);

	let seed_bytes = vec![42u8; 64];

	let original_config = random_config(true);
	let original_node = setup_node(&chain_source, original_config, Some(seed_bytes.clone()));

	let premine_amount_sat = 100_000;

	let addr_1 = original_node.onchain_payment().new_address().unwrap();

	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![addr_1],
		Amount::from_sat(premine_amount_sat),
	)
	.await;
	original_node.sync_wallets().unwrap();
	assert_eq!(original_node.list_balances().spendable_onchain_balance_sats, premine_amount_sat);

	let addr_2 = original_node.onchain_payment().new_address().unwrap();

	let txid = bitcoind
		.client
		.send_to_address(&addr_2, Amount::from_sat(premine_amount_sat))
		.unwrap()
		.0
		.parse()
		.unwrap();
	wait_for_tx(&electrsd.client, txid).await;

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await;

	original_node.sync_wallets().unwrap();
	assert_eq!(
		original_node.list_balances().spendable_onchain_balance_sats,
		premine_amount_sat * 2
	);

	original_node.stop().unwrap();
	drop(original_node);

	// Now we start from scratch, only the seed remains the same.
	let recovered_config = random_config(true);
	let recovered_node = setup_node(&chain_source, recovered_config, Some(seed_bytes));

	recovered_node.sync_wallets().unwrap();
	assert_eq!(
		recovered_node.list_balances().spendable_onchain_balance_sats,
		premine_amount_sat * 2
	);

	// Check we sync even when skipping some addresses.
	let _addr_3 = recovered_node.onchain_payment().new_address().unwrap();
	let _addr_4 = recovered_node.onchain_payment().new_address().unwrap();
	let _addr_5 = recovered_node.onchain_payment().new_address().unwrap();
	let addr_6 = recovered_node.onchain_payment().new_address().unwrap();

	let txid = bitcoind
		.client
		.send_to_address(&addr_6, Amount::from_sat(premine_amount_sat))
		.unwrap()
		.0
		.parse()
		.unwrap();
	wait_for_tx(&electrsd.client, txid).await;

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await;

	recovered_node.sync_wallets().unwrap();
	assert_eq!(
		recovered_node.list_balances().spendable_onchain_balance_sats,
		premine_amount_sat * 3
	);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_rbf_via_mempool() {
	run_rbf_test(false).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_rbf_via_direct_block_insertion() {
	run_rbf_test(true).await;
}

// `is_insert_block`:
// - `true`: transaction is mined immediately (no mempool), testing confirmed-Tx handling.
// - `false`: transaction stays in mempool until confirmation, testing unconfirmed-Tx handling.
async fn run_rbf_test(is_insert_block: bool) {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source_bitcoind = TestChainSource::BitcoindRpcSync(&bitcoind);
	let chain_source_electrsd = TestChainSource::Electrum(&electrsd);
	let chain_source_esplora = TestChainSource::Esplora(&electrsd);

	macro_rules! config_node {
		($chain_source:expr, $anchor_channels:expr) => {{
			let config_a = random_config($anchor_channels);
			let node = setup_node(&$chain_source, config_a, None);
			node
		}};
	}
	let anchor_channels = false;
	let nodes = vec![
		config_node!(chain_source_electrsd, anchor_channels),
		config_node!(chain_source_bitcoind, anchor_channels),
		config_node!(chain_source_esplora, anchor_channels),
	];

	let (bitcoind, electrs) = (&bitcoind.client, &electrsd.client);
	premine_blocks(bitcoind, electrs).await;

	// Helpers declaration before starting the test
	let all_addrs =
		nodes.iter().map(|node| node.onchain_payment().new_address().unwrap()).collect::<Vec<_>>();
	let amount_sat = 2_100_000;
	let mut txid;
	macro_rules! distribute_funds_all_nodes {
		() => {
			txid = distribute_funds_unconfirmed(
				bitcoind,
				electrs,
				all_addrs.clone(),
				Amount::from_sat(amount_sat),
			)
			.await;
		};
	}
	macro_rules! validate_balances {
		($expected_balance_sat:expr, $is_spendable:expr) => {
			let spend_balance = if $is_spendable { $expected_balance_sat } else { 0 };
			for node in &nodes {
				node.sync_wallets().unwrap();
				let balances = node.list_balances();
				assert_eq!(balances.spendable_onchain_balance_sats, spend_balance);
				assert_eq!(balances.total_onchain_balance_sats, $expected_balance_sat);
			}
		};
	}

	let scripts_buf: HashSet<ScriptBuf> =
		all_addrs.iter().map(|addr| addr.script_pubkey()).collect();
	let mut tx;
	let mut fee_output_index;

	// Modify the output to the nodes
	distribute_funds_all_nodes!();
	validate_balances!(amount_sat, false);
	(tx, fee_output_index) = prepare_rbf(electrs, txid, &scripts_buf);
	tx.output.iter_mut().for_each(|output| {
		if scripts_buf.contains(&output.script_pubkey) {
			let new_addr = bitcoind.new_address().unwrap();
			output.script_pubkey = new_addr.script_pubkey();
		}
	});
	bump_fee_and_broadcast(bitcoind, electrs, tx, fee_output_index, is_insert_block).await;
	validate_balances!(0, is_insert_block);

	// Not modifying the output scripts, but still bumping the fee.
	distribute_funds_all_nodes!();
	validate_balances!(amount_sat, false);
	(tx, fee_output_index) = prepare_rbf(electrs, txid, &scripts_buf);
	bump_fee_and_broadcast(bitcoind, electrs, tx, fee_output_index, is_insert_block).await;
	validate_balances!(amount_sat, is_insert_block);

	let mut final_amount_sat = amount_sat * 2;
	let value_sat = 21_000;

	// Increase the value of the nodes' outputs
	distribute_funds_all_nodes!();
	(tx, fee_output_index) = prepare_rbf(electrs, txid, &scripts_buf);
	tx.output.iter_mut().for_each(|output| {
		if scripts_buf.contains(&output.script_pubkey) {
			output.value = Amount::from_sat(output.value.to_sat() + value_sat);
		}
	});
	bump_fee_and_broadcast(bitcoind, electrs, tx, fee_output_index, is_insert_block).await;
	final_amount_sat += value_sat;
	validate_balances!(final_amount_sat, is_insert_block);

	// Decreases the value of the nodes' outputs
	distribute_funds_all_nodes!();
	final_amount_sat += amount_sat;
	(tx, fee_output_index) = prepare_rbf(electrs, txid, &scripts_buf);
	tx.output.iter_mut().for_each(|output| {
		if scripts_buf.contains(&output.script_pubkey) {
			output.value = Amount::from_sat(output.value.to_sat() - value_sat);
		}
	});
	bump_fee_and_broadcast(bitcoind, electrs, tx, fee_output_index, is_insert_block).await;
	final_amount_sat -= value_sat;
	validate_balances!(final_amount_sat, is_insert_block);

	if !is_insert_block {
		generate_blocks_and_wait(bitcoind, electrs, 1).await;
		validate_balances!(final_amount_sat, true);
	}

	// Check if it is possible to send all funds from the node
	let mut txids = Vec::new();
	let addr = bitcoind.new_address().unwrap();
	nodes.iter().for_each(|node| {
		let txid = node.onchain_payment().send_all_to_address(&addr, true, None).unwrap();
		txids.push(txid);
	});
	for txid in txids {
		wait_for_tx(electrs, txid).await;
	}
	generate_blocks_and_wait(bitcoind, electrs, 6).await;
	validate_balances!(0, true);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn sign_verify_msg() {
	let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let config = random_config(true);
	let chain_source = TestChainSource::Esplora(&electrsd);
	let node = setup_node(&chain_source, config, None);

	// Tests arbitrary message signing and later verification
	let msg = "OK computer".as_bytes();
	let sig = node.sign_message(msg);
	let pkey = node.node_id();
	assert!(node.verify_signature(msg, sig.as_str(), &pkey));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn connection_multi_listen() {
	let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);

	let node_id_b = node_b.node_id();

	let node_addrs_b = node_b.listening_addresses().unwrap();
	for node_addr_b in &node_addrs_b {
		node_a.connect(node_id_b, node_addr_b.clone(), false).unwrap();
		node_a.disconnect(node_id_b).unwrap();
	}
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn connection_restart_behavior() {
	do_connection_restart_behavior(true).await;
	do_connection_restart_behavior(false).await;
}

async fn do_connection_restart_behavior(persist: bool) {
	let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);

	let node_id_a = node_a.node_id();
	let node_id_b = node_b.node_id();

	let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();
	node_a.connect(node_id_b, node_addr_b, persist).unwrap();

	let peer_details_a = node_a.list_peers().first().unwrap().clone();
	assert_eq!(peer_details_a.node_id, node_id_b);
	assert_eq!(peer_details_a.is_persisted, persist);
	assert!(peer_details_a.is_connected);

	let peer_details_b = node_b.list_peers().first().unwrap().clone();
	assert_eq!(peer_details_b.node_id, node_id_a);
	assert_eq!(peer_details_b.is_persisted, false);
	assert!(peer_details_a.is_connected);

	// Restart nodes.
	node_a.stop().unwrap();
	node_b.stop().unwrap();
	node_b.start().unwrap();
	node_a.start().unwrap();

	// Sleep a bit to allow for the reconnect to happen.
	tokio::time::sleep(std::time::Duration::from_secs(5)).await;

	if persist {
		let peer_details_a = node_a.list_peers().first().unwrap().clone();
		assert_eq!(peer_details_a.node_id, node_id_b);
		assert_eq!(peer_details_a.is_persisted, persist);
		assert!(peer_details_a.is_connected);

		let peer_details_b = node_b.list_peers().first().unwrap().clone();
		assert_eq!(peer_details_b.node_id, node_id_a);
		assert_eq!(peer_details_b.is_persisted, false);
		assert!(peer_details_a.is_connected);
	} else {
		assert!(node_a.list_peers().is_empty());
		assert!(node_b.list_peers().is_empty());
	}
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn concurrent_connections_succeed() {
	let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);

	let node_a = Arc::new(node_a);
	let node_b = Arc::new(node_b);

	let node_id_b = node_b.node_id();
	let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

	let mut handles = Vec::new();
	for _ in 0..10 {
		let thread_node = Arc::clone(&node_a);
		let thread_addr = node_addr_b.clone();
		let handle = std::thread::spawn(move || {
			thread_node.connect(node_id_b, thread_addr, false).unwrap();
		});
		handles.push(handle);
	}

	for h in handles {
		h.join().unwrap();
	}
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn splice_channel() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);

	let address_a = node_a.onchain_payment().new_address().unwrap();
	let address_b = node_b.onchain_payment().new_address().unwrap();
	let premine_amount_sat = 5_000_000;
	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![address_a, address_b],
		Amount::from_sat(premine_amount_sat),
	)
	.await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	assert_eq!(node_a.list_balances().total_onchain_balance_sats, premine_amount_sat);
	assert_eq!(node_b.list_balances().total_onchain_balance_sats, premine_amount_sat);

	open_channel(&node_a, &node_b, 4_000_000, false, &electrsd).await;

	// Open a channel with Node A contributing the funding
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	let user_channel_id_a = expect_channel_ready_event!(node_a, node_b.node_id());
	let user_channel_id_b = expect_channel_ready_event!(node_b, node_a.node_id());

	let opening_transaction_fee_sat = 156;
	let closing_transaction_fee_sat = 614;
	let anchor_output_sat = 330;

	assert_eq!(
		node_a.list_balances().total_onchain_balance_sats,
		premine_amount_sat - 4_000_000 - opening_transaction_fee_sat
	);
	assert_eq!(
		node_a.list_balances().total_lightning_balance_sats,
		4_000_000 - closing_transaction_fee_sat - anchor_output_sat
	);
	assert_eq!(node_b.list_balances().total_lightning_balance_sats, 0);

	// Test that splicing and payments fail when there are insufficient funds
	let address = node_b.onchain_payment().new_address().unwrap();
	let amount_msat = 400_000_000;

	assert_eq!(
		node_b.splice_in(&user_channel_id_b, node_b.node_id(), 5_000_000),
		Err(NodeError::ChannelSplicingFailed),
	);
	assert_eq!(
		node_b.splice_out(&user_channel_id_b, node_b.node_id(), &address, amount_msat / 1000),
		Err(NodeError::ChannelSplicingFailed),
	);
	assert_eq!(
		node_b.spontaneous_payment().send(amount_msat, node_a.node_id(), None),
		Err(NodeError::PaymentSendingFailed)
	);

	// Splice-in funds for Node B so that it has outbound liquidity to make a payment
	node_b.splice_in(&user_channel_id_b, node_a.node_id(), 4_000_000).unwrap();

	expect_splice_pending_event!(node_a, node_b.node_id());
	expect_splice_pending_event!(node_b, node_a.node_id());

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	expect_channel_ready_event!(node_a, node_b.node_id());
	expect_channel_ready_event!(node_b, node_a.node_id());

	let splice_in_fee_sat = 252;

	assert_eq!(
		node_b.list_balances().total_onchain_balance_sats,
		premine_amount_sat - 4_000_000 - splice_in_fee_sat
	);
	assert_eq!(node_b.list_balances().total_lightning_balance_sats, 4_000_000);

	let payment_id =
		node_b.spontaneous_payment().send(amount_msat, node_a.node_id(), None).unwrap();

	expect_payment_successful_event!(node_b, Some(payment_id), None);
	expect_payment_received_event!(node_a, amount_msat);

	// Mine a block to give time for the HTLC to resolve
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 1).await;

	assert_eq!(
		node_a.list_balances().total_lightning_balance_sats,
		4_000_000 - closing_transaction_fee_sat - anchor_output_sat + amount_msat / 1000
	);
	assert_eq!(node_b.list_balances().total_lightning_balance_sats, 4_000_000 - amount_msat / 1000);

	// Splice-out funds for Node A from the payment sent by Node B
	let address = node_a.onchain_payment().new_address().unwrap();
	node_a.splice_out(&user_channel_id_a, node_b.node_id(), &address, amount_msat / 1000).unwrap();

	expect_splice_pending_event!(node_a, node_b.node_id());
	expect_splice_pending_event!(node_b, node_a.node_id());

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	expect_channel_ready_event!(node_a, node_b.node_id());
	expect_channel_ready_event!(node_b, node_a.node_id());

	let splice_out_fee_sat = 183;

	assert_eq!(
		node_a.list_balances().total_onchain_balance_sats,
		premine_amount_sat - 4_000_000 - opening_transaction_fee_sat + amount_msat / 1000
	);
	assert_eq!(
		node_a.list_balances().total_lightning_balance_sats,
		4_000_000 - closing_transaction_fee_sat - anchor_output_sat - splice_out_fee_sat
	);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn simple_bolt12_send_receive() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);

	let address_a = node_a.onchain_payment().new_address().unwrap();
	let premine_amount_sat = 5_000_000;
	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![address_a],
		Amount::from_sat(premine_amount_sat),
	)
	.await;

	node_a.sync_wallets().unwrap();
	open_channel(&node_a, &node_b, 4_000_000, true, &electrsd).await;

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	expect_channel_ready_event!(node_a, node_b.node_id());
	expect_channel_ready_event!(node_b, node_a.node_id());

	// Sleep until we broadcasted a node announcement.
	while node_b.status().latest_node_announcement_broadcast_timestamp.is_none() {
		tokio::time::sleep(std::time::Duration::from_millis(10)).await;
	}

	// Sleep one more sec to make sure the node announcement propagates.
	tokio::time::sleep(std::time::Duration::from_secs(1)).await;

	let expected_amount_msat = 100_000_000;
	let offer =
		node_b.bolt12_payment().receive(expected_amount_msat, "asdf", None, Some(1)).unwrap();
	let expected_quantity = Some(1);
	let expected_payer_note = Some("Test".to_string());
	let payment_id = node_a
		.bolt12_payment()
		.send(&offer, expected_quantity, expected_payer_note.clone(), None)
		.unwrap();

	expect_payment_successful_event!(node_a, Some(payment_id), None);
	let node_a_payments =
		node_a.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Bolt12Offer { .. }));
	assert_eq!(node_a_payments.len(), 1);
	match node_a_payments.first().unwrap().kind {
		PaymentKind::Bolt12Offer {
			hash,
			preimage,
			secret: _,
			offer_id,
			quantity: ref qty,
			payer_note: ref note,
		} => {
			assert!(hash.is_some());
			assert!(preimage.is_some());
			assert_eq!(offer_id, offer.id());
			assert_eq!(&expected_quantity, qty);
			assert_eq!(expected_payer_note.unwrap(), note.clone().unwrap().0);
			// TODO: We should eventually set and assert the secret sender-side, too, but the BOLT12
			// API currently doesn't allow to do that.
		},
		_ => {
			panic!("Unexpected payment kind");
		},
	}
	assert_eq!(node_a_payments.first().unwrap().amount_msat, Some(expected_amount_msat));

	expect_payment_received_event!(node_b, expected_amount_msat);
	let node_b_payments =
		node_b.list_payments_with_filter(|p| matches!(p.kind, PaymentKind::Bolt12Offer { .. }));
	assert_eq!(node_b_payments.len(), 1);
	match node_b_payments.first().unwrap().kind {
		PaymentKind::Bolt12Offer { hash, preimage, secret, offer_id, .. } => {
			assert!(hash.is_some());
			assert!(preimage.is_some());
			assert!(secret.is_some());
			assert_eq!(offer_id, offer.id());
		},
		_ => {
			panic!("Unexpected payment kind");
		},
	}
	assert_eq!(node_b_payments.first().unwrap().amount_msat, Some(expected_amount_msat));

	// Test send_using_amount
	let offer_amount_msat = 100_000_000;
	let less_than_offer_amount = offer_amount_msat - 10_000;
	let expected_amount_msat = offer_amount_msat + 10_000;
	let offer = node_b.bolt12_payment().receive(offer_amount_msat, "asdf", None, Some(1)).unwrap();
	let expected_quantity = Some(1);
	let expected_payer_note = Some("Test".to_string());
	assert!(node_a
		.bolt12_payment()
		.send_using_amount(&offer, less_than_offer_amount, None, None, None)
		.is_err());
	let payment_id = node_a
		.bolt12_payment()
		.send_using_amount(
			&offer,
			expected_amount_msat,
			expected_quantity,
			expected_payer_note.clone(),
			None,
		)
		.unwrap();

	expect_payment_successful_event!(node_a, Some(payment_id), None);
	let node_a_payments = node_a.list_payments_with_filter(|p| {
		matches!(p.kind, PaymentKind::Bolt12Offer { .. }) && p.id == payment_id
	});
	assert_eq!(node_a_payments.len(), 1);
	let payment_hash = match node_a_payments.first().unwrap().kind {
		PaymentKind::Bolt12Offer {
			hash,
			preimage,
			secret: _,
			offer_id,
			quantity: ref qty,
			payer_note: ref note,
		} => {
			assert!(hash.is_some());
			assert!(preimage.is_some());
			assert_eq!(offer_id, offer.id());
			assert_eq!(&expected_quantity, qty);
			assert_eq!(expected_payer_note.unwrap(), note.clone().unwrap().0);
			// TODO: We should eventually set and assert the secret sender-side, too, but the BOLT12
			// API currently doesn't allow to do that.
			hash.unwrap()
		},
		_ => {
			panic!("Unexpected payment kind");
		},
	};
	assert_eq!(node_a_payments.first().unwrap().amount_msat, Some(expected_amount_msat));

	expect_payment_received_event!(node_b, expected_amount_msat);
	let node_b_payment_id = PaymentId(payment_hash.0);
	let node_b_payments = node_b.list_payments_with_filter(|p| {
		matches!(p.kind, PaymentKind::Bolt12Offer { .. }) && p.id == node_b_payment_id
	});
	assert_eq!(node_b_payments.len(), 1);
	match node_b_payments.first().unwrap().kind {
		PaymentKind::Bolt12Offer { hash, preimage, secret, offer_id, .. } => {
			assert!(hash.is_some());
			assert!(preimage.is_some());
			assert!(secret.is_some());
			assert_eq!(offer_id, offer.id());
		},
		_ => {
			panic!("Unexpected payment kind");
		},
	}
	assert_eq!(node_b_payments.first().unwrap().amount_msat, Some(expected_amount_msat));

	// Now node_b refunds the amount node_a just overpaid.
	let overpaid_amount = expected_amount_msat - offer_amount_msat;
	let expected_quantity = Some(1);
	let expected_payer_note = Some("Test".to_string());
	let refund = node_b
		.bolt12_payment()
		.initiate_refund(
			overpaid_amount,
			3600,
			expected_quantity,
			expected_payer_note.clone(),
			None,
		)
		.unwrap();
	let invoice = node_a.bolt12_payment().request_refund_payment(&refund).unwrap();
	expect_payment_received_event!(node_a, overpaid_amount);

	let node_b_payment_id = node_b
		.list_payments_with_filter(|p| {
			matches!(p.kind, PaymentKind::Bolt12Refund { .. })
				&& p.amount_msat == Some(overpaid_amount)
		})
		.first()
		.unwrap()
		.id;
	expect_payment_successful_event!(node_b, Some(node_b_payment_id), None);

	let node_b_payments = node_b.list_payments_with_filter(|p| {
		matches!(p.kind, PaymentKind::Bolt12Refund { .. }) && p.id == node_b_payment_id
	});
	assert_eq!(node_b_payments.len(), 1);
	match node_b_payments.first().unwrap().kind {
		PaymentKind::Bolt12Refund {
			hash,
			preimage,
			secret: _,
			quantity: ref qty,
			payer_note: ref note,
		} => {
			assert!(hash.is_some());
			assert!(preimage.is_some());
			assert_eq!(&expected_quantity, qty);
			assert_eq!(expected_payer_note.unwrap(), note.clone().unwrap().0)
			// TODO: We should eventually set and assert the secret sender-side, too, but the BOLT12
			// API currently doesn't allow to do that.
		},
		_ => {
			panic!("Unexpected payment kind");
		},
	}
	assert_eq!(node_b_payments.first().unwrap().amount_msat, Some(overpaid_amount));

	let node_a_payment_id = PaymentId(invoice.payment_hash().0);
	let node_a_payments = node_a.list_payments_with_filter(|p| {
		matches!(p.kind, PaymentKind::Bolt12Refund { .. }) && p.id == node_a_payment_id
	});
	assert_eq!(node_a_payments.len(), 1);
	match node_a_payments.first().unwrap().kind {
		PaymentKind::Bolt12Refund { hash, preimage, secret, .. } => {
			assert!(hash.is_some());
			assert!(preimage.is_some());
			assert!(secret.is_some());
		},
		_ => {
			panic!("Unexpected payment kind");
		},
	}
	assert_eq!(node_a_payments.first().unwrap().amount_msat, Some(overpaid_amount));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn async_payment() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);

	let mut config_sender = random_config(true);
	config_sender.node_config.listening_addresses = None;
	config_sender.node_config.node_alias = None;
	config_sender.log_writer =
		TestLogWriter::Custom(Arc::new(MultiNodeLogger::new("sender      ".to_string())));
	let node_sender = setup_node_for_async_payments(
		&chain_source,
		config_sender,
		None,
		Some(AsyncPaymentsRole::Client),
	);

	let mut config_sender_lsp = random_config(true);
	config_sender_lsp.log_writer =
		TestLogWriter::Custom(Arc::new(MultiNodeLogger::new("sender_lsp  ".to_string())));
	let node_sender_lsp = setup_node_for_async_payments(
		&chain_source,
		config_sender_lsp,
		None,
		Some(AsyncPaymentsRole::Server),
	);

	let mut config_receiver_lsp = random_config(true);
	config_receiver_lsp.log_writer =
		TestLogWriter::Custom(Arc::new(MultiNodeLogger::new("receiver_lsp".to_string())));

	let node_receiver_lsp = setup_node_for_async_payments(
		&chain_source,
		config_receiver_lsp,
		None,
		Some(AsyncPaymentsRole::Server),
	);

	let mut config_receiver = random_config(true);
	config_receiver.node_config.listening_addresses = None;
	config_receiver.node_config.node_alias = None;
	config_receiver.log_writer =
		TestLogWriter::Custom(Arc::new(MultiNodeLogger::new("receiver    ".to_string())));
	let node_receiver = setup_node(&chain_source, config_receiver, None);

	let address_sender = node_sender.onchain_payment().new_address().unwrap();
	let address_sender_lsp = node_sender_lsp.onchain_payment().new_address().unwrap();
	let address_receiver_lsp = node_receiver_lsp.onchain_payment().new_address().unwrap();
	let address_receiver = node_receiver.onchain_payment().new_address().unwrap();
	let premine_amount_sat = 4_000_000;
	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![address_sender, address_sender_lsp, address_receiver_lsp, address_receiver],
		Amount::from_sat(premine_amount_sat),
	)
	.await;

	node_sender.sync_wallets().unwrap();
	node_sender_lsp.sync_wallets().unwrap();
	node_receiver_lsp.sync_wallets().unwrap();
	node_receiver.sync_wallets().unwrap();

	open_channel(&node_sender, &node_sender_lsp, 400_000, false, &electrsd).await;
	open_channel(&node_sender_lsp, &node_receiver_lsp, 400_000, true, &electrsd).await;
	open_channel_push_amt(
		&node_receiver,
		&node_receiver_lsp,
		400_000,
		Some(200_000_000),
		false,
		&electrsd,
	)
	.await;

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_sender.sync_wallets().unwrap();
	node_sender_lsp.sync_wallets().unwrap();
	node_receiver_lsp.sync_wallets().unwrap();
	node_receiver.sync_wallets().unwrap();

	expect_channel_ready_event!(node_sender, node_sender_lsp.node_id());
	expect_channel_ready_event!(node_sender_lsp, node_sender.node_id());
	expect_channel_ready_event!(node_sender_lsp, node_receiver_lsp.node_id());
	expect_channel_ready_event!(node_receiver_lsp, node_sender_lsp.node_id());
	expect_channel_ready_event!(node_receiver_lsp, node_receiver.node_id());
	expect_channel_ready_event!(node_receiver, node_receiver_lsp.node_id());

	let has_node_announcements = |node: &ldk_node::Node| {
		node.network_graph()
			.list_nodes()
			.iter()
			.filter(|n| {
				node.network_graph().node(n).map_or(false, |info| info.announcement_info.is_some())
			})
			.count() >= 2
	};

	// Wait for everyone to see all channels and node announcements.
	while node_sender.network_graph().list_channels().len() < 1
		|| node_sender_lsp.network_graph().list_channels().len() < 1
		|| node_receiver_lsp.network_graph().list_channels().len() < 1
		|| node_receiver.network_graph().list_channels().len() < 1
		|| !has_node_announcements(&node_sender)
		|| !has_node_announcements(&node_sender_lsp)
		|| !has_node_announcements(&node_receiver_lsp)
		|| !has_node_announcements(&node_receiver)
	{
		tokio::time::sleep(std::time::Duration::from_millis(100)).await;
	}

	let recipient_id = vec![1, 2, 3];
	let blinded_paths =
		node_receiver_lsp.bolt12_payment().blinded_paths_for_async_recipient(recipient_id).unwrap();
	node_receiver.bolt12_payment().set_paths_to_static_invoice_server(blinded_paths).unwrap();

	let offer = loop {
		if let Ok(offer) = node_receiver.bolt12_payment().receive_async() {
			break offer;
		}

		tokio::time::sleep(std::time::Duration::from_millis(100)).await;
	};

	node_receiver.stop().unwrap();

	let payment_id =
		node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None, None).unwrap();

	// Sleep to allow the payment reach a state where the htlc is held and waiting for the receiver to come online.
	tokio::time::sleep(std::time::Duration::from_millis(3000)).await;

	node_receiver.start().unwrap();

	expect_payment_successful_event!(node_sender, Some(payment_id), None);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_node_announcement_propagation() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);

	// Node A will use both listening and announcement addresses
	let mut config_a = random_config(true);
	let node_a_alias_string = "ldk-node-a".to_string();
	let mut node_a_alias_bytes = [0u8; 32];
	node_a_alias_bytes[..node_a_alias_string.as_bytes().len()]
		.copy_from_slice(node_a_alias_string.as_bytes());
	let node_a_node_alias = Some(NodeAlias(node_a_alias_bytes));
	let node_a_announcement_addresses = random_listening_addresses();
	config_a.node_config.node_alias = node_a_node_alias.clone();
	config_a.node_config.listening_addresses = Some(random_listening_addresses());
	config_a.node_config.announcement_addresses = Some(node_a_announcement_addresses.clone());

	// Node B will only use listening addresses
	let mut config_b = random_config(true);
	let node_b_alias_string = "ldk-node-b".to_string();
	let mut node_b_alias_bytes = [0u8; 32];
	node_b_alias_bytes[..node_b_alias_string.as_bytes().len()]
		.copy_from_slice(node_b_alias_string.as_bytes());
	let node_b_node_alias = Some(NodeAlias(node_b_alias_bytes));
	let node_b_listening_addresses = random_listening_addresses();
	config_b.node_config.node_alias = node_b_node_alias.clone();
	config_b.node_config.listening_addresses = Some(node_b_listening_addresses.clone());
	config_b.node_config.announcement_addresses = None;

	let node_a = setup_node(&chain_source, config_a, None);
	let node_b = setup_node(&chain_source, config_b, None);

	let address_a = node_a.onchain_payment().new_address().unwrap();
	let premine_amount_sat = 5_000_000;
	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![address_a],
		Amount::from_sat(premine_amount_sat),
	)
	.await;

	node_a.sync_wallets().unwrap();

	// Open an announced channel from node_a to node_b
	open_channel(&node_a, &node_b, 4_000_000, true, &electrsd).await;

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	expect_channel_ready_event!(node_a, node_b.node_id());
	expect_channel_ready_event!(node_b, node_a.node_id());

	// Wait until node_b broadcasts a node announcement
	while node_b.status().latest_node_announcement_broadcast_timestamp.is_none() {
		tokio::time::sleep(std::time::Duration::from_millis(10)).await;
	}

	// Sleep to make sure the node announcement propagates
	tokio::time::sleep(std::time::Duration::from_secs(1)).await;

	// Get node info from the other node's perspective
	let node_a_info = node_b.network_graph().node(&NodeId::from_pubkey(&node_a.node_id())).unwrap();
	let node_a_announcement_info = node_a_info.announcement_info.as_ref().unwrap();

	let node_b_info = node_a.network_graph().node(&NodeId::from_pubkey(&node_b.node_id())).unwrap();
	let node_b_announcement_info = node_b_info.announcement_info.as_ref().unwrap();

	// Assert that the aliases and addresses match the expected values
	#[cfg(not(feature = "uniffi"))]
	assert_eq!(node_a_announcement_info.alias(), &node_a_node_alias.unwrap());
	#[cfg(feature = "uniffi")]
	assert_eq!(node_a_announcement_info.alias, node_a_alias_string);

	#[cfg(not(feature = "uniffi"))]
	assert_eq!(node_a_announcement_info.addresses(), &node_a_announcement_addresses);
	#[cfg(feature = "uniffi")]
	assert_eq!(node_a_announcement_info.addresses, node_a_announcement_addresses);

	#[cfg(not(feature = "uniffi"))]
	assert_eq!(node_b_announcement_info.alias(), &node_b_node_alias.unwrap());
	#[cfg(feature = "uniffi")]
	assert_eq!(node_b_announcement_info.alias, node_b_alias_string);

	#[cfg(not(feature = "uniffi"))]
	assert_eq!(node_b_announcement_info.addresses(), &node_b_listening_addresses);
	#[cfg(feature = "uniffi")]
	assert_eq!(node_b_announcement_info.addresses, node_b_listening_addresses);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn generate_bip21_uri() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);

	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);

	let address_a = node_a.onchain_payment().new_address().unwrap();
	let premined_sats = 5_000_000;

	let expected_amount_sats = 100_000;
	let expiry_sec = 4_000;

	// Test 1: Verify URI generation (on-chain + BOLT11) works
	// even before any channels are opened. This checks the graceful fallback behavior.
	let initial_uqr_payment = node_b
		.unified_qr_payment()
		.receive(expected_amount_sats, "asdf", expiry_sec)
		.expect("Failed to generate URI");
	println!("Initial URI (no channels): {}", initial_uqr_payment);

	assert!(initial_uqr_payment.contains("bitcoin:"));
	assert!(initial_uqr_payment.contains("lightning="));
	assert!(!initial_uqr_payment.contains("lno=")); // BOLT12 requires channels

	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![address_a],
		Amount::from_sat(premined_sats),
	)
	.await;

	node_a.sync_wallets().unwrap();
	open_channel(&node_a, &node_b, 4_000_000, true, &electrsd).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	expect_channel_ready_event!(node_a, node_b.node_id());
	expect_channel_ready_event!(node_b, node_a.node_id());

	// Test 2: Verify URI generation (on-chain + BOLT11 + BOLT12) works after channels are established.
	let uqr_payment = node_b
		.unified_qr_payment()
		.receive(expected_amount_sats, "asdf", expiry_sec)
		.expect("Failed to generate URI");

	println!("Generated URI: {}", uqr_payment);
	assert!(uqr_payment.contains("bitcoin:"));
	assert!(uqr_payment.contains("lightning="));
	assert!(uqr_payment.contains("lno="));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn unified_qr_send_receive() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);

	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);

	let address_a = node_a.onchain_payment().new_address().unwrap();
	let premined_sats = 5_000_000;

	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![address_a],
		Amount::from_sat(premined_sats),
	)
	.await;

	node_a.sync_wallets().unwrap();
	open_channel(&node_a, &node_b, 4_000_000, true, &electrsd).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	expect_channel_ready_event!(node_a, node_b.node_id());
	expect_channel_ready_event!(node_b, node_a.node_id());

	// Sleep until we broadcast a node announcement.
	while node_b.status().latest_node_announcement_broadcast_timestamp.is_none() {
		tokio::time::sleep(std::time::Duration::from_millis(10)).await;
	}

	// Sleep one more sec to make sure the node announcement propagates.
	tokio::time::sleep(std::time::Duration::from_secs(1)).await;

	let expected_amount_sats = 100_000;
	let expiry_sec = 4_000;

	let uqr_payment = node_b.unified_qr_payment().receive(expected_amount_sats, "asdf", expiry_sec);
	let uri_str = uqr_payment.clone().unwrap();
	let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str, None) {
		Ok(QrPaymentResult::Bolt12 { payment_id }) => {
			println!("\nBolt12 payment sent successfully with PaymentID: {:?}", payment_id);
			payment_id
		},
		Ok(QrPaymentResult::Bolt11 { payment_id: _ }) => {
			panic!("Expected Bolt12 payment but got Bolt11");
		},
		Ok(QrPaymentResult::Onchain { txid: _ }) => {
			panic!("Expected Bolt12 payment but get On-chain transaction");
		},
		Err(e) => {
			panic!("Expected Bolt12 payment but got error: {:?}", e);
		},
	};

	expect_payment_successful_event!(node_a, Some(offer_payment_id), None);

	// Cut off the BOLT12 part to fallback to BOLT11.
	let uri_str_without_offer = uri_str.split("&lno=").next().unwrap();
	let invoice_payment_id: PaymentId =
		match node_a.unified_qr_payment().send(uri_str_without_offer, None) {
			Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
				panic!("Expected Bolt11 payment but got Bolt12");
			},
			Ok(QrPaymentResult::Bolt11 { payment_id }) => {
				println!("\nBolt11 payment sent successfully with PaymentID: {:?}", payment_id);
				payment_id
			},
			Ok(QrPaymentResult::Onchain { txid: _ }) => {
				panic!("Expected Bolt11 payment but got on-chain transaction");
			},
			Err(e) => {
				panic!("Expected Bolt11 payment but got error: {:?}", e);
			},
		};
	expect_payment_successful_event!(node_a, Some(invoice_payment_id), None);

	let expect_onchain_amount_sats = 800_000;
	let onchain_uqr_payment =
		node_b.unified_qr_payment().receive(expect_onchain_amount_sats, "asdf", 4_000).unwrap();

	// Cut off any lightning part to fallback to on-chain only.
	let uri_str_without_lightning = onchain_uqr_payment.split("&lightning=").next().unwrap();
	let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning, None) {
		Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
			panic!("Expected on-chain payment but got Bolt12")
		},
		Ok(QrPaymentResult::Bolt11 { payment_id: _ }) => {
			panic!("Expected on-chain payment but got Bolt11");
		},
		Ok(QrPaymentResult::Onchain { txid }) => {
			println!("\nOn-chain transaction successful with Txid: {}", txid);
			txid
		},
		Err(e) => {
			panic!("Expected on-chain payment but got error: {:?}", e);
		},
	};

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	wait_for_tx(&electrsd.client, txid).await;

	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();

	assert_eq!(node_b.list_balances().total_onchain_balance_sats, 800_000);
	assert_eq!(node_b.list_balances().total_lightning_balance_sats, 200_000);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn lsps2_client_service_integration() {
	do_lsps2_client_service_integration(true).await;
	do_lsps2_client_service_integration(false).await;
}

async fn do_lsps2_client_service_integration(client_trusts_lsp: bool) {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());

	let sync_config = EsploraSyncConfig { background_sync_config: None };

	// Setup three nodes: service, client, and payer
	let channel_opening_fee_ppm = 10_000;
	let channel_over_provisioning_ppm = 100_000;
	let lsps2_service_config = LSPS2ServiceConfig {
		require_token: None,
		advertise_service: false,
		channel_opening_fee_ppm,
		channel_over_provisioning_ppm,
		max_payment_size_msat: 1_000_000_000,
		min_payment_size_msat: 0,
		min_channel_lifetime: 100,
		min_channel_opening_fee_msat: 0,
		max_client_to_self_delay: 1024,
		client_trusts_lsp,
	};

	let service_config = random_config(true);
	setup_builder!(service_builder, service_config.node_config);
	service_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
	service_builder.set_liquidity_provider_lsps2(lsps2_service_config);
	let service_node = service_builder.build().unwrap();
	service_node.start().unwrap();

	let service_node_id = service_node.node_id();
	let service_addr = service_node.listening_addresses().unwrap().first().unwrap().clone();

	let client_config = random_config(true);
	setup_builder!(client_builder, client_config.node_config);
	client_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
	client_builder.set_liquidity_source_lsps2(service_node_id, service_addr, None);
	let client_node = client_builder.build().unwrap();
	client_node.start().unwrap();

	let payer_config = random_config(true);
	setup_builder!(payer_builder, payer_config.node_config);
	payer_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
	let payer_node = payer_builder.build().unwrap();
	payer_node.start().unwrap();

	let service_addr = service_node.onchain_payment().new_address().unwrap();
	let client_addr = client_node.onchain_payment().new_address().unwrap();
	let payer_addr = payer_node.onchain_payment().new_address().unwrap();

	let premine_amount_sat = 10_000_000;

	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![service_addr, client_addr, payer_addr],
		Amount::from_sat(premine_amount_sat),
	)
	.await;
	service_node.sync_wallets().unwrap();
	client_node.sync_wallets().unwrap();
	payer_node.sync_wallets().unwrap();

	// Open a channel payer -> service that will allow paying the JIT invoice
	println!("Opening channel payer_node -> service_node!");
	open_channel(&payer_node, &service_node, 5_000_000, false, &electrsd).await;

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	service_node.sync_wallets().unwrap();
	payer_node.sync_wallets().unwrap();
	expect_channel_ready_event!(payer_node, service_node.node_id());
	expect_channel_ready_event!(service_node, payer_node.node_id());

	let invoice_description =
		Bolt11InvoiceDescription::Direct(Description::new(String::from("asdf")).unwrap());
	let jit_amount_msat = 100_000_000;

	println!("Generating JIT invoice!");
	let jit_invoice = client_node
		.bolt11_payment()
		.receive_via_jit_channel(jit_amount_msat, &invoice_description.into(), 1024, None)
		.unwrap();

	// Have the payer_node pay the invoice, therby triggering channel open service_node -> client_node.
	println!("Paying JIT invoice!");
	let payment_id = payer_node.bolt11_payment().send(&jit_invoice, None).unwrap();
	expect_channel_pending_event!(service_node, client_node.node_id());
	expect_channel_ready_event!(service_node, client_node.node_id());
	expect_event!(service_node, PaymentForwarded);
	expect_channel_pending_event!(client_node, service_node.node_id());
	expect_channel_ready_event!(client_node, service_node.node_id());

	let service_fee_msat = (jit_amount_msat * channel_opening_fee_ppm as u64) / 1_000_000;
	let expected_received_amount_msat = jit_amount_msat - service_fee_msat;
	expect_payment_successful_event!(payer_node, Some(payment_id), None);
	let client_payment_id =
		expect_payment_received_event!(client_node, expected_received_amount_msat).unwrap();
	let client_payment = client_node.payment(&client_payment_id).unwrap();
	match client_payment.kind {
		PaymentKind::Bolt11Jit { counterparty_skimmed_fee_msat, .. } => {
			assert_eq!(counterparty_skimmed_fee_msat, Some(service_fee_msat));
		},
		_ => panic!("Unexpected payment kind"),
	}

	let expected_channel_overprovisioning_msat =
		(expected_received_amount_msat * channel_over_provisioning_ppm as u64) / 1_000_000;
	let expected_channel_size_sat =
		(expected_received_amount_msat + expected_channel_overprovisioning_msat) / 1000;
	let channel_value_sats = client_node.list_channels().first().unwrap().channel_value_sats;
	assert_eq!(channel_value_sats, expected_channel_size_sat);

	println!("Generating regular invoice!");
	let invoice_description =
		Bolt11InvoiceDescription::Direct(Description::new(String::from("asdf")).unwrap()).into();
	let amount_msat = 5_000_000;
	let invoice =
		client_node.bolt11_payment().receive(amount_msat, &invoice_description, 1024).unwrap();

	// Have the payer_node pay the invoice, to check regular forwards service_node -> client_node
	// are working as expected.
	println!("Paying regular invoice!");
	let payment_id = payer_node.bolt11_payment().send(&invoice, None).unwrap();
	expect_payment_successful_event!(payer_node, Some(payment_id), None);
	expect_event!(service_node, PaymentForwarded);
	expect_payment_received_event!(client_node, amount_msat);

	////////////////////////////////////////////////////////////////////////////
	// receive_via_jit_channel_for_hash and claim_for_hash
	////////////////////////////////////////////////////////////////////////////
	println!("Generating JIT invoice!");
	// Increase the amount to make sure it does not fit into the existing channels.
	let jit_amount_msat = 200_000_000;
	let manual_preimage = PaymentPreimage([42u8; 32]);
	let manual_payment_hash: PaymentHash = manual_preimage.into();
	let jit_invoice = client_node
		.bolt11_payment()
		.receive_via_jit_channel_for_hash(
			jit_amount_msat,
			&invoice_description,
			1024,
			None,
			manual_payment_hash,
		)
		.unwrap();

	// Have the payer_node pay the invoice, therby triggering channel open service_node -> client_node.
	println!("Paying JIT invoice!");
	let payment_id = payer_node.bolt11_payment().send(&jit_invoice, None).unwrap();
	expect_channel_pending_event!(service_node, client_node.node_id());
	expect_channel_ready_event!(service_node, client_node.node_id());
	expect_channel_pending_event!(client_node, service_node.node_id());
	expect_channel_ready_event!(client_node, service_node.node_id());

	let service_fee_msat = (jit_amount_msat * channel_opening_fee_ppm as u64) / 1_000_000;
	let expected_received_amount_msat = jit_amount_msat - service_fee_msat;
	let claimable_amount_msat = expect_payment_claimable_event!(
		client_node,
		payment_id,
		manual_payment_hash,
		expected_received_amount_msat
	);
	println!("Claiming payment!");
	client_node
		.bolt11_payment()
		.claim_for_hash(manual_payment_hash, claimable_amount_msat, manual_preimage)
		.unwrap();

	expect_event!(service_node, PaymentForwarded);
	expect_payment_successful_event!(payer_node, Some(payment_id), None);
	let client_payment_id =
		expect_payment_received_event!(client_node, expected_received_amount_msat).unwrap();
	let client_payment = client_node.payment(&client_payment_id).unwrap();
	match client_payment.kind {
		PaymentKind::Bolt11Jit { counterparty_skimmed_fee_msat, .. } => {
			assert_eq!(counterparty_skimmed_fee_msat, Some(service_fee_msat));
		},
		_ => panic!("Unexpected payment kind"),
	}

	////////////////////////////////////////////////////////////////////////////
	// receive_via_jit_channel_for_hash and fail_for_hash
	////////////////////////////////////////////////////////////////////////////
	println!("Generating JIT invoice!");
	// Increase the amount to make sure it does not fit into the existing channels.
	let jit_amount_msat = 400_000_000;
	let manual_preimage = PaymentPreimage([43u8; 32]);
	let manual_payment_hash: PaymentHash = manual_preimage.into();
	let jit_invoice = client_node
		.bolt11_payment()
		.receive_via_jit_channel_for_hash(
			jit_amount_msat,
			&invoice_description,
			1024,
			None,
			manual_payment_hash,
		)
		.unwrap();

	// Have the payer_node pay the invoice, therby triggering channel open service_node -> client_node.
	println!("Paying JIT invoice!");
	let payment_id = payer_node.bolt11_payment().send(&jit_invoice, None).unwrap();
	expect_channel_pending_event!(service_node, client_node.node_id());
	expect_channel_ready_event!(service_node, client_node.node_id());
	expect_channel_pending_event!(client_node, service_node.node_id());
	expect_channel_ready_event!(client_node, service_node.node_id());

	let service_fee_msat = (jit_amount_msat * channel_opening_fee_ppm as u64) / 1_000_000;
	let expected_received_amount_msat = jit_amount_msat - service_fee_msat;
	expect_payment_claimable_event!(
		client_node,
		payment_id,
		manual_payment_hash,
		expected_received_amount_msat
	);
	println!("Failing payment!");
	client_node.bolt11_payment().fail_for_hash(manual_payment_hash).unwrap();

	expect_event!(payer_node, PaymentFailed);
	assert_eq!(client_node.payment(&payment_id).unwrap().status, PaymentStatus::Failed);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn facade_logging() {
	let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);

	let logger = init_log_logger(LevelFilter::Trace);
	let mut config = random_config(false);
	config.log_writer = TestLogWriter::LogFacade;

	println!("== Facade logging starts ==");
	let _node = setup_node(&chain_source, config, None);

	assert!(!logger.retrieve_logs().is_empty());
	for (_, entry) in logger.retrieve_logs().iter().enumerate() {
		validate_log_entry(entry);
	}
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn spontaneous_send_with_custom_preimage() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let (node_a, node_b) = setup_two_nodes(&chain_source, false, true, false);

	let address_a = node_a.onchain_payment().new_address().unwrap();
	let premine_sat = 1_000_000;
	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![address_a],
		Amount::from_sat(premine_sat),
	)
	.await;
	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();
	open_channel(&node_a, &node_b, 500_000, true, &electrsd).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	node_a.sync_wallets().unwrap();
	node_b.sync_wallets().unwrap();
	expect_channel_ready_event!(node_a, node_b.node_id());
	expect_channel_ready_event!(node_b, node_a.node_id());

	let seed = b"test_payment_preimage";
	let bytes: Sha256Hash = Sha256Hash::hash(seed);
	let custom_bytes = bytes.to_byte_array();
	let custom_preimage = PaymentPreimage(custom_bytes);

	let amount_msat = 100_000;
	let payment_id = node_a
		.spontaneous_payment()
		.send_with_preimage(amount_msat, node_b.node_id(), custom_preimage, None)
		.unwrap();

	// check payment status and verify stored preimage
	expect_payment_successful_event!(node_a, Some(payment_id), None);
	let details: PaymentDetails =
		node_a.list_payments_with_filter(|p| p.id == payment_id).first().unwrap().clone();
	assert_eq!(details.status, PaymentStatus::Succeeded);
	if let PaymentKind::Spontaneous { preimage: Some(pi), .. } = details.kind {
		assert_eq!(pi.0, custom_bytes);
	} else {
		panic!("Expected a spontaneous PaymentKind with a preimage");
	}

	// Verify receiver side (node_b)
	expect_payment_received_event!(node_b, amount_msat);
	let receiver_payments: Vec<PaymentDetails> = node_b.list_payments_with_filter(|p| {
		p.direction == PaymentDirection::Inbound
			&& matches!(p.kind, PaymentKind::Spontaneous { .. })
	});

	assert_eq!(receiver_payments.len(), 1);
	let receiver_details = &receiver_payments[0];
	assert_eq!(receiver_details.status, PaymentStatus::Succeeded);
	assert_eq!(receiver_details.amount_msat, Some(amount_msat));
	assert_eq!(receiver_details.direction, PaymentDirection::Inbound);

	// Verify receiver also has the same preimage
	if let PaymentKind::Spontaneous { preimage: Some(pi), .. } = &receiver_details.kind {
		assert_eq!(pi.0, custom_bytes);
	} else {
		panic!("Expected receiver to have spontaneous PaymentKind with preimage");
	}
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn drop_in_async_context() {
	let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
	let chain_source = TestChainSource::Esplora(&electrsd);
	let seed_bytes = vec![42u8; 64];

	let config = random_config(true);
	let node = setup_node(&chain_source, config, Some(seed_bytes));
	node.stop().unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn lsps2_client_trusts_lsp() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();

	let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());

	let sync_config = EsploraSyncConfig { background_sync_config: None };

	// Setup three nodes: service, client, and payer
	let channel_opening_fee_ppm = 10_000;
	let channel_over_provisioning_ppm = 100_000;
	let lsps2_service_config = LSPS2ServiceConfig {
		require_token: None,
		advertise_service: false,
		channel_opening_fee_ppm,
		channel_over_provisioning_ppm,
		max_payment_size_msat: 1_000_000_000,
		min_payment_size_msat: 0,
		min_channel_lifetime: 100,
		min_channel_opening_fee_msat: 0,
		max_client_to_self_delay: 1024,
		client_trusts_lsp: true,
	};

	let service_config = random_config(true);
	setup_builder!(service_builder, service_config.node_config);
	service_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
	service_builder.set_liquidity_provider_lsps2(lsps2_service_config);
	let service_node = service_builder.build().unwrap();
	service_node.start().unwrap();
	let service_node_id = service_node.node_id();
	let service_addr = service_node.listening_addresses().unwrap().first().unwrap().clone();

	let client_config = random_config(true);
	setup_builder!(client_builder, client_config.node_config);
	client_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
	client_builder.set_liquidity_source_lsps2(service_node_id, service_addr.clone(), None);
	let client_node = client_builder.build().unwrap();
	client_node.start().unwrap();
	let client_node_id = client_node.node_id();

	let payer_config = random_config(true);
	setup_builder!(payer_builder, payer_config.node_config);
	payer_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
	let payer_node = payer_builder.build().unwrap();
	payer_node.start().unwrap();

	let service_addr_onchain = service_node.onchain_payment().new_address().unwrap();
	let client_addr_onchain = client_node.onchain_payment().new_address().unwrap();
	let payer_addr_onchain = payer_node.onchain_payment().new_address().unwrap();

	let premine_amount_sat = 10_000_000;

	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![service_addr_onchain, client_addr_onchain, payer_addr_onchain],
		Amount::from_sat(premine_amount_sat),
	)
	.await;
	service_node.sync_wallets().unwrap();
	client_node.sync_wallets().unwrap();
	payer_node.sync_wallets().unwrap();
	println!("Premine complete!");
	// Open a channel payer -> service that will allow paying the JIT invoice
	open_channel(&payer_node, &service_node, 5_000_000, false, &electrsd).await;

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	service_node.sync_wallets().unwrap();
	payer_node.sync_wallets().unwrap();
	expect_channel_ready_event!(payer_node, service_node.node_id());
	expect_channel_ready_event!(service_node, payer_node.node_id());

	let invoice_description =
		Bolt11InvoiceDescription::Direct(Description::new(String::from("asdf")).unwrap());
	let jit_amount_msat = 100_000_000;

	println!("Generating JIT invoice!");
	let manual_preimage = PaymentPreimage([42u8; 32]);
	let manual_payment_hash: PaymentHash = manual_preimage.into();
	let res = client_node
		.bolt11_payment()
		.receive_via_jit_channel_for_hash(
			jit_amount_msat,
			&invoice_description.into(),
			1024,
			None,
			manual_payment_hash,
		)
		.unwrap();

	// Have the payer_node pay the invoice, therby triggering channel open service_node -> client_node.
	println!("Paying JIT invoice!");
	let payment_id = payer_node.bolt11_payment().send(&res, None).unwrap();
	println!("Payment ID: {:?}", payment_id);
	let funding_txo = expect_channel_pending_event!(service_node, client_node.node_id());
	expect_channel_ready_event!(service_node, client_node.node_id());
	expect_channel_pending_event!(client_node, service_node.node_id());
	expect_channel_ready_event!(client_node, service_node.node_id());

	// Check the funding transaction hasn't been broadcasted yet and nodes aren't seeing it.
	println!("Try to find funding tx... It won't be found yet, as the client has not claimed it.");
	tokio::time::sleep(std::time::Duration::from_secs(3)).await;
	let mempool = bitcoind.client.get_raw_mempool().unwrap().into_model().unwrap();
	let funding_tx_found = mempool.0.iter().any(|txid| *txid == funding_txo.txid);
	assert!(!funding_tx_found, "Funding transaction should NOT be broadcast yet");

	service_node.sync_wallets().unwrap();
	client_node.sync_wallets().unwrap();
	assert_eq!(
		client_node
			.list_channels()
			.iter()
			.find(|c| c.counterparty_node_id == service_node_id)
			.unwrap()
			.confirmations,
		Some(0)
	);
	assert_eq!(
		service_node
			.list_channels()
			.iter()
			.find(|c| c.counterparty_node_id == client_node_id)
			.unwrap()
			.confirmations,
		Some(0)
	);

	// Now claim the JIT payment, which should release the funding transaction
	let service_fee_msat = (jit_amount_msat * channel_opening_fee_ppm as u64) / 1_000_000;
	let expected_received_amount_msat = jit_amount_msat - service_fee_msat;

	let _ = expect_payment_claimable_event!(
		client_node,
		payment_id,
		manual_payment_hash,
		expected_received_amount_msat
	);

	client_node
		.bolt11_payment()
		.claim_for_hash(manual_payment_hash, jit_amount_msat, manual_preimage)
		.unwrap();

	expect_payment_successful_event!(payer_node, Some(payment_id), None);

	let _ = expect_payment_received_event!(client_node, expected_received_amount_msat).unwrap();

	// Check the nodes pick up on the confirmed funding tx now.
	wait_for_tx(&electrsd.client, funding_txo.txid).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	service_node.sync_wallets().unwrap();
	client_node.sync_wallets().unwrap();
	assert_eq!(
		client_node
			.list_channels()
			.iter()
			.find(|c| c.counterparty_node_id == service_node_id)
			.unwrap()
			.confirmations,
		Some(6)
	);
	assert_eq!(
		service_node
			.list_channels()
			.iter()
			.find(|c| c.counterparty_node_id == client_node_id)
			.unwrap()
			.confirmations,
		Some(6)
	);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn lsps2_lsp_trusts_client_but_client_does_not_claim() {
	let (bitcoind, electrsd) = setup_bitcoind_and_electrsd();

	let esplora_url = format!("http://{}", electrsd.esplora_url.as_ref().unwrap());

	let sync_config = EsploraSyncConfig { background_sync_config: None };

	// Setup three nodes: service, client, and payer
	let channel_opening_fee_ppm = 10_000;
	let channel_over_provisioning_ppm = 100_000;
	let lsps2_service_config = LSPS2ServiceConfig {
		require_token: None,
		advertise_service: false,
		channel_opening_fee_ppm,
		channel_over_provisioning_ppm,
		max_payment_size_msat: 1_000_000_000,
		min_payment_size_msat: 0,
		min_channel_lifetime: 100,
		min_channel_opening_fee_msat: 0,
		max_client_to_self_delay: 1024,
		client_trusts_lsp: false,
	};

	let service_config = random_config(true);
	setup_builder!(service_builder, service_config.node_config);
	service_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
	service_builder.set_liquidity_provider_lsps2(lsps2_service_config);
	let service_node = service_builder.build().unwrap();
	service_node.start().unwrap();

	let service_node_id = service_node.node_id();
	let service_addr = service_node.listening_addresses().unwrap().first().unwrap().clone();

	let client_config = random_config(true);
	setup_builder!(client_builder, client_config.node_config);
	client_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
	client_builder.set_liquidity_source_lsps2(service_node_id, service_addr.clone(), None);
	let client_node = client_builder.build().unwrap();
	client_node.start().unwrap();

	let client_node_id = client_node.node_id();

	let payer_config = random_config(true);
	setup_builder!(payer_builder, payer_config.node_config);
	payer_builder.set_chain_source_esplora(esplora_url.clone(), Some(sync_config));
	let payer_node = payer_builder.build().unwrap();
	payer_node.start().unwrap();

	let service_addr_onchain = service_node.onchain_payment().new_address().unwrap();
	let client_addr_onchain = client_node.onchain_payment().new_address().unwrap();
	let payer_addr_onchain = payer_node.onchain_payment().new_address().unwrap();

	let premine_amount_sat = 10_000_000;

	premine_and_distribute_funds(
		&bitcoind.client,
		&electrsd.client,
		vec![service_addr_onchain, client_addr_onchain, payer_addr_onchain],
		Amount::from_sat(premine_amount_sat),
	)
	.await;
	service_node.sync_wallets().unwrap();
	client_node.sync_wallets().unwrap();
	payer_node.sync_wallets().unwrap();
	println!("Premine complete!");
	// Open a channel payer -> service that will allow paying the JIT invoice
	open_channel(&payer_node, &service_node, 5_000_000, false, &electrsd).await;

	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	service_node.sync_wallets().unwrap();
	payer_node.sync_wallets().unwrap();
	expect_channel_ready_event!(payer_node, service_node.node_id());
	expect_channel_ready_event!(service_node, payer_node.node_id());

	let invoice_description =
		Bolt11InvoiceDescription::Direct(Description::new(String::from("asdf")).unwrap());
	let jit_amount_msat = 100_000_000;

	println!("Generating JIT invoice!");
	let manual_preimage = PaymentPreimage([42u8; 32]);
	let manual_payment_hash: PaymentHash = manual_preimage.into();
	let res = client_node
		.bolt11_payment()
		.receive_via_jit_channel_for_hash(
			jit_amount_msat,
			&invoice_description.into(),
			1024,
			None,
			manual_payment_hash,
		)
		.unwrap();

	// Have the payer_node pay the invoice, therby triggering channel open service_node -> client_node.
	println!("Paying JIT invoice!");
	let _payment_id = payer_node.bolt11_payment().send(&res, None).unwrap();
	let funding_txo = expect_channel_pending_event!(service_node, client_node.node_id());
	expect_channel_ready_event!(service_node, client_node.node_id());
	expect_channel_pending_event!(client_node, service_node.node_id());
	expect_channel_ready_event!(client_node, service_node.node_id());
	println!("Waiting for funding transaction to be broadcast...");

	// Check the nodes pick up on the confirmed funding tx now.
	wait_for_tx(&electrsd.client, funding_txo.txid).await;
	generate_blocks_and_wait(&bitcoind.client, &electrsd.client, 6).await;
	service_node.sync_wallets().unwrap();
	client_node.sync_wallets().unwrap();
	assert_eq!(
		client_node
			.list_channels()
			.iter()
			.find(|c| c.counterparty_node_id == service_node_id)
			.unwrap()
			.confirmations,
		Some(6)
	);
	assert_eq!(
		service_node
			.list_channels()
			.iter()
			.find(|c| c.counterparty_node_id == client_node_id)
			.unwrap()
			.confirmations,
		Some(6)
	);
}