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