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