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