lightning 0.2.2

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

// 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.

//! Functional tests for the BOLT 12 Offers payment flow.
//!
//! [`ChannelManager`] provides utilities to create [`Offer`]s and [`Refund`]s along with utilities
//! to initiate and request payment for them, respectively. It also manages the payment flow via
//! implementing [`OffersMessageHandler`]. This module tests that functionality, including the
//! resulting [`Event`] generation.
//!
//! Two-node success tests use an announced channel:
//!
//! Alice --- Bob
//!
//! While two-node failure tests use an unannounced channel:
//!
//! Alice ... Bob
//!
//! Six-node tests use unannounced channels for the sender and recipient and announced channels for
//! the rest of the network.
//!
//!               nodes[4]
//!              /        \
//!             /          \
//!            /            \
//! Alice ... Bob -------- Charlie ... David
//!            \            /
//!             \          /
//!              \        /
//!               nodes[5]
//!
//! Unnamed nodes are needed to ensure unannounced nodes can create two-hop blinded paths.
//!
//! Nodes without channels are disconnected and connected as needed to ensure that deterministic
//! blinded paths are used.

use bitcoin::network::Network;
use bitcoin::secp256k1::{PublicKey, Secp256k1};
use core::time::Duration;
use crate::blinded_path::IntroductionNode;
use crate::blinded_path::message::BlindedMessagePath;
use crate::blinded_path::payment::{Bolt12OfferContext, Bolt12RefundContext, PaymentContext};
use crate::blinded_path::message::OffersContext;
use crate::events::{ClosureReason, Event, HTLCHandlingFailureType, PaidBolt12Invoice, PaymentFailureReason, PaymentPurpose};
use crate::ln::channelmanager::{Bolt12PaymentError, PaymentId, RecentPaymentDetails, RecipientOnionFields, Retry, self};
use crate::types::features::Bolt12InvoiceFeatures;
use crate::ln::functional_test_utils::*;
use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, Init, NodeAnnouncement, OnionMessage, OnionMessageHandler, RoutingMessageHandler, SocketAddress, UnsignedGossipMessage, UnsignedNodeAnnouncement};
use crate::ln::outbound_payment::IDEMPOTENCY_TIMEOUT_TICKS;
use crate::offers::invoice::Bolt12Invoice;
use crate::offers::invoice_error::InvoiceError;
use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestFields};
use crate::offers::nonce::Nonce;
use crate::offers::parse::Bolt12SemanticError;
use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageSendInstructions, NodeIdMessageRouter, NullMessageRouter, PeeledOnion, PADDED_PATH_LENGTH};
use crate::onion_message::offers::OffersMessage;
use crate::routing::gossip::{NodeAlias, NodeId};
use crate::routing::router::{PaymentParameters, RouteParameters, RouteParametersConfig};
use crate::sign::{NodeSigner, Recipient};
use crate::util::ser::Writeable;

/// This used to determine whether we built a compact path or not, but now its just a random
/// constant we apply to blinded path expiry in these tests.
const MAX_SHORT_LIVED_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24);

use crate::prelude::*;

macro_rules! expect_recent_payment {
	($node: expr, $payment_state: path, $payment_id: expr) => {
		match $node.node.list_recent_payments().first() {
			Some(&$payment_state { payment_id: actual_payment_id, .. }) => {
				assert_eq!($payment_id, actual_payment_id);
			},
			Some(_) => panic!("Unexpected recent payment state"),
			None => panic!("No recent payments"),
		}
	}
}

fn connect_peers<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>) {
	let node_id_a = node_a.node.get_our_node_id();
	let node_id_b = node_b.node.get_our_node_id();

	let init_a = Init {
		features: node_a.init_features(node_id_b),
		networks: None,
		remote_network_address: None,
	};
	let init_b = Init {
		features: node_b.init_features(node_id_a),
		networks: None,
		remote_network_address: None,
	};

	node_a.node.peer_connected(node_id_b, &init_b, true).unwrap();
	node_b.node.peer_connected(node_id_a, &init_a, false).unwrap();
	node_a.onion_messenger.peer_connected(node_id_b, &init_b, true).unwrap();
	node_b.onion_messenger.peer_connected(node_id_a, &init_a, false).unwrap();
}

fn disconnect_peers<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, peers: &[&Node<'a, 'b, 'c>]) {
	for node_b in peers {
		node_a.node.peer_disconnected(node_b.node.get_our_node_id());
		node_b.node.peer_disconnected(node_a.node.get_our_node_id());
		node_a.onion_messenger.peer_disconnected(node_b.node.get_our_node_id());
		node_b.onion_messenger.peer_disconnected(node_a.node.get_our_node_id());
	}
}

fn announce_node_address<'a, 'b, 'c>(
	node: &Node<'a, 'b, 'c>, peers: &[&Node<'a, 'b, 'c>], address: SocketAddress,
) {
	let features = node.onion_messenger.provided_node_features()
		| node.gossip_sync.provided_node_features();
	let rgb = [0u8; 3];
	let announcement = UnsignedNodeAnnouncement {
		features,
		timestamp: 1000,
		node_id: NodeId::from_pubkey(&node.keys_manager.get_node_id(Recipient::Node).unwrap()),
		rgb,
		alias: NodeAlias([0u8; 32]),
		addresses: vec![address],
		excess_address_data: Vec::new(),
		excess_data: Vec::new(),
	};
	let signature = node.keys_manager.sign_gossip_message(
		UnsignedGossipMessage::NodeAnnouncement(&announcement)
	).unwrap();

	let msg = NodeAnnouncement {
		signature,
		contents: announcement
	};

	let node_pubkey = node.node.get_our_node_id();
	node.gossip_sync.handle_node_announcement(None, &msg).unwrap();
	for peer in peers {
		peer.gossip_sync.handle_node_announcement(Some(node_pubkey), &msg).unwrap();
	}
}

fn resolve_introduction_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, path: &BlindedMessagePath) -> PublicKey {
	path.public_introduction_node_id(&node.network_graph.read_only())
		.and_then(|node_id| node_id.as_pubkey().ok())
		.unwrap()
}

fn check_compact_path_introduction_node<'a, 'b, 'c>(
	path: &BlindedMessagePath,
	lookup_node: &Node<'a, 'b, 'c>,
	expected_introduction_node: PublicKey,
) -> bool {
	let introduction_node_id = resolve_introduction_node(lookup_node, path);
	introduction_node_id == expected_introduction_node
		&& matches!(path.introduction_node(), IntroductionNode::DirectedShortChannelId(..))
}

fn route_bolt12_payment<'a, 'b, 'c>(
	node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], invoice: &Bolt12Invoice
) {
	// Monitor added when handling the invoice onion message.
	check_added_monitors(node, 1);

	let mut events = node.node.get_and_clear_pending_msg_events();
	assert_eq!(events.len(), 1);
	let ev = remove_first_msg_event_to_node(&path[0].node.get_our_node_id(), &mut events);

	// Use a fake payment_hash and bypass checking for the PaymentClaimable event since the
	// invoice contains the payment_hash but it was encrypted inside an onion message.
	let amount_msats = invoice.amount_msats();
	let payment_hash = invoice.payment_hash();
	let args = PassAlongPathArgs::new(node, path, amount_msats, payment_hash, ev)
		.without_clearing_recipient_events();
	do_pass_along_path(args);
}

fn claim_bolt12_payment<'a, 'b, 'c>(
	node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], expected_payment_context: PaymentContext, invoice: &Bolt12Invoice
) {
	let recipient = &path[path.len() - 1];
	let payment_purpose = match get_event!(recipient, Event::PaymentClaimable) {
		Event::PaymentClaimable { purpose, .. } => purpose,
		_ => panic!("No Event::PaymentClaimable"),
	};
	let payment_preimage = match payment_purpose.preimage() {
		Some(preimage) => preimage,
		None => panic!("No preimage in Event::PaymentClaimable"),
	};
	match payment_purpose {
		PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
			assert_eq!(PaymentContext::Bolt12Offer(payment_context), expected_payment_context);
		},
		PaymentPurpose::Bolt12RefundPayment { payment_context, .. } => {
			assert_eq!(PaymentContext::Bolt12Refund(payment_context), expected_payment_context);
		},
		_ => panic!("Unexpected payment purpose: {:?}", payment_purpose),
	}
	if let Some(inv) = claim_payment(node, path, payment_preimage) {
		assert_eq!(inv, PaidBolt12Invoice::Bolt12Invoice(invoice.to_owned()));
	} else {
		panic!("Expected PaidInvoice::Bolt12Invoice");
	};
}

fn extract_offer_nonce<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, message: &OnionMessage) -> Nonce {
	match node.onion_messenger.peel_onion_message(message) {
		Ok(PeeledOnion::Offers(_, Some(OffersContext::InvoiceRequest { nonce }), _)) => nonce,
		Ok(PeeledOnion::Offers(_, context, _)) => panic!("Unexpected onion message context: {:?}", context),
		Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
		Ok(_) => panic!("Unexpected onion message"),
		Err(e) => panic!("Failed to process onion message {:?}", e),
	}
}

pub(super) fn extract_invoice_request<'a, 'b, 'c>(
	node: &Node<'a, 'b, 'c>, message: &OnionMessage
) -> (InvoiceRequest, BlindedMessagePath) {
	match node.onion_messenger.peel_onion_message(message) {
		Ok(PeeledOnion::Offers(message, _, reply_path)) => match message {
			OffersMessage::InvoiceRequest(invoice_request) => (invoice_request, reply_path.unwrap()),
			OffersMessage::Invoice(invoice) => panic!("Unexpected invoice: {:?}", invoice),
			OffersMessage::StaticInvoice(invoice) => panic!("Unexpected static invoice: {:?}", invoice),
			OffersMessage::InvoiceError(error) => panic!("Unexpected invoice_error: {:?}", error),
		},
		Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
		Ok(_) => panic!("Unexpected onion message"),
		Err(e) => panic!("Failed to process onion message {:?}", e),
	}
}

fn extract_invoice<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, message: &OnionMessage) -> (Bolt12Invoice, BlindedMessagePath) {
	match node.onion_messenger.peel_onion_message(message) {
		Ok(PeeledOnion::Offers(message, _, reply_path)) => match message {
			OffersMessage::InvoiceRequest(invoice_request) => panic!("Unexpected invoice_request: {:?}", invoice_request),
			OffersMessage::Invoice(invoice) => (invoice, reply_path.unwrap()),
			OffersMessage::StaticInvoice(invoice) => panic!("Unexpected static invoice: {:?}", invoice),
			OffersMessage::InvoiceError(error) => panic!("Unexpected invoice_error: {:?}", error),
		},
		Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
		Ok(_) => panic!("Unexpected onion message"),
		Err(e) => panic!("Failed to process onion message {:?}", e),
	}
}

fn extract_invoice_error<'a, 'b, 'c>(
	node: &Node<'a, 'b, 'c>, message: &OnionMessage
) -> InvoiceError {
	match node.onion_messenger.peel_onion_message(message) {
		Ok(PeeledOnion::Offers(message, _, _)) => match message {
			OffersMessage::InvoiceRequest(invoice_request) => panic!("Unexpected invoice_request: {:?}", invoice_request),
			OffersMessage::Invoice(invoice) => panic!("Unexpected invoice: {:?}", invoice),
			OffersMessage::StaticInvoice(invoice) => panic!("Unexpected invoice: {:?}", invoice),
			OffersMessage::InvoiceError(error) => error,
		},
		Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
		Ok(_) => panic!("Unexpected onion message"),
		Err(e) => panic!("Failed to process onion message {:?}", e),
	}
}

/// Checks that an offer can be created with no blinded paths.
#[test]
fn create_offer_with_no_blinded_path() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();

	let router = NullMessageRouter {};
	let offer = alice.node
		.create_offer_builder_using_router(&router).unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_eq!(offer.issuer_signing_pubkey(), Some(alice_id));
	assert!(offer.paths().is_empty());
}

/// Checks that a refund can be created with no blinded paths.
#[test]
fn create_refund_with_no_blinded_path() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);

	let router = NullMessageRouter {};
	let refund = alice.node
		.create_refund_builder_using_router(&router, 10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	assert_eq!(refund.amount_msats(), 10_000_000);
	assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
	assert_eq!(refund.payer_signing_pubkey(), alice_id);
	assert!(refund.paths().is_empty());
}

/// Checks that blinded paths without Tor-only nodes are preferred when constructing an offer.
#[test]
fn prefers_non_tor_nodes_in_blinded_paths() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	// Add an extra channel so that more than one of Bob's peers have MIN_PEER_CHANNELS.
	create_announced_chan_between_nodes_with_value(&nodes, 4, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let tor = SocketAddress::OnionV2([255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]);
	announce_node_address(charlie, &[alice, bob, david, &nodes[4], &nodes[5]], tor.clone());

	let offer = bob.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_ne!(offer.issuer_signing_pubkey(), Some(bob_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		let introduction_node_id = resolve_introduction_node(david, &path);
		assert_ne!(introduction_node_id, bob_id);
		assert_ne!(introduction_node_id, charlie_id);
	}

	// Use a one-hop blinded path when Bob is announced and all his peers are Tor-only.
	announce_node_address(&nodes[4], &[alice, bob, charlie, david, &nodes[5]], tor.clone());
	announce_node_address(&nodes[5], &[alice, bob, charlie, david, &nodes[4]], tor.clone());

	let offer = bob.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_ne!(offer.issuer_signing_pubkey(), Some(bob_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		let introduction_node_id = resolve_introduction_node(david, &path);
		assert_eq!(introduction_node_id, bob_id);
	}
}

/// Checks that blinded paths prefer an introduction node that is the most connected.
#[test]
fn prefers_more_connected_nodes_in_blinded_paths() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	// Add extra channels so that more than one of Bob's peers have MIN_PEER_CHANNELS and one has
	// more than the others.
	create_announced_chan_between_nodes_with_value(&nodes, 0, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let bob_id = bob.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let offer = bob.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_ne!(offer.issuer_signing_pubkey(), Some(bob_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		let introduction_node_id = resolve_introduction_node(david, &path);
		assert_eq!(introduction_node_id, nodes[4].node.get_our_node_id());
	}
}

/// Tests the dummy hop behavior of Offers based on the message router used:
/// - Compact paths (`DefaultMessageRouter`) should not include dummy hops.
/// - Node ID paths (`NodeIdMessageRouter`) may include 0 to [`MAX_DUMMY_HOPS_COUNT`] dummy hops.
///
/// Also verifies that the resulting paths are functional: the counterparty can respond with a valid `invoice_request`.
#[test]
fn check_dummy_hop_pattern_in_offer() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	// Case 1: DefaultMessageRouter → uses compact blinded paths (via SCIDs)
	// Expected: No dummy hops; each path contains only the recipient.
	let default_router = DefaultMessageRouter::new(alice.network_graph, alice.keys_manager);

	let compact_offer = alice.node
		.create_offer_builder_using_router(&default_router).unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();

	assert!(!compact_offer.paths().is_empty());

	for path in compact_offer.paths() {
		assert_eq!(
			path.blinded_hops().len(), 1,
			"Compact paths must include only the recipient"
		);
	}

	let payment_id = PaymentId([1; 32]);
	bob.node.pay_for_offer(&compact_offer, None, payment_id, Default::default()).unwrap();

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);

	assert_eq!(invoice_request.amount_msats(), Some(10_000_000));
	assert_ne!(invoice_request.payer_signing_pubkey(), bob_id);
	assert!(check_compact_path_introduction_node(&reply_path, alice, bob_id));

	// Case 2: NodeIdMessageRouter → uses node ID-based blinded paths
	// Expected: 0 to MAX_DUMMY_HOPS_COUNT dummy hops, followed by recipient.
	let node_id_router = NodeIdMessageRouter::new(alice.network_graph, alice.keys_manager);

	let padded_offer = alice.node
		.create_offer_builder_using_router(&node_id_router).unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();

	assert!(!padded_offer.paths().is_empty());
	assert!(padded_offer.paths().iter().all(|path| path.blinded_hops().len() == PADDED_PATH_LENGTH));

	let payment_id = PaymentId([2; 32]);
	bob.node.pay_for_offer(&padded_offer, None, payment_id, Default::default()).unwrap();

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);

	assert_eq!(invoice_request.amount_msats(), Some(10_000_000));
	assert_ne!(invoice_request.payer_signing_pubkey(), bob_id);
	assert!(check_compact_path_introduction_node(&reply_path, alice, bob_id));
}

/// Checks that blinded paths are compact for short-lived offers.
#[test]
fn creates_short_lived_offer() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];

	let offer = alice.node
		.create_offer_builder().unwrap()
		.build().unwrap();
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		let introduction_node_id = resolve_introduction_node(bob, &path);
		assert_eq!(introduction_node_id, alice_id);
		assert!(matches!(path.introduction_node(), &IntroductionNode::DirectedShortChannelId(..)));
	}
}

/// Checks that blinded paths are not compact for long-lived offers.
#[test]
fn creates_long_lived_offer() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();

	let router = NodeIdMessageRouter::new(alice.network_graph, alice.keys_manager);
	let offer = alice.node
		.create_offer_builder_using_router(&router)
		.unwrap()
		.build().unwrap();
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(alice_id));
	}
}

/// Checks that blinded paths are compact for short-lived refunds.
#[test]
fn creates_short_lived_refund() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let absolute_expiry = bob.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY;
	let payment_id = PaymentId([1; 32]);
	let refund = bob.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
	assert!(!refund.paths().is_empty());
	for path in refund.paths() {
		let introduction_node_id = resolve_introduction_node(alice, &path);
		assert_eq!(introduction_node_id, bob_id);
		assert!(matches!(path.introduction_node(), &IntroductionNode::DirectedShortChannelId(..)));
	}
}

/// Checks that blinded paths are not compact for long-lived refunds.
#[test]
fn creates_long_lived_refund() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let absolute_expiry = bob.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY
		+ Duration::from_secs(1);
	let payment_id = PaymentId([1; 32]);

	let router = NodeIdMessageRouter::new(bob.network_graph, bob.keys_manager);
	let refund = bob.node
		.create_refund_builder_using_router(&router, 10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
	assert!(!refund.paths().is_empty());
	for path in refund.paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(bob_id));
	}
}

/// Checks that an offer can be paid through blinded paths and that ephemeral pubkeys are used
/// rather than exposing a node's pubkey.
#[test]
fn creates_and_pays_for_offer_using_two_hop_blinded_path() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let offer = alice.node
		.create_offer_builder()
		.unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_ne!(offer.issuer_signing_pubkey(), Some(alice_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		assert!(check_compact_path_introduction_node(&path, alice, bob_id));
	}

	let payment_id = PaymentId([1; 32]);
	david.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);

	connect_peers(david, bob);

	let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(david_id, &onion_message);

	connect_peers(alice, charlie);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
	let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
		offer_id: offer.id(),
		invoice_request: InvoiceRequestFields {
			payer_signing_pubkey: invoice_request.payer_signing_pubkey(),
			quantity: None,
			payer_note_truncated: None,
			human_readable_name: None,
		},
	});
	assert_eq!(invoice_request.amount_msats(), Some(10_000_000));
	assert_ne!(invoice_request.payer_signing_pubkey(), david_id);
	assert!(check_compact_path_introduction_node(&reply_path, bob, charlie_id));

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
	charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	david.onion_messenger.handle_onion_message(charlie_id, &onion_message);

	let (invoice, reply_path) = extract_invoice(david, &onion_message);
	assert_eq!(invoice.amount_msats(), 10_000_000);
	assert_ne!(invoice.signing_pubkey(), alice_id);
	assert!(!invoice.payment_paths().is_empty());
	for path in invoice.payment_paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(bob_id));
	}
	// Both Bob and Charlie have an equal number of channels and need to be connected
	// to Alice when she's handling the message. Therefore, either Bob or Charlie could
	// serve as the introduction node for the reply path back to Alice.
	assert!(
		check_compact_path_introduction_node(&reply_path, david, bob_id) ||
		check_compact_path_introduction_node(&reply_path, david, charlie_id)
	);

	route_bolt12_payment(david, &[charlie, bob, alice], &invoice);
	expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);

	claim_bolt12_payment(david, &[charlie, bob, alice], payment_context, &invoice);
	expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
}

/// Checks that a refund can be paid through blinded paths and that ephemeral pubkeys are used
/// rather than exposing a node's pubkey.
#[test]
fn creates_and_pays_for_refund_using_two_hop_blinded_path() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	let refund = david.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	assert_eq!(refund.amount_msats(), 10_000_000);
	assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
	assert_ne!(refund.payer_signing_pubkey(), david_id);
	assert!(!refund.paths().is_empty());
	for path in refund.paths() {
		assert!(check_compact_path_introduction_node(&path, david, charlie_id));
	}
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
	let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();

	connect_peers(alice, charlie);

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
	charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	david.onion_messenger.handle_onion_message(charlie_id, &onion_message);

	let (invoice, reply_path) = extract_invoice(david, &onion_message);
	assert_eq!(invoice, expected_invoice);

	assert_eq!(invoice.amount_msats(), 10_000_000);
	assert_ne!(invoice.signing_pubkey(), alice_id);
	assert!(!invoice.payment_paths().is_empty());
	for path in invoice.payment_paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(bob_id));
	}
	assert!(check_compact_path_introduction_node(&reply_path, alice, bob_id));

	route_bolt12_payment(david, &[charlie, bob, alice], &invoice);
	expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);

	claim_bolt12_payment(david, &[charlie, bob, alice], payment_context, &invoice);
	expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
}

/// Checks that an offer can be paid through a one-hop blinded path and that ephemeral pubkeys are
/// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the
/// introduction node of the blinded path.
#[test]
fn creates_and_pays_for_offer_using_one_hop_blinded_path() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let offer = alice.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_ne!(offer.issuer_signing_pubkey(), Some(alice_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		assert!(check_compact_path_introduction_node(&path, bob, alice_id));
	}

	let payment_id = PaymentId([1; 32]);
	bob.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
	let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
		offer_id: offer.id(),
		invoice_request: InvoiceRequestFields {
			payer_signing_pubkey: invoice_request.payer_signing_pubkey(),
			quantity: None,
			payer_note_truncated: None,
			human_readable_name: None,
		},
	});
	assert_eq!(invoice_request.amount_msats(), Some(10_000_000));
	assert_ne!(invoice_request.payer_signing_pubkey(), bob_id);
	assert!(check_compact_path_introduction_node(&reply_path, alice, bob_id));

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let (invoice, reply_path) = extract_invoice(bob, &onion_message);
	assert_eq!(invoice.amount_msats(), 10_000_000);
	assert_ne!(invoice.signing_pubkey(), alice_id);
	assert!(!invoice.payment_paths().is_empty());
	for path in invoice.payment_paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(alice_id));
	}
	assert!(check_compact_path_introduction_node(&reply_path, bob, alice_id));

	route_bolt12_payment(bob, &[alice], &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);

	claim_bolt12_payment(bob, &[alice], payment_context, &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
}

/// Checks that a refund can be paid through a one-hop blinded path and that ephemeral pubkeys are
/// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the
/// introduction node of the blinded path.
#[test]
fn creates_and_pays_for_refund_using_one_hop_blinded_path() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	let refund = bob.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	assert_eq!(refund.amount_msats(), 10_000_000);
	assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
	assert_ne!(refund.payer_signing_pubkey(), bob_id);
	assert!(!refund.paths().is_empty());
	for path in refund.paths() {
		assert!(check_compact_path_introduction_node(&path, alice, bob_id));
	}
	expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
	let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let (invoice, reply_path) = extract_invoice(bob, &onion_message);
	assert_eq!(invoice, expected_invoice);

	assert_eq!(invoice.amount_msats(), 10_000_000);
	assert_ne!(invoice.signing_pubkey(), alice_id);
	assert!(!invoice.payment_paths().is_empty());
	for path in invoice.payment_paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(alice_id));
	}
	assert!(check_compact_path_introduction_node(&reply_path, bob, alice_id));

	route_bolt12_payment(bob, &[alice], &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);

	claim_bolt12_payment(bob, &[alice], payment_context, &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
}

/// Checks that an invoice for an offer without any blinded paths can be requested. Note that while
/// the requested is sent directly using the node's pubkey, the response and the payment still use
/// blinded paths as required by the spec.
#[test]
fn pays_for_offer_without_blinded_paths() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let offer = alice.node
		.create_offer_builder().unwrap()
		.clear_paths()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_eq!(offer.issuer_signing_pubkey(), Some(alice_id));
	assert!(offer.paths().is_empty());

	let payment_id = PaymentId([1; 32]);
	bob.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (invoice_request, _) = extract_invoice_request(alice, &onion_message);
	let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
		offer_id: offer.id(),
		invoice_request: InvoiceRequestFields {
			payer_signing_pubkey: invoice_request.payer_signing_pubkey(),
			quantity: None,
			payer_note_truncated: None,
			human_readable_name: None,
		},
	});

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let (invoice, _) = extract_invoice(bob, &onion_message);
	route_bolt12_payment(bob, &[alice], &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);

	claim_bolt12_payment(bob, &[alice], payment_context, &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
}

/// Checks that a refund without any blinded paths can be paid. Note that while the invoice is sent
/// directly using the node's pubkey, the payment still use blinded paths as required by the spec.
#[test]
fn pays_for_refund_without_blinded_paths() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	let refund = bob.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.clear_paths()
		.build().unwrap();
	assert_eq!(refund.payer_signing_pubkey(), bob_id);
	assert!(refund.paths().is_empty());
	expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
	let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let (invoice, _) = extract_invoice(bob, &onion_message);
	assert_eq!(invoice, expected_invoice);

	route_bolt12_payment(bob, &[alice], &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);

	claim_bolt12_payment(bob, &[alice], payment_context, &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
}

/// This test checks that when multiple potential introduction nodes are available for the payer,
/// multiple `invoice_request` messages are sent for the offer, each with a different `reply_path`.
#[test]
fn send_invoice_requests_with_distinct_reply_path() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(7);
	let node_cfgs = create_node_cfgs(7, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		7, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None, None]
	);
	let nodes = create_network(7, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	// Introduce another potential introduction node, node[6], as a candidate
	create_unannounced_chan_between_nodes_with_value(&nodes, 3, 6, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 6, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 4, 6, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 5, 6, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5], &nodes[6]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let offer = alice.node
		.create_offer_builder()
		.unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_ne!(offer.issuer_signing_pubkey(), Some(alice_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		assert!(check_compact_path_introduction_node(&path, alice, bob_id));
	}

	let payment_id = PaymentId([1; 32]);
	david.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
	connect_peers(david, bob);

	// Send, extract and verify the first Invoice Request message
	let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(david_id, &onion_message);

	connect_peers(alice, charlie);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (_, reply_path) = extract_invoice_request(alice, &onion_message);
	assert!(check_compact_path_introduction_node(&reply_path, alice, charlie_id));

	// Send, extract and verify the second Invoice Request message
	let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(david_id, &onion_message);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (_, reply_path) = extract_invoice_request(alice, &onion_message);
	assert!(check_compact_path_introduction_node(&reply_path, alice, nodes[6].node.get_our_node_id()));
}

/// This test checks that when multiple potential introduction nodes are available for the payee,
/// multiple `Invoice` messages are sent for the Refund, each with a different `reply_path`.
#[test]
fn send_invoice_for_refund_with_distinct_reply_path() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(7);
	let node_cfgs = create_node_cfgs(7, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		7, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None, None]
	);
	let nodes = create_network(7, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	// Introduce another potential introduction node, node[6], as a candidate
	create_unannounced_chan_between_nodes_with_value(&nodes, 3, 6, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 6, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 4, 6, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 5, 6, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5], &nodes[6]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	let refund = alice.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	assert_ne!(refund.payer_signing_pubkey(), alice_id);
	for path in refund.paths() {
		assert!(check_compact_path_introduction_node(&path, alice, bob_id));
	}
	expect_recent_payment!(alice, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let _expected_invoice = david.node.request_refund_payment(&refund).unwrap();

	connect_peers(david, bob);

	let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(david_id, &onion_message);

	connect_peers(alice, charlie);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();

	let (_, reply_path) = extract_invoice(alice, &onion_message);
	assert!(check_compact_path_introduction_node(&reply_path, alice, charlie_id));

	// Send, extract and verify the second Invoice Request message
	let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(david_id, &onion_message);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();

	let (_, reply_path) = extract_invoice(alice, &onion_message);
	assert!(check_compact_path_introduction_node(&reply_path, alice, nodes[6].node.get_our_node_id()));
}

/// Verifies that the invoice request message can be retried if it fails to reach the
/// payee on the first attempt.
#[test]
fn creates_and_pays_for_offer_with_retry() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let offer = alice.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_ne!(offer.issuer_signing_pubkey(), Some(alice_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		assert!(check_compact_path_introduction_node(&path, bob, alice_id));
	}
	let payment_id = PaymentId([1; 32]);
	bob.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let _lost_onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	assert!(bob.onion_messenger.next_onion_message_for_peer(alice_id).is_none());

	// Simulate a scenario where the original onion_message is lost before reaching Alice.
	// Use handle_message_received to regenerate the message.
	bob.node.message_received();
	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();

	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
	let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
		offer_id: offer.id(),
		invoice_request: InvoiceRequestFields {
			payer_signing_pubkey: invoice_request.payer_signing_pubkey(),
			quantity: None,
			payer_note_truncated: None,
			human_readable_name: None,
		},
	});
	assert_eq!(invoice_request.amount_msats(), Some(10_000_000));
	assert_ne!(invoice_request.payer_signing_pubkey(), bob_id);
	assert!(check_compact_path_introduction_node(&reply_path, alice, bob_id));
	let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(alice_id, &onion_message);

	// Expect no more OffersMessage to be enqueued by this point, even after calling
	// handle_message_received.
	bob.node.message_received();

	assert!(bob.onion_messenger.next_onion_message_for_peer(alice_id).is_none());

	let (invoice, _) = extract_invoice(bob, &onion_message);
	assert_eq!(invoice.amount_msats(), 10_000_000);
	assert_ne!(invoice.signing_pubkey(), alice_id);
	assert!(!invoice.payment_paths().is_empty());
	for path in invoice.payment_paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(alice_id));
	}
	route_bolt12_payment(bob, &[alice], &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
	claim_bolt12_payment(bob, &[alice], payment_context, &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
}

/// Checks that a deferred invoice can be paid asynchronously from an Event::InvoiceReceived.
#[test]
fn pays_bolt12_invoice_asynchronously() {
	let mut manually_pay_cfg = test_default_channel_config();
	manually_pay_cfg.manually_handle_bolt12_invoices = true;

	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_pay_cfg)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let offer = alice.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();

	let payment_id = PaymentId([1; 32]);
	bob.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (invoice_request, _) = extract_invoice_request(alice, &onion_message);
	let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
		offer_id: offer.id(),
		invoice_request: InvoiceRequestFields {
			payer_signing_pubkey: invoice_request.payer_signing_pubkey(),
			quantity: None,
			payer_note_truncated: None,
			human_readable_name: None,
		},
	});

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(alice_id, &onion_message);

	// Re-process the same onion message to ensure idempotency —
	// we should not generate a duplicate `InvoiceReceived` event.
	bob.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let mut events = bob.node.get_and_clear_pending_events();
	assert_eq!(events.len(), 1);

	let (invoice, context) = match events.pop().unwrap() {
		Event::InvoiceReceived { payment_id: actual_payment_id, invoice, context, .. } => {
			assert_eq!(actual_payment_id, payment_id);
			(invoice, context)
		},
		_ => panic!("No Event::InvoiceReceived"),
	};
	assert_eq!(invoice.amount_msats(), 10_000_000);
	assert_ne!(invoice.signing_pubkey(), alice_id);
	assert!(!invoice.payment_paths().is_empty());
	for path in invoice.payment_paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(alice_id));
	}

	assert!(bob.node.send_payment_for_bolt12_invoice(&invoice, context.as_ref()).is_ok());
	assert_eq!(
		bob.node.send_payment_for_bolt12_invoice(&invoice, context.as_ref()),
		Err(Bolt12PaymentError::DuplicateInvoice),
	);

	route_bolt12_payment(bob, &[alice], &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);

	claim_bolt12_payment(bob, &[alice], payment_context, &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);

	assert_eq!(
		bob.node.send_payment_for_bolt12_invoice(&invoice, context.as_ref()),
		Err(Bolt12PaymentError::DuplicateInvoice),
	);

	for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
		bob.node.timer_tick_occurred();
	}

	assert_eq!(
		bob.node.send_payment_for_bolt12_invoice(&invoice, context.as_ref()),
		Err(Bolt12PaymentError::UnexpectedInvoice),
	);
}

/// Checks that an offer can be created using an unannounced node as a blinded path's introduction
/// node. This is only preferred if there are no other options which may indicated either the offer
/// is intended for the unannounced node or that the node is actually announced (e.g., an LSP) but
/// the recipient doesn't have a network graph.
#[test]
fn creates_offer_with_blinded_path_using_unannounced_introduction_node() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let offer = alice.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_ne!(offer.issuer_signing_pubkey(), Some(alice_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(bob_id));
	}

	let payment_id = PaymentId([1; 32]);
	bob.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
	let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
		offer_id: offer.id(),
		invoice_request: InvoiceRequestFields {
			payer_signing_pubkey: invoice_request.payer_signing_pubkey(),
			quantity: None,
			payer_note_truncated: None,
			human_readable_name: None,
		},
	});
	assert_ne!(invoice_request.payer_signing_pubkey(), bob_id);
	assert_eq!(reply_path.introduction_node(), &IntroductionNode::NodeId(alice_id));

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let (invoice, reply_path) = extract_invoice(bob, &onion_message);
	assert_ne!(invoice.signing_pubkey(), alice_id);
	assert!(!invoice.payment_paths().is_empty());
	for path in invoice.payment_paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(bob_id));
	}
	assert_eq!(reply_path.introduction_node(), &IntroductionNode::NodeId(bob_id));

	route_bolt12_payment(bob, &[alice], &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);

	claim_bolt12_payment(bob, &[alice], payment_context, &invoice);
	expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
}

/// Checks that a refund can be created using an unannounced node as a blinded path's introduction
/// node. This is only preferred if there are no other options which may indicated either the refund
/// is intended for the unannounced node or that the node is actually announced (e.g., an LSP) but
/// the sender doesn't have a network graph.
#[test]
fn creates_refund_with_blinded_path_using_unannounced_introduction_node() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let alice_id = alice.node.get_our_node_id();
	let bob = &nodes[1];
	let bob_id = bob.node.get_our_node_id();

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	let refund = bob.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	assert_ne!(refund.payer_signing_pubkey(), bob_id);
	assert!(!refund.paths().is_empty());
	for path in refund.paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(alice_id));
	}
	expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);

	let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();

	let (invoice, _reply_path) = extract_invoice(bob, &onion_message);
	assert_eq!(invoice, expected_invoice);
	assert_ne!(invoice.signing_pubkey(), alice_id);
	assert!(!invoice.payment_paths().is_empty());
	for path in invoice.payment_paths() {
		assert_eq!(path.introduction_node(), &IntroductionNode::NodeId(bob_id));
	}
}

/// Check that authentication fails when an invoice request is handled using the wrong context
/// (i.e., was sent directly or over an unexpected blinded path).
#[test]
fn fails_authentication_when_handling_invoice_request() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let offer = alice.node
		.create_offer_builder()
		.unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_eq!(offer.metadata(), None);
	assert_ne!(offer.issuer_signing_pubkey(), Some(alice_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		assert!(check_compact_path_introduction_node(&path, alice, bob_id));
	}

	let invalid_path = alice.node
		.create_offer_builder()
		.unwrap()
		.build().unwrap()
		.paths().first().unwrap()
		.clone();
	assert!(check_compact_path_introduction_node(&invalid_path, alice, bob_id));

	// Send the invoice request directly to Alice instead of using a blinded path.
	let payment_id = PaymentId([1; 32]);
	david.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);

	connect_peers(david, alice);
	match &mut david.node.flow.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
		MessageSendInstructions::WithSpecifiedReplyPath { destination, .. } =>
			*destination = Destination::Node(alice_id),
		_ => panic!(),
	}

	let onion_message = david.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(david_id, &onion_message);

	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
	assert_eq!(invoice_request.amount_msats(), Some(10_000_000));
	assert_ne!(invoice_request.payer_signing_pubkey(), david_id);
	assert!(check_compact_path_introduction_node(&reply_path, david, charlie_id));

	assert_eq!(alice.onion_messenger.next_onion_message_for_peer(charlie_id), None);

	david.node.abandon_payment(payment_id);
	get_event!(david, Event::PaymentFailed);

	// Send the invoice request to Alice using an invalid blinded path.
	let payment_id = PaymentId([2; 32]);
	david.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);

	match &mut david.node.flow.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
		MessageSendInstructions::WithSpecifiedReplyPath { destination, .. } =>
			*destination = Destination::BlindedPath(invalid_path),
		_ => panic!(),
	}

	connect_peers(david, bob);

	let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(david_id, &onion_message);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
	assert_eq!(invoice_request.amount_msats(), Some(10_000_000));
	assert_ne!(invoice_request.payer_signing_pubkey(), david_id);
	assert!(check_compact_path_introduction_node(&reply_path, david, charlie_id));

	assert_eq!(alice.onion_messenger.next_onion_message_for_peer(charlie_id), None);
}

/// Check that authentication fails when an invoice is handled using the wrong context (i.e., was
/// sent over an unexpected blinded path).
#[test]
fn fails_authentication_when_handling_invoice_for_offer() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let offer = alice.node
		.create_offer_builder()
		.unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();
	assert_ne!(offer.issuer_signing_pubkey(), Some(alice_id));
	assert!(!offer.paths().is_empty());
	for path in offer.paths() {
		assert!(check_compact_path_introduction_node(&path, alice, bob_id));
	}

	// Initiate an invoice request, but abandon tracking it.
	let payment_id = PaymentId([1; 32]);
	david.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	david.node.abandon_payment(payment_id);
	get_event!(david, Event::PaymentFailed);

	// Don't send the invoice request, but grab its reply path to use with a different request.
	let invalid_reply_path = {
		let mut pending_offers_messages = david.node.flow.pending_offers_messages.lock().unwrap();
		let pending_invoice_request = pending_offers_messages.pop().unwrap();
		pending_offers_messages.clear();
		match pending_invoice_request.1 {
			MessageSendInstructions::WithSpecifiedReplyPath { reply_path, .. } => reply_path,
			_ => panic!(),
		}
	};

	let payment_id = PaymentId([2; 32]);
	david.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);

	// Swap out the reply path to force authentication to fail when handling the invoice since it
	// will be sent over the wrong blinded path.
	{
		let mut pending_offers_messages = david.node.flow.pending_offers_messages.lock().unwrap();
		let mut pending_invoice_request = pending_offers_messages.first_mut().unwrap();
		match &mut pending_invoice_request.1 {
			MessageSendInstructions::WithSpecifiedReplyPath { reply_path, .. } =>
				*reply_path = invalid_reply_path,
			_ => panic!(),
		}
	}

	connect_peers(david, bob);

	let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(david_id, &onion_message);

	connect_peers(alice, charlie);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
	assert_eq!(invoice_request.amount_msats(), Some(10_000_000));
	assert_ne!(invoice_request.payer_signing_pubkey(), david_id);
	assert!(check_compact_path_introduction_node(&reply_path, david, charlie_id));

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
	charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	david.onion_messenger.handle_onion_message(charlie_id, &onion_message);

	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
}

/// Check that authentication fails when an invoice is handled using the wrong context (i.e., was
/// sent directly or over an unexpected blinded path).
#[test]
fn fails_authentication_when_handling_invoice_for_refund() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	let refund = david.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	assert_ne!(refund.payer_signing_pubkey(), david_id);
	assert!(!refund.paths().is_empty());
	for path in refund.paths() {
		assert!(check_compact_path_introduction_node(&path, david, charlie_id));
	}
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);

	// Send the invoice directly to David instead of using a blinded path.
	let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();

	connect_peers(david, alice);
	match &mut alice.node.flow.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
		MessageSendInstructions::WithSpecifiedReplyPath { destination, .. } =>
			*destination = Destination::Node(david_id),
		_ => panic!(),
	}

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	david.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let (invoice, _) = extract_invoice(david, &onion_message);
	assert_eq!(invoice, expected_invoice);

	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
	david.node.abandon_payment(payment_id);
	get_event!(david, Event::PaymentFailed);

	// Send the invoice to David using an invalid blinded path.
	let invalid_path = refund.paths().first().unwrap().clone();
	let payment_id = PaymentId([2; 32]);
	let refund = david.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	assert_ne!(refund.payer_signing_pubkey(), david_id);
	assert!(!refund.paths().is_empty());
	for path in refund.paths() {
		assert!(check_compact_path_introduction_node(&path, david, charlie_id));
	}

	let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();

	match &mut alice.node.flow.pending_offers_messages.lock().unwrap().first_mut().unwrap().1 {
		MessageSendInstructions::WithSpecifiedReplyPath { destination, .. } =>
			*destination = Destination::BlindedPath(invalid_path),
		_ => panic!(),
	}

	connect_peers(alice, charlie);

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
	charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	david.onion_messenger.handle_onion_message(charlie_id, &onion_message);

	let (invoice, _) = extract_invoice(david, &onion_message);
	assert_eq!(invoice, expected_invoice);

	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
}

/// Fails creating or paying an offer when a blinded path cannot be created because no peers are
/// connected.
#[test]
fn fails_creating_or_paying_for_offer_without_connected_peers() {
	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);

	disconnect_peers(alice, &[bob, charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, charlie, &nodes[4], &nodes[5]]);

	match alice.node.create_offer_builder() {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
	}

	let mut args = ReconnectArgs::new(alice, bob);
	args.send_channel_ready = (true, true);
	reconnect_nodes(args);

	let absolute_expiry = alice.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY;
	let offer = alice.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.absolute_expiry(absolute_expiry)
		.build().unwrap();

	let payment_id = PaymentId([1; 32]);

	match david.node.pay_for_offer(&offer, None, payment_id, Default::default()) {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
	}

	assert!(nodes[0].node.list_recent_payments().is_empty());

	let mut args = ReconnectArgs::new(charlie, david);
	args.send_channel_ready = (true, true);
	reconnect_nodes(args);

	assert!(david.node.pay_for_offer(&offer, None, payment_id, Default::default()).is_ok());
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
}

/// Fails creating or sending an invoice for a refund when a blinded path cannot be created because
/// no peers are connected.
#[test]
fn fails_creating_refund_or_sending_invoice_without_connected_peers() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);

	disconnect_peers(alice, &[bob, charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, charlie, &nodes[4], &nodes[5]]);

	let absolute_expiry = david.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY;
	let payment_id = PaymentId([1; 32]);
	match david.node.create_refund_builder(
		10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default()
	) {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
	}

	let mut args = ReconnectArgs::new(charlie, david);
	args.send_channel_ready = (true, true);
	reconnect_nodes(args);

	let refund = david.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();

	match alice.node.request_refund_payment(&refund) {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
	}

	let mut args = ReconnectArgs::new(alice, bob);
	args.send_channel_ready = (true, true);
	reconnect_nodes(args);

	assert!(alice.node.request_refund_payment(&refund).is_ok());
}

/// Fails creating an invoice request when the offer contains an unsupported chain.
#[test]
fn fails_creating_invoice_request_for_unsupported_chain() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let bob = &nodes[1];

	let offer = alice.node
		.create_offer_builder().unwrap()
		.clear_chains()
		.chain(Network::Signet)
		.build().unwrap();

	match bob.node.pay_for_offer(&offer, None, PaymentId([1; 32]), Default::default()) {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
	}
}

/// Fails requesting a payment when the refund contains an unsupported chain.
#[test]
fn fails_sending_invoice_with_unsupported_chain_for_refund() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let alice = &nodes[0];
	let bob = &nodes[1];

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	let refund = bob.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.chain(Network::Signet)
		.build().unwrap();

	match alice.node.request_refund_payment(&refund) {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
	}
}

/// Fails creating an invoice request when a blinded reply path cannot be created.
#[test]
fn fails_creating_invoice_request_without_blinded_reply_path() {
	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, charlie, &nodes[4], &nodes[5]]);

	let offer = alice.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();

	match david.node.pay_for_offer(&offer, None, PaymentId([1; 32]), Default::default()) {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
	}

	assert!(nodes[0].node.list_recent_payments().is_empty());
}

#[test]
fn fails_creating_invoice_request_with_duplicate_payment_id() {
	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, _bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);

	let offer = alice.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();

	let payment_id = PaymentId([1; 32]);
	assert!(david.node.pay_for_offer( &offer, None, payment_id, Default::default()).is_ok());
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);

	match david.node.pay_for_offer(&offer, None, payment_id, Default::default()) {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::DuplicatePaymentId),
	}

	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
}

#[test]
fn fails_creating_refund_with_duplicate_payment_id() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	assert!(
		nodes[0].node.create_refund_builder(
			10_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default()
		).is_ok()
	);
	expect_recent_payment!(nodes[0], RecentPaymentDetails::AwaitingInvoice, payment_id);

	match nodes[0].node.create_refund_builder(
		10_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default()
	) {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::DuplicatePaymentId),
	}

	expect_recent_payment!(nodes[0], RecentPaymentDetails::AwaitingInvoice, payment_id);
}

#[test]
fn fails_sending_invoice_without_blinded_payment_paths_for_offer() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	// Clearing route_blinding prevents forming any payment paths since the node is unannounced.
	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.clear_route_blinding();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let offer = alice.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();

	let payment_id = PaymentId([1; 32]);
	david.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();

	connect_peers(david, bob);

	let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(david_id, &onion_message);

	connect_peers(alice, charlie);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
	charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	david.onion_messenger.handle_onion_message(charlie_id, &onion_message);

	let invoice_error = extract_invoice_error(david, &onion_message);
	assert_eq!(invoice_error, InvoiceError::from(Bolt12SemanticError::MissingPaths));

	// Confirm that david drops this failed payment from his pending outbound payments.
	match get_event!(david, Event::PaymentFailed) {
		Event::PaymentFailed { payment_id: actual_payment_id, reason, .. } => {
			assert_eq!(payment_id, actual_payment_id);
			assert_eq!(reason, Some(PaymentFailureReason::InvoiceRequestRejected));
		},
		_ => panic!("No Event::PaymentFailed"),
	}
}

#[test]
fn fails_sending_invoice_without_blinded_payment_paths_for_refund() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	// Clearing route_blinding prevents forming any payment paths since the node is unannounced.
	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.clear_route_blinding();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	let refund = david.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();

	match alice.node.request_refund_payment(&refund) {
		Ok(_) => panic!("Expected error"),
		Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
	}
}

#[test]
fn fails_paying_invoice_more_than_once() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let absolute_expiry = Duration::from_secs(u64::MAX);
	let payment_id = PaymentId([1; 32]);
	let refund = david.node
		.create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), RouteParametersConfig::default())
		.unwrap()
		.build().unwrap();
	expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);

	// Alice sends the first invoice
	alice.node.request_refund_payment(&refund).unwrap();

	connect_peers(alice, charlie);

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
	charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	david.onion_messenger.handle_onion_message(charlie_id, &onion_message);

	// David initiates paying the first invoice
	let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
	let (invoice1, _) = extract_invoice(david, &onion_message);

	route_bolt12_payment(david, &[charlie, bob, alice], &invoice1);
	expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);

	disconnect_peers(alice, &[charlie]);

	// Alice sends the second invoice
	alice.node.request_refund_payment(&refund).unwrap();

	connect_peers(alice, charlie);
	connect_peers(david, bob);

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
	charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	david.onion_messenger.handle_onion_message(charlie_id, &onion_message);

	let (invoice2, _) = extract_invoice(david, &onion_message);
	assert_eq!(invoice1.payer_metadata(), invoice2.payer_metadata());

	// David doesn't initiate paying the second invoice
	assert!(david.onion_messenger.next_onion_message_for_peer(bob_id).is_none());
	assert!(david.node.get_and_clear_pending_msg_events().is_empty());

	// Complete paying the first invoice
	claim_bolt12_payment(david, &[charlie, bob, alice], payment_context, &invoice1);
	expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
}

#[test]
fn fails_paying_invoice_with_unknown_required_features() {
	let mut accept_forward_cfg = test_default_channel_config();
	accept_forward_cfg.accept_forwards_to_priv_channels = true;

	// Clearing route_blinding prevents forming any payment paths since the node is unannounced.
	let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
	features.set_onion_messages_optional();
	features.set_route_blinding_optional();

	let chanmon_cfgs = create_chanmon_cfgs(6);
	let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);

	*node_cfgs[1].override_init_features.borrow_mut() = Some(features);

	let node_chanmgrs = create_node_chanmgrs(
		6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
	);
	let nodes = create_network(6, &node_cfgs, &node_chanmgrs);

	create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
	create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
	create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);

	let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
	let alice_id = alice.node.get_our_node_id();
	let bob_id = bob.node.get_our_node_id();
	let charlie_id = charlie.node.get_our_node_id();
	let david_id = david.node.get_our_node_id();

	disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
	disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);

	let offer = alice.node
		.create_offer_builder().unwrap()
		.amount_msats(10_000_000)
		.build().unwrap();

	let payment_id = PaymentId([1; 32]);
	david.node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();

	connect_peers(david, bob);

	let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	bob.onion_messenger.handle_onion_message(david_id, &onion_message);

	connect_peers(alice, charlie);

	let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	alice.onion_messenger.handle_onion_message(bob_id, &onion_message);

	let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
	let nonce = extract_offer_nonce(alice, &onion_message);

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
	charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

	// Drop the invoice in favor for one with unknown required features.
	let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	let (invoice, _) = extract_invoice(david, &onion_message);

	let payment_paths = invoice.payment_paths().to_vec();
	let payment_hash = invoice.payment_hash();

	let expanded_key = alice.keys_manager.get_expanded_key();
	let secp_ctx = Secp256k1::new();

	let created_at = alice.node.duration_since_epoch();
	let invoice = invoice_request
		.verify_using_recipient_data(nonce, &expanded_key, &secp_ctx).unwrap()
		.respond_using_derived_keys_no_std(payment_paths, payment_hash, created_at).unwrap()
		.features_unchecked(Bolt12InvoiceFeatures::unknown())
		.build_and_sign(&secp_ctx).unwrap();

	// Enqueue an onion message containing the new invoice.
	let instructions = MessageSendInstructions::WithoutReplyPath {
		destination: Destination::BlindedPath(reply_path),
	};
	let message = OffersMessage::Invoice(invoice);
	alice.node.flow.pending_offers_messages.lock().unwrap().push((message, instructions));

	let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
	charlie.onion_messenger.handle_onion_message(alice_id, &onion_message);

	let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
	david.onion_messenger.handle_onion_message(charlie_id, &onion_message);

	// Confirm that david drops this failed payment from his pending outbound payments.
	match get_event!(david, Event::PaymentFailed) {
		Event::PaymentFailed {
			payment_id: event_payment_id,
			payment_hash: Some(event_payment_hash),
			reason: Some(event_reason),
		} => {
			assert_eq!(event_payment_id, payment_id);
			assert_eq!(event_payment_hash, payment_hash);
			assert_eq!(event_reason, PaymentFailureReason::UnknownRequiredFeatures);
		},
		_ => panic!("Expected Event::PaymentFailed with reason"),
	}
}

#[test]
fn rejects_keysend_to_non_static_invoice_path() {
	// Test that we'll fail a keysend payment that was sent over a non-static BOLT 12 invoice path.
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);

	// First pay the offer and save the payment preimage and invoice.
	let offer = nodes[1].node.create_offer_builder().unwrap().build().unwrap();
	let amt_msat = 5000;
	let payment_id = PaymentId([1; 32]);
	nodes[0].node.pay_for_offer(&offer, Some(amt_msat), payment_id, Default::default()).unwrap();
	let invreq_om = nodes[0].onion_messenger.next_onion_message_for_peer(nodes[1].node.get_our_node_id()).unwrap();
	nodes[1].onion_messenger.handle_onion_message(nodes[0].node.get_our_node_id(), &invreq_om);
	let invoice_om = nodes[1].onion_messenger.next_onion_message_for_peer(nodes[0].node.get_our_node_id()).unwrap();
	let invoice = extract_invoice(&nodes[0], &invoice_om).0;
	nodes[0].onion_messenger.handle_onion_message(nodes[1].node.get_our_node_id(), &invoice_om);

	route_bolt12_payment(&nodes[0], &[&nodes[1]], &invoice);
	expect_recent_payment!(nodes[0], RecentPaymentDetails::Pending, payment_id);

	let payment_preimage = match get_event!(nodes[1], Event::PaymentClaimable) {
		Event::PaymentClaimable { purpose, .. } => purpose.preimage().unwrap(),
		_ => panic!()
	};

	claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
	expect_recent_payment!(&nodes[0], RecentPaymentDetails::Fulfilled, payment_id);

	// Time out the payment from recent payments so we can attempt to pay it again via keysend.
	for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
		nodes[0].node.timer_tick_occurred();
		nodes[1].node.timer_tick_occurred();
	}

	// Pay the invoice via keysend now that we have the preimage and make sure the recipient fails it
	// due to incorrect payment context.
	let pay_params = PaymentParameters::from_bolt12_invoice(&invoice);
	let route_params = RouteParameters::from_payment_params_and_value(pay_params, amt_msat);
	let keysend_payment_id = PaymentId([2; 32]);
	let payment_hash = nodes[0].node.send_spontaneous_payment(
		Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), keysend_payment_id,
		route_params, Retry::Attempts(0)
	).unwrap();
	check_added_monitors!(nodes[0], 1);
	let mut events = nodes[0].node.get_and_clear_pending_msg_events();
	assert_eq!(events.len(), 1);
	let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
	let route: &[&[&Node]] = &[&[&nodes[1]]];

	let args = PassAlongPathArgs::new(&nodes[0], route[0], amt_msat, payment_hash, ev)
		.with_payment_preimage(payment_preimage)
		.expect_failure(HTLCHandlingFailureType::Receive { payment_hash });
	do_pass_along_path(args);
	let mut updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
	nodes[0].node.handle_update_fail_htlc(nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
	do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
	expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
}

#[test]
fn no_double_pay_with_stale_channelmanager() {
	// This tests the following bug:
	// - An outbound payment is AwaitingInvoice
	// - We receive an invoice and lock the HTLCs into the relevant ChannelMonitors
	// - The monitors are successfully persisted, but the ChannelManager fails to persist, so the
	//   payment remains AwaitingInvoice
	// - We restart, causing the channels to close due to a stale ChannelManager
	// - We receive a duplicate invoice, and attempt to pay it again due to the payment still being
	//   AwaitingInvoice in the stale ChannelManager
	// After the fix for this, we will notice that the payment is already locked into the monitors on
	// startup and transition the incorrectly-AwaitingInvoice payment to Retryable, which prevents
	// double-paying on duplicate invoice receipt.
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let persister;
	let chain_monitor;
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
	let alice_deserialized;
	let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
	let chan_id_0 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000).2;
	let chan_id_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000).2;

	let alice_id = nodes[0].node.get_our_node_id();
	let bob_id = nodes[1].node.get_our_node_id();

	let amt_msat = nodes[0].node.list_usable_channels()[0].next_outbound_htlc_limit_msat + 1; // Force MPP
	let offer = nodes[1].node
		.create_offer_builder().unwrap()
		.clear_paths()
		.amount_msats(amt_msat)
		.build().unwrap();
	assert_eq!(offer.issuer_signing_pubkey(), Some(bob_id));
	assert!(offer.paths().is_empty());

	let payment_id = PaymentId([1; 32]);
	nodes[0].node.pay_for_offer(&offer, None, payment_id, Default::default()).unwrap();
	expect_recent_payment!(nodes[0], RecentPaymentDetails::AwaitingInvoice, payment_id);

	let invreq_om = nodes[0].onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
	nodes[1].onion_messenger.handle_onion_message(alice_id, &invreq_om);

	// Save the manager while the payment is in state AwaitingInvoice so we can reload it later.
	let alice_chan_manager_serialized = nodes[0].node.encode();

	let invoice_om = nodes[1].onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
	nodes[0].onion_messenger.handle_onion_message(bob_id, &invoice_om);
	let payment_hash = extract_invoice(&nodes[0], &invoice_om).0.payment_hash();

	let expected_route: &[&[&Node]] = &[&[&nodes[1]], &[&nodes[1]]];
	let mut events = nodes[0].node.get_and_clear_pending_msg_events();
	assert_eq!(events.len(), 2);
	check_added_monitors!(nodes[0], 2);

	let ev = remove_first_msg_event_to_node(&bob_id, &mut events);
	let args = PassAlongPathArgs::new(&nodes[0], expected_route[0], amt_msat, payment_hash, ev)
		.without_clearing_recipient_events();
	do_pass_along_path(args);

	let ev = remove_first_msg_event_to_node(&bob_id, &mut events);
	let args = PassAlongPathArgs::new(&nodes[0], expected_route[0], amt_msat, payment_hash, ev)
		.without_clearing_recipient_events();
	do_pass_along_path(args);

	expect_recent_payment!(nodes[0], RecentPaymentDetails::Pending, payment_id);
	match get_event!(nodes[1], Event::PaymentClaimable) {
		Event::PaymentClaimable { .. } => {},
		_ => panic!("No Event::PaymentClaimable"),
	}

	// Reload with the stale manager and check that receiving the invoice again won't result in a
	// duplicate payment attempt.
	let monitor_0 = get_monitor!(nodes[0], chan_id_0).encode();
	let monitor_1 = get_monitor!(nodes[0], chan_id_1).encode();
	reload_node!(nodes[0], &alice_chan_manager_serialized, &[&monitor_0, &monitor_1], persister, chain_monitor, alice_deserialized);
	// The stale manager results in closing the channels.
	check_closed_event!(nodes[0], 2, ClosureReason::OutdatedChannelManager, [bob_id, bob_id], 10_000_000);
	check_added_monitors!(nodes[0], 2);

	// Alice receives a duplicate invoice, but the payment should be transitioned to Retryable by now.
	nodes[0].onion_messenger.handle_onion_message(bob_id, &invoice_om);
	// Previously, Alice would've attempted to pay the invoice a 2nd time. In this test case, this 2nd
	// attempt would have resulted in a PaymentFailed event here, since the only channels between
	// Alice and Bob is closed. Since no 2nd attempt should be made, check that no events are
	// generated in response to the duplicate invoice.
	assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
}