lightning 0.3.0-beta1

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
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
//! Various unit tests covering HTLC handling as well as tests covering channel reserve tracking.

use crate::events::{ClosureReason, Event, HTLCHandlingFailureType, PaymentPurpose};
use crate::ln::chan_utils::{
	self, commit_tx_fee_sat, commitment_tx_base_weight, second_stage_tx_fees_sat,
	shared_anchor_script_pubkey, CommitmentTransaction, HTLCOutputInCommitment,
	COMMITMENT_TX_WEIGHT_PER_HTLC, TRUC_CHILD_MAX_WEIGHT,
};
use crate::ln::channel::{
	get_holder_selected_channel_reserve_satoshis, Channel, ANCHOR_OUTPUT_VALUE_SATOSHI,
	FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT,
	MIN_CHAN_DUST_LIMIT_SATOSHIS,
};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::channelmanager::{PaymentId, RAACommitmentOrder, TrustedChannelFeatures};
use crate::ln::functional_test_utils::*;
use crate::ln::msgs::{self, BaseMessageHandler, ChannelMessageHandler, MessageSendEvent};
use crate::ln::onion_utils::{self, AttributionData};
use crate::ln::outbound_payment::RecipientOnionFields;
use crate::ln::types::ChannelId;
use crate::routing::router::PaymentParameters;
use crate::sign::ecdsa::EcdsaChannelSigner;
use crate::sign::tx_builder::{SpecTxBuilder, TxBuilder};
use crate::sign::ChannelSigner;
use crate::types::features::ChannelTypeFeatures;
use crate::types::payment::{PaymentHash, PaymentPreimage};
use crate::util::config::UserConfig;
use crate::util::errors::APIError;

use lightning_macros::xtest;

use bitcoin::secp256k1::{Secp256k1, SecretKey};
use bitcoin::{Amount, Transaction};

fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
	// A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
	// but only for them. Because some LSPs do it with some level of trust of the clients (for a
	// substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
	// in normal testing, we test it explicitly here.
	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);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let default_config = UserConfig::default();

	// Have node0 initiate a channel to node1 with aforementioned parameters
	let mut push_amt = 100_000_000;
	let feerate_per_kw = 253;
	let channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
	push_amt -= feerate_per_kw as u64
		* (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC)
		/ 1000 * 1000;
	push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, 0, &default_config, false)
		.unwrap()
		* 1000;
	push_amt -= 2 * 330_000;

	let push = if send_from_initiator { 0 } else { push_amt };
	let temp_channel_id =
		nodes[0].node.create_channel(node_b_id, 100_000, push, 42, None, None).unwrap();
	let mut open_channel_message =
		get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id);
	if !send_from_initiator {
		open_channel_message.channel_reserve_satoshis = 0;
		open_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
	}
	handle_and_accept_open_channel(&nodes[1], node_a_id, &open_channel_message);

	// Extract the channel accept message from node1 to node0
	let mut accept_channel_message =
		get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id);
	if send_from_initiator {
		accept_channel_message.channel_reserve_satoshis = 0;
		accept_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
	}
	nodes[0].node.handle_accept_channel(node_b_id, &accept_channel_message);
	{
		let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
		let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
		let mut sender_node_per_peer_lock;
		let mut sender_node_peer_state_lock;

		let channel = get_channel_ref!(
			sender_node,
			counterparty_node,
			sender_node_per_peer_lock,
			sender_node_peer_state_lock,
			temp_channel_id
		);
		assert!(channel.is_unfunded_v1());
		channel.funding_mut().holder_selected_channel_reserve_satoshis = 0;
		channel.context_mut().holder_max_htlc_value_in_flight_msat = 100_000_000;
	}

	let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
	let funding_msgs =
		create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
	create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);

	// nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
	// security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
	if send_from_initiator {
		send_payment(
			&nodes[0],
			&[&nodes[1]],
			100_000_000
				- commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features)
				- 2 * 330_000,
		);
	} else {
		send_payment(&nodes[1], &[&nodes[0]], push_amt);
	}
}

#[xtest(feature = "_externalize_tests")]
pub fn test_counterparty_no_reserve() {
	do_test_counterparty_no_reserve(true);
	do_test_counterparty_no_reserve(false);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_channel_reserve_holding_cell_htlcs() {
	let chanmon_cfgs = create_chanmon_cfgs(3);
	let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
	// When this test was written, the default base fee floated based on the HTLC count.
	// It is now fixed, so we simply set the fee to the expected value here.
	let mut config = test_legacy_channel_config();
	config.channel_config.forwarding_fee_base_msat = 239;

	let configs = [Some(config.clone()), Some(config.clone()), Some(config.clone())];
	let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &configs);
	let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();
	let node_c_id = nodes[2].node.get_our_node_id();

	let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
	let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
	let chan_2_user_id = nodes[2].node.list_channels()[0].user_channel_id;

	let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
	let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);

	let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
	let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);

	macro_rules! expect_forward {
		($node: expr) => {{
			let mut events = $node.node.get_and_clear_pending_msg_events();
			assert_eq!(events.len(), 1);
			check_added_monitors(&$node, 1);
			let payment_event = SendEvent::from_event(events.remove(0));
			payment_event
		}};
	}

	let feemsat = 239; // set above
	let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
	let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
	let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);

	let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;

	// attempt to send amt_msat > their_max_htlc_value_in_flight_msat
	{
		let payment_params = PaymentParameters::from_node_id(node_c_id, TEST_FINAL_CLTV)
			.with_bolt11_features(nodes[2].node.bolt11_invoice_features())
			.unwrap()
			.with_max_channel_saturation_power_of_half(0);
		let (mut route, our_payment_hash, _, our_payment_secret) =
			get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
		route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
		assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));

		let onion = RecipientOnionFields::secret_only(our_payment_secret, route.get_total_amount());
		let id = PaymentId(our_payment_hash.0);
		let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id);
		unwrap_send_err!(nodes[0], res, true, APIError::ChannelUnavailable { .. }, {});
		assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
	}

	// channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
	// nodes[0]'s wealth
	loop {
		let amt_msat = recv_value_0 + total_fee_msat;
		// 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
		// Also, ensure that each payment has enough to be over the dust limit to
		// ensure it'll be included in each commit tx fee calculation.
		let commit_tx_fee_all_htlcs =
			2 * commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
		let ensure_htlc_amounts_above_dust_buffer =
			3 * (stat01.counterparty_dust_limit_msat + 1000);
		if stat01.value_to_self_msat
			< stat01.channel_reserve_msat
				+ commit_tx_fee_all_htlcs
				+ ensure_htlc_amounts_above_dust_buffer
				+ amt_msat
		{
			break;
		}

		let payment_params = PaymentParameters::from_node_id(node_c_id, TEST_FINAL_CLTV)
			.with_bolt11_features(nodes[2].node.bolt11_invoice_features())
			.unwrap()
			.with_max_channel_saturation_power_of_half(0);
		let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
		let (payment_preimage, ..) =
			send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
		claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);

		let (stat01_, stat11_, stat12_, stat22_) = (
			get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
			get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
			get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
			get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
		);

		assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
		assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
		assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
		assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
		stat01 = stat01_;
		stat11 = stat11_;
		stat12 = stat12_;
		stat22 = stat22_;
	}

	// adding pending output.
	// 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
	// The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
	// after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
	// divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
	// to test channel channel reserve policy at the edges of what amount is sendable, i.e.
	// cases where 1 msat over X amount will cause a payment failure, but anything less than
	// that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
	// the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
	// is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
	// policy.
	let commit_tx_fee_2_htlcs = 2 * commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
	let recv_value_1 = (stat01.value_to_self_msat
		- stat01.channel_reserve_msat
		- total_fee_msat
		- commit_tx_fee_2_htlcs)
		/ 2;
	let amt_msat_1 = recv_value_1 + total_fee_msat;

	let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) =
		get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
	let payment_event_1 = {
		let route = route_1.clone();
		let onion = RecipientOnionFields::secret_only(our_payment_secret_1, recv_value_1);
		let id = PaymentId(our_payment_hash_1.0);
		nodes[0].node.send_payment_with_route(route, our_payment_hash_1, onion, id).unwrap();
		check_added_monitors(&nodes[0], 1);

		let mut events = nodes[0].node.get_and_clear_pending_msg_events();
		assert_eq!(events.len(), 1);
		SendEvent::from_event(events.remove(0))
	};
	nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event_1.msgs[0]);

	// channel reserve test with htlc pending output > 0
	let recv_value_2 = stat01.value_to_self_msat
		- amt_msat_1
		- stat01.channel_reserve_msat
		- total_fee_msat
		- commit_tx_fee_2_htlcs;
	{
		let mut route = route_1.clone();
		route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
		let (_, our_payment_hash, our_payment_secret) =
			get_payment_preimage_hash(&nodes[2], None, None);
		let onion = RecipientOnionFields::secret_only(our_payment_secret, route.get_total_amount());
		let id = PaymentId(our_payment_hash.0);
		let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id);
		unwrap_send_err!(nodes[0], res, true, APIError::ChannelUnavailable { .. }, {});
		assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
	}

	// split the rest to test holding cell
	let commit_tx_fee_3_htlcs = 2 * commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
	let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
	let recv_value_21 = recv_value_2 / 2 - additional_htlc_cost_msat / 2;
	let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
	{
		let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
		assert_eq!(
			stat.value_to_self_msat
				- (stat.pending_outbound_htlcs_amount_msat
					+ recv_value_21 + recv_value_22
					+ total_fee_msat + total_fee_msat
					+ commit_tx_fee_3_htlcs),
			stat.channel_reserve_msat
		);
	}

	// now see if they go through on both sides
	let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) =
		get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
	// but this will stuck in the holding cell
	let onion = RecipientOnionFields::secret_only(our_payment_secret_21, recv_value_21);
	let id = PaymentId(our_payment_hash_21.0);
	nodes[0].node.send_payment_with_route(route_21, our_payment_hash_21, onion, id).unwrap();
	check_added_monitors(&nodes[0], 0);
	let events = nodes[0].node.get_and_clear_pending_events();
	assert_eq!(events.len(), 0);

	// test with outbound holding cell amount > 0
	{
		let (mut route, our_payment_hash, _, our_payment_secret) =
			get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
		route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
		let onion = RecipientOnionFields::secret_only(our_payment_secret, route.get_total_amount());
		let id = PaymentId(our_payment_hash.0);
		let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id);
		unwrap_send_err!(nodes[0], res, true, APIError::ChannelUnavailable { .. }, {});
		assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
	}

	let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) =
		get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
	// this will also stuck in the holding cell
	let onion = RecipientOnionFields::secret_only(our_payment_secret_22, recv_value_22);
	let id = PaymentId(our_payment_hash_22.0);
	nodes[0].node.send_payment_with_route(route_22, our_payment_hash_22, onion, id).unwrap();
	check_added_monitors(&nodes[0], 0);
	assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
	assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());

	// flush the pending htlc
	nodes[1].node.handle_commitment_signed_batch_test(node_a_id, &payment_event_1.commitment_msg);
	let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs(&nodes[1], &node_a_id);
	check_added_monitors(&nodes[1], 1);

	// the pending htlc should be promoted to committed
	nodes[0].node.handle_revoke_and_ack(node_b_id, &as_revoke_and_ack);
	check_added_monitors(&nodes[0], 1);
	let commitment_update_2 = get_htlc_update_msgs(&nodes[0], &node_b_id);

	nodes[0].node.handle_commitment_signed_batch_test(node_b_id, &as_commitment_signed);
	let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, node_b_id);
	// No commitment_signed so get_event_msg's assert(len == 1) passes
	check_added_monitors(&nodes[0], 1);

	nodes[1].node.handle_revoke_and_ack(node_a_id, &bs_revoke_and_ack);
	assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
	check_added_monitors(&nodes[1], 1);

	expect_and_process_pending_htlcs(&nodes[1], false);

	let ref payment_event_11 = expect_forward!(nodes[1]);
	nodes[2].node.handle_update_add_htlc(node_b_id, &payment_event_11.msgs[0]);
	let commitment = &payment_event_11.commitment_msg;
	do_commitment_signed_dance(&nodes[2], &nodes[1], commitment, false, false);

	expect_and_process_pending_htlcs(&nodes[2], false);
	expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);

	// flush the htlcs in the holding cell
	assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
	nodes[1].node.handle_update_add_htlc(node_a_id, &commitment_update_2.update_add_htlcs[0]);
	nodes[1].node.handle_update_add_htlc(node_a_id, &commitment_update_2.update_add_htlcs[1]);
	let commitment = &commitment_update_2.commitment_signed;
	do_commitment_signed_dance(&nodes[1], &nodes[0], commitment, false, false);
	expect_and_process_pending_htlcs(&nodes[1], false);

	let ref payment_event_3 = expect_forward!(nodes[1]);
	assert_eq!(payment_event_3.msgs.len(), 2);
	nodes[2].node.handle_update_add_htlc(node_b_id, &payment_event_3.msgs[0]);
	nodes[2].node.handle_update_add_htlc(node_b_id, &payment_event_3.msgs[1]);

	do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_3.commitment_msg, false, false);
	expect_and_process_pending_htlcs(&nodes[2], false);

	let events = nodes[2].node.get_and_clear_pending_events();
	assert_eq!(events.len(), 2);
	match events[0] {
		Event::PaymentClaimable {
			ref payment_hash,
			ref purpose,
			amount_msat,
			receiver_node_id,
			ref receiving_channel_ids,
			..
		} => {
			assert_eq!(our_payment_hash_21, *payment_hash);
			assert_eq!(recv_value_21, amount_msat);
			assert_eq!(node_c_id, receiver_node_id.unwrap());
			assert_eq!(*receiving_channel_ids, vec![(chan_2.2, Some(chan_2_user_id))]);
			match &purpose {
				PaymentPurpose::Bolt11InvoicePayment {
					payment_preimage, payment_secret, ..
				} => {
					assert!(payment_preimage.is_none());
					assert_eq!(our_payment_secret_21, *payment_secret);
				},
				_ => panic!("expected PaymentPurpose::Bolt11InvoicePayment"),
			}
		},
		_ => panic!("Unexpected event"),
	}
	match events[1] {
		Event::PaymentClaimable {
			ref payment_hash,
			ref purpose,
			amount_msat,
			receiver_node_id,
			ref receiving_channel_ids,
			..
		} => {
			assert_eq!(our_payment_hash_22, *payment_hash);
			assert_eq!(recv_value_22, amount_msat);
			assert_eq!(node_c_id, receiver_node_id.unwrap());
			assert_eq!(*receiving_channel_ids, vec![(chan_2.2, Some(chan_2_user_id))]);
			match &purpose {
				PaymentPurpose::Bolt11InvoicePayment {
					payment_preimage, payment_secret, ..
				} => {
					assert!(payment_preimage.is_none());
					assert_eq!(our_payment_secret_22, *payment_secret);
				},
				_ => panic!("expected PaymentPurpose::Bolt11InvoicePayment"),
			}
		},
		_ => panic!("Unexpected event"),
	}

	claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage_1);
	claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage_21);
	claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage_22);

	let commit_tx_fee_0_htlcs = 2 * commit_tx_fee_msat(feerate, 1, &channel_type_features);
	let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
	send_payment(&nodes[0], &[&nodes[1], &nodes[2]], recv_value_3);

	let commit_tx_fee_1_htlc = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
	let expected_value_to_self = stat01.value_to_self_msat
		- (recv_value_1 + total_fee_msat)
		- (recv_value_21 + total_fee_msat)
		- (recv_value_22 + total_fee_msat)
		- (recv_value_3 + total_fee_msat);
	let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
	assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
	assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);

	let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
	assert_eq!(
		stat2.value_to_self_msat,
		stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3
	);
}

#[xtest(feature = "_externalize_tests")]
pub fn channel_reserve_in_flight_removes() {
	// In cases where one side claims an HTLC, it thinks it has additional available funds that it
	// can send to its counterparty, but due to update ordering, the other side may not yet have
	// considered those HTLCs fully removed.
	// This tests that we don't count HTLCs which will not be included in the next remote
	// commitment transaction towards the reserve value (as it implies no commitment transaction
	// will be generated which violates the remote reserve value).
	// This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
	// To test this we:
	//  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
	//    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
	//    you only consider the value of the first HTLC, it may not),
	//  * start routing a third HTLC from A to B,
	//  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
	//    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
	//  * deliver the first fulfill from B
	//  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
	//    claim,
	//  * deliver A's response CS and RAA.
	//    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
	//    removed it fully. B now has the push_msat plus the first two HTLCs in value.
	//  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
	//    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);

	let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
	// Route the first two HTLCs.
	let payment_value_1 =
		b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
	let (payment_preimage_1, payment_hash_1, ..) =
		route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
	let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);

	// Start routing the third HTLC (this is just used to get everyone in the right state).
	let (route, payment_hash_3, payment_preimage_3, payment_secret_3) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
	let send_1 = {
		let onion = RecipientOnionFields::secret_only(payment_secret_3, 100000);
		let id = PaymentId(payment_hash_3.0);
		nodes[0].node.send_payment_with_route(route, payment_hash_3, onion, id).unwrap();
		check_added_monitors(&nodes[0], 1);
		let mut events = nodes[0].node.get_and_clear_pending_msg_events();
		assert_eq!(events.len(), 1);
		SendEvent::from_event(events.remove(0))
	};

	// Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
	// initial fulfill/CS.
	nodes[1].node.claim_funds(payment_preimage_1);
	expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
	check_added_monitors(&nodes[1], 1);
	let mut bs_removes = get_htlc_update_msgs(&nodes[1], &node_a_id);

	// This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
	// remove the second HTLC when we send the HTLC back from B to A.
	nodes[1].node.claim_funds(payment_preimage_2);
	expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
	check_added_monitors(&nodes[1], 1);
	assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());

	nodes[0].node.handle_update_fulfill_htlc(node_b_id, bs_removes.update_fulfill_htlcs.remove(0));
	nodes[0].node.handle_commitment_signed_batch_test(node_b_id, &bs_removes.commitment_signed);
	check_added_monitors(&nodes[0], 1);
	let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, node_b_id);
	expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);

	nodes[1].node.handle_update_add_htlc(node_a_id, &send_1.msgs[0]);
	nodes[1].node.handle_commitment_signed_batch_test(node_a_id, &send_1.commitment_msg);
	check_added_monitors(&nodes[1], 1);
	// B is already AwaitingRAA, so cant generate a CS here
	let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, node_a_id);

	nodes[1].node.handle_revoke_and_ack(node_a_id, &as_raa);
	check_added_monitors(&nodes[1], 1);
	let mut bs_cs = get_htlc_update_msgs(&nodes[1], &node_a_id);

	nodes[0].node.handle_revoke_and_ack(node_b_id, &bs_raa);
	check_added_monitors(&nodes[0], 1);
	let as_cs = get_htlc_update_msgs(&nodes[0], &node_b_id);

	nodes[1].node.handle_commitment_signed_batch_test(node_a_id, &as_cs.commitment_signed);
	check_added_monitors(&nodes[1], 1);
	let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, node_a_id);

	// The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
	// RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
	// However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
	// can no longer broadcast a commitment transaction with it and B has the preimage so can go
	// on-chain as necessary).
	nodes[0].node.handle_update_fulfill_htlc(node_b_id, bs_cs.update_fulfill_htlcs.remove(0));
	nodes[0].node.handle_commitment_signed_batch_test(node_b_id, &bs_cs.commitment_signed);
	check_added_monitors(&nodes[0], 1);
	let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, node_b_id);
	expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);

	nodes[1].node.handle_revoke_and_ack(node_a_id, &as_raa);
	check_added_monitors(&nodes[1], 1);
	assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());

	expect_and_process_pending_htlcs(&nodes[1], false);
	expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);

	// Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
	// resolve the second HTLC from A's point of view.
	nodes[0].node.handle_revoke_and_ack(node_b_id, &bs_raa);
	check_added_monitors(&nodes[0], 1);
	expect_payment_path_successful!(nodes[0]);
	let as_cs = get_htlc_update_msgs(&nodes[0], &node_b_id);

	// Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
	// to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
	let (route, payment_hash_4, payment_preimage_4, payment_secret_4) =
		get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
	let send_2 = {
		let onion = RecipientOnionFields::secret_only(payment_secret_4, 10000);
		let id = PaymentId(payment_hash_4.0);
		nodes[1].node.send_payment_with_route(route, payment_hash_4, onion, id).unwrap();
		check_added_monitors(&nodes[1], 1);
		let mut events = nodes[1].node.get_and_clear_pending_msg_events();
		assert_eq!(events.len(), 1);
		SendEvent::from_event(events.remove(0))
	};

	nodes[0].node.handle_update_add_htlc(node_b_id, &send_2.msgs[0]);
	nodes[0].node.handle_commitment_signed_batch_test(node_b_id, &send_2.commitment_msg);
	check_added_monitors(&nodes[0], 1);
	let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, node_b_id);

	// Now just resolve all the outstanding messages/HTLCs for completeness...

	nodes[1].node.handle_commitment_signed_batch_test(node_a_id, &as_cs.commitment_signed);
	check_added_monitors(&nodes[1], 1);
	let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, node_a_id);

	nodes[1].node.handle_revoke_and_ack(node_a_id, &as_raa);
	check_added_monitors(&nodes[1], 1);

	nodes[0].node.handle_revoke_and_ack(node_b_id, &bs_raa);
	check_added_monitors(&nodes[0], 1);
	expect_payment_path_successful!(nodes[0]);
	let as_cs = get_htlc_update_msgs(&nodes[0], &node_b_id);

	nodes[1].node.handle_commitment_signed_batch_test(node_a_id, &as_cs.commitment_signed);
	check_added_monitors(&nodes[1], 1);
	let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, node_a_id);

	nodes[0].node.handle_revoke_and_ack(node_b_id, &bs_raa);
	check_added_monitors(&nodes[0], 1);

	expect_and_process_pending_htlcs(&nodes[0], false);
	expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);

	claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
	claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
}

#[xtest(feature = "_externalize_tests")]
pub fn holding_cell_htlc_counting() {
	// Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
	// to ensure we don't end up with HTLCs sitting around in our holding cell for several
	// commitment dance rounds.
	let chanmon_cfgs = create_chanmon_cfgs(3);
	let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
	let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();
	let node_c_id = nodes[2].node.get_our_node_id();

	create_announced_chan_between_nodes(&nodes, 0, 1);
	let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);

	// Fetch a route in advance as we will be unable to once we're unable to send.
	let (route, payment_hash_1, _, payment_secret_1) =
		get_route_and_payment_hash!(nodes[1], nodes[2], 100000);

	let mut payments = Vec::new();
	for _ in 0..50 {
		let (route, payment_hash, payment_preimage, payment_secret) =
			get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
		let onion = RecipientOnionFields::secret_only(payment_secret, 100000);
		let id = PaymentId(payment_hash.0);
		nodes[1].node.send_payment_with_route(route, payment_hash, onion, id).unwrap();
		payments.push((payment_preimage, payment_hash));
	}
	check_added_monitors(&nodes[1], 1);

	let mut events = nodes[1].node.get_and_clear_pending_msg_events();
	assert_eq!(events.len(), 1);
	let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
	assert_eq!(initial_payment_event.node_id, node_c_id);

	// There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
	// the holding cell waiting on B's RAA to send. At this point we should not be able to add
	// another HTLC.
	{
		let onion = RecipientOnionFields::secret_only(payment_secret_1, 100000);
		let id = PaymentId(payment_hash_1.0);
		let res = nodes[1].node.send_payment_with_route(route, payment_hash_1, onion, id);
		unwrap_send_err!(nodes[1], res, true, APIError::ChannelUnavailable { .. }, {});
		assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
	}

	// This should also be true if we try to forward a payment.
	let (route, payment_hash_2, _, payment_secret_2) =
		get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
	let onion = RecipientOnionFields::secret_only(payment_secret_2, 100000);
	let id = PaymentId(payment_hash_2.0);
	nodes[0].node.send_payment_with_route(route, payment_hash_2, onion, id).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 payment_event = SendEvent::from_event(events.pop().unwrap());
	assert_eq!(payment_event.node_id, node_b_id);

	nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]);
	do_commitment_signed_dance(&nodes[1], &nodes[0], &payment_event.commitment_msg, false, false);
	// We have to forward pending HTLCs twice - once tries to forward the payment forward (and
	// fails), the second will process the resulting failure and fail the HTLC backward.
	expect_and_process_pending_htlcs(&nodes[1], true);
	let fail = HTLCHandlingFailureType::Forward { node_id: Some(node_c_id), channel_id: chan_2.2 };
	let events = nodes[1].node.get_and_clear_pending_events();
	expect_htlc_failure_conditions(events, &[fail]);
	check_added_monitors(&nodes[1], 1);

	let bs_fail_updates = get_htlc_update_msgs(&nodes[1], &node_a_id);
	nodes[0].node.handle_update_fail_htlc(node_b_id, &bs_fail_updates.update_fail_htlcs[0]);
	let commitment = &bs_fail_updates.commitment_signed;
	do_commitment_signed_dance(&nodes[0], &nodes[1], commitment, false, true);

	let failing_scid = chan_2.0.contents.short_channel_id;
	expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, failing_scid, false);

	// Now forward all the pending HTLCs and claim them back
	nodes[2].node.handle_update_add_htlc(node_b_id, &initial_payment_event.msgs[0]);
	nodes[2]
		.node
		.handle_commitment_signed_batch_test(node_b_id, &initial_payment_event.commitment_msg);
	check_added_monitors(&nodes[2], 1);

	let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs(&nodes[2], &node_b_id);
	nodes[1].node.handle_revoke_and_ack(node_c_id, &bs_revoke_and_ack);
	check_added_monitors(&nodes[1], 1);
	let as_updates = get_htlc_update_msgs(&nodes[1], &node_c_id);

	nodes[1].node.handle_commitment_signed_batch_test(node_c_id, &bs_commitment_signed);
	check_added_monitors(&nodes[1], 1);
	let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, node_c_id);

	for ref update in as_updates.update_add_htlcs.iter() {
		nodes[2].node.handle_update_add_htlc(node_b_id, update);
	}
	nodes[2].node.handle_commitment_signed_batch_test(node_b_id, &as_updates.commitment_signed);
	check_added_monitors(&nodes[2], 1);
	nodes[2].node.handle_revoke_and_ack(node_b_id, &as_raa);
	check_added_monitors(&nodes[2], 1);
	let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs(&nodes[2], &node_b_id);

	nodes[1].node.handle_revoke_and_ack(node_c_id, &bs_revoke_and_ack);
	check_added_monitors(&nodes[1], 1);
	nodes[1].node.handle_commitment_signed_batch_test(node_c_id, &bs_commitment_signed);
	check_added_monitors(&nodes[1], 1);
	let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, node_c_id);

	nodes[2].node.handle_revoke_and_ack(node_b_id, &as_final_raa);
	check_added_monitors(&nodes[2], 1);

	expect_and_process_pending_htlcs(&nodes[2], false);

	let events = nodes[2].node.get_and_clear_pending_events();
	assert_eq!(events.len(), payments.len());
	for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
		match event {
			&Event::PaymentClaimable { ref payment_hash, .. } => {
				assert_eq!(*payment_hash, *hash);
			},
			_ => panic!("Unexpected event"),
		};
	}

	for (preimage, _) in payments.drain(..) {
		claim_payment(&nodes[1], &[&nodes[2]], preimage);
	}

	send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_basic_channel_reserve() {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let legacy_cfg = test_legacy_channel_config();
	let node_chanmgrs =
		create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]);
	let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);

	let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
	let channel_reserve = chan_stat.channel_reserve_msat;

	// The 2* and +1 are for the fee spike reserve.
	let commit_tx_fee = 2 * commit_tx_fee_msat(
		get_feerate!(nodes[0], nodes[1], chan.2),
		1 + 1,
		&get_channel_type_features!(nodes[0], nodes[1], chan.2),
	);
	let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
	let (mut route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
	route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
	let onion = RecipientOnionFields::secret_only(our_payment_secret, max_can_send + 1);
	let id = PaymentId(our_payment_hash.0);
	let err = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id);
	unwrap_send_err!(nodes[0], err, true, APIError::ChannelUnavailable { .. }, {});
	assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());

	send_payment(&nodes[0], &[&nodes[1]], max_can_send);
}

#[xtest(feature = "_externalize_tests")]
fn test_fee_spike_violation_fails_htlc() {
	let cfg = test_legacy_channel_config();
	do_test_fee_spike_buffer(Some(cfg), true)
}

#[test]
fn test_zero_fee_commitments_no_fee_spike_buffer() {
	let mut cfg = test_default_channel_config();
	cfg.channel_handshake_config.negotiate_anchor_zero_fee_commitments = true;

	do_test_fee_spike_buffer(Some(cfg), false)
}

pub fn do_test_fee_spike_buffer(cfg: Option<UserConfig>, htlc_fails: bool) {
	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, &[cfg.clone(), cfg]);
	let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let chan_amt_sat = 100000;
	let push_amt_msat = 95000000;
	let chan =
		create_announced_chan_between_nodes_with_value(&nodes, 0, 1, chan_amt_sat, push_amt_msat);

	let (mut route, payment_hash, _, payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
	route.paths[0].hops[0].fee_msat += 1;
	// Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
	let secp_ctx = Secp256k1::new();
	let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");

	let cur_height = nodes[1].node.best_block.read().unwrap().height + 1;

	let payment_amt_msat = 3460001;
	let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv);
	let recipient_onion_fields =
		RecipientOnionFields::secret_only(payment_secret, payment_amt_msat);
	let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::test_build_onion_payloads(
		&route.paths[0],
		&recipient_onion_fields,
		cur_height,
		&None,
		None,
		None,
	)
	.unwrap();
	let onion_packet =
		onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash)
			.unwrap();
	let msg = msgs::UpdateAddHTLC {
		channel_id: chan.2,
		htlc_id: 0,
		amount_msat: htlc_msat,
		payment_hash,
		cltv_expiry: htlc_cltv,
		onion_routing_packet: onion_packet,
		skimmed_fee_msat: None,
		blinding_point: None,
		hold_htlc: None,
		accountable: None,
	};

	nodes[1].node.handle_update_add_htlc(node_a_id, &msg);

	// Now manually create the commitment_signed message corresponding to the update_add
	// nodes[0] just sent. In the code for construction of this message, "local" refers
	// to the sender of the message, and "remote" refers to the receiver.

	let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);

	const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;

	let (local_secret, next_local_point) = {
		let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
		let chan_lock = per_peer_state.get(&node_b_id).unwrap().lock().unwrap();
		let local_chan = chan_lock.channel_by_id.get(&chan.2).and_then(Channel::as_funded).unwrap();
		let chan_signer = local_chan.get_signer();
		// Make the signer believe we validated another commitment, so we can release the secret
		chan_signer.get_enforcement_state().last_holder_commitment -= 1;

		(
			chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER).unwrap(),
			chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx).unwrap(),
		)
	};
	let remote_point = {
		let per_peer_lock;
		let mut peer_state_lock;

		let channel = get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, chan.2);
		let chan_signer = channel.as_funded().unwrap().get_signer();
		chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx).unwrap()
	};

	// Build the remote commitment transaction so we can sign it, and then later use the
	// signature for the commitment_signed message.
	let accepted_htlc_info = HTLCOutputInCommitment {
		offered: false,
		amount_msat: payment_amt_msat,
		cltv_expiry: htlc_cltv,
		payment_hash,
		transaction_output_index: Some(1),
	};

	let local_chan_balance_msat = chan_amt_sat * 1000 - push_amt_msat;
	let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;

	let res = {
		let per_peer_lock;
		let mut peer_state_lock;

		let channel = get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan.2);
		let chan_signer = channel.as_funded().unwrap().get_signer();

		let (commitment_tx, _stats) = SpecTxBuilder {}.build_commitment_transaction(
			false,
			commitment_number,
			&remote_point,
			&channel.funding().channel_transaction_parameters,
			&secp_ctx,
			local_chan_balance_msat,
			vec![accepted_htlc_info],
			feerate_per_kw,
			MIN_CHAN_DUST_LIMIT_SATOSHIS,
			&nodes[0].logger,
		);
		let params = &channel.funding().channel_transaction_parameters;
		chan_signer
			.sign_counterparty_commitment(params, &commitment_tx, Vec::new(), Vec::new(), &secp_ctx)
			.unwrap()
	};

	let commit_signed_msg = msgs::CommitmentSigned {
		channel_id: chan.2,
		signature: res.0,
		htlc_signatures: res.1,
		funding_txid: None,
	};

	// Send the commitment_signed message to the nodes[1].
	nodes[1].node.handle_commitment_signed(node_a_id, &commit_signed_msg);
	let _ = nodes[1].node.get_and_clear_pending_msg_events();

	// Send the RAA to nodes[1].
	let raa_msg = msgs::RevokeAndACK {
		channel_id: chan.2,
		per_commitment_secret: local_secret,
		next_per_commitment_point: next_local_point,
		release_htlc_message_paths: Vec::new(),
	};
	nodes[1].node.handle_revoke_and_ack(node_a_id, &raa_msg);
	expect_and_process_pending_htlcs(&nodes[1], false);

	if htlc_fails {
		expect_htlc_handling_failed_destinations!(
			nodes[1].node.get_and_clear_pending_events(),
			&[HTLCHandlingFailureType::Receive { payment_hash }]
		);

		let events = nodes[1].node.get_and_clear_pending_msg_events();
		assert_eq!(events.len(), 1);

		// Make sure the HTLC failed in the way we expect.
		match events[0] {
			MessageSendEvent::UpdateHTLCs {
				updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. },
				..
			} => {
				assert_eq!(update_fail_htlcs.len(), 1);
				update_fail_htlcs[0].clone()
			},
			_ => panic!("Unexpected event"),
		};
		nodes[1].logger.assert_log(
			"lightning::ln::channel",
			"Attempting to fail HTLC due to fee spike buffer violation. Rebalancing is required."
				.to_string(),
			1,
		);

		check_added_monitors(&nodes[1], 3);
	} else {
		expect_payment_claimable!(nodes[1], payment_hash, payment_secret, payment_amt_msat);
		check_added_monitors(&nodes[1], 2);
	}
}

#[xtest(feature = "_externalize_tests")]
pub fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
	let mut chanmon_cfgs = create_chanmon_cfgs(2);
	// Set the fee rate for the channel very high, to the point where the fundee
	// sending any above-dust amount would result in a channel reserve violation.
	// In this test we check that we would be prevented from sending an HTLC in
	// this situation.
	let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let legacy_cfg = test_legacy_channel_config();
	let node_chanmgrs =
		create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]);
	let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let default_config = UserConfig::default();
	let channel_type_features = ChannelTypeFeatures::only_static_remote_key();

	let mut push_amt = 100_000_000;
	push_amt -= commit_tx_fee_msat(
		feerate_per_kw,
		MIN_AFFORDABLE_HTLC_COUNT as u64,
		&channel_type_features,
	);

	push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, 0, &default_config, false)
		.unwrap()
		* 1000;

	let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);

	// Fetch a route in advance as we will be unable to once we're unable to send.
	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
	// Sending exactly enough to hit the reserve amount should be accepted
	for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
		route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
	}

	// However one more HTLC should be significantly over the reserve amount and fail.
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 1_000_000);
	let id = PaymentId(our_payment_hash.0);
	let res = nodes[1].node.send_payment_with_route(route, our_payment_hash, onion, id);
	unwrap_send_err!(nodes[1], res, true, APIError::ChannelUnavailable { .. }, {});
	assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
}

#[xtest(feature = "_externalize_tests")]
pub fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
	// Test that if we receive many dust HTLCs over an outbound channel, they don't count when
	// calculating our commitment transaction fee (this was previously broken).
	let mut chanmon_cfgs = create_chanmon_cfgs(2);
	let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();

	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let legacy_cfg = test_legacy_channel_config();
	let node_chanmgrs =
		create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]);
	let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let default_config = UserConfig::default();
	let channel_type_features = ChannelTypeFeatures::only_static_remote_key();

	// Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
	// channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
	// transaction fee with 0 HTLCs (183 sats)).
	let mut push_amt = 100_000_000;
	push_amt -= commit_tx_fee_msat(
		feerate_per_kw,
		MIN_AFFORDABLE_HTLC_COUNT as u64,
		&channel_type_features,
	);
	push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, 0, &default_config, false)
		.unwrap()
		* 1000;
	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);

	let (_htlc_success_tx_fee_sat, htlc_timeout_tx_fee_sat) =
		second_stage_tx_fees_sat(&channel_type_features, feerate_per_kw);
	let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
		+ htlc_timeout_tx_fee_sat * 1000
		- 1;
	// In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
	// reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
	// commitment transaction fee.
	route_payment(&nodes[1], &[&nodes[0]], dust_amt);

	// Send four HTLCs to cover the initial push_msat buffer we're required to include
	for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
		route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
	}

	// One more than the dust amt should fail, however.
	let (mut route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
	route.paths[0].hops[0].fee_msat += 1;
	let onion = RecipientOnionFields::secret_only(our_payment_secret, dust_amt + 1);
	let id = PaymentId(our_payment_hash.0);
	let res = nodes[1].node.send_payment_with_route(route, our_payment_hash, onion, id);
	unwrap_send_err!(nodes[1], res, true, APIError::ChannelUnavailable { .. }, {});
}

#[xtest(feature = "_externalize_tests")]
pub fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
	// Test that if we receive many dust HTLCs over an inbound channel, they don't count when
	// calculating our counterparty's commitment transaction fee (this was previously broken).
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let legacy_cfg = test_legacy_channel_config();
	let node_chanmgrs =
		create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]);
	let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);

	let payment_amt = 46000; // Dust amount

	// In the previous code, these first four payments would succeed.
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);

	// Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);

	// And this last payment previously resulted in nodes[1] closing on its inbound-channel
	// counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
	// transaction fee and therefore perceived this next payment as a channel reserve violation.
	route_payment(&nodes[0], &[&nodes[1]], payment_amt);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
	let chanmon_cfgs = create_chanmon_cfgs(3);
	let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
	let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
	let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();

	let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
	let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);

	let feemsat = 239;
	let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
	let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
	let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
	let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);

	// Add a 2* and +1 for the fee spike reserve.
	let commit_tx_fee_2_htlc = 2 * commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
	let recv_value_1 = (chan_stat.value_to_self_msat
		- chan_stat.channel_reserve_msat
		- total_routing_fee_msat
		- commit_tx_fee_2_htlc)
		/ 2;
	let amt_msat_1 = recv_value_1 + total_routing_fee_msat;

	// Add a pending HTLC.
	let (route_1, our_payment_hash_1, _, our_payment_secret_1) =
		get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
	let payment_event_1 = {
		let onion = RecipientOnionFields::secret_only(our_payment_secret_1, amt_msat_1);
		let id = PaymentId(our_payment_hash_1.0);
		let route = route_1.clone();
		nodes[0].node.send_payment_with_route(route, our_payment_hash_1, onion, id).unwrap();
		check_added_monitors(&nodes[0], 1);

		let mut events = nodes[0].node.get_and_clear_pending_msg_events();
		assert_eq!(events.len(), 1);
		SendEvent::from_event(events.remove(0))
	};
	nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event_1.msgs[0]);

	// Attempt to trigger a channel reserve violation --> payment failure.
	let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
	let recv_value_2 = chan_stat.value_to_self_msat
		- amt_msat_1
		- chan_stat.channel_reserve_msat
		- total_routing_fee_msat
		- commit_tx_fee_2_htlcs
		+ 1;
	let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
	let mut route_2 = route_1.clone();
	route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;

	// Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
	let secp_ctx = Secp256k1::new();
	let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
	let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
	let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv);
	let recipient_onion_fields = RecipientOnionFields::spontaneous_empty(recv_value_2);
	let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::test_build_onion_payloads(
		&route_2.paths[0],
		&recipient_onion_fields,
		cur_height,
		&None,
		None,
		None,
	)
	.unwrap();
	let onion_packet = onion_utils::construct_onion_packet(
		onion_payloads,
		onion_keys,
		[0; 32],
		&our_payment_hash_1,
	)
	.unwrap();
	let msg = msgs::UpdateAddHTLC {
		channel_id: chan.2,
		htlc_id: 1,
		amount_msat: htlc_msat + 1,
		payment_hash: our_payment_hash_1,
		cltv_expiry: htlc_cltv,
		onion_routing_packet: onion_packet,
		skimmed_fee_msat: None,
		blinding_point: None,
		hold_htlc: None,
		accountable: None,
	};

	nodes[1].node.handle_update_add_htlc(node_a_id, &msg);
	// Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
	nodes[1].logger.assert_log_contains(
		"lightning::ln::channelmanager",
		"Remote HTLC add would put them under remote reserve value",
		3,
	);
	assert_eq!(nodes[1].node.list_channels().len(), 1);
	let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap();
	assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
	check_added_monitors(&nodes[1], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data.clone() };
	check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_payment_route_reaching_same_channel_twice() {
	//A route should not go through the same channel twice
	//It is enforced when constructing a route.
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_b_id = nodes[1].node.get_our_node_id();

	let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);

	let payment_params = PaymentParameters::from_node_id(node_b_id, 0)
		.with_bolt11_features(nodes[1].node.bolt11_invoice_features())
		.unwrap();
	let (mut route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);

	// Extend the path by itself, essentially simulating route going through same channel twice
	let cloned_hops = route.paths[0].hops.clone();
	route.paths[0].hops.extend_from_slice(&cloned_hops);

	unwrap_send_err!(nodes[0], nodes[0].node.send_payment_with_route(route, our_payment_hash,
		RecipientOnionFields::secret_only(our_payment_secret, 100000000), PaymentId(our_payment_hash.0)
	), false, APIError::InvalidRoute { ref err },
	assert_eq!(err, &"Path went through the same channel twice"));
	assert!(nodes[0].node.list_recent_payments().is_empty());
}

// BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
// BOLT 2 Requirement: MUST NOT offer amount_msat it cannot pay for in the remote commitment transaction at the current feerate_per_kw (see "Updating Fees") while maintaining its channel reserve.
//TODO: I don't believe this is explicitly enforced when sending an HTLC but as the Fee aspect of the BOLT specs is in flux leaving this as a TODO.

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
	//BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);

	let (mut route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
	route.paths[0].hops[0].fee_msat = 100;

	let onion = RecipientOnionFields::secret_only(our_payment_secret, 100);
	let id = PaymentId(our_payment_hash.0);
	let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id);
	unwrap_send_err!(nodes[0], res, true, APIError::ChannelUnavailable { .. }, {});
	assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
	//BOLT2 Requirement: MUST offer amount_msat greater than 0.
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);

	let (mut route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
	route.paths[0].hops[0].fee_msat = 0;
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 0);
	let id = PaymentId(our_payment_hash.0);
	let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id);
	unwrap_send_err!(nodes[0], res,
		true, APIError::ChannelUnavailable { ref err },
		assert_eq!(err, "Cannot send 0-msat HTLC"));

	assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
	nodes[0].logger.assert_log_contains(
		"lightning::ln::channelmanager",
		"Cannot send 0-msat HTLC",
		2,
	);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
	//BOLT2 Requirement: MUST offer amount_msat greater than 0.
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);

	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 100000);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();
	check_added_monitors(&nodes[0], 1);
	let mut updates = get_htlc_update_msgs(&nodes[0], &node_b_id);
	updates.update_add_htlcs[0].amount_msat = 0;

	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);
	nodes[1].logger.assert_log_contains(
		"lightning::ln::channelmanager",
		"Remote side tried to send a 0-msat HTLC",
		3,
	);
	check_closed_broadcast(&nodes[1], 1, true);
	check_added_monitors(&nodes[1], 1);
	let reason = ClosureReason::ProcessingError {
		err: "Remote side tried to send a 0-msat HTLC".to_string(),
	};
	check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
	//BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
	//It is enforced when constructing a route.
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_b_id = nodes[1].node.get_our_node_id();

	let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);

	let mut payment_params = PaymentParameters::from_node_id(node_b_id, 0)
		.with_bolt11_features(nodes[1].node.bolt11_invoice_features())
		.unwrap();
	payment_params.max_total_cltv_expiry_delta = 500000001;
	let (mut route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
	route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;

	let onion = RecipientOnionFields::secret_only(our_payment_secret, 100000000);
	let id = PaymentId(our_payment_hash.0);
	let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id);
	unwrap_send_err!(nodes[0], res, true, APIError::InvalidRoute { ref err },
		assert_eq!(err, &"Channel CLTV overflowed?"));
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
	//BOLT 2 Requirement: if result would be offering more than the remote's max_accepted_htlcs HTLCs, in the remote commitment transaction: MUST NOT add an HTLC.
	//BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
	//BOLT 2 Requirement: MUST increase the value of id by 1 for each successive 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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();

	let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
	let max_accepted_htlcs = {
		let per_peer_lock;
		let mut peer_state_lock;

		let channel = get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, chan.2);
		channel.context().counterparty_max_accepted_htlcs as u64
	};

	// Fetch a route in advance as we will be unable to once we're unable to send.
	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
	for i in 0..max_accepted_htlcs {
		let (route, our_payment_hash, _, our_payment_secret) =
			get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
		let payment_event = {
			let onion = RecipientOnionFields::secret_only(our_payment_secret, 100000);
			let id = PaymentId(our_payment_hash.0);
			nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();
			check_added_monitors(&nodes[0], 1);

			let mut events = nodes[0].node.get_and_clear_pending_msg_events();
			assert_eq!(events.len(), 1);
			if let MessageSendEvent::UpdateHTLCs {
				updates: msgs::CommitmentUpdate { update_add_htlcs: ref htlcs, .. },
				..
			} = events[0]
			{
				assert_eq!(htlcs[0].htlc_id, i);
			} else {
				assert!(false);
			}
			SendEvent::from_event(events.remove(0))
		};
		nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]);
		check_added_monitors(&nodes[1], 0);
		let commitment = &payment_event.commitment_msg;
		do_commitment_signed_dance(&nodes[1], &nodes[0], commitment, false, false);

		expect_and_process_pending_htlcs(&nodes[1], false);
		expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
	}
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 100000);
	let id = PaymentId(our_payment_hash.0);
	let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id);
	unwrap_send_err!(nodes[0], res, true, APIError::ChannelUnavailable { .. }, {});

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

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
	//BOLT 2 Requirement: if the sum of total offered HTLCs would exceed the remote's max_htlc_value_in_flight_msat: MUST NOT add an HTLC.
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let channel_value = 100000;
	let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
	let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2)
		.counterparty_max_htlc_value_in_flight_msat;

	send_payment(&nodes[0], &[&nodes[1]], max_in_flight);

	let (mut route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
	// Manually create a route over our max in flight (which our router normally automatically
	// limits us to.
	route.paths[0].hops[0].fee_msat = max_in_flight + 1;
	let onion = RecipientOnionFields::secret_only(our_payment_secret, max_in_flight + 1);
	let id = PaymentId(our_payment_hash.0);
	let res = nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id);
	unwrap_send_err!(nodes[0], res, true, APIError::ChannelUnavailable { .. }, {});
	assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());

	send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
}

// BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
	//BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
	let htlc_minimum_msat = {
		let per_peer_lock;
		let mut peer_state_lock;

		let channel = get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan.2);
		channel.context().get_holder_htlc_minimum_msat()
	};

	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
	let onion = RecipientOnionFields::secret_only(our_payment_secret, htlc_minimum_msat);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();
	check_added_monitors(&nodes[0], 1);
	let mut updates = get_htlc_update_msgs(&nodes[0], &node_b_id);
	updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat - 1;
	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);
	assert!(nodes[1].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap();
	assert!(regex::Regex::new(r"Remote side tried to send less than our minimum HTLC value\. Lower limit: \(\d+\)\. Actual: \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
	check_added_monitors(&nodes[1], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
	//BOLT2 Requirement: receiving an amount_msat that the sending node cannot afford at the current feerate_per_kw (while maintaining its channel reserve): SHOULD fail the channel
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let legacy_cfg = test_legacy_channel_config();
	let node_chanmgrs =
		create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]);
	let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);

	let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
	let channel_reserve = chan_stat.channel_reserve_msat;
	let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
	let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
	// The 2* and +1 are for the fee spike reserve.
	let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);

	let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
	let onion = RecipientOnionFields::secret_only(our_payment_secret, max_can_send);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();
	check_added_monitors(&nodes[0], 1);
	let mut updates = get_htlc_update_msgs(&nodes[0], &node_b_id);

	// Even though channel-initiator senders are required to respect the fee_spike_reserve,
	// at this time channel-initiatee receivers are not required to enforce that senders
	// respect the fee_spike_reserve.
	updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);

	assert!(nodes[1].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap();
	assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
	check_added_monitors(&nodes[1], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
	//BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
	//BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();

	let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);

	let send_amt = 3999999;
	let (mut route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
	route.paths[0].hops[0].fee_msat = send_amt;
	let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
	let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
	let onion_keys = onion_utils::construct_onion_keys(
		&Secp256k1::signing_only(),
		&route.paths[0],
		&session_priv,
	);
	let recipient_onion_fields = RecipientOnionFields::secret_only(our_payment_secret, send_amt);
	let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::test_build_onion_payloads(
		&route.paths[0],
		&recipient_onion_fields,
		cur_height,
		&None,
		None,
		None,
	)
	.unwrap();
	let onion_packet =
		onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash)
			.unwrap();

	let mut msg = msgs::UpdateAddHTLC {
		channel_id: chan.2,
		htlc_id: 0,
		amount_msat: 1000,
		payment_hash: our_payment_hash,
		cltv_expiry: htlc_cltv,
		onion_routing_packet: onion_packet.clone(),
		skimmed_fee_msat: None,
		blinding_point: None,
		hold_htlc: None,
		accountable: None,
	};

	for i in 0..50 {
		msg.htlc_id = i as u64;
		nodes[1].node.handle_update_add_htlc(node_a_id, &msg);
	}
	msg.htlc_id = (50) as u64;
	nodes[1].node.handle_update_add_htlc(node_a_id, &msg);

	assert!(nodes[1].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap();
	assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)")
		.unwrap()
		.is_match(err_msg.data.as_str()));
	check_added_monitors(&nodes[1], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
	//OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);

	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 1000000);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();
	check_added_monitors(&nodes[0], 1);
	let mut updates = get_htlc_update_msgs(&nodes[0], &node_b_id);
	updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], nodes[0], chan.2)
		.counterparty_max_htlc_value_in_flight_msat
		+ 1;
	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);

	assert!(nodes[1].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap();
	assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value")
		.unwrap()
		.is_match(err_msg.data.as_str()));
	check_added_monitors(&nodes[1], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[1], 1, reason, &[node_a_id], 1000000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
	//BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
	let reason = RecipientOnionFields::secret_only(our_payment_secret, 1000000);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, reason, id).unwrap();
	check_added_monitors(&nodes[0], 1);
	let mut updates = get_htlc_update_msgs(&nodes[0], &node_b_id);
	updates.update_add_htlcs[0].cltv_expiry = 500000000;
	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);

	assert!(nodes[1].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap();
	assert_eq!(err_msg.data, "Remote provided CLTV expiry in seconds instead of block height");
	check_added_monitors(&nodes[1], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
	//BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
	// We test this by first testing that that repeated HTLCs pass commitment signature checks
	// after disconnect and that non-sequential htlc_ids result in a channel failure.
	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	create_announced_chan_between_nodes(&nodes, 0, 1);
	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 1000000);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();

	check_added_monitors(&nodes[0], 1);
	let updates = get_htlc_update_msgs(&nodes[0], &node_b_id);
	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);

	//Disconnect and Reconnect
	nodes[0].node.peer_disconnected(node_b_id);
	nodes[1].node.peer_disconnected(node_a_id);

	let init_msg = msgs::Init {
		features: nodes[0].node.init_features(),
		networks: None,
		remote_network_address: None,
	};
	nodes[0].node.peer_connected(node_b_id, &init_msg, true).unwrap();
	let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
	assert_eq!(reestablish_1.len(), 1);

	nodes[1].node.peer_connected(node_a_id, &init_msg, false).unwrap();
	let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
	assert_eq!(reestablish_2.len(), 1);

	nodes[0].node.handle_channel_reestablish(node_b_id, &reestablish_2[0]);
	handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
	nodes[1].node.handle_channel_reestablish(node_a_id, &reestablish_1[0]);
	handle_chan_reestablish_msgs!(nodes[1], nodes[0]);

	//Resend HTLC
	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);
	assert_eq!(updates.commitment_signed.len(), 1);
	assert_eq!(updates.commitment_signed[0].htlc_signatures.len(), 1);
	nodes[1].node.handle_commitment_signed_batch_test(node_a_id, &updates.commitment_signed);
	check_added_monitors(&nodes[1], 1);
	let _bs_responses = get_revoke_commit_msgs(&nodes[1], &node_a_id);

	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);

	assert!(nodes[1].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap();
	assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)")
		.unwrap()
		.is_match(err_msg.data.as_str()));
	check_added_monitors(&nodes[1], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[1], 1, reason, &[node_a_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
	//BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:	MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.

	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
	let (route, our_payment_hash, our_payment_preimage, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 1000000);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();

	check_added_monitors(&nodes[0], 1);
	let updates = get_htlc_update_msgs(&nodes[0], &node_b_id);
	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);

	let update_msg = msgs::UpdateFulfillHTLC {
		channel_id: chan.2,
		htlc_id: 0,
		payment_preimage: our_payment_preimage,
		attribution_data: None,
	};

	nodes[0].node.handle_update_fulfill_htlc(node_b_id, update_msg);

	assert!(nodes[0].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap();
	assert!(regex::Regex::new(
		r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed"
	)
	.unwrap()
	.is_match(err_msg.data.as_str()));
	check_added_monitors(&nodes[0], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[0], 1, reason, &[node_b_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
	//BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:	MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.

	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let chan = create_announced_chan_between_nodes(&nodes, 0, 1);

	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 1000000);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();
	check_added_monitors(&nodes[0], 1);
	let updates = get_htlc_update_msgs(&nodes[0], &node_b_id);
	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);

	let update_msg = msgs::UpdateFailHTLC {
		channel_id: chan.2,
		htlc_id: 0,
		reason: Vec::new(),
		attribution_data: Some(AttributionData::new()),
	};

	nodes[0].node.handle_update_fail_htlc(node_b_id, &update_msg);

	assert!(nodes[0].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap();
	assert!(regex::Regex::new(
		r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed"
	)
	.unwrap()
	.is_match(err_msg.data.as_str()));
	check_added_monitors(&nodes[0], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[0], 1, reason, &[node_b_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
	//BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:	MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.

	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let chan = create_announced_chan_between_nodes(&nodes, 0, 1);

	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 1000000);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();
	check_added_monitors(&nodes[0], 1);
	let updates = get_htlc_update_msgs(&nodes[0], &node_b_id);
	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);
	let update_msg = msgs::UpdateFailMalformedHTLC {
		channel_id: chan.2,
		htlc_id: 0,
		sha256_of_onion: [1; 32],
		failure_code: 0x8000,
	};

	nodes[0].node.handle_update_fail_malformed_htlc(node_b_id, &update_msg);

	assert!(nodes[0].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap();
	assert!(regex::Regex::new(
		r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed"
	)
	.unwrap()
	.is_match(err_msg.data.as_str()));
	check_added_monitors(&nodes[0], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[0], 1, reason, &[node_b_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
	//BOLT 2 Requirement: A receiving node:	if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.

	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);

	let node_b_id = nodes[1].node.get_our_node_id();

	create_announced_chan_between_nodes(&nodes, 0, 1);

	let (our_payment_preimage, our_payment_hash, ..) =
		route_payment(&nodes[0], &[&nodes[1]], 100_000);

	nodes[1].node.claim_funds(our_payment_preimage);
	check_added_monitors(&nodes[1], 1);
	expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);

	let events = nodes[1].node.get_and_clear_pending_msg_events();
	assert_eq!(events.len(), 1);
	let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
		match events[0] {
			MessageSendEvent::UpdateHTLCs {
				updates:
					msgs::CommitmentUpdate {
						ref update_add_htlcs,
						ref update_fulfill_htlcs,
						ref update_fail_htlcs,
						ref update_fail_malformed_htlcs,
						ref update_fee,
						..
					},
				..
			} => {
				assert!(update_add_htlcs.is_empty());
				assert_eq!(update_fulfill_htlcs.len(), 1);
				assert!(update_fail_htlcs.is_empty());
				assert!(update_fail_malformed_htlcs.is_empty());
				assert!(update_fee.is_none());
				update_fulfill_htlcs[0].clone()
			},
			_ => panic!("Unexpected event"),
		}
	};

	update_fulfill_msg.htlc_id = 1;

	nodes[0].node.handle_update_fulfill_htlc(node_b_id, update_fulfill_msg);

	assert!(nodes[0].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap();
	assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
	check_added_monitors(&nodes[0], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[0], 1, reason, &[node_b_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
	//BOLT 2 Requirement: A receiving node:	if the payment_preimage value in update_fulfill_htlc doesn't SHA256 hash to the corresponding HTLC payment_hash	MUST fail the channel.

	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);

	let node_b_id = nodes[1].node.get_our_node_id();

	create_announced_chan_between_nodes(&nodes, 0, 1);

	let (our_payment_preimage, our_payment_hash, ..) =
		route_payment(&nodes[0], &[&nodes[1]], 100_000);

	nodes[1].node.claim_funds(our_payment_preimage);
	check_added_monitors(&nodes[1], 1);
	expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);

	let events = nodes[1].node.get_and_clear_pending_msg_events();
	assert_eq!(events.len(), 1);
	let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
		match events[0] {
			MessageSendEvent::UpdateHTLCs {
				updates:
					msgs::CommitmentUpdate {
						ref update_add_htlcs,
						ref update_fulfill_htlcs,
						ref update_fail_htlcs,
						ref update_fail_malformed_htlcs,
						ref update_fee,
						..
					},
				..
			} => {
				assert!(update_add_htlcs.is_empty());
				assert_eq!(update_fulfill_htlcs.len(), 1);
				assert!(update_fail_htlcs.is_empty());
				assert!(update_fail_malformed_htlcs.is_empty());
				assert!(update_fee.is_none());
				update_fulfill_htlcs[0].clone()
			},
			_ => panic!("Unexpected event"),
		}
	};

	update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);

	nodes[0].node.handle_update_fulfill_htlc(node_b_id, update_fulfill_msg);

	assert!(nodes[0].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap();
	assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage")
		.unwrap()
		.is_match(err_msg.data.as_str()));
	check_added_monitors(&nodes[0], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[0], 1, reason, &[node_b_id], 100000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
	//BOLT 2 Requirement: A receiving node: if the BADONION bit in failure_code is not set for update_fail_malformed_htlc MUST fail the channel.

	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);

	let (route, our_payment_hash, _, our_payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
	let onion = RecipientOnionFields::secret_only(our_payment_secret, 1000000);
	let id = PaymentId(our_payment_hash.0);
	nodes[0].node.send_payment_with_route(route, our_payment_hash, onion, id).unwrap();
	check_added_monitors(&nodes[0], 1);

	let mut updates = get_htlc_update_msgs(&nodes[0], &node_b_id);
	updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message

	nodes[1].node.handle_update_add_htlc(node_a_id, &updates.update_add_htlcs[0]);
	check_added_monitors(&nodes[1], 0);
	do_commitment_signed_dance(&nodes[1], &nodes[0], &updates.commitment_signed, false, true);
	expect_and_process_pending_htlcs(&nodes[1], false);
	expect_htlc_handling_failed_destinations!(
		nodes[1].node.get_and_clear_pending_events(),
		&[HTLCHandlingFailureType::InvalidOnion]
	);
	check_added_monitors(&nodes[1], 1);

	let events = nodes[1].node.get_and_clear_pending_msg_events();

	let mut update_msg: msgs::UpdateFailMalformedHTLC = {
		match events[0] {
			MessageSendEvent::UpdateHTLCs {
				updates:
					msgs::CommitmentUpdate {
						ref update_add_htlcs,
						ref update_fulfill_htlcs,
						ref update_fail_htlcs,
						ref update_fail_malformed_htlcs,
						ref update_fee,
						..
					},
				..
			} => {
				assert!(update_add_htlcs.is_empty());
				assert!(update_fulfill_htlcs.is_empty());
				assert!(update_fail_htlcs.is_empty());
				assert_eq!(update_fail_malformed_htlcs.len(), 1);
				assert!(update_fee.is_none());
				update_fail_malformed_htlcs[0].clone()
			},
			_ => panic!("Unexpected event"),
		}
	};
	update_msg.failure_code &= !0x8000;
	nodes[0].node.handle_update_fail_malformed_htlc(node_b_id, &update_msg);

	assert!(nodes[0].node.list_channels().is_empty());
	let err_msg = check_closed_broadcast(&nodes[0], 1, true).pop().unwrap();
	assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
	check_added_monitors(&nodes[0], 1);
	let reason = ClosureReason::ProcessingError { err: err_msg.data };
	check_closed_event(&nodes[0], 1, reason, &[node_b_id], 1000000);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_dust_limit_fee_accounting() {
	do_test_dust_limit_fee_accounting(false);
	do_test_dust_limit_fee_accounting(true);
}

pub fn do_test_dust_limit_fee_accounting(can_afford: bool) {
	// Test that when a channel funder sends HTLCs exactly on the dust limit
	// of the funder, the fundee correctly accounts for the additional fee on the
	// funder's commitment transaction due to those additional non-dust HTLCs when
	// checking for any infrigements on the funder's reserve.

	let channel_type = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();

	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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	// Set a HTLC amount that is equal to the dust limit of the funder
	const HTLC_AMT_SAT: u64 = 354;

	const CHANNEL_VALUE_SAT: u64 = 100_000;

	const FEERATE_PER_KW: u32 = 253;

	let commit_tx_fee_sat =
		chan_utils::commit_tx_fee_sat(FEERATE_PER_KW, MIN_AFFORDABLE_HTLC_COUNT, &channel_type);

	// By default the reserve is set to 1% or 1000sat, whichever is higher
	let channel_reserve_satoshis = 1_000;

	// Set node 0's balance to pay for exactly MIN_AFFORDABLE_HTLC_COUNT non-dust HTLCs on the channel, minus some offset
	let node_0_balance_sat = commit_tx_fee_sat
		+ channel_reserve_satoshis
		+ 2 * crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI
		+ MIN_AFFORDABLE_HTLC_COUNT as u64 * HTLC_AMT_SAT
		- if can_afford { 0 } else { 1 };
	let mut node_1_balance_sat = CHANNEL_VALUE_SAT - node_0_balance_sat;

	let chan_id = create_chan_between_nodes_with_value(
		&nodes[0],
		&nodes[1],
		CHANNEL_VALUE_SAT,
		node_1_balance_sat * 1000,
	)
	.3;

	{
		// Double check the reserve that node 0 has to maintain here
		let per_peer_state_lock;
		let mut peer_state_lock;
		let chan =
			get_channel_ref!(nodes[1], nodes[0], per_peer_state_lock, peer_state_lock, chan_id);
		assert_eq!(
			chan.funding().holder_selected_channel_reserve_satoshis,
			channel_reserve_satoshis
		);
	}
	{
		// Double check the dust limit on node 0's commitment transactions; when node 0
		// adds a HTLC, node 1 will check that the fee on node 0's commitment transaction
		// does not dip under the node 1 selected reserve.
		let per_peer_state_lock;
		let mut peer_state_lock;
		let chan =
			get_channel_ref!(nodes[0], nodes[1], per_peer_state_lock, peer_state_lock, chan_id);
		assert_eq!(chan.context().holder_dust_limit_satoshis, HTLC_AMT_SAT);
	}

	// Precompute the route to skip any router complaints when sending the last HTLC
	let (route_0_1, payment_hash_0_1, _, payment_secret_0_1) =
		get_route_and_payment_hash!(nodes[0], nodes[1], HTLC_AMT_SAT * 1000);

	let mut htlcs = Vec::new();
	for _ in 0..MIN_AFFORDABLE_HTLC_COUNT - 1 {
		let (_payment_preimage, payment_hash, ..) =
			route_payment(&nodes[0], &[&nodes[1]], HTLC_AMT_SAT * 1000);
		// Grab a snapshot of these HTLCs to manually build the commitment transaction later...
		let accepted_htlc = HTLCOutputInCommitment {
			offered: false,
			amount_msat: HTLC_AMT_SAT * 1000,
			// Hard-coded to match the expected value
			cltv_expiry: 81,
			payment_hash,
			transaction_output_index: None,
		};
		htlcs.push(accepted_htlc);
	}

	// Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
	let secp_ctx = Secp256k1::new();
	let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");

	let cur_height = nodes[1].node.best_block.read().unwrap().height + 1;

	let onion_keys =
		onion_utils::construct_onion_keys(&secp_ctx, &route_0_1.paths[0], &session_priv);
	let recipient_onion_fields =
		RecipientOnionFields::secret_only(payment_secret_0_1, HTLC_AMT_SAT * 1000);
	let (onion_payloads, amount_msat, cltv_expiry) = onion_utils::test_build_onion_payloads(
		&route_0_1.paths[0],
		&recipient_onion_fields,
		cur_height,
		&None,
		None,
		None,
	)
	.unwrap();
	let onion_routing_packet =
		onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash_0_1)
			.unwrap();
	// Double check the hard-coded value
	assert_eq!(cltv_expiry, 81);
	let msg = msgs::UpdateAddHTLC {
		channel_id: chan_id,
		htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64 - 1,
		amount_msat,
		payment_hash: payment_hash_0_1,
		cltv_expiry,
		onion_routing_packet,
		skimmed_fee_msat: None,
		blinding_point: None,
		hold_htlc: None,
		accountable: None,
	};

	nodes[1].node.handle_update_add_htlc(node_a_id, &msg);

	if !can_afford {
		let err = "Remote HTLC add would put them under remote reserve value".to_string();
		nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", &err, 3);
		let events = nodes[1].node.get_and_clear_pending_msg_events();
		assert_eq!(events.len(), 2);
		let reason = ClosureReason::ProcessingError { err };
		check_closed_event(&nodes[1], 1, reason, &[node_a_id], CHANNEL_VALUE_SAT);
		check_added_monitors(&nodes[1], 1);
	} else {
		// Now manually create the commitment_signed message corresponding to the update_add
		// nodes[0] just sent. In the code for construction of this message, "local" refers
		// to the sender of the message, and "remote" refers to the receiver.

		const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;

		let (local_secret, next_local_point) = {
			let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
			let chan_lock = per_peer_state.get(&node_b_id).unwrap().lock().unwrap();
			let local_chan =
				chan_lock.channel_by_id.get(&chan_id).and_then(Channel::as_funded).unwrap();
			let chan_signer = local_chan.get_signer();
			// Make the signer believe we validated another commitment, so we can release the secret
			chan_signer.get_enforcement_state().last_holder_commitment -= 1;

			(
				chan_signer
					.release_commitment_secret(
						INITIAL_COMMITMENT_NUMBER - MIN_AFFORDABLE_HTLC_COUNT as u64 + 1,
					)
					.unwrap(),
				chan_signer
					.get_per_commitment_point(
						INITIAL_COMMITMENT_NUMBER - MIN_AFFORDABLE_HTLC_COUNT as u64,
						&secp_ctx,
					)
					.unwrap(),
			)
		};
		let remote_point = {
			let per_peer_lock;
			let mut peer_state_lock;

			let channel =
				get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, chan_id);
			let chan_signer = channel.as_funded().unwrap().get_signer();
			chan_signer
				.get_per_commitment_point(
					INITIAL_COMMITMENT_NUMBER - MIN_AFFORDABLE_HTLC_COUNT as u64,
					&secp_ctx,
				)
				.unwrap()
		};

		// Build the remote commitment transaction so we can sign it, and then later use the
		// signature for the commitment_signed message.
		let local_chan_balance = node_0_balance_sat
			- HTLC_AMT_SAT * MIN_AFFORDABLE_HTLC_COUNT as u64
			- 2 * crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI
			- chan_utils::commit_tx_fee_sat(
				FEERATE_PER_KW,
				MIN_AFFORDABLE_HTLC_COUNT,
				&channel_type,
			);

		let accepted_htlc_info = HTLCOutputInCommitment {
			offered: false,
			amount_msat: HTLC_AMT_SAT * 1000,
			cltv_expiry,
			payment_hash: payment_hash_0_1,
			transaction_output_index: None,
		};
		htlcs.push(accepted_htlc_info);

		let commitment_number = INITIAL_COMMITMENT_NUMBER - MIN_AFFORDABLE_HTLC_COUNT as u64;

		let res = {
			let per_peer_lock;
			let mut peer_state_lock;

			let channel =
				get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, chan_id);
			let chan_signer = channel.as_funded().unwrap().get_signer();

			let commitment_tx = CommitmentTransaction::new(
				commitment_number,
				&remote_point,
				node_1_balance_sat,
				local_chan_balance,
				FEERATE_PER_KW,
				htlcs,
				&channel.funding().channel_transaction_parameters.as_counterparty_broadcastable(),
				&secp_ctx,
			);
			let params = &channel.funding().channel_transaction_parameters;
			chan_signer
				.sign_counterparty_commitment(
					params,
					&commitment_tx,
					Vec::new(),
					Vec::new(),
					&secp_ctx,
				)
				.unwrap()
		};

		let commit_signed_msg = msgs::CommitmentSigned {
			channel_id: chan_id,
			signature: res.0,
			htlc_signatures: res.1,
			funding_txid: None,
		};

		// Send the commitment_signed message to the nodes[1].
		nodes[1].node.handle_commitment_signed(node_a_id, &commit_signed_msg);
		let _ = nodes[1].node.get_and_clear_pending_msg_events();

		// Send the RAA to nodes[1].
		let raa_msg = msgs::RevokeAndACK {
			channel_id: chan_id,
			per_commitment_secret: local_secret,
			next_per_commitment_point: next_local_point,
			release_htlc_message_paths: Vec::new(),
		};
		nodes[1].node.handle_revoke_and_ack(node_a_id, &raa_msg);

		// The HTLC actually fails here in `fn validate_commitment_signed` due to a fee spike buffer
		// violation. It nonetheless passed all checks in `fn validate_update_add_htlc`.

		expect_and_process_pending_htlcs(&nodes[1], false);
		expect_htlc_handling_failed_destinations!(
			nodes[1].node.get_and_clear_pending_events(),
			&[HTLCHandlingFailureType::Receive { payment_hash: payment_hash_0_1 }]
		);

		let events = nodes[1].node.get_and_clear_pending_msg_events();
		assert_eq!(events.len(), 1);
		// Make sure the HTLC failed in the way we expect.
		match events[0] {
			MessageSendEvent::UpdateHTLCs {
				updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. },
				..
			} => {
				assert_eq!(update_fail_htlcs.len(), 1);
				update_fail_htlcs[0].clone()
			},
			_ => panic!("Unexpected event"),
		};
		nodes[1].logger.assert_log(
			"lightning::ln::channel",
			"Attempting to fail HTLC due to fee spike buffer violation. Rebalancing is required."
				.to_string(),
			1,
		);

		check_added_monitors(&nodes[1], 3);
	}
}

#[xtest(feature = "_externalize_tests")]
fn test_create_channel_to_trusted_peer_0reserve() {
	let mut config = test_default_channel_config();

	// Anchor channels
	config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
	config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = false;
	let channel_type = do_test_create_channel_to_trusted_peer_0reserve(config.clone());
	assert_eq!(channel_type, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());

	// 0FC channels
	config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false;
	config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = true;
	let channel_type = do_test_create_channel_to_trusted_peer_0reserve(config.clone());
	assert_eq!(channel_type, ChannelTypeFeatures::anchors_zero_fee_commitments());
}

fn do_test_create_channel_to_trusted_peer_0reserve(mut config: UserConfig) -> ChannelTypeFeatures {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let channel_value_sat = 100_000;

	let temp_channel_id = nodes[0]
		.node
		.create_channel_to_trusted_peer_0reserve(node_b_id, channel_value_sat, 0, 42, None, None)
		.unwrap();
	let mut open_channel_message =
		get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id);
	handle_and_accept_open_channel(&nodes[1], node_a_id, &open_channel_message);
	let mut accept_channel_message =
		get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id);
	nodes[0].node.handle_accept_channel(node_b_id, &accept_channel_message);
	let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
	let funding_msgs =
		create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
	create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);

	let details = &nodes[0].node.list_channels()[0];
	let reserve_sat = details.unspendable_punishment_reserve.unwrap();
	assert_ne!(reserve_sat, 0);
	let channel_type = details.channel_type.clone().unwrap();
	let feerate_per_kw = details.feerate_sat_per_1000_weight.unwrap();
	let anchors_sat =
		if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() {
			2 * 330
		} else {
			0
		};
	let reserved_commit_tx_fee_sat = chan_utils::commit_tx_fee_sat(
		feerate_per_kw,
		2, // We reserve space for two HTLCs, the next outbound non-dust HTLC, and the fee spike buffer HTLC
		&channel_type,
	);

	let max_outbound_htlc_sat =
		channel_value_sat - anchors_sat - reserved_commit_tx_fee_sat - reserve_sat;
	assert_eq!(details.next_outbound_htlc_limit_msat, max_outbound_htlc_sat * 1000);
	send_payment(&nodes[0], &[&nodes[1]], max_outbound_htlc_sat * 1000);

	let details = &nodes[1].node.list_channels()[0];
	assert_eq!(details.unspendable_punishment_reserve.unwrap(), 0);
	// Assert that the fundee can send back the full amount they just received, since they have 0-reserve.
	assert_eq!(details.next_outbound_htlc_limit_msat, max_outbound_htlc_sat * 1000);
	send_payment(&nodes[1], &[&nodes[0]], max_outbound_htlc_sat * 1000);

	channel_type
}

#[xtest(feature = "_externalize_tests")]
fn test_accept_inbound_channel_from_trusted_peer_0reserve() {
	let mut config = test_default_channel_config();

	// Anchor channels
	config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
	config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = false;
	let channel_type = do_test_accept_inbound_channel_from_trusted_peer_0reserve(config.clone());
	assert_eq!(channel_type, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());

	// 0FC channels
	config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false;
	config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = true;
	let channel_type = do_test_accept_inbound_channel_from_trusted_peer_0reserve(config.clone());
	assert_eq!(channel_type, ChannelTypeFeatures::anchors_zero_fee_commitments());
}

fn do_test_accept_inbound_channel_from_trusted_peer_0reserve(
	mut config: UserConfig,
) -> ChannelTypeFeatures {
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let channel_value_sat = 100_000;

	nodes[0].node.create_channel(node_b_id, channel_value_sat, 0, 42, None, None).unwrap();

	let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id);
	nodes[1].node.handle_open_channel(node_a_id, &open_channel);
	let events = nodes[1].node.get_and_clear_pending_events();
	assert_eq!(events.len(), 1);
	match events[0] {
		Event::OpenChannelRequest { temporary_channel_id: chan_id, .. } => {
			nodes[1]
				.node
				.accept_inbound_channel_from_trusted_peer(
					&chan_id,
					&node_a_id,
					0,
					TrustedChannelFeatures::ZeroReserve,
					None,
				)
				.unwrap();
		},
		_ => panic!("Unexpected event"),
	};

	let mut accept_channel_msg =
		get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id);
	nodes[0].node.handle_accept_channel(node_b_id, &accept_channel_msg);

	let (chan_id, tx, _) = create_funding_transaction(&nodes[0], &node_b_id, channel_value_sat, 42);

	nodes[0].node.funding_transaction_generated(chan_id, node_b_id, tx.clone()).unwrap();
	nodes[1].node.handle_funding_created(
		node_a_id,
		&get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_b_id),
	);
	check_added_monitors(&nodes[1], 1);
	expect_channel_pending_event(&nodes[1], &node_a_id);

	nodes[0].node.handle_funding_signed(
		node_b_id,
		&get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, node_a_id),
	);
	check_added_monitors(&nodes[0], 1);
	expect_channel_pending_event(&nodes[0], &node_b_id);

	let (channel_ready, _channel_id) =
		create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
	let (announcement, as_update, bs_update) =
		create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
	update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);

	let details = &nodes[0].node.list_channels()[0];
	assert_eq!(details.unspendable_punishment_reserve.unwrap(), 0);
	let channel_type = details.channel_type.clone().unwrap();
	let feerate_per_kw = details.feerate_sat_per_1000_weight.unwrap();
	let anchors_sat =
		if channel_type == ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies() {
			2 * 330
		} else {
			0
		};
	let reserved_commit_tx_fee_sat = chan_utils::commit_tx_fee_sat(
		feerate_per_kw,
		2, // We reserve space for two HTLCs, the next outbound non-dust HTLC, and the fee spike buffer HTLC
		&channel_type,
	);

	let max_outbound_htlc_sat = channel_value_sat - reserved_commit_tx_fee_sat - anchors_sat;
	assert_eq!(details.next_outbound_htlc_limit_msat, max_outbound_htlc_sat * 1000);
	send_payment(&nodes[0], &[&nodes[1]], max_outbound_htlc_sat * 1000);

	let details = &nodes[1].node.list_channels()[0];
	let reserve_sat = details.unspendable_punishment_reserve.unwrap();
	assert_ne!(reserve_sat, 0);
	let max_outbound_htlc_sat = max_outbound_htlc_sat - reserve_sat;
	assert_eq!(details.next_outbound_htlc_limit_msat, max_outbound_htlc_sat * 1000);
	send_payment(&nodes[1], &[&nodes[0]], max_outbound_htlc_sat * 1000);

	channel_type
}

#[xtest(feature = "_externalize_tests")]
fn test_0reserve_no_outputs() {
	do_test_0reserve_no_outputs_keyed_anchors(true);
	do_test_0reserve_no_outputs_keyed_anchors(false);

	do_test_0reserve_no_outputs_p2a_anchor();
}

pub(crate) fn setup_0reserve_no_outputs_channels<'a, 'b, 'c, 'd>(
	nodes: &'a Vec<Node<'b, 'c, 'd>>, channel_value_sat: u64, dust_limit_satoshis: u64,
) -> (ChannelId, Transaction) {
	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	// Create a channel with an identical, high dust limit and zero-reserve on both sides to make our lives easier

	nodes[0]
		.node
		.create_channel_to_trusted_peer_0reserve(node_b_id, channel_value_sat, 0, 42, None, None)
		.unwrap();

	let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id);
	open_channel.common_fields.dust_limit_satoshis = dust_limit_satoshis;
	nodes[1].node.handle_open_channel(node_a_id, &open_channel);
	let events = nodes[1].node.get_and_clear_pending_events();
	assert_eq!(events.len(), 1);
	match events[0] {
		Event::OpenChannelRequest { temporary_channel_id: chan_id, .. } => {
			nodes[1]
				.node
				.accept_inbound_channel_from_trusted_peer(
					&chan_id,
					&node_a_id,
					0,
					TrustedChannelFeatures::ZeroReserve,
					None,
				)
				.unwrap();
		},
		_ => panic!("Unexpected event"),
	};

	let mut accept_channel_msg =
		get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id);
	accept_channel_msg.common_fields.dust_limit_satoshis = dust_limit_satoshis;
	nodes[0].node.handle_accept_channel(node_b_id, &accept_channel_msg);

	let (chan_id, tx, _) = create_funding_transaction(&nodes[0], &node_b_id, channel_value_sat, 42);

	nodes[0].node.funding_transaction_generated(chan_id, node_b_id, tx.clone()).unwrap();
	nodes[1].node.handle_funding_created(
		node_a_id,
		&get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_b_id),
	);
	check_added_monitors(&nodes[1], 1);
	expect_channel_pending_event(&nodes[1], &node_a_id);

	nodes[0].node.handle_funding_signed(
		node_b_id,
		&get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, node_a_id),
	);
	check_added_monitors(&nodes[0], 1);
	expect_channel_pending_event(&nodes[0], &node_b_id);

	assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
	assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
	nodes[0].tx_broadcaster.clear();

	let (channel_ready, channel_id) =
		create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
	let (announcement, as_update, bs_update) =
		create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
	update_nodes_with_chan_announce(nodes, 0, 1, &announcement, &as_update, &bs_update);

	{
		let mut per_peer_lock;
		let mut peer_state_lock;
		let channel =
			get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, channel_id);
		if let Some(mut chan) = channel.as_funded_mut() {
			chan.context.holder_dust_limit_satoshis = dust_limit_satoshis;
		} else {
			panic!("Unexpected Channel phase");
		}
	}

	{
		let mut per_peer_lock;
		let mut peer_state_lock;
		let channel =
			get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, channel_id);
		if let Some(mut chan) = channel.as_funded_mut() {
			chan.context.holder_dust_limit_satoshis = dust_limit_satoshis;
		} else {
			panic!("Unexpected Channel phase");
		}
	}

	(channel_id, tx)
}

fn manually_trigger_update_fail_htlc<'a, 'b, 'c, 'd>(
	nodes: &'a Vec<Node<'b, 'c, 'd>>, channel_id: ChannelId, value_to_self_msat: u64,
	dust_limit_satoshis: u64, payment_hash: PaymentHash,
	htlcs_in_commitment: Vec<HTLCOutputInCommitment>, can_afford_but_reserve_is_breached: bool,
) {
	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();
	let secp_ctx = Secp256k1::new();

	// Now manually create the commitment_signed message corresponding to the update_add
	// nodes[0] just sent. In the code for construction of this message, "local" refers
	// to the sender of the message, and "remote" refers to the receiver.

	let feerate_per_kw = get_feerate!(nodes[0], nodes[1], channel_id);

	let (local_secret, next_local_point) = {
		let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
		let chan_lock = per_peer_state.get(&node_b_id).unwrap().lock().unwrap();
		let local_chan =
			chan_lock.channel_by_id.get(&channel_id).and_then(Channel::as_funded).unwrap();
		let chan_signer = local_chan.get_signer();
		// Make the signer believe we validated another commitment, so we can release the secret
		let commit_number = chan_signer.get_enforcement_state().last_holder_commitment;
		chan_signer.get_enforcement_state().last_holder_commitment -= 1;

		(
			chan_signer.release_commitment_secret(commit_number).unwrap(),
			chan_signer.get_per_commitment_point(commit_number - 2, &secp_ctx).unwrap(),
		)
	};
	let (remote_commit_number, remote_point) = {
		let per_peer_lock;
		let mut peer_state_lock;

		let channel =
			get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, channel_id);
		let chan_signer = channel.as_funded().unwrap().get_signer();
		let commit_number = chan_signer.get_enforcement_state().last_holder_commitment;
		let remote_point =
			chan_signer.get_per_commitment_point(commit_number - 1, &secp_ctx).unwrap();
		(commit_number - 1, remote_point)
	};

	// Build the remote commitment transaction so we can sign it, and then later use the
	// signature for the commitment_signed message.
	let res = {
		let per_peer_lock;
		let mut peer_state_lock;

		let channel =
			get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, channel_id);
		let chan_signer = channel.as_funded().unwrap().get_signer();

		let (commitment_tx, _stats) = SpecTxBuilder {}.build_commitment_transaction(
			false,
			remote_commit_number,
			&remote_point,
			&channel.funding().channel_transaction_parameters,
			&secp_ctx,
			value_to_self_msat,
			htlcs_in_commitment,
			feerate_per_kw,
			dust_limit_satoshis,
			&nodes[0].logger,
		);
		let params = &channel.funding().channel_transaction_parameters;
		chan_signer
			.sign_counterparty_commitment(params, &commitment_tx, Vec::new(), Vec::new(), &secp_ctx)
			.unwrap()
	};

	let commit_signed_msg = msgs::CommitmentSigned {
		channel_id,
		signature: res.0,
		htlc_signatures: res.1,
		funding_txid: None,
	};

	// Send the commitment_signed message to the nodes[1].
	nodes[1].node.handle_commitment_signed(node_a_id, &commit_signed_msg);
	let _ = nodes[1].node.get_and_clear_pending_msg_events();

	// Send the RAA to nodes[1].
	let raa_msg = msgs::RevokeAndACK {
		channel_id,
		per_commitment_secret: local_secret,
		next_per_commitment_point: next_local_point,
		release_htlc_message_paths: Vec::new(),
	};
	nodes[1].node.handle_revoke_and_ack(node_a_id, &raa_msg);
	expect_and_process_pending_htlcs(&nodes[1], false);

	expect_htlc_handling_failed_destinations!(
		nodes[1].node.get_and_clear_pending_events(),
		&[HTLCHandlingFailureType::Receive { payment_hash }]
	);

	let events = nodes[1].node.get_and_clear_pending_msg_events();
	assert_eq!(events.len(), 1);

	// Make sure the HTLC failed in the way we expect.
	match events[0] {
		MessageSendEvent::UpdateHTLCs {
			updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. },
			..
		} => {
			assert_eq!(update_fail_htlcs.len(), 1);
			update_fail_htlcs[0].clone()
		},
		_ => panic!("Unexpected event"),
	};
	let log_string =
		if can_afford_but_reserve_is_breached {
			String::from("Attempting to fail HTLC due to fee spike buffer violation. Rebalancing is required.")
		} else {
			String::from("Attempting to fail HTLC due to balance exhausted on remote commitment")
		};
	nodes[1].logger.assert_log("lightning::ln::channel", log_string, 1);

	check_added_monitors(&nodes[1], 3);
}

fn do_test_0reserve_no_outputs_keyed_anchors(payment_success: bool) {
	let mut config = test_default_channel_config();

	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;

	let channel_type = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();

	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let _node_b_id = nodes[1].node.get_our_node_id();

	let feerate_per_kw = 253;
	let anchors_sat = 2 * ANCHOR_OUTPUT_VALUE_SATOSHI;
	let dust_limit_satoshis: u64 = 546;
	let channel_value_sat = {
		// min opener balance is the fee for 4 HTLCs, the anchors, and the dust limit
		let min_channel_size =
			commit_tx_fee_sat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT, &channel_type)
				+ anchors_sat + dust_limit_satoshis;
		assert!(min_channel_size > 1002);
		min_channel_size
	};

	let (channel_id, _funding_tx) =
		setup_0reserve_no_outputs_channels(&nodes, channel_value_sat, dust_limit_satoshis);
	assert_eq!(nodes[0].node.list_channels()[0].channel_type.as_ref().unwrap(), &channel_type);

	// Sending the biggest dust HTLC possible trims our balance output!
	let max_dust_htlc_sat = dust_limit_satoshis - 1;
	assert!(
		channel_value_sat
			.saturating_sub(anchors_sat)
			.saturating_sub(commit_tx_fee_sat(feerate_per_kw, 0, &channel_type))
			.saturating_sub(max_dust_htlc_sat)
			< dust_limit_satoshis
	);

	// We can afford the fee for an additional non-dust HTLC plus the fee spike HTLC, so we can send
	// non-dust HTLCs
	let capacity_minus_max_commitment_fee_sat =
		channel_value_sat - anchors_sat - commit_tx_fee_sat(feerate_per_kw, 2, &channel_type);
	assert!(capacity_minus_max_commitment_fee_sat > dust_limit_satoshis);
	// And since the biggest dust HTLC results in no outputs on the commitment,
	// we can *only* send non-dust HTLCs
	let details_0 = &nodes[0].node.list_channels()[0];
	assert_eq!(details_0.next_outbound_htlc_minimum_msat, dust_limit_satoshis * 1000);
	assert_eq!(
		details_0.next_outbound_htlc_limit_msat,
		capacity_minus_max_commitment_fee_sat * 1000
	);

	// Send the smallest non-dust HTLC possible, this will pass both holder and counterparty validation
	//
	// One msat below the non-dust HTLC value will break counterparty validation at
	// `validate_update_add_htlc`. This is why we don't bother taking a look at the range between the
	// failure of `can_accept_incoming_htlc` and the failure of `validate_update_add_htlc`.
	let sender_amount_msat = dust_limit_satoshis * 1000;

	let (sender_amount_msat, receiver_amount_msat) = if payment_success {
		(sender_amount_msat, sender_amount_msat)
	} else {
		(sender_amount_msat, sender_amount_msat - 1)
	};

	if payment_success {
		send_payment(&nodes[0], &[&nodes[1]], sender_amount_msat);
		// Node 1 the fundee has 0-reserve too, so whatever they receive, they can send right back!
		// Node 0 should *always* have the funds to cover the fee of a single non-dust HTLC from node 1.
		assert_eq!(
			nodes[1].node.list_channels()[0].next_outbound_htlc_limit_msat,
			sender_amount_msat
		);
		send_payment(&nodes[1], &[&nodes[0]], sender_amount_msat);
	} else {
		let (route, payment_hash, _, payment_secret) =
			get_route_and_payment_hash!(nodes[0], nodes[1], sender_amount_msat);
		let secp_ctx = Secp256k1::new();
		let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
		let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
		let onion_keys =
			onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv);
		let recipient_onion_fields =
			RecipientOnionFields::secret_only(payment_secret, sender_amount_msat);
		let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::test_build_onion_payloads(
			&route.paths[0],
			&recipient_onion_fields,
			cur_height,
			&None,
			None,
			None,
		)
		.unwrap();
		assert_eq!(htlc_msat, sender_amount_msat);
		let onion_packet =
			onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash)
				.unwrap();
		let msg = msgs::UpdateAddHTLC {
			channel_id,
			htlc_id: 0,
			amount_msat: receiver_amount_msat,
			payment_hash,
			cltv_expiry: htlc_cltv,
			onion_routing_packet: onion_packet,
			skimmed_fee_msat: None,
			blinding_point: None,
			hold_htlc: None,
			accountable: None,
		};

		nodes[1].node.handle_update_add_htlc(node_a_id, &msg);

		nodes[1].logger.assert_log_contains(
			"lightning::ln::channelmanager",
			"Remote HTLC add would overdraw remaining funds",
			3,
		);
		assert_eq!(nodes[1].node.list_channels().len(), 0);
		let err_msg = check_closed_broadcast(&nodes[1], 1, true).pop().unwrap();
		assert_eq!(err_msg.data, "Remote HTLC add would overdraw remaining funds");
		let reason = ClosureReason::ProcessingError {
			err: "Remote HTLC add would overdraw remaining funds".to_string(),
		};
		check_added_monitors(&nodes[1], 1);
		check_closed_event(&nodes[1], 1, reason, &[node_a_id], channel_value_sat);
	}
}

fn do_test_0reserve_no_outputs_p2a_anchor() {
	let mut config = test_default_channel_config();
	config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false;
	config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = true;

	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;

	let channel_type = ChannelTypeFeatures::anchors_zero_fee_commitments();

	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let _node_a_id = nodes[0].node.get_our_node_id();
	let _node_b_id = nodes[1].node.get_our_node_id();

	let dust_limit_satoshis: u64 = 546;
	let channel_value_sat = 1000;

	let _channel_id =
		setup_0reserve_no_outputs_channels(&nodes, channel_value_sat, dust_limit_satoshis);
	assert_eq!(nodes[0].node.list_channels()[0].channel_type.as_ref().unwrap(), &channel_type);

	// Sending the biggest dust HTLC possible trims our balance output!
	let max_dust_htlc_sat = dust_limit_satoshis - 1;
	assert!(channel_value_sat.saturating_sub(max_dust_htlc_sat) < dust_limit_satoshis);

	// We'll always have the P2A output on the commitment, so we are free to send any size HTLC,
	// including those that result in only a single output on the commitment, the P2A output.
	let details_0 = &nodes[0].node.list_channels()[0];
	assert_eq!(details_0.next_outbound_htlc_minimum_msat, 1000);
	// 0FC + 0-reserve baby!
	assert_eq!(details_0.next_outbound_htlc_limit_msat, channel_value_sat * 1000);

	// Send the max size dust HTLC; this results in a commitment with only the P2A output present
	let sender_amount_msat = max_dust_htlc_sat * 1000;

	send_payment(&nodes[0], &[&nodes[1]], sender_amount_msat);
	// Node 1 the fundee has 0-reserve too, so whatever they receive, they can send right back!
	assert_eq!(nodes[1].node.list_channels()[0].next_outbound_htlc_limit_msat, sender_amount_msat);
	send_payment(&nodes[1], &[&nodes[0]], sender_amount_msat);
}

#[xtest(feature = "_externalize_tests")]
pub fn test_0reserve_force_close_with_single_p2a_output() {
	do_test_0reserve_force_close_with_single_p2a_output(false);
	do_test_0reserve_force_close_with_single_p2a_output(true);
}

fn do_test_0reserve_force_close_with_single_p2a_output(high_feerate: bool) {
	let mut config = test_default_channel_config();
	config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false;
	config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = true;

	let chanmon_cfgs = create_chanmon_cfgs(2);
	if high_feerate {
		let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
		*feerate_lock = 2500;
	}
	if high_feerate {
		let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
		*feerate_lock = 2500;
	}
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;

	let channel_type = ChannelTypeFeatures::anchors_zero_fee_commitments();

	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let coinbase_tx = provide_anchor_reserves(&nodes);

	let _node_a_id = nodes[0].node.get_our_node_id();
	let _node_b_id = nodes[1].node.get_our_node_id();

	let dust_limit_satoshis: u64 = 546;
	// This is the fundee 1000sat reserve + 2 min HTLCs
	let channel_value_sat = 1002;

	let (channel_id, funding_tx) =
		setup_0reserve_no_outputs_channels(&nodes, channel_value_sat, dust_limit_satoshis);
	assert_eq!(nodes[0].node.list_channels()[0].channel_type.as_ref().unwrap(), &channel_type);

	// Send the smallest HTLC possible that trims our own balance output, this will be a dust HTLC
	let htlc_sat = channel_value_sat - dust_limit_satoshis + 1;
	assert!(htlc_sat < dust_limit_satoshis);
	route_payment(&nodes[0], &[&nodes[1]], htlc_sat * 1000);

	let commitment_tx = get_local_commitment_txn!(nodes[0], channel_id).pop().unwrap();
	let commitment_txid = commitment_tx.compute_txid();

	let message = "Channel force-closed".to_owned();
	nodes[0]
		.node
		.force_close_broadcasting_latest_txn(
			&channel_id,
			&nodes[1].node.get_our_node_id(),
			message.clone(),
		)
		.unwrap();
	check_closed_broadcast(&nodes[0], 1, true);
	check_added_monitors(&nodes[0], 1);
	let reason = ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true), message };
	check_closed_event(&nodes[0], 1, reason, &[nodes[1].node.get_our_node_id()], channel_value_sat);

	let mut events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
	assert_eq!(events.len(), 1);
	match events.pop().unwrap() {
		Event::BumpTransaction(bump_event) => {
			nodes[0].bump_tx_handler.handle_event(&bump_event);
		},
		_ => panic!("Unexpected event"),
	}
	let txns = nodes[0].tx_broadcaster.txn_broadcast();

	if high_feerate {
		assert_eq!(txns.len(), 2);
		check_spends!(txns[1], txns[0], coinbase_tx);
		assert!(txns[1].weight().to_wu() < TRUC_CHILD_MAX_WEIGHT);
		assert_eq!(txns[1].input.len(), 2);
		assert_eq!(txns[1].output.len(), 1);

		assert_eq!(txns[0].compute_txid(), commitment_txid);
		assert_eq!(txns[0].input.len(), 1);
		assert_eq!(txns[0].output.len(), 1);
		assert_eq!(txns[0].output[0].value, Amount::from_sat(240));
		assert_eq!(txns[0].output[0].script_pubkey, shared_anchor_script_pubkey());
		check_spends!(txns[0], funding_tx);

		nodes[0].logger.assert_log(
			"lightning::events::bump_transaction",
			format!(
				"Broadcasting anchor transaction {} to bump channel close with txid {}",
				txns[1].compute_txid(),
				txns[0].compute_txid()
			),
			1,
		);
	} else {
		assert_eq!(txns.len(), 1);
		assert_eq!(txns[0].compute_txid(), commitment_txid);
		assert_eq!(txns[0].input.len(), 1);
		assert_eq!(txns[0].output.len(), 1);
		assert_eq!(txns[0].output[0].value, Amount::from_sat(240));
		assert_eq!(txns[0].output[0].script_pubkey, shared_anchor_script_pubkey());
		check_spends!(txns[0], funding_tx);

		let weight = txns[0].weight();
		let feerate = (channel_value_sat - 240) * 1000 / weight.to_wu();

		nodes[0].logger.assert_log(
			"lightning::events::bump_transaction",
			format!(
				"Pre-signed commitment {} already has feerate {} sat/kW above required 253 sat/kW, broadcasting.",
				txns[0].compute_txid(),
				feerate,
			),
			1,
		);
	}
}

#[xtest(feature = "_externalize_tests")]
fn test_0reserve_zero_conf_combined() {
	// Test that zero-reserve and zero-conf features work together: a channel that
	// is immediately usable (no confirmations needed) and has zero reserve for the opener.
	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	let mut config = test_default_channel_config();
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;
	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let node_b_id = nodes[1].node.get_our_node_id();

	let channel_value_sat = 100_000;

	// Node 0 creates a channel to node 1.
	nodes[0].node.create_channel(node_b_id, channel_value_sat, 0, 42, None, None).unwrap();
	let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, node_b_id);

	// Node 1 accepts with both zero-conf AND zero-reserve.
	nodes[1].node.handle_open_channel(node_a_id, &open_channel);
	let events = nodes[1].node.get_and_clear_pending_events();
	assert_eq!(events.len(), 1);
	match events[0] {
		Event::OpenChannelRequest { temporary_channel_id: chan_id, .. } => {
			nodes[1]
				.node
				.accept_inbound_channel_from_trusted_peer(
					&chan_id,
					&node_a_id,
					0,
					TrustedChannelFeatures::ZeroConfZeroReserve,
					None,
				)
				.unwrap();
		},
		_ => panic!("Unexpected event"),
	};

	// Verify zero-conf: minimum_depth should be 0.
	let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, node_a_id);
	assert_eq!(accept_channel.common_fields.minimum_depth, 0);
	nodes[0].node.handle_accept_channel(node_b_id, &accept_channel);

	// Create the funding transaction (no block confirmations needed for zero-conf).
	let (temporary_channel_id, tx, _) =
		create_funding_transaction(&nodes[0], &node_b_id, channel_value_sat, 42);
	nodes[0]
		.node
		.funding_transaction_generated(temporary_channel_id, node_b_id, tx.clone())
		.unwrap();
	let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, node_b_id);

	// Node 1 handles funding_created and immediately sends both FundingSigned and ChannelReady.
	nodes[1].node.handle_funding_created(node_a_id, &funding_created);
	check_added_monitors(&nodes[1], 1);
	let bs_signed_locked = nodes[1].node.get_and_clear_pending_msg_events();
	assert_eq!(bs_signed_locked.len(), 2);

	let as_channel_ready;
	match &bs_signed_locked[0] {
		MessageSendEvent::SendFundingSigned { node_id, msg } => {
			assert_eq!(*node_id, node_a_id);
			nodes[0].node.handle_funding_signed(node_b_id, &msg);
			expect_channel_pending_event(&nodes[0], &node_b_id);
			expect_channel_pending_event(&nodes[1], &node_a_id);
			check_added_monitors(&nodes[0], 1);

			assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
			assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
			nodes[0].tx_broadcaster.clear();

			as_channel_ready =
				get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, node_b_id);
		},
		_ => panic!("Unexpected event"),
	}
	match &bs_signed_locked[1] {
		MessageSendEvent::SendChannelReady { node_id, msg } => {
			assert_eq!(*node_id, node_a_id);
			nodes[0].node.handle_channel_ready(node_b_id, &msg);
			expect_channel_ready_event(&nodes[0], &node_b_id);
		},
		_ => panic!("Unexpected event"),
	}

	nodes[1].node.handle_channel_ready(node_a_id, &as_channel_ready);
	expect_channel_ready_event(&nodes[1], &node_a_id);

	let as_channel_update =
		get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, node_b_id);
	let bs_channel_update =
		get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, node_a_id);
	nodes[0].node.handle_channel_update(node_b_id, &bs_channel_update);
	nodes[1].node.handle_channel_update(node_a_id, &as_channel_update);

	// Channel should be immediately usable without any block confirmations.
	assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
	assert_eq!(nodes[1].node.list_usable_channels().len(), 1);

	// Verify zero-reserve: opener (node 0) should have 0 reserve.
	let details_a = &nodes[0].node.list_channels()[0];
	let node_0_reserve = details_a.unspendable_punishment_reserve.unwrap();
	let node_0_max_htlc = details_a.next_outbound_htlc_limit_msat;
	let channel_type = details_a.channel_type.clone().unwrap();
	assert_eq!(node_0_reserve, 0);
	assert_eq!(channel_type, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());
	assert!(details_a.is_usable);
	assert_eq!(details_a.confirmations.unwrap(), 0);
	assert_eq!(
		node_0_max_htlc,
		(channel_value_sat - commit_tx_fee_sat(253, 2, &channel_type) - 2 * 330) * 1000
	);

	// Verify acceptor (node 1) has a non-zero reserve.
	let details_b = &nodes[1].node.list_channels()[0];
	assert_ne!(details_b.unspendable_punishment_reserve.unwrap(), 0);
	assert!(details_b.is_usable);

	// Send payments in both directions to verify the combined feature works end-to-end.
	send_payment(&nodes[0], &[&nodes[1]], node_0_max_htlc);

	let details_b = &nodes[1].node.list_channels()[0];
	let node_1_reserve = details_b.unspendable_punishment_reserve.unwrap();
	let node_1_max_htlc = details_b.next_outbound_htlc_limit_msat;
	assert_eq!(node_1_reserve, 1000);
	assert_eq!(node_1_max_htlc, node_0_max_htlc - node_1_reserve * 1000);
	send_payment(&nodes[1], &[&nodes[0]], node_1_max_htlc);
}

#[xtest(feature = "_externalize_tests")]
fn test_outbound_vs_available_capacity_outbound_htlc_limit_spiked_feerate() {
	let mut config = test_default_channel_config();
	config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false;
	config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = false;

	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;

	let channel_type = ChannelTypeFeatures::only_static_remote_key();

	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let _node_a_id = nodes[0].node.get_our_node_id();
	let _node_b_id = nodes[1].node.get_our_node_id();

	const FEERATE: u32 = 253;
	const MULTIPLE: u32 = FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
	const SPIKED_FEERATE: u32 = FEERATE * MULTIPLE;
	const DUST_LIMIT_MSAT: u64 = 354 * 1000;
	const CHANNEL_VALUE_MSAT: u64 = 10_000 * 1000;
	const NODE_0_VALUE_TO_SELF_MSAT: u64 = 5000 * 1000;
	const NODE_1_VALUE_TO_SELF_MSAT: u64 = 5000 * 1000;
	const CHANNEL_RESERVE_MSAT: u64 = 1000 * 1000;

	// Find the HTLC amount that will be non-dust at the current feerate, but dust at the spiked feerate
	const SPIKED_DUST_HTLC_MSAT: u64 = 688 * 1000;
	const HTLC_SPIKE_DUST_LIMIT_MSAT: u64 = 689 * 1000;
	let htlc_timeout_spike_tx_fee_msat =
		second_stage_tx_fees_sat(&channel_type, SPIKED_FEERATE).1 * 1000;
	assert_eq!(HTLC_SPIKE_DUST_LIMIT_MSAT, DUST_LIMIT_MSAT + htlc_timeout_spike_tx_fee_msat);

	let channel_id =
		create_announced_chan_between_nodes_with_value(&nodes, 0, 1, CHANNEL_VALUE_MSAT / 1000, 0)
			.2;
	assert_eq!(nodes[0].node.list_channels()[0].channel_type.as_ref().unwrap(), &channel_type);
	{
		// Quick double-check on the dust limit to make sure HTLCs would be dust at 2x the
		// feerate...
		let mut per_peer_lock;
		let mut peer_state_lock;

		let channel =
			get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, channel_id);
		assert_eq!(channel.context().holder_dust_limit_satoshis * 1000, DUST_LIMIT_MSAT);
	}

	// Balance the channel so each side has 5_000 sats
	send_payment(&nodes[0], &[&nodes[1]], NODE_1_VALUE_TO_SELF_MSAT);

	let count_total_htlcs = |details: &ChannelDetails| {
		details.pending_outbound_htlcs.len() + details.pending_inbound_htlcs.len()
	};
	let count_node_0_nondust_htlcs = || {
		let mut txs = get_local_commitment_txn!(nodes[0], channel_id);
		let commitment_tx = &txs[0];
		commitment_tx
			.output
			.iter()
			.filter(|output| output.value.to_sat() * 1000 == SPIKED_DUST_HTLC_MSAT)
			.count()
	};
	let count_node_1_nondust_htlcs = || {
		let mut txs = get_local_commitment_txn!(nodes[1], channel_id);
		let commitment_tx = &txs[0];
		commitment_tx
			.output
			.iter()
			.filter(|output| output.value.to_sat() * 1000 == SPIKED_DUST_HTLC_MSAT)
			.count()
	};

	// Sanity check
	{
		let reserved_fee_sat = commit_tx_fee_sat(SPIKED_FEERATE, 2, &channel_type);
		let node_0_outbound_capacity_msat = NODE_0_VALUE_TO_SELF_MSAT - CHANNEL_RESERVE_MSAT;
		let node_0_available_capacity_msat =
			node_0_outbound_capacity_msat - reserved_fee_sat * 1000;
		let node_0_details = &nodes[0].node.list_channels()[0];
		assert_eq!(node_0_details.outbound_capacity_msat, node_0_outbound_capacity_msat);
		assert_eq!(node_0_details.next_outbound_htlc_limit_msat, node_0_available_capacity_msat);
		assert_eq!(count_total_htlcs(&node_0_details), 0);
		assert_eq!(count_node_0_nondust_htlcs(), 0);
	}

	// Route 2 688sat HTLCs from node 0 to node 1
	for i in 1..3 {
		route_payment(&nodes[0], &[&nodes[1]], SPIKED_DUST_HTLC_MSAT);

		let max_reserved_fee_msat = commit_tx_fee_sat(SPIKED_FEERATE, 2 + i, &channel_type) * 1000;
		let node_0_outbound_capacity_msat =
			NODE_0_VALUE_TO_SELF_MSAT - SPIKED_DUST_HTLC_MSAT * i as u64 - CHANNEL_RESERVE_MSAT;
		let node_0_available_capacity_msat = node_0_outbound_capacity_msat - max_reserved_fee_msat;
		// Node 0 can send non-dust HTLCs throughout
		assert!(node_0_available_capacity_msat >= HTLC_SPIKE_DUST_LIMIT_MSAT);
		let node_0_details = &nodes[0].node.list_channels()[0];
		assert_eq!(node_0_details.outbound_capacity_msat, node_0_outbound_capacity_msat);
		assert_eq!(node_0_details.next_outbound_htlc_limit_msat, node_0_available_capacity_msat);
		assert_eq!(count_total_htlcs(&node_0_details), i);
		assert_eq!(count_node_0_nondust_htlcs(), i);
	}

	let node_0_details = &nodes[0].node.list_channels()[0];
	let local_nondust_htlc_count = 2;
	assert_eq!(count_total_htlcs(&node_0_details), local_nondust_htlc_count);
	assert_eq!(count_node_0_nondust_htlcs(), local_nondust_htlc_count);
	assert_eq!(count_node_1_nondust_htlcs(), local_nondust_htlc_count);

	let node_0_outbound_capacity_msat = node_0_details.outbound_capacity_msat;

	// Route 2 688sat HTLCs from node 1 to node 0
	for i in 1..3 {
		route_payment(&nodes[1], &[&nodes[0]], SPIKED_DUST_HTLC_MSAT);

		let node_1_outbound_capacity_msat =
			NODE_1_VALUE_TO_SELF_MSAT - SPIKED_DUST_HTLC_MSAT * i as u64 - CHANNEL_RESERVE_MSAT;
		assert!(node_1_outbound_capacity_msat >= HTLC_SPIKE_DUST_LIMIT_MSAT);
		let node_1_details = &nodes[1].node.list_channels()[0];
		assert_eq!(node_1_details.outbound_capacity_msat, node_1_outbound_capacity_msat);
		assert_eq!(node_1_details.next_outbound_htlc_limit_msat, node_1_outbound_capacity_msat);

		let nondust_htlc_count = 2 + i;
		// At the current feerate, 688sat HTLCs are present on both commitments
		assert_eq!(count_node_0_nondust_htlcs(), nondust_htlc_count);
		assert_eq!(count_node_1_nondust_htlcs(), nondust_htlc_count);

		assert_eq!(
			nodes[0].node.list_channels()[0].outbound_capacity_msat,
			node_0_outbound_capacity_msat
		);
		let max_reserved_fee_msat =
			commit_tx_fee_sat(SPIKED_FEERATE, nondust_htlc_count + 2, &channel_type) * 1000;
		assert_eq!(
			nodes[0].node.list_channels()[0].next_outbound_htlc_limit_msat,
			node_0_outbound_capacity_msat - max_reserved_fee_msat
		);
	}
}

/// Make sure that we do not account for HTLCs going from non-dust to dust at the spiked feerate
/// when checking the fee spike buffer in `can_accept_incoming_htlc`. This is required to make sure
/// that we can afford *any* increase in the feerate between 1x to 2x, instead of checking whether
/// we can afford only the 2x increase in the feerate.
#[xtest(feature = "_externalize_tests")]
fn test_fail_cannot_afford_dust_htlcs_at_spike_multiple_if_nondust_at_base_feerate() {
	let mut config = test_default_channel_config();
	config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false;
	config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = false;

	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;

	let channel_type = ChannelTypeFeatures::only_static_remote_key();

	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	let node_a_id = nodes[0].node.get_our_node_id();
	let _node_b_id = nodes[1].node.get_our_node_id();

	const FEERATE: u32 = 253;
	const MULTIPLE: u32 = FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32;
	const SPIKED_FEERATE: u32 = FEERATE * MULTIPLE;
	const DUST_LIMIT_MSAT: u64 = 354 * 1000;
	const CHANNEL_VALUE_MSAT: u64 = 10_000 * 1000;
	const NODE_0_VALUE_TO_SELF_MSAT: u64 = 5_000 * 1000;
	const NODE_1_VALUE_TO_SELF_MSAT: u64 = 5_000 * 1000;
	const CHANNEL_RESERVE_MSAT: u64 = 1_000 * 1_000;

	let channel_id = create_announced_chan_between_nodes_with_value(
		&nodes,
		0,
		1,
		CHANNEL_VALUE_MSAT / 1000,
		NODE_1_VALUE_TO_SELF_MSAT,
	)
	.2;
	assert_eq!(nodes[0].node.list_channels()[0].channel_type.as_ref().unwrap(), &channel_type);

	// Find the HTLC amount that will be non-dust at the current feerate,
	// but dust at the spiked feerate.
	const SPIKED_DUST_HTLC_MSAT: u64 = 688 * 1000;
	const HTLC_SPIKE_DUST_LIMIT_MSAT: u64 = 689 * 1000;
	// When checking the fee spike buffer in `can_accept_incoming_htlc`, we check the remote
	// commitment, hence inbound HTLCs will be offered HTLCs, and use the timeout dust limit.
	let htlc_timeout_spike_tx_fee_msat =
		second_stage_tx_fees_sat(&channel_type, SPIKED_FEERATE).1 * 1000;
	assert_eq!(HTLC_SPIKE_DUST_LIMIT_MSAT, DUST_LIMIT_MSAT + htlc_timeout_spike_tx_fee_msat);

	// Calculate here the dust limit at the current feerate so we know when node 0 cannot send
	// any further non-dust HTLCs at the current feerate.
	let htlc_timeout_tx_fee_msat = second_stage_tx_fees_sat(&channel_type, FEERATE).1 * 1000;
	let htlc_dust_limit_msat = DUST_LIMIT_MSAT + htlc_timeout_tx_fee_msat;
	// Make sure the HTLC will be non-dust at the current feerate
	assert!(SPIKED_DUST_HTLC_MSAT > htlc_dust_limit_msat);

	// Place a few non-dust HTLCs on the commitment, these HTLCs would get trimmed upon a 2x
	// increase in the feerate.
	let mut sent_htlcs_count: usize = 0;
	let mut payment_hashes = Vec::new();
	while nodes[0].node.list_channels()[0].next_outbound_htlc_limit_msat >= htlc_dust_limit_msat {
		let (_preimage, hash, _secret, _id) =
			route_payment(&nodes[0], &[&nodes[1]], SPIKED_DUST_HTLC_MSAT);
		payment_hashes.push(hash);
		sent_htlcs_count += 1;
	}
	assert_eq!(sent_htlcs_count, 4);

	// Check the outbound and available capacities
	let node_0_outbound_capacity_msat = NODE_0_VALUE_TO_SELF_MSAT
		- sent_htlcs_count as u64 * SPIKED_DUST_HTLC_MSAT
		- CHANNEL_RESERVE_MSAT;
	let node_0_details = &nodes[0].node.list_channels()[0];
	assert_eq!(node_0_details.outbound_capacity_msat, node_0_outbound_capacity_msat);
	// Node 0 can now only send dust HTLCs, so we reserve the fees for a single additional
	// inbound non-dust HTLC.
	let min_reserved_fee_msat =
		commit_tx_fee_sat(SPIKED_FEERATE, sent_htlcs_count + 1, &channel_type) * 1000;
	let node_0_available_capacity_msat = node_0_outbound_capacity_msat - min_reserved_fee_msat;
	assert_eq!(node_0_details.next_outbound_htlc_limit_msat, node_0_available_capacity_msat);

	// Then send an identical, 5th non-dust HTLC, bypass the validation from the holder, and
	// check that the counterparty fails it due to a fee spike buffer violation.

	// First check the maths

	// Node 0 can afford an exact 2x increase in the feerate
	let spiked_commit_tx_fee_msat = commit_tx_fee_sat(SPIKED_FEERATE, 0, &channel_type) * 1000;
	assert!((node_0_outbound_capacity_msat - SPIKED_DUST_HTLC_MSAT)
		.checked_sub(spiked_commit_tx_fee_msat)
		.is_some());
	// Node 0 can afford a 5th non-dust HTLC at the current feerate, so `update_add_htlc`
	// validation will pass.
	let real_commit_tx_fee_msat = commit_tx_fee_sat(FEERATE, 5, &channel_type) * 1000;
	assert!((node_0_outbound_capacity_msat - SPIKED_DUST_HTLC_MSAT)
		.checked_sub(real_commit_tx_fee_msat)
		.is_some());
	// But we don't account for the HTLC trimming effect of the spike multiple feerate increase,
	//  so the 5th HTLC should be rejected at `can_accept_incoming_htlc`!
	let expected_commit_tx_fee_msat = commit_tx_fee_sat(SPIKED_FEERATE, 5, &channel_type) * 1000;
	assert!((node_0_outbound_capacity_msat - SPIKED_DUST_HTLC_MSAT)
		.checked_sub(expected_commit_tx_fee_msat)
		.is_none());

	// Then run the experiment

	let sender_amount_msat = node_0_available_capacity_msat;
	let receiver_amount_msat = SPIKED_DUST_HTLC_MSAT;
	let (route, payment_hash, _, payment_secret) =
		get_route_and_payment_hash!(nodes[0], nodes[1], sender_amount_msat);
	let secp_ctx = Secp256k1::new();
	let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
	let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
	let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv);
	let recipient_onion_fields =
		RecipientOnionFields::secret_only(payment_secret, sender_amount_msat);
	let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::test_build_onion_payloads(
		&route.paths[0],
		&recipient_onion_fields,
		cur_height,
		&None,
		None,
		None,
	)
	.unwrap();
	assert_eq!(htlc_msat, sender_amount_msat);
	let onion_packet =
		onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash)
			.unwrap();
	let msg = msgs::UpdateAddHTLC {
		channel_id,
		htlc_id: sent_htlcs_count as u64,
		amount_msat: receiver_amount_msat,
		payment_hash,
		cltv_expiry: htlc_cltv,
		onion_routing_packet: onion_packet,
		skimmed_fee_msat: None,
		blinding_point: None,
		hold_htlc: None,
		accountable: None,
	};

	nodes[1].node.handle_update_add_htlc(node_a_id, &msg);

	let htlcs_in_tx = vec![
		HTLCOutputInCommitment {
			offered: false,
			cltv_expiry: 81,
			payment_hash: payment_hashes.iter().find(|hash| hash.0[0] == 0x75).unwrap().clone(),
			amount_msat: 688_000,
			transaction_output_index: Some(0),
		},
		HTLCOutputInCommitment {
			offered: false,
			cltv_expiry: 81,
			payment_hash: payment_hashes.iter().find(|hash| hash.0[0] == 0x64).unwrap().clone(),
			amount_msat: 688_000,
			transaction_output_index: Some(1),
		},
		HTLCOutputInCommitment {
			offered: false,
			cltv_expiry: 81,
			payment_hash,
			amount_msat: 688_000,
			transaction_output_index: Some(2),
		},
		HTLCOutputInCommitment {
			offered: false,
			cltv_expiry: 81,
			payment_hash: payment_hashes.iter().find(|hash| hash.0[0] == 0x72).unwrap().clone(),
			amount_msat: 688_000,
			transaction_output_index: Some(3),
		},
		HTLCOutputInCommitment {
			offered: false,
			cltv_expiry: 81,
			payment_hash: payment_hashes.iter().find(|hash| hash.0[0] == 0x66).unwrap().clone(),
			amount_msat: 688_000,
			transaction_output_index: Some(4),
		},
	];

	manually_trigger_update_fail_htlc(
		&nodes,
		channel_id,
		NODE_0_VALUE_TO_SELF_MSAT,
		DUST_LIMIT_MSAT / 1000,
		payment_hash,
		htlcs_in_tx,
		true,
	);
}

#[xtest(feature = "_externalize_tests")]
fn test_available_balances_both_commitments_dust_on_funder_commitment() {
	let mut config = test_default_channel_config();

	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;

	let channel_type = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();

	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	const FEERATE: u32 = 253;
	const TOTAL_ANCHORS_MSAT: u64 = 2 * 330_000;
	const NODE_0_DUST_LIMIT_MSAT: u64 = 10_000 * 1000;
	const NODE_1_DUST_LIMIT_MSAT: u64 = 354 * 1000;
	const CHANNEL_VALUE_MSAT: u64 = 50_000 * 1000;
	const NODE_0_VALUE_TO_SELF_MSAT: u64 = 25_000 * 1000;
	const NODE_1_VALUE_TO_SELF_MSAT: u64 = 25_000 * 1000;
	const NODE_0_SELECTED_CHANNEL_RESERVE_MSAT: u64 = 1_000 * 1_000;
	const NODE_1_SELECTED_CHANNEL_RESERVE_MSAT: u64 = 10_000 * 1_000;

	let channel_id = create_announced_chan_between_nodes_with_value(
		&nodes,
		0,
		1,
		CHANNEL_VALUE_MSAT / 1000,
		NODE_1_VALUE_TO_SELF_MSAT,
	)
	.2;
	assert_eq!(nodes[0].node.list_channels()[0].channel_type.as_ref().unwrap(), &channel_type);

	{
		let per_peer_state_lock;
		let mut peer_state_lock;
		let chan =
			get_channel_ref!(nodes[0], nodes[1], per_peer_state_lock, peer_state_lock, channel_id);
		chan.context_mut().holder_dust_limit_satoshis = NODE_0_DUST_LIMIT_MSAT / 1000;
		chan.funding_mut().counterparty_selected_channel_reserve_satoshis =
			Some(NODE_1_SELECTED_CHANNEL_RESERVE_MSAT / 1000);
		assert_eq!(chan.context().counterparty_dust_limit_satoshis, NODE_1_DUST_LIMIT_MSAT / 1000);
		assert_eq!(
			chan.funding().holder_selected_channel_reserve_satoshis,
			NODE_0_SELECTED_CHANNEL_RESERVE_MSAT / 1000
		);
	}

	{
		let per_peer_state_lock;
		let mut peer_state_lock;
		let chan =
			get_channel_ref!(nodes[1], nodes[0], per_peer_state_lock, peer_state_lock, channel_id);
		chan.context_mut().counterparty_dust_limit_satoshis = NODE_0_DUST_LIMIT_MSAT / 1000;
		chan.funding_mut().holder_selected_channel_reserve_satoshis =
			NODE_1_SELECTED_CHANNEL_RESERVE_MSAT / 1000;
		assert_eq!(chan.context().holder_dust_limit_satoshis, NODE_1_DUST_LIMIT_MSAT / 1000);
		assert_eq!(
			chan.funding().counterparty_selected_channel_reserve_satoshis,
			Some(NODE_0_SELECTED_CHANNEL_RESERVE_MSAT / 1000)
		);
	}

	// This HTLC is only present on node 1's commitment
	const SNEAKY_HTLC_MSAT: u64 = 5_000_000;

	route_payment(&nodes[1], &[&nodes[0]], SNEAKY_HTLC_MSAT);

	let node_1_details = &nodes[1].node.list_channels()[0];
	let expected_outbound_capacity_msat =
		NODE_1_VALUE_TO_SELF_MSAT - SNEAKY_HTLC_MSAT - NODE_0_SELECTED_CHANNEL_RESERVE_MSAT;
	assert_eq!(node_1_details.outbound_capacity_msat, expected_outbound_capacity_msat);
	let expected_available_capacity_msat = expected_outbound_capacity_msat;
	assert_eq!(node_1_details.next_outbound_htlc_limit_msat, expected_available_capacity_msat);
	let expected_splice_out_max =
		NODE_1_VALUE_TO_SELF_MSAT / 1000 - SNEAKY_HTLC_MSAT / 1000 - NODE_1_DUST_LIMIT_MSAT / 1000;
	assert_eq!(node_1_details.next_splice_out_maximum_sat, expected_splice_out_max);

	let node_0_details = &nodes[0].node.list_channels()[0];
	let expected_outbound_capacity_msat =
		NODE_0_VALUE_TO_SELF_MSAT - NODE_1_SELECTED_CHANNEL_RESERVE_MSAT - TOTAL_ANCHORS_MSAT;
	assert_eq!(node_0_details.outbound_capacity_msat, expected_outbound_capacity_msat);
	let expected_available_capacity_msat =
		expected_outbound_capacity_msat - commit_tx_fee_sat(FEERATE, 3, &channel_type) * 1000;
	assert_eq!(node_0_details.next_outbound_htlc_limit_msat, expected_available_capacity_msat);
	let expected_splice_out_max = NODE_0_VALUE_TO_SELF_MSAT / 1000
		- TOTAL_ANCHORS_MSAT / 1000
		- commit_tx_fee_sat(FEERATE, 2, &channel_type)
		- NODE_0_DUST_LIMIT_MSAT / 1000;
	assert_eq!(node_0_details.next_splice_out_maximum_sat, expected_splice_out_max);

	let node_0_payment_msat = expected_available_capacity_msat;
	send_payment(&nodes[0], &[&nodes[1]], node_0_payment_msat);

	route_payment(&nodes[1], &[&nodes[0]], SNEAKY_HTLC_MSAT);
	route_payment(&nodes[1], &[&nodes[0]], SNEAKY_HTLC_MSAT);

	let node_0_details = &nodes[0].node.list_channels()[0];
	let expected_outbound_capacity_msat = NODE_0_VALUE_TO_SELF_MSAT
		- node_0_payment_msat
		- NODE_1_SELECTED_CHANNEL_RESERVE_MSAT
		- TOTAL_ANCHORS_MSAT;
	assert_eq!(node_0_details.outbound_capacity_msat, expected_outbound_capacity_msat);
	assert_eq!(
		node_0_details.outbound_capacity_msat,
		commit_tx_fee_sat(FEERATE, 3, &channel_type) * 1000
	);
	assert_eq!(node_0_details.next_outbound_htlc_limit_msat, 0);
	assert_eq!(node_0_details.next_splice_out_maximum_sat, 0);

	let node_1_details = &nodes[1].node.list_channels()[0];
	let expected_outbound_capacity_msat = NODE_1_VALUE_TO_SELF_MSAT + node_0_payment_msat
		- 3 * SNEAKY_HTLC_MSAT
		- NODE_0_SELECTED_CHANNEL_RESERVE_MSAT;
	assert_eq!(node_1_details.outbound_capacity_msat, expected_outbound_capacity_msat);
	let (_htlc_success_tx_fee_sat, htlc_timeout_tx_fee_sat) =
		second_stage_tx_fees_sat(&channel_type, FEERATE);
	let expected_available_capacity_msat =
		(NODE_1_DUST_LIMIT_MSAT / 1000 + htlc_timeout_tx_fee_sat) * 1000 - 1;
	assert_eq!(node_1_details.next_outbound_htlc_limit_msat, expected_available_capacity_msat);
	let expected_splice_out_max = NODE_1_VALUE_TO_SELF_MSAT / 1000 + node_0_payment_msat / 1000
		- 3 * SNEAKY_HTLC_MSAT / 1000
		- NODE_1_DUST_LIMIT_MSAT / 1000;
	assert_eq!(node_1_details.next_splice_out_maximum_sat, expected_splice_out_max);
}

#[xtest(feature = "_externalize_tests")]
fn test_available_balances_both_commitments_dust_on_fundee_commitment() {
	let mut config = test_default_channel_config();

	let chanmon_cfgs = create_chanmon_cfgs(2);
	let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
	config.channel_handshake_config.announced_channel_max_inbound_htlc_value_in_flight_percentage =
		100;

	let channel_type = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();

	let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
	let nodes = create_network(2, &node_cfgs, &node_chanmgrs);

	const FEERATE: u32 = 253;
	const TOTAL_ANCHORS_MSAT: u64 = 2 * 330_000;
	const NODE_0_DUST_LIMIT_MSAT: u64 = 354 * 1000;
	const NODE_1_DUST_LIMIT_MSAT: u64 = 10_000 * 1000;
	const CHANNEL_VALUE_MSAT: u64 = 50_000 * 1000;
	const NODE_0_VALUE_TO_SELF_MSAT: u64 = 25_000 * 1000;
	const NODE_1_VALUE_TO_SELF_MSAT: u64 = 25_000 * 1000;
	const NODE_0_SELECTED_CHANNEL_RESERVE_MSAT: u64 = 10_000 * 1_000;
	const NODE_1_SELECTED_CHANNEL_RESERVE_MSAT: u64 = 1_000 * 1_000;

	let channel_id = create_announced_chan_between_nodes_with_value(
		&nodes,
		0,
		1,
		CHANNEL_VALUE_MSAT / 1000,
		NODE_1_VALUE_TO_SELF_MSAT,
	)
	.2;
	assert_eq!(nodes[0].node.list_channels()[0].channel_type.as_ref().unwrap(), &channel_type);

	{
		let per_peer_state_lock;
		let mut peer_state_lock;
		let chan =
			get_channel_ref!(nodes[0], nodes[1], per_peer_state_lock, peer_state_lock, channel_id);
		chan.context_mut().counterparty_dust_limit_satoshis = NODE_1_DUST_LIMIT_MSAT / 1000;
		chan.funding_mut().holder_selected_channel_reserve_satoshis =
			NODE_0_SELECTED_CHANNEL_RESERVE_MSAT / 1000;
		assert_eq!(chan.context().holder_dust_limit_satoshis, NODE_0_DUST_LIMIT_MSAT / 1000);
		assert_eq!(
			chan.funding().counterparty_selected_channel_reserve_satoshis,
			Some(NODE_1_SELECTED_CHANNEL_RESERVE_MSAT / 1000)
		);
	}

	{
		let per_peer_state_lock;
		let mut peer_state_lock;
		let chan =
			get_channel_ref!(nodes[1], nodes[0], per_peer_state_lock, peer_state_lock, channel_id);
		chan.context_mut().holder_dust_limit_satoshis = NODE_1_DUST_LIMIT_MSAT / 1000;
		chan.funding_mut().counterparty_selected_channel_reserve_satoshis =
			Some(NODE_0_SELECTED_CHANNEL_RESERVE_MSAT / 1000);
		assert_eq!(chan.context().counterparty_dust_limit_satoshis, NODE_0_DUST_LIMIT_MSAT / 1000);
		assert_eq!(
			chan.funding().holder_selected_channel_reserve_satoshis,
			NODE_1_SELECTED_CHANNEL_RESERVE_MSAT / 1000
		);
	}

	// This HTLC is only present on node 0's commitment
	const SNEAKY_HTLC_MSAT: u64 = 5_000_000;

	route_payment(&nodes[1], &[&nodes[0]], SNEAKY_HTLC_MSAT);

	let node_1_details = &nodes[1].node.list_channels()[0];
	let expected_outbound_capacity_msat =
		NODE_1_VALUE_TO_SELF_MSAT - SNEAKY_HTLC_MSAT - NODE_0_SELECTED_CHANNEL_RESERVE_MSAT;
	assert_eq!(node_1_details.outbound_capacity_msat, expected_outbound_capacity_msat);
	let expected_available_capacity_msat = expected_outbound_capacity_msat;
	assert_eq!(node_1_details.next_outbound_htlc_limit_msat, expected_available_capacity_msat);
	let expected_splice_out_max =
		NODE_1_VALUE_TO_SELF_MSAT / 1000 - SNEAKY_HTLC_MSAT / 1000 - NODE_1_DUST_LIMIT_MSAT / 1000;
	assert_eq!(node_1_details.next_splice_out_maximum_sat, expected_splice_out_max);

	let node_0_details = &nodes[0].node.list_channels()[0];

	let expected_outbound_capacity_msat =
		NODE_0_VALUE_TO_SELF_MSAT - NODE_1_SELECTED_CHANNEL_RESERVE_MSAT - TOTAL_ANCHORS_MSAT;
	assert_eq!(node_0_details.outbound_capacity_msat, expected_outbound_capacity_msat);

	let expected_splice_out_max = NODE_0_VALUE_TO_SELF_MSAT / 1000
		- TOTAL_ANCHORS_MSAT / 1000
		- commit_tx_fee_sat(FEERATE, 2, &channel_type)
		- NODE_0_DUST_LIMIT_MSAT / 1000;
	assert_eq!(node_0_details.next_splice_out_maximum_sat, expected_splice_out_max);

	let expected_available_capacity_msat =
		expected_outbound_capacity_msat - commit_tx_fee_sat(FEERATE, 3, &channel_type) * 1000;
	assert_eq!(node_0_details.next_outbound_htlc_limit_msat, expected_available_capacity_msat);

	let node_0_payment_msat = expected_available_capacity_msat;
	send_payment(&nodes[0], &[&nodes[1]], node_0_payment_msat);

	route_payment(&nodes[1], &[&nodes[0]], SNEAKY_HTLC_MSAT);
	route_payment(&nodes[1], &[&nodes[0]], SNEAKY_HTLC_MSAT);

	let node_0_details = &nodes[0].node.list_channels()[0];
	let expected_outbound_capacity_msat = NODE_0_VALUE_TO_SELF_MSAT
		- node_0_payment_msat
		- NODE_1_SELECTED_CHANNEL_RESERVE_MSAT
		- TOTAL_ANCHORS_MSAT;
	assert_eq!(node_0_details.outbound_capacity_msat, expected_outbound_capacity_msat);
	assert_eq!(
		node_0_details.outbound_capacity_msat,
		commit_tx_fee_sat(FEERATE, 3, &channel_type) * 1000
	);
	assert_eq!(node_0_details.next_outbound_htlc_limit_msat, 0);

	let local_balance_before_fee_sat =
		NODE_0_VALUE_TO_SELF_MSAT / 1000 - node_0_payment_msat / 1000 - TOTAL_ANCHORS_MSAT / 1000;
	let post_splice_delta_above_reserve = commit_tx_fee_sat(FEERATE, 4, &channel_type);
	let divident_sat = local_balance_before_fee_sat * 100 + 100
		- (post_splice_delta_above_reserve * 100)
		- CHANNEL_VALUE_MSAT / 1000;
	let expected_splice_out_max = (divident_sat - 1) / 99;
	assert_eq!(node_0_details.next_splice_out_maximum_sat, expected_splice_out_max);

	let node_1_details = &nodes[1].node.list_channels()[0];
	let expected_outbound_capacity_msat = NODE_1_VALUE_TO_SELF_MSAT + node_0_payment_msat
		- 3 * SNEAKY_HTLC_MSAT
		- NODE_0_SELECTED_CHANNEL_RESERVE_MSAT;
	assert_eq!(node_1_details.outbound_capacity_msat, expected_outbound_capacity_msat);
	let (htlc_success_tx_fee_sat, _htlc_timeout_tx_fee_sat) =
		second_stage_tx_fees_sat(&channel_type, FEERATE);
	let expected_available_capacity_msat =
		(NODE_0_DUST_LIMIT_MSAT / 1000 + htlc_success_tx_fee_sat) * 1000 - 1;
	assert_eq!(node_1_details.next_outbound_htlc_limit_msat, expected_available_capacity_msat);
	let expected_splice_out_max = NODE_1_VALUE_TO_SELF_MSAT / 1000 + node_0_payment_msat / 1000
		- 3 * SNEAKY_HTLC_MSAT / 1000
		- NODE_1_DUST_LIMIT_MSAT / 1000;
	assert_eq!(node_1_details.next_splice_out_maximum_sat, expected_splice_out_max);
}