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