Merge pull request #2606 from wpaulino/anchors-counterparty-htlc-claim-sequence
[rust-lightning] / lightning / src / chain / package.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Various utilities to assemble claimable outpoints in package of one or more transactions. Those
11 //! packages are attached metadata, guiding their aggregable or fee-bumping re-schedule. This file
12 //! also includes witness weight computation and fee computation methods.
13
14 use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
15 use bitcoin::blockdata::transaction::{TxOut,TxIn, Transaction, EcdsaSighashType};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::Script;
18
19 use bitcoin::hash_types::Txid;
20
21 use bitcoin::secp256k1::{SecretKey,PublicKey};
22
23 use crate::ln::PaymentPreimage;
24 use crate::ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment};
25 use crate::ln::chan_utils;
26 use crate::ln::msgs::DecodeError;
27 use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
28 use crate::sign::WriteableEcdsaChannelSigner;
29 use crate::chain::onchaintx::{ExternalHTLCClaim, OnchainTxHandler};
30 use crate::util::logger::Logger;
31 use crate::util::ser::{Readable, Writer, Writeable, RequiredWrapper};
32
33 use crate::io;
34 use crate::prelude::*;
35 use core::cmp;
36 use core::convert::TryInto;
37 use core::mem;
38 use core::ops::Deref;
39 use bitcoin::{PackedLockTime, Sequence, Witness};
40 use crate::ln::features::ChannelTypeFeatures;
41
42 use super::chaininterface::LowerBoundedFeeEstimator;
43
44 const MAX_ALLOC_SIZE: usize = 64*1024;
45
46
47 pub(crate) fn weight_revoked_offered_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
48         // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
49         const WEIGHT_REVOKED_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 133;
50         const WEIGHT_REVOKED_OFFERED_HTLC_ANCHORS: u64 = WEIGHT_REVOKED_OFFERED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
51         if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_REVOKED_OFFERED_HTLC_ANCHORS } else { WEIGHT_REVOKED_OFFERED_HTLC }
52 }
53
54 pub(crate) fn weight_revoked_received_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
55         // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
56         const WEIGHT_REVOKED_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 +  139;
57         const WEIGHT_REVOKED_RECEIVED_HTLC_ANCHORS: u64 = WEIGHT_REVOKED_RECEIVED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
58         if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_REVOKED_RECEIVED_HTLC_ANCHORS } else { WEIGHT_REVOKED_RECEIVED_HTLC }
59 }
60
61 pub(crate) fn weight_offered_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
62         // number_of_witness_elements + sig_length + counterpartyhtlc_sig  + preimage_length + preimage + witness_script_length + witness_script
63         const WEIGHT_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 32 + 1 + 133;
64         const WEIGHT_OFFERED_HTLC_ANCHORS: u64 = WEIGHT_OFFERED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
65         if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_OFFERED_HTLC_ANCHORS } else { WEIGHT_OFFERED_HTLC }
66 }
67
68 pub(crate) fn weight_received_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
69         // number_of_witness_elements + sig_length + counterpartyhtlc_sig + empty_vec_length + empty_vec + witness_script_length + witness_script
70         const WEIGHT_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 139;
71         const WEIGHT_RECEIVED_HTLC_ANCHORS: u64 = WEIGHT_RECEIVED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
72         if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_RECEIVED_HTLC_ANCHORS } else { WEIGHT_RECEIVED_HTLC }
73 }
74
75 /// Verifies deserializable channel type features
76 pub(crate) fn verify_channel_type_features(channel_type_features: &Option<ChannelTypeFeatures>, additional_permitted_features: Option<&ChannelTypeFeatures>) -> Result<(), DecodeError> {
77         if let Some(features) = channel_type_features.as_ref() {
78                 if features.requires_unknown_bits() {
79                         return Err(DecodeError::UnknownRequiredFeature);
80                 }
81
82                 let mut supported_feature_set = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
83                 supported_feature_set.set_scid_privacy_required();
84                 supported_feature_set.set_zero_conf_required();
85
86                 // allow the passing of an additional necessary permitted flag
87                 if let Some(additional_permitted_features) = additional_permitted_features {
88                         supported_feature_set |= additional_permitted_features;
89                 }
90
91                 if !features.is_subset(&supported_feature_set) {
92                         return Err(DecodeError::UnknownRequiredFeature);
93                 }
94         }
95
96         Ok(())
97 }
98
99 // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
100 pub(crate) const WEIGHT_REVOKED_OUTPUT: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 77;
101
102 /// Height delay at which transactions are fee-bumped/rebroadcasted with a low priority.
103 const LOW_FREQUENCY_BUMP_INTERVAL: u32 = 15;
104 /// Height delay at which transactions are fee-bumped/rebroadcasted with a middle priority.
105 const MIDDLE_FREQUENCY_BUMP_INTERVAL: u32 = 3;
106 /// Height delay at which transactions are fee-bumped/rebroadcasted with a high priority.
107 const HIGH_FREQUENCY_BUMP_INTERVAL: u32 = 1;
108
109 /// A struct to describe a revoked output and corresponding information to generate a solving
110 /// witness spending a commitment `to_local` output or a second-stage HTLC transaction output.
111 ///
112 /// CSV and pubkeys are used as part of a witnessScript redeeming a balance output, amount is used
113 /// as part of the signature hash and revocation secret to generate a satisfying witness.
114 #[derive(Clone, PartialEq, Eq)]
115 pub(crate) struct RevokedOutput {
116         per_commitment_point: PublicKey,
117         counterparty_delayed_payment_base_key: PublicKey,
118         counterparty_htlc_base_key: PublicKey,
119         per_commitment_key: SecretKey,
120         weight: u64,
121         amount: u64,
122         on_counterparty_tx_csv: u16,
123         is_counterparty_balance_on_anchors: Option<()>,
124 }
125
126 impl RevokedOutput {
127         pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, per_commitment_key: SecretKey, amount: u64, on_counterparty_tx_csv: u16, is_counterparty_balance_on_anchors: bool) -> Self {
128                 RevokedOutput {
129                         per_commitment_point,
130                         counterparty_delayed_payment_base_key,
131                         counterparty_htlc_base_key,
132                         per_commitment_key,
133                         weight: WEIGHT_REVOKED_OUTPUT,
134                         amount,
135                         on_counterparty_tx_csv,
136                         is_counterparty_balance_on_anchors: if is_counterparty_balance_on_anchors { Some(()) } else { None }
137                 }
138         }
139 }
140
141 impl_writeable_tlv_based!(RevokedOutput, {
142         (0, per_commitment_point, required),
143         (2, counterparty_delayed_payment_base_key, required),
144         (4, counterparty_htlc_base_key, required),
145         (6, per_commitment_key, required),
146         (8, weight, required),
147         (10, amount, required),
148         (12, on_counterparty_tx_csv, required),
149         (14, is_counterparty_balance_on_anchors, option)
150 });
151
152 /// A struct to describe a revoked offered output and corresponding information to generate a
153 /// solving witness.
154 ///
155 /// HTLCOuputInCommitment (hash timelock, direction) and pubkeys are used to generate a suitable
156 /// witnessScript.
157 ///
158 /// CSV is used as part of a witnessScript redeeming a balance output, amount is used as part
159 /// of the signature hash and revocation secret to generate a satisfying witness.
160 #[derive(Clone, PartialEq, Eq)]
161 pub(crate) struct RevokedHTLCOutput {
162         per_commitment_point: PublicKey,
163         counterparty_delayed_payment_base_key: PublicKey,
164         counterparty_htlc_base_key: PublicKey,
165         per_commitment_key: SecretKey,
166         weight: u64,
167         amount: u64,
168         htlc: HTLCOutputInCommitment,
169 }
170
171 impl RevokedHTLCOutput {
172         pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, per_commitment_key: SecretKey, amount: u64, htlc: HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> Self {
173                 let weight = if htlc.offered { weight_revoked_offered_htlc(channel_type_features) } else { weight_revoked_received_htlc(channel_type_features) };
174                 RevokedHTLCOutput {
175                         per_commitment_point,
176                         counterparty_delayed_payment_base_key,
177                         counterparty_htlc_base_key,
178                         per_commitment_key,
179                         weight,
180                         amount,
181                         htlc
182                 }
183         }
184 }
185
186 impl_writeable_tlv_based!(RevokedHTLCOutput, {
187         (0, per_commitment_point, required),
188         (2, counterparty_delayed_payment_base_key, required),
189         (4, counterparty_htlc_base_key, required),
190         (6, per_commitment_key, required),
191         (8, weight, required),
192         (10, amount, required),
193         (12, htlc, required),
194 });
195
196 /// A struct to describe a HTLC output on a counterparty commitment transaction.
197 ///
198 /// HTLCOutputInCommitment (hash, timelock, directon) and pubkeys are used to generate a suitable
199 /// witnessScript.
200 ///
201 /// The preimage is used as part of the witness.
202 ///
203 /// Note that on upgrades, some features of existing outputs may be missed.
204 #[derive(Clone, PartialEq, Eq)]
205 pub(crate) struct CounterpartyOfferedHTLCOutput {
206         per_commitment_point: PublicKey,
207         counterparty_delayed_payment_base_key: PublicKey,
208         counterparty_htlc_base_key: PublicKey,
209         preimage: PaymentPreimage,
210         htlc: HTLCOutputInCommitment,
211         channel_type_features: ChannelTypeFeatures,
212 }
213
214 impl CounterpartyOfferedHTLCOutput {
215         pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, preimage: PaymentPreimage, htlc: HTLCOutputInCommitment, channel_type_features: ChannelTypeFeatures) -> Self {
216                 CounterpartyOfferedHTLCOutput {
217                         per_commitment_point,
218                         counterparty_delayed_payment_base_key,
219                         counterparty_htlc_base_key,
220                         preimage,
221                         htlc,
222                         channel_type_features,
223                 }
224         }
225 }
226
227 impl Writeable for CounterpartyOfferedHTLCOutput {
228         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
229                 let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
230                 write_tlv_fields!(writer, {
231                         (0, self.per_commitment_point, required),
232                         (2, self.counterparty_delayed_payment_base_key, required),
233                         (4, self.counterparty_htlc_base_key, required),
234                         (6, self.preimage, required),
235                         (8, self.htlc, required),
236                         (10, legacy_deserialization_prevention_marker, option),
237                         (11, self.channel_type_features, required),
238                 });
239                 Ok(())
240         }
241 }
242
243 impl Readable for CounterpartyOfferedHTLCOutput {
244         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
245                 let mut per_commitment_point = RequiredWrapper(None);
246                 let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
247                 let mut counterparty_htlc_base_key = RequiredWrapper(None);
248                 let mut preimage = RequiredWrapper(None);
249                 let mut htlc = RequiredWrapper(None);
250                 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
251                 let mut channel_type_features = None;
252
253                 read_tlv_fields!(reader, {
254                         (0, per_commitment_point, required),
255                         (2, counterparty_delayed_payment_base_key, required),
256                         (4, counterparty_htlc_base_key, required),
257                         (6, preimage, required),
258                         (8, htlc, required),
259                         (10, _legacy_deserialization_prevention_marker, option),
260                         (11, channel_type_features, option),
261                 });
262
263                 verify_channel_type_features(&channel_type_features, None)?;
264
265                 Ok(Self {
266                         per_commitment_point: per_commitment_point.0.unwrap(),
267                         counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
268                         counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
269                         preimage: preimage.0.unwrap(),
270                         htlc: htlc.0.unwrap(),
271                         channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
272                 })
273         }
274 }
275
276 /// A struct to describe a HTLC output on a counterparty commitment transaction.
277 ///
278 /// HTLCOutputInCommitment (hash, timelock, directon) and pubkeys are used to generate a suitable
279 /// witnessScript.
280 ///
281 /// Note that on upgrades, some features of existing outputs may be missed.
282 #[derive(Clone, PartialEq, Eq)]
283 pub(crate) struct CounterpartyReceivedHTLCOutput {
284         per_commitment_point: PublicKey,
285         counterparty_delayed_payment_base_key: PublicKey,
286         counterparty_htlc_base_key: PublicKey,
287         htlc: HTLCOutputInCommitment,
288         channel_type_features: ChannelTypeFeatures,
289 }
290
291 impl CounterpartyReceivedHTLCOutput {
292         pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, htlc: HTLCOutputInCommitment, channel_type_features: ChannelTypeFeatures) -> Self {
293                 CounterpartyReceivedHTLCOutput {
294                         per_commitment_point,
295                         counterparty_delayed_payment_base_key,
296                         counterparty_htlc_base_key,
297                         htlc,
298                         channel_type_features
299                 }
300         }
301 }
302
303 impl Writeable for CounterpartyReceivedHTLCOutput {
304         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
305                 let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
306                 write_tlv_fields!(writer, {
307                         (0, self.per_commitment_point, required),
308                         (2, self.counterparty_delayed_payment_base_key, required),
309                         (4, self.counterparty_htlc_base_key, required),
310                         (6, self.htlc, required),
311                         (8, legacy_deserialization_prevention_marker, option),
312                         (9, self.channel_type_features, required),
313                 });
314                 Ok(())
315         }
316 }
317
318 impl Readable for CounterpartyReceivedHTLCOutput {
319         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
320                 let mut per_commitment_point = RequiredWrapper(None);
321                 let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
322                 let mut counterparty_htlc_base_key = RequiredWrapper(None);
323                 let mut htlc = RequiredWrapper(None);
324                 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
325                 let mut channel_type_features = None;
326
327                 read_tlv_fields!(reader, {
328                         (0, per_commitment_point, required),
329                         (2, counterparty_delayed_payment_base_key, required),
330                         (4, counterparty_htlc_base_key, required),
331                         (6, htlc, required),
332                         (8, _legacy_deserialization_prevention_marker, option),
333                         (9, channel_type_features, option),
334                 });
335
336                 verify_channel_type_features(&channel_type_features, None)?;
337
338                 Ok(Self {
339                         per_commitment_point: per_commitment_point.0.unwrap(),
340                         counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
341                         counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
342                         htlc: htlc.0.unwrap(),
343                         channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
344                 })
345         }
346 }
347
348 /// A struct to describe a HTLC output on holder commitment transaction.
349 ///
350 /// Either offered or received, the amount is always used as part of the bip143 sighash.
351 /// Preimage is only included as part of the witness in former case.
352 ///
353 /// Note that on upgrades, some features of existing outputs may be missed.
354 #[derive(Clone, PartialEq, Eq)]
355 pub(crate) struct HolderHTLCOutput {
356         preimage: Option<PaymentPreimage>,
357         amount_msat: u64,
358         /// Defaults to 0 for HTLC-Success transactions, which have no expiry
359         cltv_expiry: u32,
360         channel_type_features: ChannelTypeFeatures,
361 }
362
363 impl HolderHTLCOutput {
364         pub(crate) fn build_offered(amount_msat: u64, cltv_expiry: u32, channel_type_features: ChannelTypeFeatures) -> Self {
365                 HolderHTLCOutput {
366                         preimage: None,
367                         amount_msat,
368                         cltv_expiry,
369                         channel_type_features,
370                 }
371         }
372
373         pub(crate) fn build_accepted(preimage: PaymentPreimage, amount_msat: u64, channel_type_features: ChannelTypeFeatures) -> Self {
374                 HolderHTLCOutput {
375                         preimage: Some(preimage),
376                         amount_msat,
377                         cltv_expiry: 0,
378                         channel_type_features,
379                 }
380         }
381 }
382
383 impl Writeable for HolderHTLCOutput {
384         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
385                 let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
386                 write_tlv_fields!(writer, {
387                         (0, self.amount_msat, required),
388                         (2, self.cltv_expiry, required),
389                         (4, self.preimage, option),
390                         (6, legacy_deserialization_prevention_marker, option),
391                         (7, self.channel_type_features, required),
392                 });
393                 Ok(())
394         }
395 }
396
397 impl Readable for HolderHTLCOutput {
398         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
399                 let mut amount_msat = RequiredWrapper(None);
400                 let mut cltv_expiry = RequiredWrapper(None);
401                 let mut preimage = None;
402                 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
403                 let mut channel_type_features = None;
404
405                 read_tlv_fields!(reader, {
406                         (0, amount_msat, required),
407                         (2, cltv_expiry, required),
408                         (4, preimage, option),
409                         (6, _legacy_deserialization_prevention_marker, option),
410                         (7, channel_type_features, option),
411                 });
412
413                 verify_channel_type_features(&channel_type_features, None)?;
414
415                 Ok(Self {
416                         amount_msat: amount_msat.0.unwrap(),
417                         cltv_expiry: cltv_expiry.0.unwrap(),
418                         preimage,
419                         channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
420                 })
421         }
422 }
423
424 /// A struct to describe the channel output on the funding transaction.
425 ///
426 /// witnessScript is used as part of the witness redeeming the funding utxo.
427 ///
428 /// Note that on upgrades, some features of existing outputs may be missed.
429 #[derive(Clone, PartialEq, Eq)]
430 pub(crate) struct HolderFundingOutput {
431         funding_redeemscript: Script,
432         pub(crate) funding_amount: Option<u64>,
433         channel_type_features: ChannelTypeFeatures,
434 }
435
436
437 impl HolderFundingOutput {
438         pub(crate) fn build(funding_redeemscript: Script, funding_amount: u64, channel_type_features: ChannelTypeFeatures) -> Self {
439                 HolderFundingOutput {
440                         funding_redeemscript,
441                         funding_amount: Some(funding_amount),
442                         channel_type_features,
443                 }
444         }
445 }
446
447 impl Writeable for HolderFundingOutput {
448         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
449                 let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
450                 write_tlv_fields!(writer, {
451                         (0, self.funding_redeemscript, required),
452                         (1, self.channel_type_features, required),
453                         (2, legacy_deserialization_prevention_marker, option),
454                         (3, self.funding_amount, option),
455                 });
456                 Ok(())
457         }
458 }
459
460 impl Readable for HolderFundingOutput {
461         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
462                 let mut funding_redeemscript = RequiredWrapper(None);
463                 let mut _legacy_deserialization_prevention_marker: Option<()> = None;
464                 let mut channel_type_features = None;
465                 let mut funding_amount = None;
466
467                 read_tlv_fields!(reader, {
468                         (0, funding_redeemscript, required),
469                         (1, channel_type_features, option),
470                         (2, _legacy_deserialization_prevention_marker, option),
471                         (3, funding_amount, option)
472                 });
473
474                 verify_channel_type_features(&channel_type_features, None)?;
475
476                 Ok(Self {
477                         funding_redeemscript: funding_redeemscript.0.unwrap(),
478                         channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key()),
479                         funding_amount
480                 })
481         }
482 }
483
484 /// A wrapper encapsulating all in-protocol differing outputs types.
485 ///
486 /// The generic API offers access to an outputs common attributes or allow transformation such as
487 /// finalizing an input claiming the output.
488 #[derive(Clone, PartialEq, Eq)]
489 pub(crate) enum PackageSolvingData {
490         RevokedOutput(RevokedOutput),
491         RevokedHTLCOutput(RevokedHTLCOutput),
492         CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput),
493         CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput),
494         HolderHTLCOutput(HolderHTLCOutput),
495         HolderFundingOutput(HolderFundingOutput),
496 }
497
498 impl PackageSolvingData {
499         fn amount(&self) -> u64 {
500                 let amt = match self {
501                         PackageSolvingData::RevokedOutput(ref outp) => outp.amount,
502                         PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.amount,
503                         PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000,
504                         PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000,
505                         PackageSolvingData::HolderHTLCOutput(ref outp) => {
506                                 debug_assert!(outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
507                                 outp.amount_msat / 1000
508                         },
509                         PackageSolvingData::HolderFundingOutput(ref outp) => {
510                                 debug_assert!(outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
511                                 outp.funding_amount.unwrap()
512                         }
513                 };
514                 amt
515         }
516         fn weight(&self) -> usize {
517                 match self {
518                         PackageSolvingData::RevokedOutput(ref outp) => outp.weight as usize,
519                         PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.weight as usize,
520                         PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => weight_offered_htlc(&outp.channel_type_features) as usize,
521                         PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => weight_received_htlc(&outp.channel_type_features) as usize,
522                         PackageSolvingData::HolderHTLCOutput(ref outp) => {
523                                 debug_assert!(outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
524                                 if outp.preimage.is_none() {
525                                         weight_offered_htlc(&outp.channel_type_features) as usize
526                                 } else {
527                                         weight_received_htlc(&outp.channel_type_features) as usize
528                                 }
529                         },
530                         // Since HolderFundingOutput maps to an untractable package that is already signed, its
531                         // weight can be determined from the transaction itself.
532                         PackageSolvingData::HolderFundingOutput(..) => unreachable!(),
533                 }
534         }
535         fn is_compatible(&self, input: &PackageSolvingData) -> bool {
536                 match self {
537                         PackageSolvingData::RevokedOutput(..) => {
538                                 match input {
539                                         PackageSolvingData::RevokedHTLCOutput(..) => { true },
540                                         PackageSolvingData::RevokedOutput(..) => { true },
541                                         _ => { false }
542                                 }
543                         },
544                         PackageSolvingData::RevokedHTLCOutput(..) => {
545                                 match input {
546                                         PackageSolvingData::RevokedOutput(..) => { true },
547                                         PackageSolvingData::RevokedHTLCOutput(..) => { true },
548                                         _ => { false }
549                                 }
550                         },
551                         _ => { mem::discriminant(self) == mem::discriminant(&input) }
552                 }
553         }
554         fn as_tx_input(&self, previous_output: BitcoinOutPoint) -> TxIn {
555                 let sequence = match self {
556                         PackageSolvingData::RevokedOutput(_) => Sequence::ENABLE_RBF_NO_LOCKTIME,
557                         PackageSolvingData::RevokedHTLCOutput(_) => Sequence::ENABLE_RBF_NO_LOCKTIME,
558                         PackageSolvingData::CounterpartyOfferedHTLCOutput(outp) => if outp.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
559                                 Sequence::from_consensus(1)
560                         } else {
561                                 Sequence::ENABLE_RBF_NO_LOCKTIME
562                         },
563                         PackageSolvingData::CounterpartyReceivedHTLCOutput(outp) => if outp.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
564                                 Sequence::from_consensus(1)
565                         } else {
566                                 Sequence::ENABLE_RBF_NO_LOCKTIME
567                         },
568                         _ => {
569                                 debug_assert!(false, "This should not be reachable by 'untractable' or 'malleable with external funding' packages");
570                                 Sequence::ENABLE_RBF_NO_LOCKTIME
571                         },
572                 };
573                 TxIn {
574                         previous_output,
575                         script_sig: Script::new(),
576                         sequence,
577                         witness: Witness::new(),
578                 }
579         }
580         fn finalize_input<Signer: WriteableEcdsaChannelSigner>(&self, bumped_tx: &mut Transaction, i: usize, onchain_handler: &mut OnchainTxHandler<Signer>) -> bool {
581                 match self {
582                         PackageSolvingData::RevokedOutput(ref outp) => {
583                                 let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
584                                 let witness_script = chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, outp.on_counterparty_tx_csv, &chan_keys.broadcaster_delayed_payment_key);
585                                 //TODO: should we panic on signer failure ?
586                                 if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_output(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &onchain_handler.secp_ctx) {
587                                         let mut ser_sig = sig.serialize_der().to_vec();
588                                         ser_sig.push(EcdsaSighashType::All as u8);
589                                         bumped_tx.input[i].witness.push(ser_sig);
590                                         bumped_tx.input[i].witness.push(vec!(1));
591                                         bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
592                                 } else { return false; }
593                         },
594                         PackageSolvingData::RevokedHTLCOutput(ref outp) => {
595                                 let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
596                                 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, &onchain_handler.channel_type_features(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
597                                 //TODO: should we panic on signer failure ?
598                                 if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_htlc(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &outp.htlc, &onchain_handler.secp_ctx) {
599                                         let mut ser_sig = sig.serialize_der().to_vec();
600                                         ser_sig.push(EcdsaSighashType::All as u8);
601                                         bumped_tx.input[i].witness.push(ser_sig);
602                                         bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
603                                         bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
604                                 } else { return false; }
605                         },
606                         PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => {
607                                 let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
608                                 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, &onchain_handler.channel_type_features(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
609
610                                 if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
611                                         let mut ser_sig = sig.serialize_der().to_vec();
612                                         ser_sig.push(EcdsaSighashType::All as u8);
613                                         bumped_tx.input[i].witness.push(ser_sig);
614                                         bumped_tx.input[i].witness.push(outp.preimage.0.to_vec());
615                                         bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
616                                 }
617                         },
618                         PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => {
619                                 let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
620                                 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, &onchain_handler.channel_type_features(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
621
622                                 if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
623                                         let mut ser_sig = sig.serialize_der().to_vec();
624                                         ser_sig.push(EcdsaSighashType::All as u8);
625                                         bumped_tx.input[i].witness.push(ser_sig);
626                                         // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
627                                         bumped_tx.input[i].witness.push(vec![]);
628                                         bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
629                                 }
630                         },
631                         _ => { panic!("API Error!"); }
632                 }
633                 true
634         }
635         fn get_finalized_tx<Signer: WriteableEcdsaChannelSigner>(&self, outpoint: &BitcoinOutPoint, onchain_handler: &mut OnchainTxHandler<Signer>) -> Option<Transaction> {
636                 match self {
637                         PackageSolvingData::HolderHTLCOutput(ref outp) => {
638                                 debug_assert!(!outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
639                                 return onchain_handler.get_fully_signed_htlc_tx(outpoint, &outp.preimage);
640                         }
641                         PackageSolvingData::HolderFundingOutput(ref outp) => {
642                                 return Some(onchain_handler.get_fully_signed_holder_tx(&outp.funding_redeemscript));
643                         }
644                         _ => { panic!("API Error!"); }
645                 }
646         }
647         fn absolute_tx_timelock(&self, current_height: u32) -> u32 {
648                 // We use `current_height` as our default locktime to discourage fee sniping and because
649                 // transactions with it always propagate.
650                 let absolute_timelock = match self {
651                         PackageSolvingData::RevokedOutput(_) => current_height,
652                         PackageSolvingData::RevokedHTLCOutput(_) => current_height,
653                         PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => current_height,
654                         PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, current_height),
655                         // HTLC timeout/success transactions rely on a fixed timelock due to the counterparty's
656                         // signature.
657                         PackageSolvingData::HolderHTLCOutput(ref outp) => {
658                                 if outp.preimage.is_some() {
659                                         debug_assert_eq!(outp.cltv_expiry, 0);
660                                 }
661                                 outp.cltv_expiry
662                         },
663                         PackageSolvingData::HolderFundingOutput(_) => current_height,
664                 };
665                 absolute_timelock
666         }
667
668         fn map_output_type_flags(&self) -> (PackageMalleability, bool) {
669                 // Post-anchor, aggregation of outputs of different types is unsafe. See https://github.com/lightning/bolts/pull/803.
670                 let (malleability, aggregable) = match self {
671                         PackageSolvingData::RevokedOutput(RevokedOutput { is_counterparty_balance_on_anchors: Some(()), .. }) => { (PackageMalleability::Malleable, false) },
672                         PackageSolvingData::RevokedOutput(RevokedOutput { is_counterparty_balance_on_anchors: None, .. }) => { (PackageMalleability::Malleable, true) },
673                         PackageSolvingData::RevokedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
674                         PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
675                         PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { (PackageMalleability::Malleable, false) },
676                         PackageSolvingData::HolderHTLCOutput(ref outp) => if outp.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
677                                 (PackageMalleability::Malleable, outp.preimage.is_some())
678                         } else {
679                                 (PackageMalleability::Untractable, false)
680                         },
681                         PackageSolvingData::HolderFundingOutput(..) => { (PackageMalleability::Untractable, false) },
682                 };
683                 (malleability, aggregable)
684         }
685 }
686
687 impl_writeable_tlv_based_enum!(PackageSolvingData, ;
688         (0, RevokedOutput),
689         (1, RevokedHTLCOutput),
690         (2, CounterpartyOfferedHTLCOutput),
691         (3, CounterpartyReceivedHTLCOutput),
692         (4, HolderHTLCOutput),
693         (5, HolderFundingOutput),
694 );
695
696 /// A malleable package might be aggregated with other packages to save on fees.
697 /// A untractable package has been counter-signed and aggregable will break cached counterparty signatures.
698 #[derive(Clone, PartialEq, Eq)]
699 pub(crate) enum PackageMalleability {
700         Malleable,
701         Untractable,
702 }
703
704 /// A structure to describe a package content that is generated by ChannelMonitor and
705 /// used by OnchainTxHandler to generate and broadcast transactions settling onchain claims.
706 ///
707 /// A package is defined as one or more transactions claiming onchain outputs in reaction
708 /// to confirmation of a channel transaction. Those packages might be aggregated to save on
709 /// fees, if satisfaction of outputs's witnessScript let's us do so.
710 ///
711 /// As packages are time-sensitive, we fee-bump and rebroadcast them at scheduled intervals.
712 /// Failing to confirm a package translate as a loss of funds for the user.
713 #[derive(Clone, PartialEq, Eq)]
714 pub struct PackageTemplate {
715         // List of onchain outputs and solving data to generate satisfying witnesses.
716         inputs: Vec<(BitcoinOutPoint, PackageSolvingData)>,
717         // Packages are deemed as malleable if we have local knwoledge of at least one set of
718         // private keys yielding a satisfying witnesses. Malleability implies that we can aggregate
719         // packages among them to save on fees or rely on RBF to bump their feerates.
720         // Untractable packages have been counter-signed and thus imply that we can't aggregate
721         // them without breaking signatures. Fee-bumping strategy will also rely on CPFP.
722         malleability: PackageMalleability,
723         // Block height after which the earlier-output belonging to this package is mature for a
724         // competing claim by the counterparty. As our chain tip becomes nearer from the timelock,
725         // the fee-bumping frequency will increase. See `OnchainTxHandler::get_height_timer`.
726         soonest_conf_deadline: u32,
727         // Determines if this package can be aggregated.
728         // Timelocked outputs belonging to the same transaction might have differing
729         // satisfying heights. Picking up the later height among the output set would be a valid
730         // aggregable strategy but it comes with at least 2 trade-offs :
731         // * earlier-output fund are going to take longer to come back
732         // * CLTV delta backing up a corresponding HTLC on an upstream channel could be swallowed
733         // by the requirement of the later-output part of the set
734         // For now, we mark such timelocked outputs as non-aggregable, though we might introduce
735         // smarter aggregable strategy in the future.
736         aggregable: bool,
737         // Cache of package feerate committed at previous (re)broadcast. If bumping resources
738         // (either claimed output value or external utxo), it will keep increasing until holder
739         // or counterparty successful claim.
740         feerate_previous: u64,
741         // Cache of next height at which fee-bumping and rebroadcast will be attempted. In
742         // the future, we might abstract it to an observed mempool fluctuation.
743         height_timer: u32,
744         // Confirmation height of the claimed outputs set transaction. In case of reorg reaching
745         // it, we wipe out and forget the package.
746         height_original: u32,
747 }
748
749 impl PackageTemplate {
750         pub(crate) fn is_malleable(&self) -> bool {
751                 self.malleability == PackageMalleability::Malleable
752         }
753         pub(crate) fn timelock(&self) -> u32 {
754                 self.soonest_conf_deadline
755         }
756         pub(crate) fn aggregable(&self) -> bool {
757                 self.aggregable
758         }
759         pub(crate) fn previous_feerate(&self) -> u64 {
760                 self.feerate_previous
761         }
762         pub(crate) fn set_feerate(&mut self, new_feerate: u64) {
763                 self.feerate_previous = new_feerate;
764         }
765         pub(crate) fn timer(&self) -> u32 {
766                 self.height_timer
767         }
768         pub(crate) fn set_timer(&mut self, new_timer: u32) {
769                 self.height_timer = new_timer;
770         }
771         pub(crate) fn outpoints(&self) -> Vec<&BitcoinOutPoint> {
772                 self.inputs.iter().map(|(o, _)| o).collect()
773         }
774         pub(crate) fn inputs(&self) -> impl ExactSizeIterator<Item = &PackageSolvingData> {
775                 self.inputs.iter().map(|(_, i)| i)
776         }
777         pub(crate) fn split_package(&mut self, split_outp: &BitcoinOutPoint) -> Option<PackageTemplate> {
778                 match self.malleability {
779                         PackageMalleability::Malleable => {
780                                 let mut split_package = None;
781                                 let timelock = self.soonest_conf_deadline;
782                                 let aggregable = self.aggregable;
783                                 let feerate_previous = self.feerate_previous;
784                                 let height_timer = self.height_timer;
785                                 let height_original = self.height_original;
786                                 self.inputs.retain(|outp| {
787                                         if *split_outp == outp.0 {
788                                                 split_package = Some(PackageTemplate {
789                                                         inputs: vec![(outp.0, outp.1.clone())],
790                                                         malleability: PackageMalleability::Malleable,
791                                                         soonest_conf_deadline: timelock,
792                                                         aggregable,
793                                                         feerate_previous,
794                                                         height_timer,
795                                                         height_original,
796                                                 });
797                                                 return false;
798                                         }
799                                         return true;
800                                 });
801                                 return split_package;
802                         },
803                         _ => {
804                                 // Note, we may try to split on remote transaction for
805                                 // which we don't have a competing one (HTLC-Success before
806                                 // timelock expiration). This explain we don't panic!
807                                 // We should refactor OnchainTxHandler::block_connected to
808                                 // only test equality on competing claims.
809                                 return None;
810                         }
811                 }
812         }
813         pub(crate) fn merge_package(&mut self, mut merge_from: PackageTemplate) {
814                 assert_eq!(self.height_original, merge_from.height_original);
815                 if self.malleability == PackageMalleability::Untractable || merge_from.malleability == PackageMalleability::Untractable {
816                         panic!("Merging template on untractable packages");
817                 }
818                 if !self.aggregable || !merge_from.aggregable {
819                         panic!("Merging non aggregatable packages");
820                 }
821                 if let Some((_, lead_input)) = self.inputs.first() {
822                         for (_, v) in merge_from.inputs.iter() {
823                                 if !lead_input.is_compatible(v) { panic!("Merging outputs from differing types !"); }
824                         }
825                 } else { panic!("Merging template on an empty package"); }
826                 for (k, v) in merge_from.inputs.drain(..) {
827                         self.inputs.push((k, v));
828                 }
829                 //TODO: verify coverage and sanity?
830                 if self.soonest_conf_deadline > merge_from.soonest_conf_deadline {
831                         self.soonest_conf_deadline = merge_from.soonest_conf_deadline;
832                 }
833                 if self.feerate_previous > merge_from.feerate_previous {
834                         self.feerate_previous = merge_from.feerate_previous;
835                 }
836                 self.height_timer = cmp::min(self.height_timer, merge_from.height_timer);
837         }
838         /// Gets the amount of all outptus being spent by this package, only valid for malleable
839         /// packages.
840         pub(crate) fn package_amount(&self) -> u64 {
841                 let mut amounts = 0;
842                 for (_, outp) in self.inputs.iter() {
843                         amounts += outp.amount();
844                 }
845                 amounts
846         }
847         pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
848                 let locktime = self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(current_height))
849                         .max().expect("There must always be at least one output to spend in a PackageTemplate");
850
851                 // If we ever try to aggregate a `HolderHTLCOutput`s with another output type, we'll likely
852                 // end up with an incorrect transaction locktime since the counterparty has included it in
853                 // its HTLC signature. This should never happen unless we decide to aggregate outputs across
854                 // different channel commitments.
855                 #[cfg(debug_assertions)] {
856                         if self.inputs.iter().any(|(_, outp)|
857                                 if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
858                                         outp.preimage.is_some()
859                                 } else {
860                                         false
861                                 }
862                         ) {
863                                 debug_assert_eq!(locktime, 0);
864                         };
865                         for timeout_htlc_expiry in self.inputs.iter().filter_map(|(_, outp)|
866                                 if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
867                                         if outp.preimage.is_none() {
868                                                 Some(outp.cltv_expiry)
869                                         } else { None }
870                                 } else { None }
871                         ) {
872                                 debug_assert_eq!(locktime, timeout_htlc_expiry);
873                         }
874                 }
875
876                 locktime
877         }
878         pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
879                 let mut inputs_weight = 0;
880                 let mut witnesses_weight = 2; // count segwit flags
881                 for (_, outp) in self.inputs.iter() {
882                         // previous_out_point: 36 bytes ; var_int: 1 byte ; sequence: 4 bytes
883                         inputs_weight += 41 * WITNESS_SCALE_FACTOR;
884                         witnesses_weight += outp.weight();
885                 }
886                 // version: 4 bytes ; count_tx_in: 1 byte ; count_tx_out: 1 byte ; lock_time: 4 bytes
887                 let transaction_weight = 10 * WITNESS_SCALE_FACTOR;
888                 // value: 8 bytes ; var_int: 1 byte ; pk_script: `destination_script.len()`
889                 let output_weight = (8 + 1 + destination_script.len()) * WITNESS_SCALE_FACTOR;
890                 inputs_weight + witnesses_weight + transaction_weight + output_weight
891         }
892         pub(crate) fn construct_malleable_package_with_external_funding<Signer: WriteableEcdsaChannelSigner>(
893                 &self, onchain_handler: &mut OnchainTxHandler<Signer>,
894         ) -> Option<Vec<ExternalHTLCClaim>> {
895                 debug_assert!(self.requires_external_funding());
896                 let mut htlcs: Option<Vec<ExternalHTLCClaim>> = None;
897                 for (previous_output, input) in &self.inputs {
898                         match input {
899                                 PackageSolvingData::HolderHTLCOutput(ref outp) => {
900                                         debug_assert!(outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
901                                         onchain_handler.generate_external_htlc_claim(&previous_output, &outp.preimage).map(|htlc| {
902                                                 htlcs.get_or_insert_with(|| Vec::with_capacity(self.inputs.len())).push(htlc);
903                                         });
904                                 }
905                                 _ => debug_assert!(false, "Expected HolderHTLCOutputs to not be aggregated with other input types"),
906                         }
907                 }
908                 htlcs
909         }
910         pub(crate) fn finalize_malleable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
911                 &self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64,
912                 destination_script: Script, logger: &L
913         ) -> Option<Transaction> where L::Target: Logger {
914                 debug_assert!(self.is_malleable());
915                 let mut bumped_tx = Transaction {
916                         version: 2,
917                         lock_time: PackedLockTime(self.package_locktime(current_height)),
918                         input: vec![],
919                         output: vec![TxOut {
920                                 script_pubkey: destination_script,
921                                 value,
922                         }],
923                 };
924                 for (outpoint, outp) in self.inputs.iter() {
925                         bumped_tx.input.push(outp.as_tx_input(*outpoint));
926                 }
927                 for (i, (outpoint, out)) in self.inputs.iter().enumerate() {
928                         log_debug!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
929                         if !out.finalize_input(&mut bumped_tx, i, onchain_handler) { return None; }
930                 }
931                 log_debug!(logger, "Finalized transaction {} ready to broadcast", bumped_tx.txid());
932                 Some(bumped_tx)
933         }
934         pub(crate) fn finalize_untractable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
935                 &self, onchain_handler: &mut OnchainTxHandler<Signer>, logger: &L,
936         ) -> Option<Transaction> where L::Target: Logger {
937                 debug_assert!(!self.is_malleable());
938                 if let Some((outpoint, outp)) = self.inputs.first() {
939                         if let Some(final_tx) = outp.get_finalized_tx(outpoint, onchain_handler) {
940                                 log_debug!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
941                                 log_debug!(logger, "Finalized transaction {} ready to broadcast", final_tx.txid());
942                                 return Some(final_tx);
943                         }
944                         return None;
945                 } else { panic!("API Error: Package must not be inputs empty"); }
946         }
947         /// In LN, output claimed are time-sensitive, which means we have to spend them before reaching some timelock expiration. At in-channel
948         /// output detection, we generate a first version of a claim tx and associate to it a height timer. A height timer is an absolute block
949         /// height that once reached we should generate a new bumped "version" of the claim tx to be sure that we safely claim outputs before
950         /// that our counterparty can do so. If timelock expires soon, height timer is going to be scaled down in consequence to increase
951         /// frequency of the bump and so increase our bets of success.
952         pub(crate) fn get_height_timer(&self, current_height: u32) -> u32 {
953                 if self.soonest_conf_deadline <= current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL {
954                         return current_height + HIGH_FREQUENCY_BUMP_INTERVAL
955                 } else if self.soonest_conf_deadline - current_height <= LOW_FREQUENCY_BUMP_INTERVAL {
956                         return current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL
957                 }
958                 current_height + LOW_FREQUENCY_BUMP_INTERVAL
959         }
960
961         /// Returns value in satoshis to be included as package outgoing output amount and feerate
962         /// which was used to generate the value. Will not return less than `dust_limit_sats` for the
963         /// value.
964         pub(crate) fn compute_package_output<F: Deref, L: Deref>(
965                 &self, predicted_weight: usize, dust_limit_sats: u64, force_feerate_bump: bool,
966                 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
967         ) -> Option<(u64, u64)>
968         where
969                 F::Target: FeeEstimator,
970                 L::Target: Logger,
971         {
972                 debug_assert!(self.malleability == PackageMalleability::Malleable, "The package output is fixed for non-malleable packages");
973                 let input_amounts = self.package_amount();
974                 assert!(dust_limit_sats as i64 > 0, "Output script must be broadcastable/have a 'real' dust limit.");
975                 // If old feerate is 0, first iteration of this claim, use normal fee calculation
976                 if self.feerate_previous != 0 {
977                         if let Some((new_fee, feerate)) = feerate_bump(
978                                 predicted_weight, input_amounts, self.feerate_previous, force_feerate_bump,
979                                 fee_estimator, logger,
980                         ) {
981                                 return Some((cmp::max(input_amounts as i64 - new_fee as i64, dust_limit_sats as i64) as u64, feerate));
982                         }
983                 } else {
984                         if let Some((new_fee, feerate)) = compute_fee_from_spent_amounts(input_amounts, predicted_weight, fee_estimator, logger) {
985                                 return Some((cmp::max(input_amounts as i64 - new_fee as i64, dust_limit_sats as i64) as u64, feerate));
986                         }
987                 }
988                 None
989         }
990
991         /// Computes a feerate based on the given confirmation target. If a previous feerate was used,
992         /// the new feerate is below it, and `force_feerate_bump` is set, we'll use a 25% increase of
993         /// the previous feerate instead of the new feerate.
994         pub(crate) fn compute_package_feerate<F: Deref>(
995                 &self, fee_estimator: &LowerBoundedFeeEstimator<F>, conf_target: ConfirmationTarget,
996                 force_feerate_bump: bool,
997         ) -> u32 where F::Target: FeeEstimator {
998                 let feerate_estimate = fee_estimator.bounded_sat_per_1000_weight(conf_target);
999                 if self.feerate_previous != 0 {
1000                         // Use the new fee estimate if it's higher than the one previously used.
1001                         if feerate_estimate as u64 > self.feerate_previous {
1002                                 feerate_estimate
1003                         } else if !force_feerate_bump {
1004                                 self.feerate_previous.try_into().unwrap_or(u32::max_value())
1005                         } else {
1006                                 // Our fee estimate has decreased, but our transaction remains unconfirmed after
1007                                 // using our previous fee estimate. This may point to an unreliable fee estimator,
1008                                 // so we choose to bump our previous feerate by 25%, making sure we don't use a
1009                                 // lower feerate or overpay by a large margin by limiting it to 5x the new fee
1010                                 // estimate.
1011                                 let previous_feerate = self.feerate_previous.try_into().unwrap_or(u32::max_value());
1012                                 let mut new_feerate = previous_feerate.saturating_add(previous_feerate / 4);
1013                                 if new_feerate > feerate_estimate * 5 {
1014                                         new_feerate = cmp::max(feerate_estimate * 5, previous_feerate);
1015                                 }
1016                                 new_feerate
1017                         }
1018                 } else {
1019                         feerate_estimate
1020                 }
1021         }
1022
1023         /// Determines whether a package contains an input which must have additional external inputs
1024         /// attached to help the spending transaction reach confirmation.
1025         pub(crate) fn requires_external_funding(&self) -> bool {
1026                 self.inputs.iter().find(|input| match input.1 {
1027                         PackageSolvingData::HolderFundingOutput(ref outp) => outp.channel_type_features.supports_anchors_zero_fee_htlc_tx(),
1028                         PackageSolvingData::HolderHTLCOutput(ref outp) => outp.channel_type_features.supports_anchors_zero_fee_htlc_tx(),
1029                         _ => false,
1030                 }).is_some()
1031         }
1032
1033         pub (crate) fn build_package(txid: Txid, vout: u32, input_solving_data: PackageSolvingData, soonest_conf_deadline: u32, height_original: u32) -> Self {
1034                 let (malleability, aggregable) = PackageSolvingData::map_output_type_flags(&input_solving_data);
1035                 let mut inputs = Vec::with_capacity(1);
1036                 inputs.push((BitcoinOutPoint { txid, vout }, input_solving_data));
1037                 PackageTemplate {
1038                         inputs,
1039                         malleability,
1040                         soonest_conf_deadline,
1041                         aggregable,
1042                         feerate_previous: 0,
1043                         height_timer: height_original,
1044                         height_original,
1045                 }
1046         }
1047 }
1048
1049 impl Writeable for PackageTemplate {
1050         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1051                 writer.write_all(&(self.inputs.len() as u64).to_be_bytes())?;
1052                 for (ref outpoint, ref rev_outp) in self.inputs.iter() {
1053                         outpoint.write(writer)?;
1054                         rev_outp.write(writer)?;
1055                 }
1056                 write_tlv_fields!(writer, {
1057                         (0, self.soonest_conf_deadline, required),
1058                         (2, self.feerate_previous, required),
1059                         (4, self.height_original, required),
1060                         (6, self.height_timer, required)
1061                 });
1062                 Ok(())
1063         }
1064 }
1065
1066 impl Readable for PackageTemplate {
1067         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1068                 let inputs_count = <u64 as Readable>::read(reader)?;
1069                 let mut inputs: Vec<(BitcoinOutPoint, PackageSolvingData)> = Vec::with_capacity(cmp::min(inputs_count as usize, MAX_ALLOC_SIZE / 128));
1070                 for _ in 0..inputs_count {
1071                         let outpoint = Readable::read(reader)?;
1072                         let rev_outp = Readable::read(reader)?;
1073                         inputs.push((outpoint, rev_outp));
1074                 }
1075                 let (malleability, aggregable) = if let Some((_, lead_input)) = inputs.first() {
1076                         PackageSolvingData::map_output_type_flags(&lead_input)
1077                 } else { return Err(DecodeError::InvalidValue); };
1078                 let mut soonest_conf_deadline = 0;
1079                 let mut feerate_previous = 0;
1080                 let mut height_timer = None;
1081                 let mut height_original = 0;
1082                 read_tlv_fields!(reader, {
1083                         (0, soonest_conf_deadline, required),
1084                         (2, feerate_previous, required),
1085                         (4, height_original, required),
1086                         (6, height_timer, option),
1087                 });
1088                 if height_timer.is_none() {
1089                         height_timer = Some(height_original);
1090                 }
1091                 Ok(PackageTemplate {
1092                         inputs,
1093                         malleability,
1094                         soonest_conf_deadline,
1095                         aggregable,
1096                         feerate_previous,
1097                         height_timer: height_timer.unwrap(),
1098                         height_original,
1099                 })
1100         }
1101 }
1102
1103 /// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
1104 /// weight. We start with the highest priority feerate returned by the node's fee estimator then
1105 /// fall-back to lower priorities until we have enough value available to suck from.
1106 ///
1107 /// If the proposed fee is less than the available spent output's values, we return the proposed
1108 /// fee and the corresponding updated feerate. If the proposed fee is equal or more than the
1109 /// available spent output's values, we return nothing
1110 fn compute_fee_from_spent_amounts<F: Deref, L: Deref>(input_amounts: u64, predicted_weight: usize, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L) -> Option<(u64, u64)>
1111         where F::Target: FeeEstimator,
1112               L::Target: Logger,
1113 {
1114         let mut updated_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::HighPriority) as u64;
1115         let mut fee = updated_feerate * (predicted_weight as u64) / 1000;
1116         if input_amounts <= fee {
1117                 updated_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal) as u64;
1118                 fee = updated_feerate * (predicted_weight as u64) / 1000;
1119                 if input_amounts <= fee {
1120                         updated_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Background) as u64;
1121                         fee = updated_feerate * (predicted_weight as u64) / 1000;
1122                         if input_amounts <= fee {
1123                                 log_error!(logger, "Failed to generate an on-chain punishment tx as even low priority fee ({} sat) was more than the entire claim balance ({} sat)",
1124                                         fee, input_amounts);
1125                                 None
1126                         } else {
1127                                 log_warn!(logger, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
1128                                         input_amounts);
1129                                 Some((fee, updated_feerate))
1130                         }
1131                 } else {
1132                         log_warn!(logger, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
1133                                 input_amounts);
1134                         Some((fee, updated_feerate))
1135                 }
1136         } else {
1137                 Some((fee, updated_feerate))
1138         }
1139 }
1140
1141 /// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
1142 /// weight. If feerates proposed by the fee-estimator have been increasing since last fee-bumping
1143 /// attempt, use them. If `force_feerate_bump` is set, we bump the feerate by 25% of the previous
1144 /// feerate, or just use the previous feerate otherwise. If a feerate bump did happen, we also
1145 /// verify that those bumping heuristics respect BIP125 rules 3) and 4) and if required adjust the
1146 /// new fee to meet the RBF policy requirement.
1147 fn feerate_bump<F: Deref, L: Deref>(
1148         predicted_weight: usize, input_amounts: u64, previous_feerate: u64, force_feerate_bump: bool,
1149         fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
1150 ) -> Option<(u64, u64)>
1151 where
1152         F::Target: FeeEstimator,
1153         L::Target: Logger,
1154 {
1155         // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
1156         let (new_fee, new_feerate) = if let Some((new_fee, new_feerate)) = compute_fee_from_spent_amounts(input_amounts, predicted_weight, fee_estimator, logger) {
1157                 if new_feerate > previous_feerate {
1158                         (new_fee, new_feerate)
1159                 } else if !force_feerate_bump {
1160                         let previous_fee = previous_feerate * (predicted_weight as u64) / 1000;
1161                         (previous_fee, previous_feerate)
1162                 } else {
1163                         // ...else just increase the previous feerate by 25% (because that's a nice number)
1164                         let bumped_feerate = previous_feerate + (previous_feerate / 4);
1165                         let bumped_fee = bumped_feerate * (predicted_weight as u64) / 1000;
1166                         if input_amounts <= bumped_fee {
1167                                 log_warn!(logger, "Can't 25% bump new claiming tx, amount {} is too small", input_amounts);
1168                                 return None;
1169                         }
1170                         (bumped_fee, bumped_feerate)
1171                 }
1172         } else {
1173                 log_warn!(logger, "Can't new-estimation bump new claiming tx, amount {} is too small", input_amounts);
1174                 return None;
1175         };
1176
1177         // Our feerates should never decrease. If it hasn't changed though, we just need to
1178         // rebroadcast/re-sign the previous claim.
1179         debug_assert!(new_feerate >= previous_feerate);
1180         if new_feerate == previous_feerate {
1181                 return Some((new_fee, new_feerate));
1182         }
1183
1184         let previous_fee = previous_feerate * (predicted_weight as u64) / 1000;
1185         let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * (predicted_weight as u64) / 1000;
1186         // BIP 125 Opt-in Full Replace-by-Fee Signaling
1187         //      * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
1188         //      * 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.
1189         let new_fee = if new_fee < previous_fee + min_relay_fee {
1190                 new_fee + previous_fee + min_relay_fee - new_fee
1191         } else {
1192                 new_fee
1193         };
1194         Some((new_fee, new_fee * 1000 / (predicted_weight as u64)))
1195 }
1196
1197 #[cfg(test)]
1198 mod tests {
1199         use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderHTLCOutput, PackageTemplate, PackageSolvingData, RevokedOutput, WEIGHT_REVOKED_OUTPUT, weight_offered_htlc, weight_received_htlc};
1200         use crate::chain::Txid;
1201         use crate::ln::chan_utils::HTLCOutputInCommitment;
1202         use crate::ln::{PaymentPreimage, PaymentHash};
1203
1204         use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
1205         use bitcoin::blockdata::script::Script;
1206         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
1207
1208         use bitcoin::hashes::hex::FromHex;
1209
1210         use bitcoin::secp256k1::{PublicKey,SecretKey};
1211         use bitcoin::secp256k1::Secp256k1;
1212         use crate::ln::features::ChannelTypeFeatures;
1213
1214         macro_rules! dumb_revk_output {
1215                 ($secp_ctx: expr, $is_counterparty_balance_on_anchors: expr) => {
1216                         {
1217                                 let dumb_scalar = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
1218                                 let dumb_point = PublicKey::from_secret_key(&$secp_ctx, &dumb_scalar);
1219                                 PackageSolvingData::RevokedOutput(RevokedOutput::build(dumb_point, dumb_point, dumb_point, dumb_scalar, 0, 0, $is_counterparty_balance_on_anchors))
1220                         }
1221                 }
1222         }
1223
1224         macro_rules! dumb_counterparty_output {
1225                 ($secp_ctx: expr, $amt: expr, $opt_anchors: expr) => {
1226                         {
1227                                 let dumb_scalar = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
1228                                 let dumb_point = PublicKey::from_secret_key(&$secp_ctx, &dumb_scalar);
1229                                 let hash = PaymentHash([1; 32]);
1230                                 let htlc = HTLCOutputInCommitment { offered: true, amount_msat: $amt, cltv_expiry: 0, payment_hash: hash, transaction_output_index: None };
1231                                 PackageSolvingData::CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput::build(dumb_point, dumb_point, dumb_point, htlc, $opt_anchors))
1232                         }
1233                 }
1234         }
1235
1236         macro_rules! dumb_counterparty_offered_output {
1237                 ($secp_ctx: expr, $amt: expr, $opt_anchors: expr) => {
1238                         {
1239                                 let dumb_scalar = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
1240                                 let dumb_point = PublicKey::from_secret_key(&$secp_ctx, &dumb_scalar);
1241                                 let hash = PaymentHash([1; 32]);
1242                                 let preimage = PaymentPreimage([2;32]);
1243                                 let htlc = HTLCOutputInCommitment { offered: false, amount_msat: $amt, cltv_expiry: 1000, payment_hash: hash, transaction_output_index: None };
1244                                 PackageSolvingData::CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput::build(dumb_point, dumb_point, dumb_point, preimage, htlc, $opt_anchors))
1245                         }
1246                 }
1247         }
1248
1249         macro_rules! dumb_htlc_output {
1250                 () => {
1251                         {
1252                                 let preimage = PaymentPreimage([2;32]);
1253                                 PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build_accepted(preimage, 0, ChannelTypeFeatures::only_static_remote_key()))
1254                         }
1255                 }
1256         }
1257
1258         #[test]
1259         #[should_panic]
1260         fn test_package_differing_heights() {
1261                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1262                 let secp_ctx = Secp256k1::new();
1263                 let revk_outp = dumb_revk_output!(secp_ctx, false);
1264
1265                 let mut package_one_hundred = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, 100);
1266                 let package_two_hundred = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, 200);
1267                 package_one_hundred.merge_package(package_two_hundred);
1268         }
1269
1270         #[test]
1271         #[should_panic]
1272         fn test_package_untractable_merge_to() {
1273                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1274                 let secp_ctx = Secp256k1::new();
1275                 let revk_outp = dumb_revk_output!(secp_ctx, false);
1276                 let htlc_outp = dumb_htlc_output!();
1277
1278                 let mut untractable_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, 100);
1279                 let malleable_package = PackageTemplate::build_package(txid, 1, htlc_outp.clone(), 1000, 100);
1280                 untractable_package.merge_package(malleable_package);
1281         }
1282
1283         #[test]
1284         #[should_panic]
1285         fn test_package_untractable_merge_from() {
1286                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1287                 let secp_ctx = Secp256k1::new();
1288                 let htlc_outp = dumb_htlc_output!();
1289                 let revk_outp = dumb_revk_output!(secp_ctx, false);
1290
1291                 let mut malleable_package = PackageTemplate::build_package(txid, 0, htlc_outp.clone(), 1000, 100);
1292                 let untractable_package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, 100);
1293                 malleable_package.merge_package(untractable_package);
1294         }
1295
1296         #[test]
1297         #[should_panic]
1298         fn test_package_noaggregation_to() {
1299                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1300                 let secp_ctx = Secp256k1::new();
1301                 let revk_outp = dumb_revk_output!(secp_ctx, false);
1302                 let revk_outp_counterparty_balance = dumb_revk_output!(secp_ctx, true);
1303
1304                 let mut noaggregation_package = PackageTemplate::build_package(txid, 0, revk_outp_counterparty_balance.clone(), 1000, 100);
1305                 let aggregation_package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, 100);
1306                 noaggregation_package.merge_package(aggregation_package);
1307         }
1308
1309         #[test]
1310         #[should_panic]
1311         fn test_package_noaggregation_from() {
1312                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1313                 let secp_ctx = Secp256k1::new();
1314                 let revk_outp = dumb_revk_output!(secp_ctx, false);
1315                 let revk_outp_counterparty_balance = dumb_revk_output!(secp_ctx, true);
1316
1317                 let mut aggregation_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, 100);
1318                 let noaggregation_package = PackageTemplate::build_package(txid, 1, revk_outp_counterparty_balance.clone(), 1000, 100);
1319                 aggregation_package.merge_package(noaggregation_package);
1320         }
1321
1322         #[test]
1323         #[should_panic]
1324         fn test_package_empty() {
1325                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1326                 let secp_ctx = Secp256k1::new();
1327                 let revk_outp = dumb_revk_output!(secp_ctx, false);
1328
1329                 let mut empty_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, 100);
1330                 empty_package.inputs = vec![];
1331                 let package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, 100);
1332                 empty_package.merge_package(package);
1333         }
1334
1335         #[test]
1336         #[should_panic]
1337         fn test_package_differing_categories() {
1338                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1339                 let secp_ctx = Secp256k1::new();
1340                 let revk_outp = dumb_revk_output!(secp_ctx, false);
1341                 let counterparty_outp = dumb_counterparty_output!(secp_ctx, 0, ChannelTypeFeatures::only_static_remote_key());
1342
1343                 let mut revoked_package = PackageTemplate::build_package(txid, 0, revk_outp, 1000, 100);
1344                 let counterparty_package = PackageTemplate::build_package(txid, 1, counterparty_outp, 1000, 100);
1345                 revoked_package.merge_package(counterparty_package);
1346         }
1347
1348         #[test]
1349         fn test_package_split_malleable() {
1350                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1351                 let secp_ctx = Secp256k1::new();
1352                 let revk_outp_one = dumb_revk_output!(secp_ctx, false);
1353                 let revk_outp_two = dumb_revk_output!(secp_ctx, false);
1354                 let revk_outp_three = dumb_revk_output!(secp_ctx, false);
1355
1356                 let mut package_one = PackageTemplate::build_package(txid, 0, revk_outp_one, 1000, 100);
1357                 let package_two = PackageTemplate::build_package(txid, 1, revk_outp_two, 1000, 100);
1358                 let package_three = PackageTemplate::build_package(txid, 2, revk_outp_three, 1000, 100);
1359
1360                 package_one.merge_package(package_two);
1361                 package_one.merge_package(package_three);
1362                 assert_eq!(package_one.outpoints().len(), 3);
1363
1364                 if let Some(split_package) = package_one.split_package(&BitcoinOutPoint { txid, vout: 1 }) {
1365                         // Packages attributes should be identical
1366                         assert!(split_package.is_malleable());
1367                         assert_eq!(split_package.soonest_conf_deadline, package_one.soonest_conf_deadline);
1368                         assert_eq!(split_package.aggregable, package_one.aggregable);
1369                         assert_eq!(split_package.feerate_previous, package_one.feerate_previous);
1370                         assert_eq!(split_package.height_timer, package_one.height_timer);
1371                         assert_eq!(split_package.height_original, package_one.height_original);
1372                 } else { panic!(); }
1373                 assert_eq!(package_one.outpoints().len(), 2);
1374         }
1375
1376         #[test]
1377         fn test_package_split_untractable() {
1378                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1379                 let htlc_outp_one = dumb_htlc_output!();
1380
1381                 let mut package_one = PackageTemplate::build_package(txid, 0, htlc_outp_one, 1000, 100);
1382                 let ret_split = package_one.split_package(&BitcoinOutPoint { txid, vout: 0});
1383                 assert!(ret_split.is_none());
1384         }
1385
1386         #[test]
1387         fn test_package_timer() {
1388                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1389                 let secp_ctx = Secp256k1::new();
1390                 let revk_outp = dumb_revk_output!(secp_ctx, false);
1391
1392                 let mut package = PackageTemplate::build_package(txid, 0, revk_outp, 1000, 100);
1393                 assert_eq!(package.timer(), 100);
1394                 package.set_timer(101);
1395                 assert_eq!(package.timer(), 101);
1396         }
1397
1398         #[test]
1399         fn test_package_amounts() {
1400                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1401                 let secp_ctx = Secp256k1::new();
1402                 let counterparty_outp = dumb_counterparty_output!(secp_ctx, 1_000_000, ChannelTypeFeatures::only_static_remote_key());
1403
1404                 let package = PackageTemplate::build_package(txid, 0, counterparty_outp, 1000, 100);
1405                 assert_eq!(package.package_amount(), 1000);
1406         }
1407
1408         #[test]
1409         fn test_package_weight() {
1410                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1411                 let secp_ctx = Secp256k1::new();
1412
1413                 // (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)
1414                 let weight_sans_output = (4 + 4 + 1 + 36 + 4 + 1 + 1 + 8 + 1) * WITNESS_SCALE_FACTOR + 2;
1415
1416                 {
1417                         let revk_outp = dumb_revk_output!(secp_ctx, false);
1418                         let package = PackageTemplate::build_package(txid, 0, revk_outp, 0, 100);
1419                         assert_eq!(package.package_weight(&Script::new()),  weight_sans_output + WEIGHT_REVOKED_OUTPUT as usize);
1420                 }
1421
1422                 {
1423                         for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
1424                                 let counterparty_outp = dumb_counterparty_output!(secp_ctx, 1_000_000, channel_type_features.clone());
1425                                 let package = PackageTemplate::build_package(txid, 0, counterparty_outp, 1000, 100);
1426                                 assert_eq!(package.package_weight(&Script::new()), weight_sans_output + weight_received_htlc(channel_type_features) as usize);
1427                         }
1428                 }
1429
1430                 {
1431                         for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
1432                                 let counterparty_outp = dumb_counterparty_offered_output!(secp_ctx, 1_000_000, channel_type_features.clone());
1433                                 let package = PackageTemplate::build_package(txid, 0, counterparty_outp, 1000, 100);
1434                                 assert_eq!(package.package_weight(&Script::new()), weight_sans_output + weight_offered_htlc(channel_type_features) as usize);
1435                         }
1436                 }
1437         }
1438 }