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