lightning 0.2.2

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

//! Various utilities to assemble claimable outpoints in package of one or more transactions. Those
//! packages are attached metadata, guiding their aggregable or fee-bumping re-schedule. This file
//! also includes witness weight computation and fee computation methods.

use bitcoin::amount::Amount;
use bitcoin::constants::WITNESS_SCALE_FACTOR;
use bitcoin::hash_types::Txid;
use bitcoin::locktime::absolute::LockTime;
use bitcoin::script::{Script, ScriptBuf};
use bitcoin::secp256k1::{PublicKey, SecretKey};
use bitcoin::sighash::EcdsaSighashType;
use bitcoin::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::transaction::Version;
use bitcoin::transaction::{Transaction, TxIn, TxOut};
use bitcoin::{Sequence, Witness};

use crate::chain::chaininterface::{
	compute_feerate_sat_per_1000_weight, ConfirmationTarget, FeeEstimator,
	FEERATE_FLOOR_SATS_PER_KW, INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT,
};
use crate::chain::channelmonitor::COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
use crate::chain::onchaintx::{FeerateStrategy, OnchainTxHandler};
use crate::chain::transaction::MaybeSignedTransaction;
use crate::ln::chan_utils::{
	self, ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction,
	TxCreationKeys,
};
use crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint};
use crate::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA;
use crate::ln::msgs::DecodeError;
use crate::sign::ecdsa::EcdsaChannelSigner;
use crate::sign::{ChannelDerivationParameters, HTLCDescriptor};
use crate::types::features::ChannelTypeFeatures;
use crate::types::payment::PaymentPreimage;
use crate::util::logger::Logger;
use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, Writeable, Writer};

use crate::io;
use core::cmp;
use core::ops::Deref;

#[allow(unused_imports)]
use crate::prelude::*;

use super::chaininterface::LowerBoundedFeeEstimator;

const MAX_ALLOC_SIZE: usize = 64 * 1024;

#[rustfmt::skip]
pub(crate) fn weight_revoked_offered_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
	// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
	const WEIGHT_REVOKED_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 133;
	const WEIGHT_REVOKED_OFFERED_HTLC_ANCHORS: u64 = WEIGHT_REVOKED_OFFERED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
	if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_REVOKED_OFFERED_HTLC_ANCHORS } else { WEIGHT_REVOKED_OFFERED_HTLC }
}

#[rustfmt::skip]
pub(crate) fn weight_revoked_received_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
	// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
	const WEIGHT_REVOKED_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 +  139;
	const WEIGHT_REVOKED_RECEIVED_HTLC_ANCHORS: u64 = WEIGHT_REVOKED_RECEIVED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
	if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_REVOKED_RECEIVED_HTLC_ANCHORS } else { WEIGHT_REVOKED_RECEIVED_HTLC }
}

#[rustfmt::skip]
pub(crate) fn weight_offered_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
	// number_of_witness_elements + sig_length + counterpartyhtlc_sig  + preimage_length + preimage + witness_script_length + witness_script
	const WEIGHT_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 32 + 1 + 133;
	const WEIGHT_OFFERED_HTLC_ANCHORS: u64 = WEIGHT_OFFERED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
	if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_OFFERED_HTLC_ANCHORS } else { WEIGHT_OFFERED_HTLC }
}

#[rustfmt::skip]
pub(crate) fn weight_received_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
	// number_of_witness_elements + sig_length + counterpartyhtlc_sig + empty_vec_length + empty_vec + witness_script_length + witness_script
	const WEIGHT_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 139;
	const WEIGHT_RECEIVED_HTLC_ANCHORS: u64 = WEIGHT_RECEIVED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
	if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_RECEIVED_HTLC_ANCHORS } else { WEIGHT_RECEIVED_HTLC }
}

/// Verifies deserializable channel type features
#[rustfmt::skip]
pub(crate) fn verify_channel_type_features(channel_type_features: &Option<ChannelTypeFeatures>, additional_permitted_features: Option<&ChannelTypeFeatures>) -> Result<(), DecodeError> {
	if let Some(features) = channel_type_features.as_ref() {
		if features.requires_unknown_bits() {
			return Err(DecodeError::UnknownRequiredFeature);
		}

		let mut supported_feature_set = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
		supported_feature_set.set_scid_privacy_required();
		supported_feature_set.set_zero_conf_required();
		supported_feature_set.set_anchor_zero_fee_commitments_required();

		// allow the passing of an additional necessary permitted flag
		if let Some(additional_permitted_features) = additional_permitted_features {
			supported_feature_set |= additional_permitted_features;
		}

		if features.requires_unknown_bits_from(&supported_feature_set) {
			return Err(DecodeError::UnknownRequiredFeature);
		}
	}

	Ok(())
}

// number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
pub(crate) const WEIGHT_REVOKED_OUTPUT: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 77;

#[cfg(not(any(test, feature = "_test_utils")))]
/// Height delay at which transactions are fee-bumped/rebroadcasted with a low priority.
const LOW_FREQUENCY_BUMP_INTERVAL: u32 = 15;
#[cfg(any(test, feature = "_test_utils"))]
/// Height delay at which transactions are fee-bumped/rebroadcasted with a low priority.
pub(crate) const LOW_FREQUENCY_BUMP_INTERVAL: u32 = 15;

/// Height delay at which transactions are fee-bumped/rebroadcasted with a middle priority.
const MIDDLE_FREQUENCY_BUMP_INTERVAL: u32 = 3;
/// Height delay at which transactions are fee-bumped/rebroadcasted with a high priority.
const HIGH_FREQUENCY_BUMP_INTERVAL: u32 = 1;

/// A struct to describe a revoked output and corresponding information to generate a solving
/// witness spending a commitment `to_local` output or a second-stage HTLC transaction output.
///
/// CSV and pubkeys are used as part of a witnessScript redeeming a balance output, amount is used
/// as part of the signature hash and revocation secret to generate a satisfying witness.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct RevokedOutput {
	per_commitment_point: PublicKey,
	counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
	counterparty_htlc_base_key: HtlcBasepoint,
	per_commitment_key: SecretKey,
	weight: u64,
	amount: Amount,
	on_counterparty_tx_csv: u16,
	channel_parameters: Option<ChannelTransactionParameters>,
	// Added in LDK 0.1.4/0.2 and always set since.
	outpoint_confirmation_height: Option<u32>,
}

impl RevokedOutput {
	#[rustfmt::skip]
	pub(crate) fn build(
		per_commitment_point: PublicKey, per_commitment_key: SecretKey, amount: Amount,
		channel_parameters: ChannelTransactionParameters,
		outpoint_confirmation_height: u32,
	) -> Self {
		let directed_params = channel_parameters.as_counterparty_broadcastable();
		let counterparty_keys = directed_params.broadcaster_pubkeys();
		let counterparty_delayed_payment_base_key = counterparty_keys.delayed_payment_basepoint;
		let counterparty_htlc_base_key = counterparty_keys.htlc_basepoint;
		let on_counterparty_tx_csv = directed_params.contest_delay();
		RevokedOutput {
			per_commitment_point,
			counterparty_delayed_payment_base_key,
			counterparty_htlc_base_key,
			per_commitment_key,
			weight: WEIGHT_REVOKED_OUTPUT,
			amount,
			on_counterparty_tx_csv,
			channel_parameters: Some(channel_parameters),
			outpoint_confirmation_height: Some(outpoint_confirmation_height),
		}
	}
}

impl_writeable_tlv_based!(RevokedOutput, {
	(0, per_commitment_point, required),
	(1, outpoint_confirmation_height, option), // Added in 0.1.4/0.2 and always set
	(2, counterparty_delayed_payment_base_key, required),
	(4, counterparty_htlc_base_key, required),
	(6, per_commitment_key, required),
	(8, weight, required),
	(10, amount, required),
	(12, on_counterparty_tx_csv, required),
	// Unused since 0.1, this setting causes downgrades to before 0.1 to refuse to
	// aggregate `RevokedOutput` claims, which is the more conservative stance.
	(14, is_counterparty_balance_on_anchors, (legacy, (), |_| Some(()))),
	(15, channel_parameters, (option: ReadableArgs, None)), // Added in 0.2.
});

/// A struct to describe a revoked offered output and corresponding information to generate a
/// solving witness.
///
/// HTLCOuputInCommitment (hash timelock, direction) and pubkeys are used to generate a suitable
/// witnessScript.
///
/// CSV is used as part of a witnessScript redeeming a balance output, amount is used as part
/// of the signature hash and revocation secret to generate a satisfying witness.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct RevokedHTLCOutput {
	per_commitment_point: PublicKey,
	counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
	counterparty_htlc_base_key: HtlcBasepoint,
	per_commitment_key: SecretKey,
	weight: u64,
	amount: u64,
	htlc: HTLCOutputInCommitment,
	channel_parameters: Option<ChannelTransactionParameters>,
	// Added in LDK 0.1.4/0.2 and always set since.
	outpoint_confirmation_height: Option<u32>,
}

impl RevokedHTLCOutput {
	pub(crate) fn build(
		per_commitment_point: PublicKey, per_commitment_key: SecretKey,
		htlc: HTLCOutputInCommitment, channel_parameters: ChannelTransactionParameters,
		outpoint_confirmation_height: u32,
	) -> Self {
		let weight = if htlc.offered {
			weight_revoked_offered_htlc(&channel_parameters.channel_type_features)
		} else {
			weight_revoked_received_htlc(&channel_parameters.channel_type_features)
		};
		let directed_params = channel_parameters.as_counterparty_broadcastable();
		let counterparty_keys = directed_params.broadcaster_pubkeys();
		let counterparty_delayed_payment_base_key = counterparty_keys.delayed_payment_basepoint;
		let counterparty_htlc_base_key = counterparty_keys.htlc_basepoint;
		RevokedHTLCOutput {
			per_commitment_point,
			counterparty_delayed_payment_base_key,
			counterparty_htlc_base_key,
			per_commitment_key,
			weight,
			amount: htlc.amount_msat / 1000,
			htlc,
			channel_parameters: Some(channel_parameters),
			outpoint_confirmation_height: Some(outpoint_confirmation_height),
		}
	}
}

impl_writeable_tlv_based!(RevokedHTLCOutput, {
	(0, per_commitment_point, required),
	(1, outpoint_confirmation_height, option), // Added in 0.1.4/0.2 and always set
	(2, counterparty_delayed_payment_base_key, required),
	(4, counterparty_htlc_base_key, required),
	(6, per_commitment_key, required),
	(8, weight, required),
	(10, amount, required),
	(12, htlc, required),
	(13, channel_parameters, (option: ReadableArgs, None)), // Added in 0.2.
});

/// A struct to describe a HTLC output on a counterparty commitment transaction.
///
/// HTLCOutputInCommitment (hash, timelock, directon) and pubkeys are used to generate a suitable
/// witnessScript.
///
/// The preimage is used as part of the witness.
///
/// Note that on upgrades, some features of existing outputs may be missed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CounterpartyOfferedHTLCOutput {
	per_commitment_point: PublicKey,
	counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
	counterparty_htlc_base_key: HtlcBasepoint,
	preimage: PaymentPreimage,
	htlc: HTLCOutputInCommitment,
	channel_type_features: ChannelTypeFeatures,
	channel_parameters: Option<ChannelTransactionParameters>,
	// Added in LDK 0.1.4/0.2 and always set since.
	outpoint_confirmation_height: Option<u32>,
}

impl CounterpartyOfferedHTLCOutput {
	pub(crate) fn build(
		per_commitment_point: PublicKey, preimage: PaymentPreimage, htlc: HTLCOutputInCommitment,
		channel_parameters: ChannelTransactionParameters,
		outpoint_confirmation_height: Option<u32>,
	) -> Self {
		let directed_params = channel_parameters.as_counterparty_broadcastable();
		let counterparty_keys = directed_params.broadcaster_pubkeys();
		let counterparty_delayed_payment_base_key = counterparty_keys.delayed_payment_basepoint;
		let counterparty_htlc_base_key = counterparty_keys.htlc_basepoint;
		let channel_type_features = channel_parameters.channel_type_features.clone();
		CounterpartyOfferedHTLCOutput {
			per_commitment_point,
			counterparty_delayed_payment_base_key,
			counterparty_htlc_base_key,
			preimage,
			htlc,
			channel_type_features,
			channel_parameters: Some(channel_parameters),
			outpoint_confirmation_height,
		}
	}
}

impl Writeable for CounterpartyOfferedHTLCOutput {
	#[rustfmt::skip]
	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
		let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
		write_tlv_fields!(writer, {
			(0, self.per_commitment_point, required),
			(1, self.outpoint_confirmation_height, option), // Added in 0.1.4/0.2, not always set
			(2, self.counterparty_delayed_payment_base_key, required),
			(4, self.counterparty_htlc_base_key, required),
			(6, self.preimage, required),
			(8, self.htlc, required),
			(10, legacy_deserialization_prevention_marker, option),
			(11, self.channel_type_features, required),
			(13, self.channel_parameters, option), // Added in 0.2.
		});
		Ok(())
	}
}

impl Readable for CounterpartyOfferedHTLCOutput {
	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
		let mut per_commitment_point = RequiredWrapper(None);
		let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
		let mut counterparty_htlc_base_key = RequiredWrapper(None);
		let mut preimage = RequiredWrapper(None);
		let mut htlc = RequiredWrapper(None);
		let mut _legacy_deserialization_prevention_marker: Option<()> = None;
		let mut channel_type_features = None;
		let mut channel_parameters = None;
		let mut outpoint_confirmation_height = None;

		read_tlv_fields!(reader, {
			(0, per_commitment_point, required),
			(1, outpoint_confirmation_height, option), // Added in 0.1.4/0.2, not always set
			(2, counterparty_delayed_payment_base_key, required),
			(4, counterparty_htlc_base_key, required),
			(6, preimage, required),
			(8, htlc, required),
			(10, _legacy_deserialization_prevention_marker, option),
			(11, channel_type_features, option),
			(13, channel_parameters, (option: ReadableArgs, None)), // Added in 0.2.
		});

		verify_channel_type_features(&channel_type_features, None)?;
		let channel_type_features =
			channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key());

		Ok(Self {
			per_commitment_point: per_commitment_point.0.unwrap(),
			counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
			counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
			preimage: preimage.0.unwrap(),
			htlc: htlc.0.unwrap(),
			channel_type_features,
			channel_parameters,
			outpoint_confirmation_height,
		})
	}
}

/// A struct to describe a HTLC output on a counterparty commitment transaction.
///
/// HTLCOutputInCommitment (hash, timelock, directon) and pubkeys are used to generate a suitable
/// witnessScript.
///
/// Note that on upgrades, some features of existing outputs may be missed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CounterpartyReceivedHTLCOutput {
	per_commitment_point: PublicKey,
	counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
	counterparty_htlc_base_key: HtlcBasepoint,
	htlc: HTLCOutputInCommitment,
	channel_type_features: ChannelTypeFeatures,
	channel_parameters: Option<ChannelTransactionParameters>,
	outpoint_confirmation_height: Option<u32>,
}

impl CounterpartyReceivedHTLCOutput {
	pub(crate) fn build(
		per_commitment_point: PublicKey, htlc: HTLCOutputInCommitment,
		channel_parameters: ChannelTransactionParameters,
		outpoint_confirmation_height: Option<u32>,
	) -> Self {
		let directed_params = channel_parameters.as_counterparty_broadcastable();
		let counterparty_keys = directed_params.broadcaster_pubkeys();
		let counterparty_delayed_payment_base_key = counterparty_keys.delayed_payment_basepoint;
		let counterparty_htlc_base_key = counterparty_keys.htlc_basepoint;
		let channel_type_features = channel_parameters.channel_type_features.clone();
		Self {
			per_commitment_point,
			counterparty_delayed_payment_base_key,
			counterparty_htlc_base_key,
			htlc,
			channel_type_features,
			channel_parameters: Some(channel_parameters),
			outpoint_confirmation_height,
		}
	}
}

impl Writeable for CounterpartyReceivedHTLCOutput {
	#[rustfmt::skip]
	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
		let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
		write_tlv_fields!(writer, {
			(0, self.per_commitment_point, required),
			(1, self.outpoint_confirmation_height, option), // Added in 0.1.4/0.2, not always set
			(2, self.counterparty_delayed_payment_base_key, required),
			(4, self.counterparty_htlc_base_key, required),
			(6, self.htlc, required),
			(8, legacy_deserialization_prevention_marker, option),
			(9, self.channel_type_features, required),
			(11, self.channel_parameters, option), // Added in 0.2.
		});
		Ok(())
	}
}

impl Readable for CounterpartyReceivedHTLCOutput {
	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
		let mut per_commitment_point = RequiredWrapper(None);
		let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
		let mut counterparty_htlc_base_key = RequiredWrapper(None);
		let mut htlc = RequiredWrapper(None);
		let mut _legacy_deserialization_prevention_marker: Option<()> = None;
		let mut channel_type_features = None;
		let mut channel_parameters = None;
		let mut outpoint_confirmation_height = None;

		read_tlv_fields!(reader, {
			(0, per_commitment_point, required),
			(1, outpoint_confirmation_height, option), // Added in 0.1.4/0.2, not always set
			(2, counterparty_delayed_payment_base_key, required),
			(4, counterparty_htlc_base_key, required),
			(6, htlc, required),
			(8, _legacy_deserialization_prevention_marker, option),
			(9, channel_type_features, option),
			(11, channel_parameters, (option: ReadableArgs, None)), // Added in 0.2.
		});

		verify_channel_type_features(&channel_type_features, None)?;
		let channel_type_features =
			channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key());

		Ok(Self {
			per_commitment_point: per_commitment_point.0.unwrap(),
			counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
			counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
			htlc: htlc.0.unwrap(),
			channel_type_features,
			channel_parameters,
			outpoint_confirmation_height,
		})
	}
}

/// A struct to describe a HTLC output on holder commitment transaction.
///
/// Either offered or received, the amount is always used as part of the bip143 sighash.
/// Preimage is only included as part of the witness in former case.
///
/// Note that on upgrades, some features of existing outputs may be missed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct HolderHTLCOutput {
	preimage: Option<PaymentPreimage>,
	amount_msat: u64,
	/// Defaults to 0 for HTLC-Success transactions, which have no expiry
	cltv_expiry: u32,
	channel_type_features: ChannelTypeFeatures,
	htlc_descriptor: Option<HTLCDescriptor>,
	outpoint_confirmation_height: Option<u32>,
}

impl HolderHTLCOutput {
	#[rustfmt::skip]
	pub(crate) fn build(
		htlc_descriptor: HTLCDescriptor, outpoint_confirmation_height: u32,
	) -> Self {
		let amount_msat = htlc_descriptor.htlc.amount_msat;
		let channel_type_features = htlc_descriptor.channel_derivation_parameters
			.transaction_parameters.channel_type_features.clone();
		Self {
			preimage: if htlc_descriptor.htlc.offered {
				None
			} else {
				Some(htlc_descriptor.preimage.expect("Preimage required for accepted holder HTLC claim"))
			},
			amount_msat,
			cltv_expiry: if htlc_descriptor.htlc.offered {
				htlc_descriptor.htlc.cltv_expiry
			} else {
				0
			},
			channel_type_features,
			htlc_descriptor: Some(htlc_descriptor),
			outpoint_confirmation_height: Some(outpoint_confirmation_height),
		}
	}

	#[rustfmt::skip]
	pub(crate) fn get_htlc_descriptor<ChannelSigner: EcdsaChannelSigner>(
		&self, onchain_tx_handler: &OnchainTxHandler<ChannelSigner>, outp: &::bitcoin::OutPoint,
	) -> Option<HTLCDescriptor> {
		// Either we have the descriptor, or we have to go construct it because it was not written.
		if let Some(htlc_descriptor) = self.htlc_descriptor.as_ref() {
			return Some(htlc_descriptor.clone());
		}

		let channel_parameters = onchain_tx_handler.channel_parameters();

		let get_htlc_descriptor = |holder_commitment: &HolderCommitmentTransaction| {
			let trusted_tx = holder_commitment.trust();
			if outp.txid != trusted_tx.txid() {
				return None;
			}

			let (htlc, counterparty_sig) =
				trusted_tx.nondust_htlcs().iter().zip(holder_commitment.counterparty_htlc_sigs.iter())
					.find(|(htlc, _)| htlc.transaction_output_index.unwrap() == outp.vout)
					.unwrap();

			Some(HTLCDescriptor {
				channel_derivation_parameters: ChannelDerivationParameters {
					value_satoshis: channel_parameters.channel_value_satoshis,
					keys_id: onchain_tx_handler.channel_keys_id(),
					transaction_parameters: channel_parameters.clone(),
				},
				commitment_txid: trusted_tx.txid(),
				per_commitment_number: trusted_tx.commitment_number(),
				per_commitment_point: trusted_tx.per_commitment_point(),
				feerate_per_kw: trusted_tx.negotiated_feerate_per_kw(),
				htlc: htlc.clone(),
				preimage: self.preimage.clone(),
				counterparty_sig: *counterparty_sig,
			})
		};

		// Check if the HTLC spends from the current holder commitment or the previous one otherwise.
		get_htlc_descriptor(onchain_tx_handler.current_holder_commitment_tx())
			.or_else(|| onchain_tx_handler.prev_holder_commitment_tx().and_then(|c| get_htlc_descriptor(c)))
	}

	#[rustfmt::skip]
	pub(crate) fn get_maybe_signed_htlc_tx<ChannelSigner: EcdsaChannelSigner>(
		&self, onchain_tx_handler: &mut OnchainTxHandler<ChannelSigner>, outp: &::bitcoin::OutPoint,
	) -> Option<MaybeSignedTransaction> {
		let htlc_descriptor = self.get_htlc_descriptor(onchain_tx_handler, outp)?;
		let channel_parameters = &htlc_descriptor.channel_derivation_parameters.transaction_parameters;
		let directed_parameters = channel_parameters.as_holder_broadcastable();
		let keys = TxCreationKeys::from_channel_static_keys(
			&htlc_descriptor.per_commitment_point, directed_parameters.broadcaster_pubkeys(),
			directed_parameters.countersignatory_pubkeys(), &onchain_tx_handler.secp_ctx,
		);

		let mut htlc_tx = chan_utils::build_htlc_transaction(
			&htlc_descriptor.commitment_txid, htlc_descriptor.feerate_per_kw,
			directed_parameters.contest_delay(), &htlc_descriptor.htlc,
			&channel_parameters.channel_type_features, &keys.broadcaster_delayed_payment_key,
			&keys.revocation_key
		);

		if let Ok(htlc_sig) = onchain_tx_handler.signer.sign_holder_htlc_transaction(
			&htlc_tx, 0, &htlc_descriptor, &onchain_tx_handler.secp_ctx,
		) {
			let htlc_redeem_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(
				&htlc_descriptor.htlc, &channel_parameters.channel_type_features,
				&keys.broadcaster_htlc_key, &keys.countersignatory_htlc_key, &keys.revocation_key,
			);
			htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
				&htlc_sig, &htlc_descriptor.counterparty_sig, &htlc_descriptor.preimage,
				&htlc_redeem_script, &channel_parameters.channel_type_features,
			);
		}

		Some(MaybeSignedTransaction(htlc_tx))
	}
}

impl Writeable for HolderHTLCOutput {
	#[rustfmt::skip]
	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
		let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
		write_tlv_fields!(writer, {
			(0, self.amount_msat, required),
			(1, self.outpoint_confirmation_height, option), // Added in 0.1.4/0.2 and always set
			(2, self.cltv_expiry, required),
			(4, self.preimage, option),
			(6, legacy_deserialization_prevention_marker, option),
			(7, self.channel_type_features, required),
			(9, self.htlc_descriptor, option), // Added in 0.2.
		});
		Ok(())
	}
}

impl Readable for HolderHTLCOutput {
	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
		let mut amount_msat = RequiredWrapper(None);
		let mut cltv_expiry = RequiredWrapper(None);
		let mut preimage = None;
		let mut _legacy_deserialization_prevention_marker: Option<()> = None;
		let mut channel_type_features = None;
		let mut htlc_descriptor = None;
		let mut outpoint_confirmation_height = None;

		read_tlv_fields!(reader, {
			(0, amount_msat, required),
			(1, outpoint_confirmation_height, option), // Added in 0.1.4/0.2 and always set
			(2, cltv_expiry, required),
			(4, preimage, option),
			(6, _legacy_deserialization_prevention_marker, option),
			(7, channel_type_features, option),
			(9, htlc_descriptor, option), // Added in 0.2.
		});

		verify_channel_type_features(&channel_type_features, None)?;
		let channel_type_features =
			channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key());

		Ok(Self {
			amount_msat: amount_msat.0.unwrap(),
			cltv_expiry: cltv_expiry.0.unwrap(),
			preimage,
			channel_type_features,
			htlc_descriptor,
			outpoint_confirmation_height,
		})
	}
}

/// A struct to describe the channel output on the funding transaction.
///
/// witnessScript is used as part of the witness redeeming the funding utxo.
///
/// Note that on upgrades, some features of existing outputs may be missed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct HolderFundingOutput {
	funding_redeemscript: ScriptBuf,
	pub(crate) funding_amount_sats: Option<u64>,
	channel_type_features: ChannelTypeFeatures,
	pub(crate) commitment_tx: Option<HolderCommitmentTransaction>,
	pub(crate) channel_parameters: Option<ChannelTransactionParameters>,
}

impl HolderFundingOutput {
	pub(crate) fn build(
		commitment_tx: HolderCommitmentTransaction,
		channel_parameters: ChannelTransactionParameters,
	) -> Self {
		let funding_redeemscript = channel_parameters.make_funding_redeemscript();
		let funding_amount_sats = channel_parameters.channel_value_satoshis;
		let channel_type_features = channel_parameters.channel_type_features.clone();
		HolderFundingOutput {
			funding_redeemscript,
			funding_amount_sats: Some(funding_amount_sats),
			channel_type_features,
			commitment_tx: Some(commitment_tx),
			channel_parameters: Some(channel_parameters),
		}
	}

	#[rustfmt::skip]
	pub(crate) fn get_maybe_signed_commitment_tx<Signer: EcdsaChannelSigner>(
		&self, onchain_tx_handler: &mut OnchainTxHandler<Signer>,
	) -> MaybeSignedTransaction {
		let channel_parameters = self.channel_parameters.as_ref()
			.unwrap_or(onchain_tx_handler.channel_parameters());
		let commitment_tx = self.commitment_tx.as_ref()
			.unwrap_or(onchain_tx_handler.current_holder_commitment_tx());
		let maybe_signed_tx = onchain_tx_handler.signer
			.sign_holder_commitment(channel_parameters, commitment_tx, &onchain_tx_handler.secp_ctx)
			.map(|holder_sig| {
				commitment_tx.add_holder_sig(&self.funding_redeemscript, holder_sig)
			})
			.unwrap_or_else(|_| {
				commitment_tx.trust().built_transaction().transaction.clone()
			});
		MaybeSignedTransaction(maybe_signed_tx)
	}
}

impl Writeable for HolderFundingOutput {
	#[rustfmt::skip]
	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
		let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
		write_tlv_fields!(writer, {
			(0, self.funding_redeemscript, required),
			(1, self.channel_type_features, required),
			(2, legacy_deserialization_prevention_marker, option),
			(3, self.funding_amount_sats, option),
			(5, self.commitment_tx, option), // Added in 0.2
			(7, self.channel_parameters, option), // Added in 0.2.
		});
		Ok(())
	}
}

impl Readable for HolderFundingOutput {
	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
		let mut funding_redeemscript = RequiredWrapper(None);
		let mut _legacy_deserialization_prevention_marker: Option<()> = None;
		let mut channel_type_features = None;
		let mut funding_amount_sats = None;
		let mut commitment_tx = None;
		let mut channel_parameters = None;

		read_tlv_fields!(reader, {
			(0, funding_redeemscript, required),
			(1, channel_type_features, option),
			(2, _legacy_deserialization_prevention_marker, option),
			(3, funding_amount_sats, option),
			(5, commitment_tx, option), // Added in 0.2.
			(7, channel_parameters, (option: ReadableArgs, None)), // Added in 0.2.
		});

		verify_channel_type_features(&channel_type_features, None)?;
		let channel_type_features =
			channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key());

		Ok(Self {
			funding_redeemscript: funding_redeemscript.0.unwrap(),
			funding_amount_sats,
			channel_type_features,
			commitment_tx,
			channel_parameters,
		})
	}
}

/// A wrapper encapsulating all in-protocol differing outputs types.
///
/// The generic API offers access to an outputs common attributes or allow transformation such as
/// finalizing an input claiming the output.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum PackageSolvingData {
	RevokedOutput(RevokedOutput),
	RevokedHTLCOutput(RevokedHTLCOutput),
	CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput),
	CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput),
	HolderHTLCOutput(HolderHTLCOutput),
	HolderFundingOutput(HolderFundingOutput),
}

impl PackageSolvingData {
	#[rustfmt::skip]
	fn amount(&self) -> u64 {
		let amt = match self {
			PackageSolvingData::RevokedOutput(ref outp) => outp.amount.to_sat(),
			PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.amount,
			PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000,
			PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000,
			PackageSolvingData::HolderHTLCOutput(ref outp) => {
				let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx();
				let free_commitments =
					outp.channel_type_features.supports_anchor_zero_fee_commitments();
				debug_assert!(free_htlcs || free_commitments);
				outp.amount_msat / 1000
			},
			PackageSolvingData::HolderFundingOutput(ref outp) => {
				let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx();
				let free_commitments =
					outp.channel_type_features.supports_anchor_zero_fee_commitments();
				debug_assert!(free_htlcs || free_commitments);
				outp.funding_amount_sats.unwrap()
			}
		};
		amt
	}
	#[rustfmt::skip]
	fn weight(&self) -> usize {
		match self {
			PackageSolvingData::RevokedOutput(ref outp) => outp.weight as usize,
			PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.weight as usize,
			PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => weight_offered_htlc(&outp.channel_type_features) as usize,
			PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => weight_received_htlc(&outp.channel_type_features) as usize,
			PackageSolvingData::HolderHTLCOutput(ref outp) => {
				let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx();
				let free_commitments =
					outp.channel_type_features.supports_anchor_zero_fee_commitments();
				debug_assert!(free_htlcs || free_commitments);
				if outp.preimage.is_none() {
					weight_offered_htlc(&outp.channel_type_features) as usize
				} else {
					weight_received_htlc(&outp.channel_type_features) as usize
				}
			},
			// Since HolderFundingOutput maps to an untractable package that is already signed, its
			// weight can be determined from the transaction itself.
			PackageSolvingData::HolderFundingOutput(..) => unreachable!(),
		}
	}

	/// Checks if this and `other` are spending types of inputs which could have descended from the
	/// same commitment transaction(s) and thus could both be spent without requiring a
	/// double-spend.
	#[rustfmt::skip]
	fn is_possibly_from_same_tx_tree(&self, other: &PackageSolvingData) -> bool {
		match self {
			PackageSolvingData::RevokedOutput(_)|PackageSolvingData::RevokedHTLCOutput(_) => {
				match other {
					PackageSolvingData::RevokedOutput(_)|
					PackageSolvingData::RevokedHTLCOutput(_) => true,
					_ => false,
				}
			},
			PackageSolvingData::CounterpartyOfferedHTLCOutput(_)|
			PackageSolvingData::CounterpartyReceivedHTLCOutput(_) => {
				match other {
					PackageSolvingData::CounterpartyOfferedHTLCOutput(_)|
					PackageSolvingData::CounterpartyReceivedHTLCOutput(_) => true,
					_ => false,
				}
			},
			PackageSolvingData::HolderHTLCOutput(_)|
			PackageSolvingData::HolderFundingOutput(_) => {
				match other {
					PackageSolvingData::HolderHTLCOutput(_)|
					PackageSolvingData::HolderFundingOutput(_) => true,
					_ => false,
				}
			},
		}
	}

	fn input_confirmation_height(&self) -> Option<u32> {
		match self {
			PackageSolvingData::RevokedOutput(RevokedOutput {
				outpoint_confirmation_height,
				..
			})
			| PackageSolvingData::RevokedHTLCOutput(RevokedHTLCOutput {
				outpoint_confirmation_height,
				..
			})
			| PackageSolvingData::CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput {
				outpoint_confirmation_height,
				..
			})
			| PackageSolvingData::CounterpartyReceivedHTLCOutput(
				CounterpartyReceivedHTLCOutput { outpoint_confirmation_height, .. },
			)
			| PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput {
				outpoint_confirmation_height,
				..
			}) => *outpoint_confirmation_height,
			// We don't bother to track `HolderFundingOutput`'s creation height as its the funding
			// transaction itself and we build `HolderFundingOutput`s before we actually get the
			// commitment transaction confirmed.
			PackageSolvingData::HolderFundingOutput(_) => None,
		}
	}

	#[rustfmt::skip]
	fn as_tx_input(&self, previous_output: BitcoinOutPoint) -> TxIn {
		let sequence = match self {
			PackageSolvingData::RevokedOutput(_) => Sequence::ENABLE_RBF_NO_LOCKTIME,
			PackageSolvingData::RevokedHTLCOutput(_) => Sequence::ENABLE_RBF_NO_LOCKTIME,
			PackageSolvingData::CounterpartyOfferedHTLCOutput(outp) => if outp.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
				Sequence::from_consensus(1)
			} else {
				Sequence::ENABLE_RBF_NO_LOCKTIME
			},
			PackageSolvingData::CounterpartyReceivedHTLCOutput(outp) => if outp.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
				Sequence::from_consensus(1)
			} else {
				Sequence::ENABLE_RBF_NO_LOCKTIME
			},
			_ => {
				debug_assert!(false, "This should not be reachable by 'untractable' or 'malleable with external funding' packages");
				Sequence::ENABLE_RBF_NO_LOCKTIME
			},
		};
		TxIn {
			previous_output,
			script_sig: ScriptBuf::new(),
			sequence,
			witness: Witness::new(),
		}
	}
	#[rustfmt::skip]
	fn finalize_input<Signer: EcdsaChannelSigner>(&self, bumped_tx: &mut Transaction, i: usize, onchain_handler: &mut OnchainTxHandler<Signer>) -> bool {
		let channel_parameters = onchain_handler.channel_parameters();
		match self {
			PackageSolvingData::RevokedOutput(ref outp) => {
				let channel_parameters = outp.channel_parameters.as_ref().unwrap_or(channel_parameters);
				let directed_parameters = channel_parameters.as_counterparty_broadcastable();
				debug_assert_eq!(
					directed_parameters.broadcaster_pubkeys().delayed_payment_basepoint,
					outp.counterparty_delayed_payment_base_key,
				);
				debug_assert_eq!(
					directed_parameters.broadcaster_pubkeys().htlc_basepoint,
					outp.counterparty_htlc_base_key,
				);
				let chan_keys = TxCreationKeys::from_channel_static_keys(
					&outp.per_commitment_point, directed_parameters.broadcaster_pubkeys(),
					directed_parameters.countersignatory_pubkeys(), &onchain_handler.secp_ctx,
				);
				let witness_script = chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, outp.on_counterparty_tx_csv, &chan_keys.broadcaster_delayed_payment_key);
				//TODO: should we panic on signer failure ?
				if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_output(channel_parameters, &bumped_tx, i, outp.amount.to_sat(), &outp.per_commitment_key, &onchain_handler.secp_ctx) {
					let mut ser_sig = sig.serialize_der().to_vec();
					ser_sig.push(EcdsaSighashType::All as u8);
					bumped_tx.input[i].witness.push(ser_sig);
					bumped_tx.input[i].witness.push(vec!(1));
					bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
				} else { return false; }
			},
			PackageSolvingData::RevokedHTLCOutput(ref outp) => {
				let channel_parameters = outp.channel_parameters.as_ref().unwrap_or(channel_parameters);
				let directed_parameters = channel_parameters.as_counterparty_broadcastable();
				debug_assert_eq!(
					directed_parameters.broadcaster_pubkeys().delayed_payment_basepoint,
					outp.counterparty_delayed_payment_base_key,
				);
				debug_assert_eq!(
					directed_parameters.broadcaster_pubkeys().htlc_basepoint,
					outp.counterparty_htlc_base_key,
				);
				let chan_keys = TxCreationKeys::from_channel_static_keys(
					&outp.per_commitment_point, directed_parameters.broadcaster_pubkeys(),
					directed_parameters.countersignatory_pubkeys(), &onchain_handler.secp_ctx,
				);
				let witness_script = chan_utils::get_htlc_redeemscript(
					&outp.htlc, &channel_parameters.channel_type_features, &chan_keys
				);
				//TODO: should we panic on signer failure ?
				if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_htlc(channel_parameters, &bumped_tx, i, outp.amount, &outp.per_commitment_key, &outp.htlc, &onchain_handler.secp_ctx) {
					let mut ser_sig = sig.serialize_der().to_vec();
					ser_sig.push(EcdsaSighashType::All as u8);
					bumped_tx.input[i].witness.push(ser_sig);
					bumped_tx.input[i].witness.push(chan_keys.revocation_key.to_public_key().serialize().to_vec());
					bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
				} else { return false; }
			},
			PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => {
				let channel_parameters = outp.channel_parameters.as_ref().unwrap_or(channel_parameters);
				let directed_parameters = channel_parameters.as_counterparty_broadcastable();
				debug_assert_eq!(
					directed_parameters.broadcaster_pubkeys().delayed_payment_basepoint,
					outp.counterparty_delayed_payment_base_key,
				);
				debug_assert_eq!(
					directed_parameters.broadcaster_pubkeys().htlc_basepoint,
					outp.counterparty_htlc_base_key,
				);
				let chan_keys = TxCreationKeys::from_channel_static_keys(
					&outp.per_commitment_point, directed_parameters.broadcaster_pubkeys(),
					directed_parameters.countersignatory_pubkeys(), &onchain_handler.secp_ctx,
				);
				let witness_script = chan_utils::get_htlc_redeemscript(
					&outp.htlc, &channel_parameters.channel_type_features, &chan_keys,
				);

				if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(channel_parameters, &bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
					let mut ser_sig = sig.serialize_der().to_vec();
					ser_sig.push(EcdsaSighashType::All as u8);
					bumped_tx.input[i].witness.push(ser_sig);
					bumped_tx.input[i].witness.push(outp.preimage.0.to_vec());
					bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
				}
			},
			PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => {
				let channel_parameters = outp.channel_parameters.as_ref().unwrap_or(channel_parameters);
				let directed_parameters = channel_parameters.as_counterparty_broadcastable();
				debug_assert_eq!(
					directed_parameters.broadcaster_pubkeys().delayed_payment_basepoint,
					outp.counterparty_delayed_payment_base_key,
				);
				debug_assert_eq!(
					directed_parameters.broadcaster_pubkeys().htlc_basepoint,
					outp.counterparty_htlc_base_key,
				);
				let chan_keys = TxCreationKeys::from_channel_static_keys(
					&outp.per_commitment_point, directed_parameters.broadcaster_pubkeys(),
					directed_parameters.countersignatory_pubkeys(), &onchain_handler.secp_ctx,
				);
				let witness_script = chan_utils::get_htlc_redeemscript(
					&outp.htlc, &channel_parameters.channel_type_features, &chan_keys,
				);

				if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(channel_parameters, &bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
					let mut ser_sig = sig.serialize_der().to_vec();
					ser_sig.push(EcdsaSighashType::All as u8);
					bumped_tx.input[i].witness.push(ser_sig);
					// Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
					bumped_tx.input[i].witness.push(vec![]);
					bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
				}
			},
			_ => { panic!("API Error!"); }
		}
		true
	}
	#[rustfmt::skip]
	fn get_maybe_finalized_tx<Signer: EcdsaChannelSigner>(&self, outpoint: &BitcoinOutPoint, onchain_handler: &mut OnchainTxHandler<Signer>) -> Option<MaybeSignedTransaction> {
		match self {
			PackageSolvingData::HolderHTLCOutput(ref outp) => {
				debug_assert!(!outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
				debug_assert!(!outp.channel_type_features.supports_anchor_zero_fee_commitments());
				outp.get_maybe_signed_htlc_tx(onchain_handler, outpoint)
			}
			PackageSolvingData::HolderFundingOutput(ref outp) => {
				Some(outp.get_maybe_signed_commitment_tx(onchain_handler))
			}
			_ => { panic!("API Error!"); }
		}
	}
	/// Some output types are locked with CHECKLOCKTIMEVERIFY and the spending transaction must
	/// have a minimum locktime, which is returned here.
	#[rustfmt::skip]
	fn minimum_locktime(&self) -> Option<u32> {
		match self {
			PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => Some(outp.htlc.cltv_expiry),
			_ => None,
		}
	}
	/// Some output types are pre-signed in such a way that the spending transaction must have an
	/// exact locktime. This returns that locktime for such outputs.
	fn signed_locktime(&self) -> Option<u32> {
		match self {
			PackageSolvingData::HolderHTLCOutput(ref outp) => {
				if outp.preimage.is_some() {
					debug_assert_eq!(outp.cltv_expiry, 0);
				}
				Some(outp.cltv_expiry)
			},
			_ => None,
		}
	}

	#[rustfmt::skip]
	fn map_output_type_flags(&self) -> PackageMalleability {
		// We classify claims into not-mergeable (i.e. transactions that have to be broadcasted
		// as-is) or merge-able (i.e. transactions we can merge with others and claim in batches),
		// which we then sub-categorize into pinnable (where our counterparty could potentially
		// also claim the transaction right now) or unpinnable (where only we can claim this
		// output). We assume we are claiming in a timely manner.
		match self {
			PackageSolvingData::RevokedOutput(RevokedOutput { .. }) =>
				PackageMalleability::Malleable(AggregationCluster::Unpinnable),
			PackageSolvingData::RevokedHTLCOutput(RevokedHTLCOutput { htlc, .. }) => {
				if htlc.offered {
					PackageMalleability::Malleable(AggregationCluster::Unpinnable)
				} else {
					PackageMalleability::Malleable(AggregationCluster::Pinnable)
				}
			},
			PackageSolvingData::CounterpartyOfferedHTLCOutput(..) =>
				PackageMalleability::Malleable(AggregationCluster::Unpinnable),
			PackageSolvingData::CounterpartyReceivedHTLCOutput(..) =>
				PackageMalleability::Malleable(AggregationCluster::Pinnable),
			PackageSolvingData::HolderHTLCOutput(ref outp) => {
				let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx();
				let free_commits = outp.channel_type_features.supports_anchor_zero_fee_commitments();

				if free_htlcs || free_commits {
					if outp.preimage.is_some() {
						PackageMalleability::Malleable(AggregationCluster::Unpinnable)
					} else {
						PackageMalleability::Malleable(AggregationCluster::Pinnable)
					}
				} else {
					PackageMalleability::Untractable
				}
			},
			PackageSolvingData::HolderFundingOutput(..) => PackageMalleability::Untractable,
		}
	}
}

impl_writeable_tlv_based_enum_legacy!(PackageSolvingData, ;
	(0, RevokedOutput),
	(1, RevokedHTLCOutput),
	(2, CounterpartyOfferedHTLCOutput),
	(3, CounterpartyReceivedHTLCOutput),
	(4, HolderHTLCOutput),
	(5, HolderFundingOutput),
);

/// We aggregate claims into clusters based on if we think the output is potentially pinnable by
/// our counterparty and whether the CLTVs required make sense to aggregate into one claim.
/// That way we avoid claiming in too many discrete transactions while also avoiding
/// unnecessarily exposing ourselves to pinning attacks or delaying claims when we could have
/// claimed at least part of the available outputs quickly and without risk.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum AggregationCluster {
	/// Our counterparty can potentially claim this output.
	Pinnable,
	/// We are the only party that can claim these funds, thus we believe they are not pinnable
	/// until they reach a CLTV/CSV expiry where our counterparty could also claim them.
	Unpinnable,
}

/// A malleable package might be aggregated with other packages to save on fees.
/// A untractable package has been counter-signed and aggregable will break cached counterparty signatures.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum PackageMalleability {
	Malleable(AggregationCluster),
	Untractable,
}

/// A structure to describe a package content that is generated by ChannelMonitor and
/// used by OnchainTxHandler to generate and broadcast transactions settling onchain claims.
///
/// A package is defined as one or more transactions claiming onchain outputs in reaction
/// to confirmation of a channel transaction. Those packages might be aggregated to save on
/// fees, if satisfaction of outputs's witnessScript let's us do so.
///
/// As packages are time-sensitive, we fee-bump and rebroadcast them at scheduled intervals.
/// Failing to confirm a package translate as a loss of funds for the user.
#[derive(Clone, Debug, Eq)]
pub struct PackageTemplate {
	// List of onchain outputs and solving data to generate satisfying witnesses.
	inputs: Vec<(BitcoinOutPoint, PackageSolvingData)>,
	// Packages are deemed as malleable if we have local knwoledge of at least one set of
	// private keys yielding a satisfying witnesses. Malleability implies that we can aggregate
	// packages among them to save on fees or rely on RBF to bump their feerates.
	// Untractable packages have been counter-signed and thus imply that we can't aggregate
	// them without breaking signatures. Fee-bumping strategy will also rely on CPFP.
	malleability: PackageMalleability,
	/// Block height at which our counterparty can potentially claim this output as well (assuming
	/// they have the keys or information required to do so).
	///
	/// This is used primarily to decide when an output becomes "pinnable" because the counterparty
	/// can potentially spend it. It is also used internally by [`Self::get_height_timer`] to
	/// identify when an output must be claimed by, depending on the type of output.
	///
	/// Note that for revoked counterparty HTLC outputs the value may be zero in some cases where
	/// we upgraded from LDK 0.1 or prior.
	counterparty_spendable_height: u32,
	// Cache of package feerate committed at previous (re)broadcast. If bumping resources
	// (either claimed output value or external utxo), it will keep increasing until holder
	// or counterparty successful claim.
	feerate_previous: u64,
	// Cache of next height at which fee-bumping and rebroadcast will be attempted. In
	// the future, we might abstract it to an observed mempool fluctuation.
	height_timer: u32,
}

impl PartialEq for PackageTemplate {
	fn eq(&self, o: &Self) -> bool {
		if self.inputs != o.inputs
			|| self.malleability != o.malleability
			|| self.feerate_previous != o.feerate_previous
			|| self.height_timer != o.height_timer
		{
			return false;
		}
		#[cfg(test)]
		{
			// In some cases we may reset `counterparty_spendable_height` to zero on reload, which
			// can cause our test assertions that ChannelMonitors round-trip exactly to trip. Here
			// we allow exactly the same case as we tweak in the `PackageTemplate` `Readable`
			// implementation.
			if self.counterparty_spendable_height == 0 {
				for (_, input) in self.inputs.iter() {
					if let PackageSolvingData::RevokedHTLCOutput(RevokedHTLCOutput {
						htlc, ..
					}) = input
					{
						if !htlc.offered && htlc.cltv_expiry != 0 {
							return true;
						}
					}
				}
			}
			if o.counterparty_spendable_height == 0 {
				for (_, input) in o.inputs.iter() {
					if let PackageSolvingData::RevokedHTLCOutput(RevokedHTLCOutput {
						htlc, ..
					}) = input
					{
						if !htlc.offered && htlc.cltv_expiry != 0 {
							return true;
						}
					}
				}
			}
		}
		self.counterparty_spendable_height == o.counterparty_spendable_height
	}
}

impl PackageTemplate {
	#[rustfmt::skip]
	pub(crate) fn can_merge_with(&self, other: &PackageTemplate, cur_height: u32) -> bool {
		match (self.malleability, other.malleability) {
			(PackageMalleability::Untractable, _) => false,
			(_, PackageMalleability::Untractable) => false,
			(PackageMalleability::Malleable(self_cluster), PackageMalleability::Malleable(other_cluster)) => {
				if self.inputs.is_empty() {
					return false;
				}
				if other.inputs.is_empty() {
					return false;
				}

				// First check the types of the inputs and don't merge if they are possibly claiming
				// from different commitment transactions at the same time.
				// This shouldn't ever happen, but if we do end up with packages trying to claim
				// funds from two different commitment transactions (which cannot possibly be
				// on-chain at the same time), we definitely shouldn't merge them.
				#[cfg(debug_assertions)]
				{
					for i in 0..self.inputs.len() {
						for j in 0..i {
							debug_assert!(self.inputs[i].1.is_possibly_from_same_tx_tree(&self.inputs[j].1));
						}
					}
					for i in 0..other.inputs.len() {
						for j in 0..i {
							assert!(other.inputs[i].1.is_possibly_from_same_tx_tree(&other.inputs[j].1));
						}
					}
				}
				if !self.inputs[0].1.is_possibly_from_same_tx_tree(&other.inputs[0].1) {
					debug_assert!(false, "We shouldn't have packages from different tx trees");
					return false;
				}

				// Check if the packages have signed locktimes. If they do, we only want to aggregate
				// packages with the same, signed locktime.
				if self.signed_locktime() != other.signed_locktime() {
					return false;
				}
				// Check if the two packages have compatible minimum locktimes.
				if self.package_locktime(cur_height) != other.package_locktime(cur_height) {
					return false;
				}

				// Now check that we only merge packages if they are both unpinnable or both
				// pinnable.
				let self_pinnable = self_cluster == AggregationCluster::Pinnable ||
					self.counterparty_spendable_height <= cur_height + COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
				let other_pinnable = other_cluster == AggregationCluster::Pinnable ||
					other.counterparty_spendable_height <= cur_height + COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
				if self_pinnable && other_pinnable {
					return true;
				}

				let self_unpinnable = self_cluster == AggregationCluster::Unpinnable &&
					self.counterparty_spendable_height > cur_height + COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
				let other_unpinnable = other_cluster == AggregationCluster::Unpinnable &&
					other.counterparty_spendable_height > cur_height + COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
				if self_unpinnable && other_unpinnable {
					return true;
				}
				false
			},
		}
	}
	pub(crate) fn is_malleable(&self) -> bool {
		matches!(self.malleability, PackageMalleability::Malleable(..))
	}
	pub(crate) fn previous_feerate(&self) -> u64 {
		self.feerate_previous
	}
	pub(crate) fn set_feerate(&mut self, new_feerate: u64) {
		self.feerate_previous = new_feerate;
	}
	pub(crate) fn timer(&self) -> u32 {
		self.height_timer
	}
	pub(crate) fn set_timer(&mut self, new_timer: u32) {
		self.height_timer = new_timer;
	}
	pub(crate) fn outpoints(&self) -> Vec<&BitcoinOutPoint> {
		self.inputs.iter().map(|(o, _)| o).collect()
	}
	pub(crate) fn outpoints_and_creation_heights(
		&self,
	) -> impl Iterator<Item = (&BitcoinOutPoint, Option<u32>)> {
		self.inputs.iter().map(|(o, p)| (o, p.input_confirmation_height()))
	}

	pub(crate) fn inputs(&self) -> impl ExactSizeIterator<Item = &PackageSolvingData> {
		self.inputs.iter().map(|(_, i)| i)
	}
	#[rustfmt::skip]
	pub(crate) fn split_package(&mut self, split_outp: &BitcoinOutPoint) -> Option<PackageTemplate> {
		match self.malleability {
			PackageMalleability::Malleable(cluster) => {
				let mut split_package = None;
				let feerate_previous = self.feerate_previous;
				let height_timer = self.height_timer;
				self.inputs.retain(|outp| {
					if *split_outp == outp.0 {
						split_package = Some(PackageTemplate {
							inputs: vec![(outp.0, outp.1.clone())],
							malleability: PackageMalleability::Malleable(cluster),
							counterparty_spendable_height: self.counterparty_spendable_height,
							feerate_previous,
							height_timer,
						});
						return false;
					}
					return true;
				});
				return split_package;
			},
			_ => {
				// Note, we may try to split on remote transaction for
				// which we don't have a competing one (HTLC-Success before
				// timelock expiration). This explain we don't panic!
				// We should refactor OnchainTxHandler::block_connected to
				// only test equality on competing claims.
				return None;
			}
		}
	}
	pub(crate) fn merge_package(
		&mut self, mut merge_from: PackageTemplate, cur_height: u32,
	) -> Result<(), PackageTemplate> {
		if !self.can_merge_with(&merge_from, cur_height) {
			return Err(merge_from);
		}
		for (k, v) in merge_from.inputs.drain(..) {
			self.inputs.push((k, v));
		}
		//TODO: verify coverage and sanity?
		if self.counterparty_spendable_height > merge_from.counterparty_spendable_height {
			self.counterparty_spendable_height = merge_from.counterparty_spendable_height;
		}
		if self.feerate_previous > merge_from.feerate_previous {
			self.feerate_previous = merge_from.feerate_previous;
		}
		self.height_timer = cmp::min(self.height_timer, merge_from.height_timer);
		Ok(())
	}
	/// Gets the amount of all outptus being spent by this package, only valid for malleable
	/// packages.
	pub(crate) fn package_amount(&self) -> u64 {
		let mut amounts = 0;
		for (_, outp) in self.inputs.iter() {
			amounts += outp.amount();
		}
		amounts
	}
	#[rustfmt::skip]
	fn signed_locktime(&self) -> Option<u32> {
		let signed_locktime = self.inputs.iter().find_map(|(_, outp)| outp.signed_locktime());
		#[cfg(debug_assertions)]
		for (_, outp) in &self.inputs {
			debug_assert!(outp.signed_locktime().is_none() || outp.signed_locktime() == signed_locktime);
		}
		signed_locktime
	}
	#[rustfmt::skip]
	pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
		let minimum_locktime = self.inputs.iter().filter_map(|(_, outp)| outp.minimum_locktime()).max();

		if let Some(signed_locktime) = self.signed_locktime() {
			debug_assert!(minimum_locktime.is_none());
			signed_locktime
		} else {
			core::cmp::max(current_height, minimum_locktime.unwrap_or(0))
		}
	}
	pub(crate) fn package_weight(&self, destination_script: &Script) -> u64 {
		let mut inputs_weight = 0;
		let mut witnesses_weight = 2; // count segwit flags
		for (_, outp) in self.inputs.iter() {
			// previous_out_point: 36 bytes ; var_int: 1 byte ; sequence: 4 bytes
			inputs_weight += 41 * WITNESS_SCALE_FACTOR;
			witnesses_weight += outp.weight();
		}
		// version: 4 bytes ; count_tx_in: 1 byte ; count_tx_out: 1 byte ; lock_time: 4 bytes
		let transaction_weight = 10 * WITNESS_SCALE_FACTOR;
		// value: 8 bytes ; var_int: 1 byte ; pk_script: `destination_script.len()`
		let output_weight = (8 + 1 + destination_script.len()) * WITNESS_SCALE_FACTOR;
		(inputs_weight + witnesses_weight + transaction_weight + output_weight) as u64
	}
	#[rustfmt::skip]
	pub(crate) fn construct_malleable_package_with_external_funding<Signer: EcdsaChannelSigner>(
		&self, onchain_handler: &mut OnchainTxHandler<Signer>,
	) -> Option<Vec<HTLCDescriptor>> {
		debug_assert!(self.requires_external_funding());
		let mut htlcs: Option<Vec<HTLCDescriptor>> = None;
		for (previous_output, input) in &self.inputs {
			match input {
				PackageSolvingData::HolderHTLCOutput(ref outp) => {
					let free_htlcs = outp.channel_type_features.supports_anchors_zero_fee_htlc_tx();
					let free_commitments =
						outp.channel_type_features.supports_anchor_zero_fee_commitments();
					debug_assert!(free_htlcs || free_commitments);
					outp.get_htlc_descriptor(onchain_handler, &previous_output).map(|htlc| {
						htlcs.get_or_insert_with(|| Vec::with_capacity(self.inputs.len())).push(htlc);
					});
				}
				_ => debug_assert!(false, "Expected HolderHTLCOutputs to not be aggregated with other input types"),
			}
		}
		htlcs
	}
	#[rustfmt::skip]
	pub(crate) fn maybe_finalize_malleable_package<L: Logger, Signer: EcdsaChannelSigner>(
		&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: Amount,
		destination_script: ScriptBuf, logger: &L
	) -> Option<MaybeSignedTransaction> {
		debug_assert!(self.is_malleable());
		let mut bumped_tx = Transaction {
			version: Version::TWO,
			lock_time: LockTime::from_consensus(self.package_locktime(current_height)),
			input: vec![],
			output: vec![TxOut {
				script_pubkey: destination_script,
				value,
			}],
		};
		for (outpoint, outp) in self.inputs.iter() {
			bumped_tx.input.push(outp.as_tx_input(*outpoint));
		}
		for (i, (outpoint, out)) in self.inputs.iter().enumerate() {
			log_debug!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
			if !out.finalize_input(&mut bumped_tx, i, onchain_handler) { continue; }
		}
		Some(MaybeSignedTransaction(bumped_tx))
	}
	#[rustfmt::skip]
	pub(crate) fn maybe_finalize_untractable_package<L: Logger, Signer: EcdsaChannelSigner>(
		&self, onchain_handler: &mut OnchainTxHandler<Signer>, logger: &L,
	) -> Option<MaybeSignedTransaction> {
		debug_assert!(!self.is_malleable());
		if let Some((outpoint, outp)) = self.inputs.first() {
			if let Some(final_tx) = outp.get_maybe_finalized_tx(outpoint, onchain_handler) {
				log_debug!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
				return Some(final_tx);
			}
			return None;
		} else { panic!("API Error: Package must not be inputs empty"); }
	}
	/// Gets the next height at which we should fee-bump this package, assuming we can do so and
	/// the package is last fee-bumped at `current_height`.
	///
	/// As the deadline with which to get a claim confirmed approaches, the rate at which the timer
	/// ticks increases.
	#[rustfmt::skip]
	pub(crate) fn get_height_timer(&self, current_height: u32) -> u32 {
		let mut height_timer = current_height + LOW_FREQUENCY_BUMP_INTERVAL;
		let timer_for_target_conf = |target_conf| -> u32 {
			if target_conf <= current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL {
				current_height + HIGH_FREQUENCY_BUMP_INTERVAL
			} else if target_conf <= current_height + LOW_FREQUENCY_BUMP_INTERVAL {
				current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL
			} else {
				current_height + LOW_FREQUENCY_BUMP_INTERVAL
			}
		};
		for (_, input) in self.inputs.iter() {
			match input {
				PackageSolvingData::RevokedOutput(_) => {
					// Revoked Outputs will become spendable by our counterparty at the height
					// where the CSV expires, which is also our `counterparty_spendable_height`.
					height_timer = cmp::min(
						height_timer,
						timer_for_target_conf(self.counterparty_spendable_height),
					);
				},
				PackageSolvingData::RevokedHTLCOutput(_) => {
					// Revoked HTLC Outputs may be spendable by our counterparty right now, but
					// after they spend them they still have to wait for an additional CSV delta
					// before they can claim the full funds. Thus, we leave the timer at
					// `LOW_FREQUENCY_BUMP_INTERVAL` until the HTLC output is spent, creating a
					// `RevokedOutput`.
				},
				PackageSolvingData::CounterpartyOfferedHTLCOutput(outp) => {
					// Incoming HTLCs being claimed by preimage should be claimed by the time their
					// CLTV unlocks.
					height_timer = cmp::min(
						height_timer,
						timer_for_target_conf(outp.htlc.cltv_expiry),
					);
				},
				PackageSolvingData::HolderHTLCOutput(outp) if outp.preimage.is_some() => {
					// We have the same deadline here as for `CounterpartyOfferedHTLCOutput`. Note
					// that `outp.cltv_expiry` is always 0 in this case, but
					// `counterparty_spendable_height` holds the real HTLC expiry.
					height_timer = cmp::min(
						height_timer,
						timer_for_target_conf(self.counterparty_spendable_height),
					);
				},
				PackageSolvingData::CounterpartyReceivedHTLCOutput(outp) => {
					// Outgoing HTLCs being claimed through their timeout should be claimed fast
					// enough to allow us to claim before the CLTV lock expires on the inbound
					// edge (assuming the HTLC was forwarded).
					height_timer = cmp::min(
						height_timer,
						timer_for_target_conf(outp.htlc.cltv_expiry + MIN_CLTV_EXPIRY_DELTA as u32),
					);
				},
				PackageSolvingData::HolderHTLCOutput(outp) => {
					// We have the same deadline for holder timeout claims as for
					// `CounterpartyReceivedHTLCOutput`
					height_timer = cmp::min(
						height_timer,
						timer_for_target_conf(outp.cltv_expiry + MIN_CLTV_EXPIRY_DELTA as u32),
					);
				},
				PackageSolvingData::HolderFundingOutput(_) => {
					// We should apply a smart heuristic here based on the HTLCs in the commitment
					// transaction, but we don't currently have that information available so
					// instead we just bump once per block.
					height_timer =
						cmp::min(height_timer, current_height + HIGH_FREQUENCY_BUMP_INTERVAL);
				},
			}
		}
		height_timer
	}

	/// Returns value in satoshis to be included as package outgoing output amount and feerate
	/// which was used to generate the value. Will not return less than `dust_limit_sats` for the
	/// value.
	#[rustfmt::skip]
	pub(crate) fn compute_package_output<F: Deref, L: Logger>(
		&self, predicted_weight: u64, dust_limit_sats: u64, feerate_strategy: &FeerateStrategy,
		conf_target: ConfirmationTarget, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
	) -> Option<(u64, u64)>
	where F::Target: FeeEstimator,
	{
		debug_assert!(matches!(self.malleability, PackageMalleability::Malleable(..)),
			"The package output is fixed for non-malleable packages");
		let input_amounts = self.package_amount();
		assert!(dust_limit_sats as i64 > 0, "Output script must be broadcastable/have a 'real' dust limit.");
		// If old feerate is 0, first iteration of this claim, use normal fee calculation
		if self.feerate_previous != 0 {
			if let Some((new_fee, feerate)) = feerate_bump(
				predicted_weight, input_amounts, dust_limit_sats, self.feerate_previous,
				feerate_strategy, conf_target, fee_estimator, logger,
			) {
				return Some((cmp::max(input_amounts.saturating_sub(new_fee), dust_limit_sats), feerate));
			}
		} else {
			if let Some((new_fee, feerate)) = compute_fee_from_spent_amounts(input_amounts, predicted_weight, conf_target, fee_estimator, logger) {
				return Some((cmp::max(input_amounts.saturating_sub(new_fee), dust_limit_sats), feerate));
			}
		}
		None
	}

	/// Computes a feerate based on the given confirmation target and feerate strategy.
	#[rustfmt::skip]
	pub(crate) fn compute_package_feerate<F: Deref>(
		&self, fee_estimator: &LowerBoundedFeeEstimator<F>, conf_target: ConfirmationTarget,
		feerate_strategy: &FeerateStrategy,
	) -> u32 where F::Target: FeeEstimator {
		let feerate_estimate = fee_estimator.bounded_sat_per_1000_weight(conf_target);
		if self.feerate_previous != 0 {
			let previous_feerate = self.feerate_previous.try_into().unwrap_or(u32::max_value());
			match feerate_strategy {
				FeerateStrategy::RetryPrevious => previous_feerate,
				FeerateStrategy::HighestOfPreviousOrNew => cmp::max(previous_feerate, feerate_estimate),
				FeerateStrategy::ForceBump => if feerate_estimate > previous_feerate {
					feerate_estimate
				} else {
					// Our fee estimate has decreased, but our transaction remains unconfirmed after
					// using our previous fee estimate. This may point to an unreliable fee estimator,
					// so we choose to bump our previous feerate by 25%, making sure we don't use a
					// lower feerate or overpay by a large margin by limiting it to 5x the new fee
					// estimate.
					let previous_feerate = self.feerate_previous.try_into().unwrap_or(u32::max_value());
					let mut new_feerate = previous_feerate.saturating_add(previous_feerate / 4);
					if new_feerate > feerate_estimate * 5 {
						new_feerate = cmp::max(feerate_estimate * 5, previous_feerate);
					}
					new_feerate
				},
			}
		} else {
			feerate_estimate
		}
	}

	/// Determines whether a package contains an input which must have additional external inputs
	/// attached to help the spending transaction reach confirmation.
	#[rustfmt::skip]
	pub(crate) fn requires_external_funding(&self) -> bool {
		self.inputs.iter().find(|input| match input.1 {
			PackageSolvingData::HolderFundingOutput(ref outp) => {
				outp.channel_type_features.supports_anchors_zero_fee_htlc_tx()
					|| outp.channel_type_features.supports_anchor_zero_fee_commitments()
			},
			PackageSolvingData::HolderHTLCOutput(ref outp) => {
				outp.channel_type_features.supports_anchors_zero_fee_htlc_tx()
					|| outp.channel_type_features.supports_anchor_zero_fee_commitments()
			},
			_ => false,
		}).is_some()
	}

	pub(crate) fn build_package(
		txid: Txid, vout: u32, input_solving_data: PackageSolvingData,
		counterparty_spendable_height: u32,
	) -> Self {
		let malleability = PackageSolvingData::map_output_type_flags(&input_solving_data);
		let inputs = vec![(BitcoinOutPoint { txid, vout }, input_solving_data)];
		PackageTemplate {
			inputs,
			malleability,
			counterparty_spendable_height,
			feerate_previous: 0,
			height_timer: 0,
		}
	}
}

impl Writeable for PackageTemplate {
	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
		writer.write_all(&(self.inputs.len() as u64).to_be_bytes())?;
		for (ref outpoint, ref rev_outp) in self.inputs.iter() {
			outpoint.write(writer)?;
			rev_outp.write(writer)?;
		}
		write_tlv_fields!(writer, {
			(0, self.counterparty_spendable_height, required),
			(2, self.feerate_previous, required),
			// Prior to 0.1, the height at which the package's inputs were mined, but was always unused
			(4, 0u32, required),
			(6, self.height_timer, required)
		});
		Ok(())
	}
}

impl Readable for PackageTemplate {
	#[rustfmt::skip]
	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
		let inputs_count = <u64 as Readable>::read(reader)?;
		let mut inputs: Vec<(BitcoinOutPoint, PackageSolvingData)> = Vec::with_capacity(cmp::min(inputs_count as usize, MAX_ALLOC_SIZE / 128));
		for _ in 0..inputs_count {
			let outpoint = Readable::read(reader)?;
			let rev_outp = Readable::read(reader)?;
			inputs.push((outpoint, rev_outp));
		}
		let malleability = if let Some((_, lead_input)) = inputs.first() {
			PackageSolvingData::map_output_type_flags(&lead_input)
		} else { return Err(DecodeError::InvalidValue); };
		let mut counterparty_spendable_height = 0;
		let mut feerate_previous = 0;
		let mut height_timer = None;
		let mut _height_original: Option<u32> = None;
		read_tlv_fields!(reader, {
			(0, counterparty_spendable_height, required),
			(2, feerate_previous, required),
			(4, _height_original, option), // Written with a dummy value since 0.1
			(6, height_timer, option),
		});
		for (_, input) in &inputs {
			if let PackageSolvingData::RevokedHTLCOutput(RevokedHTLCOutput { htlc, .. }) = input {
				// LDK versions through 0.1 set the wrong counterparty_spendable_height for
				// non-offered revoked HTLCs (ie HTLCs we sent to our counterparty which they can
				// claim with a preimage immediately). Here we detect this and reset the value to
				// zero, as the value is unused except for merging decisions which doesn't care
				// about any values below the current height.
				if !htlc.offered && htlc.cltv_expiry == counterparty_spendable_height {
					counterparty_spendable_height = 0;
				}
			}
		}
		Ok(PackageTemplate {
			inputs,
			malleability,
			counterparty_spendable_height,
			feerate_previous,
			height_timer: height_timer.unwrap_or(0),
		})
	}
}

/// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
/// weight. We first try our estimator's feerate, if it's not enough we try to sweep half of the
/// input amounts.
///
/// If the proposed fee is less than the available spent output's values, we return the proposed
/// fee and the corresponding updated feerate. If fee is under [`FEERATE_FLOOR_SATS_PER_KW`],
/// we return nothing.
#[rustfmt::skip]
fn compute_fee_from_spent_amounts<F: Deref, L: Logger>(
	input_amounts: u64, predicted_weight: u64, conf_target: ConfirmationTarget, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
) -> Option<(u64, u64)>
	where F::Target: FeeEstimator,
{
	let sweep_feerate = fee_estimator.bounded_sat_per_1000_weight(conf_target);
	let fee_rate = cmp::min(sweep_feerate, compute_feerate_sat_per_1000_weight(input_amounts / 2, predicted_weight));
	let fee = fee_rate as u64 * (predicted_weight) / 1000;

	// if the fee rate is below the floor, we don't sweep
	if fee_rate < FEERATE_FLOOR_SATS_PER_KW {
		log_error!(logger, "Failed to generate an on-chain tx with fee ({} sat/kw) was less than the floor ({} sat/kw)",
					fee_rate, FEERATE_FLOOR_SATS_PER_KW);
		None
	} else {
		Some((fee, fee_rate as u64))
	}
}

/// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
/// weight. If feerates proposed by the fee-estimator have been increasing since last fee-bumping
/// attempt, use them. If we need to force a feerate bump, we manually bump the feerate by 25% of
/// the previous feerate. If a feerate bump did happen, we also verify that those bumping heuristics
/// respect BIP125 rules 3) and 4) and if required adjust the new fee to meet the RBF policy
/// requirement.
#[rustfmt::skip]
fn feerate_bump<F: Deref, L: Logger>(
	predicted_weight: u64, input_amounts: u64, dust_limit_sats: u64, previous_feerate: u64,
	feerate_strategy: &FeerateStrategy, conf_target: ConfirmationTarget,
	fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
) -> Option<(u64, u64)>
where
	F::Target: FeeEstimator,
{
	let previous_fee = previous_feerate * predicted_weight / 1000;

	// If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
	let (new_fee, new_feerate) = if let Some((new_fee, new_feerate)) =
		compute_fee_from_spent_amounts(input_amounts, predicted_weight, conf_target, fee_estimator, logger)
	{
		log_debug!(logger, "Initiating fee rate bump from {} s/kWU ({} s) to {} s/kWU ({} s) using {:?} strategy", previous_feerate, previous_fee, new_feerate, new_fee, feerate_strategy);
		match feerate_strategy {
			FeerateStrategy::RetryPrevious => {
				let previous_fee = previous_feerate * predicted_weight / 1000;
				(previous_fee, previous_feerate)
			},
			FeerateStrategy::HighestOfPreviousOrNew => if new_feerate > previous_feerate {
				(new_fee, new_feerate)
			} else {
				let previous_fee = previous_feerate * predicted_weight / 1000;
				(previous_fee, previous_feerate)
			},
			FeerateStrategy::ForceBump => if new_feerate > previous_feerate {
				(new_fee, new_feerate)
			} else {
				// ...else just increase the previous feerate by 25% (because that's a nice number)
				let bumped_feerate = previous_feerate + (previous_feerate / 4);
				let bumped_fee = bumped_feerate * predicted_weight / 1000;

				(bumped_fee, bumped_feerate)
			},
		}
	} else {
		log_warn!(logger, "Can't bump new claiming tx, input amount {} is too small", input_amounts);
		return None;
	};

	// Our feerates should never decrease. If it hasn't changed though, we just need to
	// rebroadcast/re-sign the previous claim.
	debug_assert!(new_feerate >= previous_feerate);
	if new_feerate == previous_feerate {
		return Some((new_fee, new_feerate));
	}

	let min_relay_fee = INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT * predicted_weight / 1000;
	// BIP 125 Opt-in Full Replace-by-Fee Signaling
	// 	* 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
	//	* 4. The replacement transaction must also pay for its own bandwidth at or above the rate set by the node's minimum relay fee setting.
	let naive_new_fee = new_fee;
	let new_fee = cmp::max(new_fee, previous_fee + min_relay_fee);

	if new_fee > naive_new_fee {
		log_debug!(logger, "Naive fee bump of {}s does not meet min relay fee requirements of {}s", naive_new_fee - previous_fee, min_relay_fee);
	}

	let remaining_output_amount = input_amounts.saturating_sub(new_fee);
	if remaining_output_amount < dust_limit_sats {
		log_warn!(logger, "Can't bump new claiming tx, output amount {} would end up below dust threshold {}", remaining_output_amount, dust_limit_sats);
		return None;
	}

	let new_feerate = new_fee * 1000 / predicted_weight;
	log_debug!(logger, "Fee rate bumped by {}s from {} s/KWU ({} s) to {} s/KWU ({} s)", new_fee - previous_fee, previous_feerate, previous_fee, new_feerate, new_fee);
	Some((new_fee, new_feerate))
}

#[cfg(test)]
mod tests {
	use crate::chain::package::{
		feerate_bump, weight_offered_htlc, weight_received_htlc, CounterpartyOfferedHTLCOutput,
		CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData,
		PackageTemplate, RevokedHTLCOutput, RevokedOutput, WEIGHT_REVOKED_OUTPUT,
	};
	use crate::chain::Txid;
	use crate::ln::chan_utils::{
		ChannelTransactionParameters, HTLCOutputInCommitment, HolderCommitmentTransaction,
	};
	use crate::sign::{ChannelDerivationParameters, HTLCDescriptor};
	use crate::types::payment::{PaymentHash, PaymentPreimage};

	use bitcoin::absolute::LockTime;
	use bitcoin::amount::Amount;
	use bitcoin::constants::WITNESS_SCALE_FACTOR;
	use bitcoin::script::ScriptBuf;
	use bitcoin::transaction::OutPoint as BitcoinOutPoint;
	use bitcoin::transaction::Version;
	use bitcoin::{Transaction, TxOut};

	use bitcoin::hex::FromHex;

	use crate::chain::chaininterface::{
		ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, FEERATE_FLOOR_SATS_PER_KW,
	};
	use crate::chain::onchaintx::FeerateStrategy;
	use crate::types::features::ChannelTypeFeatures;
	use crate::util::test_utils::TestLogger;
	use bitcoin::secp256k1::Secp256k1;
	use bitcoin::secp256k1::{PublicKey, SecretKey};

	#[rustfmt::skip]
	fn fake_txid(n: u64) -> Txid {
		Transaction {
			version: Version(0),
			lock_time: LockTime::ZERO,
			input: vec![],
			output: vec![TxOut {
				value: Amount::from_sat(n),
				script_pubkey: ScriptBuf::new(),
			}],
		}.compute_txid()
	}

	#[rustfmt::skip]
	macro_rules! dumb_revk_output {
		() => {
			{
				let secp_ctx = Secp256k1::new();
				let dumb_scalar = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
				let dumb_point = PublicKey::from_secret_key(&secp_ctx, &dumb_scalar);
				let channel_parameters = ChannelTransactionParameters::test_dummy(0);
				PackageSolvingData::RevokedOutput(RevokedOutput::build(dumb_point, dumb_scalar, Amount::ZERO, channel_parameters, 0))
			}
		}
	}

	#[rustfmt::skip]
	macro_rules! dumb_revk_htlc_output {
		() => {
			{
				let secp_ctx = Secp256k1::new();
				let dumb_scalar = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
				let dumb_point = PublicKey::from_secret_key(&secp_ctx, &dumb_scalar);
				let hash = PaymentHash([1; 32]);
				let htlc = HTLCOutputInCommitment { offered: false, amount_msat: 1_000_000, cltv_expiry: 0, payment_hash: hash, transaction_output_index: None };
				let mut channel_parameters = ChannelTransactionParameters::test_dummy(0);
				channel_parameters.channel_type_features =
					ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
				PackageSolvingData::RevokedHTLCOutput(RevokedHTLCOutput::build(
					dumb_point, dumb_scalar, htlc, channel_parameters, 0,
				))
			}
		}
	}

	#[rustfmt::skip]
	macro_rules! dumb_counterparty_received_output {
		($amt: expr, $expiry: expr, $features: expr) => {
			{
				let secp_ctx = Secp256k1::new();
				let dumb_scalar = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
				let dumb_point = PublicKey::from_secret_key(&secp_ctx, &dumb_scalar);
				let hash = PaymentHash([1; 32]);
				let htlc = HTLCOutputInCommitment { offered: true, amount_msat: $amt, cltv_expiry: $expiry, payment_hash: hash, transaction_output_index: None };
				let mut channel_parameters = ChannelTransactionParameters::test_dummy(0);
				channel_parameters.channel_type_features = $features;
				PackageSolvingData::CounterpartyReceivedHTLCOutput(
					CounterpartyReceivedHTLCOutput::build(dumb_point, htlc, channel_parameters, None)
				)
			}
		}
	}

	#[rustfmt::skip]
	macro_rules! dumb_counterparty_offered_output {
		($amt: expr, $features: expr) => {
			{
				let secp_ctx = Secp256k1::new();
				let dumb_scalar = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
				let dumb_point = PublicKey::from_secret_key(&secp_ctx, &dumb_scalar);
				let hash = PaymentHash([1; 32]);
				let preimage = PaymentPreimage([2;32]);
				let htlc = HTLCOutputInCommitment { offered: false, amount_msat: $amt, cltv_expiry: 0, payment_hash: hash, transaction_output_index: None };
				let mut channel_parameters = ChannelTransactionParameters::test_dummy(0);
				channel_parameters.channel_type_features = $features;
				PackageSolvingData::CounterpartyOfferedHTLCOutput(
					CounterpartyOfferedHTLCOutput::build(dumb_point, preimage, htlc, channel_parameters, None)
				)
			}
		}
	}

	#[rustfmt::skip]
	macro_rules! dumb_accepted_htlc_output {
		($features: expr) => {
			{
				let mut channel_parameters = ChannelTransactionParameters::test_dummy(0);
				channel_parameters.channel_type_features = $features;
				let preimage = PaymentPreimage([2;32]);
				let htlc = HTLCOutputInCommitment {
					offered: false,
					amount_msat: 1337000,
					cltv_expiry: 420,
					payment_hash: PaymentHash::from(preimage),
					transaction_output_index: None,
				};
				let funding_outpoint = channel_parameters.funding_outpoint.unwrap();
				let commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, vec![htlc.clone()]);
				let trusted_tx = commitment_tx.trust();
				PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build(
					HTLCDescriptor {
						channel_derivation_parameters: ChannelDerivationParameters {
							value_satoshis: channel_parameters.channel_value_satoshis,
							keys_id: [0; 32],
							transaction_parameters: channel_parameters,
						},
						commitment_txid: trusted_tx.txid(),
						per_commitment_number: trusted_tx.commitment_number(),
						per_commitment_point: trusted_tx.per_commitment_point(),
						feerate_per_kw: trusted_tx.negotiated_feerate_per_kw(),
						htlc,
						preimage: Some(preimage),
						counterparty_sig: commitment_tx.counterparty_htlc_sigs[0].clone(),
					},
					0,
				))
			}
		}
	}

	#[rustfmt::skip]
	macro_rules! dumb_offered_htlc_output {
		($cltv_expiry: expr, $features: expr) => {
			{
				let mut channel_parameters = ChannelTransactionParameters::test_dummy(0);
				channel_parameters.channel_type_features = $features;
				let htlc = HTLCOutputInCommitment {
					offered: true,
					amount_msat: 1337000,
					cltv_expiry: $cltv_expiry,
					payment_hash: PaymentHash::from(PaymentPreimage([2;32])),
					transaction_output_index: None,
				};
				let funding_outpoint = channel_parameters.funding_outpoint.unwrap();
				let commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, vec![htlc.clone()]);
				let trusted_tx = commitment_tx.trust();
				PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build(
					HTLCDescriptor {
						channel_derivation_parameters: ChannelDerivationParameters {
							value_satoshis: channel_parameters.channel_value_satoshis,
							keys_id: [0; 32],
							transaction_parameters: channel_parameters,
						},
						commitment_txid: trusted_tx.txid(),
						per_commitment_number: trusted_tx.commitment_number(),
						per_commitment_point: trusted_tx.per_commitment_point(),
						feerate_per_kw: trusted_tx.negotiated_feerate_per_kw(),
						htlc,
						preimage: None,
						counterparty_sig: commitment_tx.counterparty_htlc_sigs[0].clone(),
					},
					0,
				))
			}
		}
	}

	#[rustfmt::skip]
	macro_rules! dumb_funding_output {
		() => {{
			let mut channel_parameters = ChannelTransactionParameters::test_dummy(0);
			let funding_outpoint = channel_parameters.funding_outpoint.unwrap();
			let commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, Vec::new());
			channel_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
			PackageSolvingData::HolderFundingOutput(HolderFundingOutput::build(
				commitment_tx, channel_parameters,
			))
		}}
	}

	#[test]
	#[rustfmt::skip]
	fn test_merge_package_untractable_funding_output() {
		let funding_outp = dumb_funding_output!();
		let htlc_outp = dumb_accepted_htlc_output!(ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());

		let mut untractable_package = PackageTemplate::build_package(fake_txid(1), 0, funding_outp.clone(), 0);
		let mut malleable_package = PackageTemplate::build_package(fake_txid(2), 0, htlc_outp.clone(), 1100);

		assert!(!untractable_package.can_merge_with(&malleable_package, 1000));
		assert!(untractable_package.merge_package(malleable_package.clone(), 1000).is_err());

		assert!(!malleable_package.can_merge_with(&untractable_package, 1000));
		assert!(malleable_package.merge_package(untractable_package.clone(), 1000).is_err());
	}

	#[test]
	#[rustfmt::skip]
	fn test_merge_empty_package() {
		let revk_outp = dumb_revk_htlc_output!();

		let mut empty_package = PackageTemplate::build_package(fake_txid(1), 0, revk_outp.clone(), 0);
		empty_package.inputs = vec![];
		let mut package = PackageTemplate::build_package(fake_txid(1), 1, revk_outp.clone(), 1100);
		assert!(empty_package.merge_package(package.clone(), 1000).is_err());
		assert!(package.merge_package(empty_package.clone(), 1000).is_err());
	}

	#[test]
	#[rustfmt::skip]
	fn test_merge_package_different_signed_locktimes() {
		// Malleable HTLC transactions are signed over the locktime, and can't be aggregated with
		// different locktimes.
		let offered_htlc_1 = dumb_offered_htlc_output!(900, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());
		let offered_htlc_2 = dumb_offered_htlc_output!(901, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());
		let accepted_htlc = dumb_accepted_htlc_output!(ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());

		let mut offered_htlc_1_package = PackageTemplate::build_package(fake_txid(1), 0, offered_htlc_1.clone(), 0);
		let mut offered_htlc_2_package = PackageTemplate::build_package(fake_txid(1), 1, offered_htlc_2.clone(), 0);
		let mut accepted_htlc_package = PackageTemplate::build_package(fake_txid(1), 2, accepted_htlc.clone(), 1001);

		assert!(!offered_htlc_2_package.can_merge_with(&offered_htlc_1_package, 1000));
		assert!(offered_htlc_2_package.merge_package(offered_htlc_1_package.clone(), 1000).is_err());
		assert!(!offered_htlc_1_package.can_merge_with(&offered_htlc_2_package, 1000));
		assert!(offered_htlc_1_package.merge_package(offered_htlc_2_package.clone(), 1000).is_err());

		assert!(!accepted_htlc_package.can_merge_with(&offered_htlc_1_package, 1000));
		assert!(accepted_htlc_package.merge_package(offered_htlc_1_package.clone(), 1000).is_err());
		assert!(!offered_htlc_1_package.can_merge_with(&accepted_htlc_package, 1000));
		assert!(offered_htlc_1_package.merge_package(accepted_htlc_package.clone(), 1000).is_err());
	}

	#[test]
	#[rustfmt::skip]
	fn test_merge_package_different_effective_locktimes() {
		// Spends of outputs can have different minimum locktimes, and are not mergeable if they are in the
		// future.
		let old_outp_1 = dumb_counterparty_received_output!(1_000_000, 900, ChannelTypeFeatures::only_static_remote_key());
		let old_outp_2 = dumb_counterparty_received_output!(1_000_000, 901, ChannelTypeFeatures::only_static_remote_key());
		let future_outp_1 = dumb_counterparty_received_output!(1_000_000, 1001, ChannelTypeFeatures::only_static_remote_key());
		let future_outp_2 = dumb_counterparty_received_output!(1_000_000, 1002, ChannelTypeFeatures::only_static_remote_key());

		let old_outp_1_package = PackageTemplate::build_package(fake_txid(1), 0, old_outp_1.clone(), 0);
		let old_outp_2_package = PackageTemplate::build_package(fake_txid(1), 1, old_outp_2.clone(), 0);
		let future_outp_1_package = PackageTemplate::build_package(fake_txid(1), 2, future_outp_1.clone(), 0);
		let future_outp_2_package = PackageTemplate::build_package(fake_txid(1), 3, future_outp_2.clone(), 0);

		assert!(old_outp_1_package.can_merge_with(&old_outp_2_package, 1000));
		assert!(old_outp_2_package.can_merge_with(&old_outp_1_package, 1000));
		assert!(old_outp_1_package.clone().merge_package(old_outp_2_package.clone(), 1000).is_ok());
		assert!(old_outp_2_package.clone().merge_package(old_outp_1_package.clone(), 1000).is_ok());

		assert!(!future_outp_1_package.can_merge_with(&future_outp_2_package, 1000));
		assert!(!future_outp_2_package.can_merge_with(&future_outp_1_package, 1000));
		assert!(future_outp_1_package.clone().merge_package(future_outp_2_package.clone(), 1000).is_err());
		assert!(future_outp_2_package.clone().merge_package(future_outp_1_package.clone(), 1000).is_err());
	}

	#[test]
	#[rustfmt::skip]
	fn test_merge_package_holder_htlc_output_clusters() {
		// Signed locktimes of 0.
		let unpinnable_1 = dumb_accepted_htlc_output!(ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());
		let unpinnable_2 = dumb_accepted_htlc_output!(ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());
		let considered_pinnable = dumb_accepted_htlc_output!(ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());
		// Signed locktimes of 1000.
		let pinnable_1 = dumb_offered_htlc_output!(1000, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());
		let pinnable_2 = dumb_offered_htlc_output!(1000, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());

		let mut unpinnable_1_package = PackageTemplate::build_package(fake_txid(1), 0, unpinnable_1.clone(), 1100);
		let mut unpinnable_2_package = PackageTemplate::build_package(fake_txid(1), 1, unpinnable_2.clone(), 1100);
		let mut considered_pinnable_package = PackageTemplate::build_package(fake_txid(1), 2, considered_pinnable.clone(), 1001);
		let mut pinnable_1_package = PackageTemplate::build_package(fake_txid(1), 3, pinnable_1.clone(), 0);
		let mut pinnable_2_package = PackageTemplate::build_package(fake_txid(1), 4, pinnable_2.clone(), 0);

		// Unpinnable with signed locktimes of 0.
		let unpinnable_cluster = [&mut unpinnable_1_package, &mut unpinnable_2_package];
		// Pinnables with signed locktime of 1000.
		let pinnable_cluster = [&mut pinnable_1_package, &mut pinnable_2_package];
		// Pinnable with signed locktime of 0.
		let considered_pinnable_cluster = [&mut considered_pinnable_package];
		// Pinnable and unpinnable malleable packages are kept separate. A package is considered
		// unpinnable if it can only be claimed by the counterparty a given amount of time in the
		// future.
		let clusters = [unpinnable_cluster.as_slice(), pinnable_cluster.as_slice(), considered_pinnable_cluster.as_slice()];

		for a in 0..clusters.len() {
			for b in 0..clusters.len() {
				for i in 0..clusters[a].len() {
					for j in 0..clusters[b].len() {
						if a != b {
							assert!(!clusters[a][i].can_merge_with(clusters[b][j], 1000));
						} else {
							if i != j {
								assert!(clusters[a][i].can_merge_with(clusters[b][j], 1000));
							}
						}
					}
				}
			}
		}

		let mut packages = vec![
			unpinnable_1_package, unpinnable_2_package, considered_pinnable_package,
			pinnable_1_package, pinnable_2_package,
		];
		for i in (1..packages.len()).rev() {
			for j in 0..i {
				if packages[i].can_merge_with(&packages[j], 1000) {
					let merge = packages.remove(i);
					assert!(packages[j].merge_package(merge, 1000).is_ok());
				}
			}
		}
		assert_eq!(packages.len(), 3);
	}

	#[test]
	#[should_panic]
	#[rustfmt::skip]
	fn test_merge_package_different_tx_trees() {
		let offered_htlc = dumb_offered_htlc_output!(900, ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies());
		let mut offered_htlc_package = PackageTemplate::build_package(fake_txid(1), 0, offered_htlc.clone(), 0);
		let counterparty_received_htlc = dumb_counterparty_received_output!(1_000_000, 900, ChannelTypeFeatures::only_static_remote_key());
		let counterparty_received_htlc_package = PackageTemplate::build_package(fake_txid(2), 0, counterparty_received_htlc.clone(), 0);

		assert!(!offered_htlc_package.can_merge_with(&counterparty_received_htlc_package, 1000));
		assert!(offered_htlc_package.merge_package(counterparty_received_htlc_package.clone(), 1000).is_err());
	}

	#[test]
	#[rustfmt::skip]
	fn test_package_split_malleable() {
		let revk_outp_one = dumb_revk_output!();
		let revk_outp_two = dumb_revk_output!();
		let revk_outp_three = dumb_revk_output!();

		let mut package_one = PackageTemplate::build_package(fake_txid(1), 0, revk_outp_one, 1100);
		let package_two = PackageTemplate::build_package(fake_txid(1), 1, revk_outp_two, 1100);
		let package_three = PackageTemplate::build_package(fake_txid(1), 2, revk_outp_three, 1100);

		assert!(package_one.merge_package(package_two, 1000).is_ok());
		assert!(package_one.merge_package(package_three, 1000).is_ok());
		assert_eq!(package_one.outpoints().len(), 3);

		if let Some(split_package) = package_one.split_package(&BitcoinOutPoint { txid: fake_txid(1), vout: 1 }) {
			// Packages attributes should be identical
			assert!(split_package.is_malleable());
			assert_eq!(split_package.counterparty_spendable_height, package_one.counterparty_spendable_height);
			assert_eq!(split_package.feerate_previous, package_one.feerate_previous);
			assert_eq!(split_package.height_timer, package_one.height_timer);
		} else { panic!(); }
		assert_eq!(package_one.outpoints().len(), 2);
	}

	#[test]
	#[rustfmt::skip]
	fn test_package_split_untractable() {
		let htlc_outp_one = dumb_accepted_htlc_output!(ChannelTypeFeatures::only_static_remote_key());

		let mut package_one = PackageTemplate::build_package(fake_txid(1), 0, htlc_outp_one, 1000);
		let ret_split = package_one.split_package(&BitcoinOutPoint { txid: fake_txid(1), vout: 0 });
		assert!(ret_split.is_none());
	}

	#[test]
	fn test_package_timer() {
		let revk_outp = dumb_revk_output!();

		let mut package = PackageTemplate::build_package(fake_txid(1), 0, revk_outp, 1000);
		assert_eq!(package.timer(), 0);
		package.set_timer(101);
		assert_eq!(package.timer(), 101);
	}

	#[test]
	#[rustfmt::skip]
	fn test_package_amounts() {
		let counterparty_outp = dumb_counterparty_received_output!(1_000_000, 1000, ChannelTypeFeatures::only_static_remote_key());

		let package = PackageTemplate::build_package(fake_txid(1), 0, counterparty_outp, 1000);
		assert_eq!(package.package_amount(), 1000);
	}

	#[test]
	#[rustfmt::skip]
	fn test_package_weight() {
		// (nVersion (4) + nLocktime (4) + count_tx_in (1) + prevout (36) + sequence (4) + script_length (1) + count_tx_out (1) + value (8) + var_int (1)) * WITNESS_SCALE_FACTOR + witness marker (2)
		let weight_sans_output = (4 + 4 + 1 + 36 + 4 + 1 + 1 + 8 + 1) * WITNESS_SCALE_FACTOR as u64 + 2;

		{
			let revk_outp = dumb_revk_output!();
			let package = PackageTemplate::build_package(fake_txid(1), 0, revk_outp, 0);
			assert_eq!(package.package_weight(&ScriptBuf::new()),  weight_sans_output + WEIGHT_REVOKED_OUTPUT);
		}

		{
			for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
				let counterparty_outp = dumb_counterparty_received_output!(1_000_000, 1000, channel_type_features.clone());
				let package = PackageTemplate::build_package(fake_txid(1), 0, counterparty_outp, 1000);
				assert_eq!(package.package_weight(&ScriptBuf::new()), weight_sans_output + weight_received_htlc(channel_type_features));
			}
		}

		{
			for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
				let counterparty_outp = dumb_counterparty_offered_output!(1_000_000, channel_type_features.clone());
				let package = PackageTemplate::build_package(fake_txid(1), 0, counterparty_outp, 1000);
				assert_eq!(package.package_weight(&ScriptBuf::new()), weight_sans_output + weight_offered_htlc(channel_type_features));
			}
		}
	}

	struct TestFeeEstimator {
		sat_per_kw: u32,
	}

	impl FeeEstimator for TestFeeEstimator {
		fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u32 {
			self.sat_per_kw
		}
	}

	#[test]
	#[rustfmt::skip]
	fn test_feerate_bump() {
		let sat_per_kw = FEERATE_FLOOR_SATS_PER_KW;
		let test_fee_estimator = &TestFeeEstimator { sat_per_kw };
		let fee_estimator = LowerBoundedFeeEstimator::new(test_fee_estimator);
		let fee_rate_strategy = FeerateStrategy::ForceBump;
		let confirmation_target = ConfirmationTarget::UrgentOnChainSweep;

		{
			// Check underflow doesn't occur
			let predicted_weight_units = 1000;
			let input_satoshis = 505;

			let logger = TestLogger::new();
			let bumped_fee_rate = feerate_bump(predicted_weight_units, input_satoshis, 546, 253, &fee_rate_strategy, confirmation_target, &fee_estimator, &logger);
			assert!(bumped_fee_rate.is_none());
			logger.assert_log_regex("lightning::chain::package", regex::Regex::new(r"Can't bump new claiming tx, input amount 505 is too small").unwrap(), 1);
		}

		{
			// Check post-25%-bump-underflow scenario satisfying the following constraints:
			// input - fee = 546
			// input - fee * 1.25 = -1

			// We accomplish that scenario with the following values:
			// input = 2734
			// fee = 2188

			let predicted_weight_units = 1000;
			let input_satoshis = 2734;

			let logger = TestLogger::new();
			let bumped_fee_rate = feerate_bump(predicted_weight_units, input_satoshis, 546, 2188, &fee_rate_strategy, confirmation_target, &fee_estimator, &logger);
			assert!(bumped_fee_rate.is_none());
			logger.assert_log_regex("lightning::chain::package", regex::Regex::new(r"Can't bump new claiming tx, output amount 0 would end up below dust threshold 546").unwrap(), 1);
		}

		{
			// Check that an output amount of 0 is caught
			let predicted_weight_units = 1000;
			let input_satoshis = 506;

			let logger = TestLogger::new();
			let bumped_fee_rate = feerate_bump(predicted_weight_units, input_satoshis, 546, 253, &fee_rate_strategy, confirmation_target, &fee_estimator, &logger);
			assert!(bumped_fee_rate.is_none());
			logger.assert_log_regex("lightning::chain::package", regex::Regex::new(r"Can't bump new claiming tx, output amount 0 would end up below dust threshold 546").unwrap(), 1);
		}

		{
			// Check that dust_threshold - 1 is blocked
			let predicted_weight_units = 1000;
			let input_satoshis = 1051;

			let logger = TestLogger::new();
			let bumped_fee_rate = feerate_bump(predicted_weight_units, input_satoshis, 546, 253, &fee_rate_strategy, confirmation_target, &fee_estimator, &logger);
			assert!(bumped_fee_rate.is_none());
			logger.assert_log_regex("lightning::chain::package", regex::Regex::new(r"Can't bump new claiming tx, output amount 545 would end up below dust threshold 546").unwrap(), 1);
		}

		{
			let predicted_weight_units = 1000;
			let input_satoshis = 1052;

			let logger = TestLogger::new();
			let bumped_fee_rate = feerate_bump(predicted_weight_units, input_satoshis, 546, 253, &fee_rate_strategy, confirmation_target, &fee_estimator, &logger).unwrap();
			assert_eq!(bumped_fee_rate, (506, 506));
			logger.assert_log_regex("lightning::chain::package", regex::Regex::new(r"Naive fee bump of 63s does not meet min relay fee requirements of 253s").unwrap(), 1);
		}
	}
}