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