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