Remove unreachable `Err` cases when constructing `TxCreationKeys`
[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                                 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);
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                         PackageSolvingData::RevokedHTLCOutput(ref outp) => {
396                                 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);
397                                 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);
398                                 //TODO: should we panic on signer failure ?
399                                 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) {
400                                         let mut ser_sig = sig.serialize_der().to_vec();
401                                         ser_sig.push(EcdsaSighashType::All as u8);
402                                         bumped_tx.input[i].witness.push(ser_sig);
403                                         bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
404                                         bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
405                                 } else { return false; }
406                         },
407                         PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => {
408                                 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);
409                                 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);
410
411                                 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) {
412                                         let mut ser_sig = sig.serialize_der().to_vec();
413                                         ser_sig.push(EcdsaSighashType::All as u8);
414                                         bumped_tx.input[i].witness.push(ser_sig);
415                                         bumped_tx.input[i].witness.push(outp.preimage.0.to_vec());
416                                         bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
417                                 }
418                         },
419                         PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => {
420                                 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);
421                                 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);
422
423                                 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
424                                 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) {
425                                         let mut ser_sig = sig.serialize_der().to_vec();
426                                         ser_sig.push(EcdsaSighashType::All as u8);
427                                         bumped_tx.input[i].witness.push(ser_sig);
428                                         // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
429                                         bumped_tx.input[i].witness.push(vec![]);
430                                         bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
431                                 }
432                         },
433                         _ => { panic!("API Error!"); }
434                 }
435                 true
436         }
437         fn get_finalized_tx<Signer: Sign>(&self, outpoint: &BitcoinOutPoint, onchain_handler: &mut OnchainTxHandler<Signer>) -> Option<Transaction> {
438                 match self {
439                         PackageSolvingData::HolderHTLCOutput(ref outp) => { return onchain_handler.get_fully_signed_htlc_tx(outpoint, &outp.preimage); }
440                         PackageSolvingData::HolderFundingOutput(ref outp) => { return Some(onchain_handler.get_fully_signed_holder_tx(&outp.funding_redeemscript)); }
441                         _ => { panic!("API Error!"); }
442                 }
443         }
444         fn absolute_tx_timelock(&self, output_conf_height: u32) -> u32 {
445                 // Get the absolute timelock at which this output can be spent given the height at which
446                 // this output was confirmed. We use `output_conf_height + 1` as a safe default as we can
447                 // be confirmed in the next block and transactions with time lock `current_height + 1`
448                 // always propagate.
449                 let absolute_timelock = match self {
450                         PackageSolvingData::RevokedOutput(_) => output_conf_height + 1,
451                         PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1,
452                         PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1,
453                         PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1),
454                         PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1),
455                         PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1,
456                 };
457                 absolute_timelock
458         }
459 }
460
461 impl_writeable_tlv_based_enum!(PackageSolvingData, ;
462         (0, RevokedOutput),
463         (1, RevokedHTLCOutput),
464         (2, CounterpartyOfferedHTLCOutput),
465         (3, CounterpartyReceivedHTLCOutput),
466         (4, HolderHTLCOutput),
467         (5, HolderFundingOutput),
468 );
469
470 /// A malleable package might be aggregated with other packages to save on fees.
471 /// A untractable package has been counter-signed and aggregable will break cached counterparty
472 /// signatures.
473 #[derive(Clone, PartialEq, Eq)]
474 pub(crate) enum PackageMalleability {
475         Malleable,
476         Untractable,
477 }
478
479 /// A structure to describe a package content that is generated by ChannelMonitor and
480 /// used by OnchainTxHandler to generate and broadcast transactions settling onchain claims.
481 ///
482 /// A package is defined as one or more transactions claiming onchain outputs in reaction
483 /// to confirmation of a channel transaction. Those packages might be aggregated to save on
484 /// fees, if satisfaction of outputs's witnessScript let's us do so.
485 ///
486 /// As packages are time-sensitive, we fee-bump and rebroadcast them at scheduled intervals.
487 /// Failing to confirm a package translate as a loss of funds for the user.
488 #[derive(Clone, PartialEq, Eq)]
489 pub struct PackageTemplate {
490         // List of onchain outputs and solving data to generate satisfying witnesses.
491         inputs: Vec<(BitcoinOutPoint, PackageSolvingData)>,
492         // Packages are deemed as malleable if we have local knwoledge of at least one set of
493         // private keys yielding a satisfying witnesses. Malleability implies that we can aggregate
494         // packages among them to save on fees or rely on RBF to bump their feerates.
495         // Untractable packages have been counter-signed and thus imply that we can't aggregate
496         // them without breaking signatures. Fee-bumping strategy will also rely on CPFP.
497         malleability: PackageMalleability,
498         // Block height after which the earlier-output belonging to this package is mature for a
499         // competing claim by the counterparty. As our chain tip becomes nearer from the timelock,
500         // the fee-bumping frequency will increase. See `OnchainTxHandler::get_height_timer`.
501         soonest_conf_deadline: u32,
502         // Determines if this package can be aggregated.
503         // Timelocked outputs belonging to the same transaction might have differing
504         // satisfying heights. Picking up the later height among the output set would be a valid
505         // aggregable strategy but it comes with at least 2 trade-offs :
506         // * earlier-output fund are going to take longer to come back
507         // * CLTV delta backing up a corresponding HTLC on an upstream channel could be swallowed
508         // by the requirement of the later-output part of the set
509         // For now, we mark such timelocked outputs as non-aggregable, though we might introduce
510         // smarter aggregable strategy in the future.
511         aggregable: bool,
512         // Cache of package feerate committed at previous (re)broadcast. If bumping resources
513         // (either claimed output value or external utxo), it will keep increasing until holder
514         // or counterparty successful claim.
515         feerate_previous: u64,
516         // Cache of next height at which fee-bumping and rebroadcast will be attempted. In
517         // the future, we might abstract it to an observed mempool fluctuation.
518         height_timer: Option<u32>,
519         // Confirmation height of the claimed outputs set transaction. In case of reorg reaching
520         // it, we wipe out and forget the package.
521         height_original: u32,
522 }
523
524 impl PackageTemplate {
525         pub(crate) fn is_malleable(&self) -> bool {
526                 self.malleability == PackageMalleability::Malleable
527         }
528         pub(crate) fn timelock(&self) -> u32 {
529                 self.soonest_conf_deadline
530         }
531         pub(crate) fn aggregable(&self) -> bool {
532                 self.aggregable
533         }
534         pub(crate) fn set_feerate(&mut self, new_feerate: u64) {
535                 self.feerate_previous = new_feerate;
536         }
537         pub(crate) fn timer(&self) -> Option<u32> {
538                 if let Some(ref timer) = self.height_timer {
539                         return Some(*timer);
540                 }
541                 None
542         }
543         pub(crate) fn set_timer(&mut self, new_timer: Option<u32>) {
544                 self.height_timer = new_timer;
545         }
546         pub(crate) fn outpoints(&self) -> Vec<&BitcoinOutPoint> {
547                 self.inputs.iter().map(|(o, _)| o).collect()
548         }
549         pub(crate) fn inputs(&self) -> impl ExactSizeIterator<Item = &PackageSolvingData> {
550                 self.inputs.iter().map(|(_, i)| i)
551         }
552         pub(crate) fn split_package(&mut self, split_outp: &BitcoinOutPoint) -> Option<PackageTemplate> {
553                 match self.malleability {
554                         PackageMalleability::Malleable => {
555                                 let mut split_package = None;
556                                 let timelock = self.soonest_conf_deadline;
557                                 let aggregable = self.aggregable;
558                                 let feerate_previous = self.feerate_previous;
559                                 let height_timer = self.height_timer;
560                                 let height_original = self.height_original;
561                                 self.inputs.retain(|outp| {
562                                         if *split_outp == outp.0 {
563                                                 split_package = Some(PackageTemplate {
564                                                         inputs: vec![(outp.0, outp.1.clone())],
565                                                         malleability: PackageMalleability::Malleable,
566                                                         soonest_conf_deadline: timelock,
567                                                         aggregable,
568                                                         feerate_previous,
569                                                         height_timer,
570                                                         height_original,
571                                                 });
572                                                 return false;
573                                         }
574                                         return true;
575                                 });
576                                 return split_package;
577                         },
578                         _ => {
579                                 // Note, we may try to split on remote transaction for
580                                 // which we don't have a competing one (HTLC-Success before
581                                 // timelock expiration). This explain we don't panic!
582                                 // We should refactor OnchainTxHandler::block_connected to
583                                 // only test equality on competing claims.
584                                 return None;
585                         }
586                 }
587         }
588         pub(crate) fn merge_package(&mut self, mut merge_from: PackageTemplate) {
589                 assert_eq!(self.height_original, merge_from.height_original);
590                 if self.malleability == PackageMalleability::Untractable || merge_from.malleability == PackageMalleability::Untractable {
591                         panic!("Merging template on untractable packages");
592                 }
593                 if !self.aggregable || !merge_from.aggregable {
594                         panic!("Merging non aggregatable packages");
595                 }
596                 if let Some((_, lead_input)) = self.inputs.first() {
597                         for (_, v) in merge_from.inputs.iter() {
598                                 if !lead_input.is_compatible(v) { panic!("Merging outputs from differing types !"); }
599                         }
600                 } else { panic!("Merging template on an empty package"); }
601                 for (k, v) in merge_from.inputs.drain(..) {
602                         self.inputs.push((k, v));
603                 }
604                 //TODO: verify coverage and sanity?
605                 if self.soonest_conf_deadline > merge_from.soonest_conf_deadline {
606                         self.soonest_conf_deadline = merge_from.soonest_conf_deadline;
607                 }
608                 if self.feerate_previous > merge_from.feerate_previous {
609                         self.feerate_previous = merge_from.feerate_previous;
610                 }
611                 self.height_timer = cmp::min(self.height_timer, merge_from.height_timer);
612         }
613         /// Gets the amount of all outptus being spent by this package, only valid for malleable
614         /// packages.
615         pub(crate) fn package_amount(&self) -> u64 {
616                 let mut amounts = 0;
617                 for (_, outp) in self.inputs.iter() {
618                         amounts += outp.amount();
619                 }
620                 amounts
621         }
622         pub(crate) fn package_timelock(&self) -> u32 {
623                 self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(self.height_original))
624                         .max().expect("There must always be at least one output to spend in a PackageTemplate")
625         }
626         pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
627                 let mut inputs_weight = 0;
628                 let mut witnesses_weight = 2; // count segwit flags
629                 for (_, outp) in self.inputs.iter() {
630                         // previous_out_point: 36 bytes ; var_int: 1 byte ; sequence: 4 bytes
631                         inputs_weight += 41 * WITNESS_SCALE_FACTOR;
632                         witnesses_weight += outp.weight();
633                 }
634                 // version: 4 bytes ; count_tx_in: 1 byte ; count_tx_out: 1 byte ; lock_time: 4 bytes
635                 let transaction_weight = 10 * WITNESS_SCALE_FACTOR;
636                 // value: 8 bytes ; var_int: 1 byte ; pk_script: `destination_script.len()`
637                 let output_weight = (8 + 1 + destination_script.len()) * WITNESS_SCALE_FACTOR;
638                 inputs_weight + witnesses_weight + transaction_weight + output_weight
639         }
640         pub(crate) fn finalize_malleable_package<L: Deref, Signer: Sign>(
641                 &self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
642         ) -> Option<Transaction> where L::Target: Logger {
643                 debug_assert!(self.is_malleable());
644                 let mut bumped_tx = Transaction {
645                         version: 2,
646                         lock_time: PackedLockTime::ZERO,
647                         input: vec![],
648                         output: vec![TxOut {
649                                 script_pubkey: destination_script,
650                                 value,
651                         }],
652                 };
653                 for (outpoint, _) in self.inputs.iter() {
654                         bumped_tx.input.push(TxIn {
655                                 previous_output: *outpoint,
656                                 script_sig: Script::new(),
657                                 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
658                                 witness: Witness::new(),
659                         });
660                 }
661                 for (i, (outpoint, out)) in self.inputs.iter().enumerate() {
662                         log_debug!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
663                         if !out.finalize_input(&mut bumped_tx, i, onchain_handler) { return None; }
664                 }
665                 log_debug!(logger, "Finalized transaction {} ready to broadcast", bumped_tx.txid());
666                 Some(bumped_tx)
667         }
668         pub(crate) fn finalize_untractable_package<L: Deref, Signer: Sign>(
669                 &self, onchain_handler: &mut OnchainTxHandler<Signer>, logger: &L,
670         ) -> Option<Transaction> where L::Target: Logger {
671                 debug_assert!(!self.is_malleable());
672                 if let Some((outpoint, outp)) = self.inputs.first() {
673                         if let Some(final_tx) = outp.get_finalized_tx(outpoint, onchain_handler) {
674                                 log_debug!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
675                                 log_debug!(logger, "Finalized transaction {} ready to broadcast", final_tx.txid());
676                                 return Some(final_tx);
677                         }
678                         return None;
679                 } else { panic!("API Error: Package must not be inputs empty"); }
680         }
681         /// In LN, output claimed are time-sensitive, which means we have to spend them before reaching some timelock expiration. At in-channel
682         /// 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
683         /// height that once reached we should generate a new bumped "version" of the claim tx to be sure that we safely claim outputs before
684         /// that our counterparty can do so. If timelock expires soon, height timer is going to be scaled down in consequence to increase
685         /// frequency of the bump and so increase our bets of success.
686         pub(crate) fn get_height_timer(&self, current_height: u32) -> u32 {
687                 if self.soonest_conf_deadline <= current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL {
688                         return current_height + HIGH_FREQUENCY_BUMP_INTERVAL
689                 } else if self.soonest_conf_deadline - current_height <= LOW_FREQUENCY_BUMP_INTERVAL {
690                         return current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL
691                 }
692                 current_height + LOW_FREQUENCY_BUMP_INTERVAL
693         }
694
695         /// Returns value in satoshis to be included as package outgoing output amount and feerate
696         /// which was used to generate the value. Will not return less than `dust_limit_sats` for the
697         /// value.
698         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)>
699                 where F::Target: FeeEstimator,
700                       L::Target: Logger,
701         {
702                 debug_assert!(self.malleability == PackageMalleability::Malleable, "The package output is fixed for non-malleable packages");
703                 let input_amounts = self.package_amount();
704                 assert!(dust_limit_sats as i64 > 0, "Output script must be broadcastable/have a 'real' dust limit.");
705                 // If old feerate is 0, first iteration of this claim, use normal fee calculation
706                 if self.feerate_previous != 0 {
707                         if let Some((new_fee, feerate)) = feerate_bump(predicted_weight, input_amounts, self.feerate_previous, fee_estimator, logger) {
708                                 return Some((cmp::max(input_amounts as i64 - new_fee as i64, dust_limit_sats as i64) as u64, feerate));
709                         }
710                 } else {
711                         if let Some((new_fee, feerate)) = compute_fee_from_spent_amounts(input_amounts, predicted_weight, 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                 }
715                 None
716         }
717
718         #[cfg(anchors)]
719         /// Computes a feerate based on the given confirmation target. If a previous feerate was used,
720         /// and the new feerate is below it, we'll use a 25% increase of the previous feerate instead of
721         /// the new one.
722         pub(crate) fn compute_package_feerate<F: Deref>(
723                 &self, fee_estimator: &LowerBoundedFeeEstimator<F>, conf_target: ConfirmationTarget,
724         ) -> u32 where F::Target: FeeEstimator {
725                 let feerate_estimate = fee_estimator.bounded_sat_per_1000_weight(conf_target);
726                 if self.feerate_previous != 0 {
727                         // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
728                         if feerate_estimate as u64 > self.feerate_previous {
729                                 feerate_estimate
730                         } else {
731                                 // ...else just increase the previous feerate by 25% (because that's a nice number)
732                                 (self.feerate_previous + (self.feerate_previous / 4)).try_into().unwrap_or(u32::max_value())
733                         }
734                 } else {
735                         feerate_estimate
736                 }
737         }
738
739         /// Determines whether a package contains an input which must have additional external inputs
740         /// attached to help the spending transaction reach confirmation.
741         pub(crate) fn requires_external_funding(&self) -> bool {
742                 self.inputs.iter().find(|input| match input.1 {
743                         PackageSolvingData::HolderFundingOutput(ref outp) => outp.opt_anchors(),
744                         _ => false,
745                 }).is_some()
746         }
747
748         pub (crate) fn build_package(txid: Txid, vout: u32, input_solving_data: PackageSolvingData, soonest_conf_deadline: u32, aggregable: bool, height_original: u32) -> Self {
749                 let malleability = match input_solving_data {
750                         PackageSolvingData::RevokedOutput(..) => PackageMalleability::Malleable,
751                         PackageSolvingData::RevokedHTLCOutput(..) => PackageMalleability::Malleable,
752                         PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => PackageMalleability::Malleable,
753                         PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => PackageMalleability::Malleable,
754                         PackageSolvingData::HolderHTLCOutput(..) => PackageMalleability::Untractable,
755                         PackageSolvingData::HolderFundingOutput(..) => PackageMalleability::Untractable,
756                 };
757                 let mut inputs = Vec::with_capacity(1);
758                 inputs.push((BitcoinOutPoint { txid, vout }, input_solving_data));
759                 PackageTemplate {
760                         inputs,
761                         malleability,
762                         soonest_conf_deadline,
763                         aggregable,
764                         feerate_previous: 0,
765                         height_timer: None,
766                         height_original,
767                 }
768         }
769 }
770
771 impl Writeable for PackageTemplate {
772         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
773                 writer.write_all(&byte_utils::be64_to_array(self.inputs.len() as u64))?;
774                 for (ref outpoint, ref rev_outp) in self.inputs.iter() {
775                         outpoint.write(writer)?;
776                         rev_outp.write(writer)?;
777                 }
778                 write_tlv_fields!(writer, {
779                         (0, self.soonest_conf_deadline, required),
780                         (2, self.feerate_previous, required),
781                         (4, self.height_original, required),
782                         (6, self.height_timer, option)
783                 });
784                 Ok(())
785         }
786 }
787
788 impl Readable for PackageTemplate {
789         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
790                 let inputs_count = <u64 as Readable>::read(reader)?;
791                 let mut inputs: Vec<(BitcoinOutPoint, PackageSolvingData)> = Vec::with_capacity(cmp::min(inputs_count as usize, MAX_ALLOC_SIZE / 128));
792                 for _ in 0..inputs_count {
793                         let outpoint = Readable::read(reader)?;
794                         let rev_outp = Readable::read(reader)?;
795                         inputs.push((outpoint, rev_outp));
796                 }
797                 let (malleability, aggregable) = if let Some((_, lead_input)) = inputs.first() {
798                         match lead_input {
799                                 PackageSolvingData::RevokedOutput(..) => { (PackageMalleability::Malleable, true) },
800                                 PackageSolvingData::RevokedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
801                                 PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
802                                 PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { (PackageMalleability::Malleable, false) },
803                                 PackageSolvingData::HolderHTLCOutput(..) => { (PackageMalleability::Untractable, false) },
804                                 PackageSolvingData::HolderFundingOutput(..) => { (PackageMalleability::Untractable, false) },
805                         }
806                 } else { return Err(DecodeError::InvalidValue); };
807                 let mut soonest_conf_deadline = 0;
808                 let mut feerate_previous = 0;
809                 let mut height_timer = None;
810                 let mut height_original = 0;
811                 read_tlv_fields!(reader, {
812                         (0, soonest_conf_deadline, required),
813                         (2, feerate_previous, required),
814                         (4, height_original, required),
815                         (6, height_timer, option),
816                 });
817                 Ok(PackageTemplate {
818                         inputs,
819                         malleability,
820                         soonest_conf_deadline,
821                         aggregable,
822                         feerate_previous,
823                         height_timer,
824                         height_original,
825                 })
826         }
827 }
828
829 /// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
830 /// weight. We start with the highest priority feerate returned by the node's fee estimator then
831 /// fall-back to lower priorities until we have enough value available to suck from.
832 ///
833 /// If the proposed fee is less than the available spent output's values, we return the proposed
834 /// fee and the corresponding updated feerate. If the proposed fee is equal or more than the
835 /// available spent output's values, we return nothing
836 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)>
837         where F::Target: FeeEstimator,
838               L::Target: Logger,
839 {
840         let mut updated_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::HighPriority) as u64;
841         let mut fee = updated_feerate * (predicted_weight as u64) / 1000;
842         if input_amounts <= fee {
843                 updated_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal) as u64;
844                 fee = updated_feerate * (predicted_weight as u64) / 1000;
845                 if input_amounts <= fee {
846                         updated_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Background) as u64;
847                         fee = updated_feerate * (predicted_weight as u64) / 1000;
848                         if input_amounts <= fee {
849                                 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)",
850                                         fee, input_amounts);
851                                 None
852                         } else {
853                                 log_warn!(logger, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
854                                         input_amounts);
855                                 Some((fee, updated_feerate))
856                         }
857                 } else {
858                         log_warn!(logger, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
859                                 input_amounts);
860                         Some((fee, updated_feerate))
861                 }
862         } else {
863                 Some((fee, updated_feerate))
864         }
865 }
866
867 /// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
868 /// weight. If feerates proposed by the fee-estimator have been increasing since last fee-bumping
869 /// attempt, use them. Otherwise, blindly bump the feerate by 25% of the previous feerate. We also
870 /// verify that those bumping heuristics respect BIP125 rules 3) and 4) and if required adjust
871 /// the new fee to meet the RBF policy requirement.
872 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)>
873         where F::Target: FeeEstimator,
874               L::Target: Logger,
875 {
876         // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
877         let new_fee = if let Some((new_fee, _)) = compute_fee_from_spent_amounts(input_amounts, predicted_weight, fee_estimator, logger) {
878                 let updated_feerate = new_fee / (predicted_weight as u64 * 1000);
879                 if updated_feerate > previous_feerate {
880                         new_fee
881                 } else {
882                         // ...else just increase the previous feerate by 25% (because that's a nice number)
883                         let new_fee = previous_feerate * (predicted_weight as u64) / 750;
884                         if input_amounts <= new_fee {
885                                 log_warn!(logger, "Can't 25% bump new claiming tx, amount {} is too small", input_amounts);
886                                 return None;
887                         }
888                         new_fee
889                 }
890         } else {
891                 log_warn!(logger, "Can't new-estimation bump new claiming tx, amount {} is too small", input_amounts);
892                 return None;
893         };
894
895         let previous_fee = previous_feerate * (predicted_weight as u64) / 1000;
896         let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * (predicted_weight as u64) / 1000;
897         // BIP 125 Opt-in Full Replace-by-Fee Signaling
898         //      * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
899         //      * 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.
900         let new_fee = if new_fee < previous_fee + min_relay_fee {
901                 new_fee + previous_fee + min_relay_fee - new_fee
902         } else {
903                 new_fee
904         };
905         Some((new_fee, new_fee * 1000 / (predicted_weight as u64)))
906 }
907
908 #[cfg(test)]
909 mod tests {
910         use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderHTLCOutput, PackageTemplate, PackageSolvingData, RevokedOutput, WEIGHT_REVOKED_OUTPUT, weight_offered_htlc, weight_received_htlc};
911         use crate::chain::Txid;
912         use crate::ln::chan_utils::HTLCOutputInCommitment;
913         use crate::ln::{PaymentPreimage, PaymentHash};
914
915         use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
916         use bitcoin::blockdata::script::Script;
917         use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
918
919         use bitcoin::hashes::hex::FromHex;
920
921         use bitcoin::secp256k1::{PublicKey,SecretKey};
922         use bitcoin::secp256k1::Secp256k1;
923
924         macro_rules! dumb_revk_output {
925                 ($secp_ctx: expr) => {
926                         {
927                                 let dumb_scalar = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
928                                 let dumb_point = PublicKey::from_secret_key(&$secp_ctx, &dumb_scalar);
929                                 PackageSolvingData::RevokedOutput(RevokedOutput::build(dumb_point, dumb_point, dumb_point, dumb_scalar, 0, 0))
930                         }
931                 }
932         }
933
934         macro_rules! dumb_counterparty_output {
935                 ($secp_ctx: expr, $amt: expr, $opt_anchors: expr) => {
936                         {
937                                 let dumb_scalar = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
938                                 let dumb_point = PublicKey::from_secret_key(&$secp_ctx, &dumb_scalar);
939                                 let hash = PaymentHash([1; 32]);
940                                 let htlc = HTLCOutputInCommitment { offered: true, amount_msat: $amt, cltv_expiry: 0, payment_hash: hash, transaction_output_index: None };
941                                 PackageSolvingData::CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput::build(dumb_point, dumb_point, dumb_point, htlc, $opt_anchors))
942                         }
943                 }
944         }
945
946         macro_rules! dumb_counterparty_offered_output {
947                 ($secp_ctx: expr, $amt: expr, $opt_anchors: expr) => {
948                         {
949                                 let dumb_scalar = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
950                                 let dumb_point = PublicKey::from_secret_key(&$secp_ctx, &dumb_scalar);
951                                 let hash = PaymentHash([1; 32]);
952                                 let preimage = PaymentPreimage([2;32]);
953                                 let htlc = HTLCOutputInCommitment { offered: false, amount_msat: $amt, cltv_expiry: 1000, payment_hash: hash, transaction_output_index: None };
954                                 PackageSolvingData::CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput::build(dumb_point, dumb_point, dumb_point, preimage, htlc, $opt_anchors))
955                         }
956                 }
957         }
958
959         macro_rules! dumb_htlc_output {
960                 () => {
961                         {
962                                 let preimage = PaymentPreimage([2;32]);
963                                 PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build_accepted(preimage, 0))
964                         }
965                 }
966         }
967
968         #[test]
969         #[should_panic]
970         fn test_package_differing_heights() {
971                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
972                 let secp_ctx = Secp256k1::new();
973                 let revk_outp = dumb_revk_output!(secp_ctx);
974
975                 let mut package_one_hundred = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, true, 100);
976                 let package_two_hundred = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, true, 200);
977                 package_one_hundred.merge_package(package_two_hundred);
978         }
979
980         #[test]
981         #[should_panic]
982         fn test_package_untractable_merge_to() {
983                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
984                 let secp_ctx = Secp256k1::new();
985                 let revk_outp = dumb_revk_output!(secp_ctx);
986                 let htlc_outp = dumb_htlc_output!();
987
988                 let mut untractable_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, true, 100);
989                 let malleable_package = PackageTemplate::build_package(txid, 1, htlc_outp.clone(), 1000, true, 100);
990                 untractable_package.merge_package(malleable_package);
991         }
992
993         #[test]
994         #[should_panic]
995         fn test_package_untractable_merge_from() {
996                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
997                 let secp_ctx = Secp256k1::new();
998                 let htlc_outp = dumb_htlc_output!();
999                 let revk_outp = dumb_revk_output!(secp_ctx);
1000
1001                 let mut malleable_package = PackageTemplate::build_package(txid, 0, htlc_outp.clone(), 1000, true, 100);
1002                 let untractable_package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, true, 100);
1003                 malleable_package.merge_package(untractable_package);
1004         }
1005
1006         #[test]
1007         #[should_panic]
1008         fn test_package_noaggregation_to() {
1009                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1010                 let secp_ctx = Secp256k1::new();
1011                 let revk_outp = dumb_revk_output!(secp_ctx);
1012
1013                 let mut noaggregation_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, false, 100);
1014                 let aggregation_package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, true, 100);
1015                 noaggregation_package.merge_package(aggregation_package);
1016         }
1017
1018         #[test]
1019         #[should_panic]
1020         fn test_package_noaggregation_from() {
1021                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1022                 let secp_ctx = Secp256k1::new();
1023                 let revk_outp = dumb_revk_output!(secp_ctx);
1024
1025                 let mut aggregation_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, true, 100);
1026                 let noaggregation_package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, false, 100);
1027                 aggregation_package.merge_package(noaggregation_package);
1028         }
1029
1030         #[test]
1031         #[should_panic]
1032         fn test_package_empty() {
1033                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1034                 let secp_ctx = Secp256k1::new();
1035                 let revk_outp = dumb_revk_output!(secp_ctx);
1036
1037                 let mut empty_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, true, 100);
1038                 empty_package.inputs = vec![];
1039                 let package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, true, 100);
1040                 empty_package.merge_package(package);
1041         }
1042
1043         #[test]
1044         #[should_panic]
1045         fn test_package_differing_categories() {
1046                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1047                 let secp_ctx = Secp256k1::new();
1048                 let revk_outp = dumb_revk_output!(secp_ctx);
1049                 let counterparty_outp = dumb_counterparty_output!(secp_ctx, 0, false);
1050
1051                 let mut revoked_package = PackageTemplate::build_package(txid, 0, revk_outp, 1000, true, 100);
1052                 let counterparty_package = PackageTemplate::build_package(txid, 1, counterparty_outp, 1000, true, 100);
1053                 revoked_package.merge_package(counterparty_package);
1054         }
1055
1056         #[test]
1057         fn test_package_split_malleable() {
1058                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1059                 let secp_ctx = Secp256k1::new();
1060                 let revk_outp_one = dumb_revk_output!(secp_ctx);
1061                 let revk_outp_two = dumb_revk_output!(secp_ctx);
1062                 let revk_outp_three = dumb_revk_output!(secp_ctx);
1063
1064                 let mut package_one = PackageTemplate::build_package(txid, 0, revk_outp_one, 1000, true, 100);
1065                 let package_two = PackageTemplate::build_package(txid, 1, revk_outp_two, 1000, true, 100);
1066                 let package_three = PackageTemplate::build_package(txid, 2, revk_outp_three, 1000, true, 100);
1067
1068                 package_one.merge_package(package_two);
1069                 package_one.merge_package(package_three);
1070                 assert_eq!(package_one.outpoints().len(), 3);
1071
1072                 if let Some(split_package) = package_one.split_package(&BitcoinOutPoint { txid, vout: 1 }) {
1073                         // Packages attributes should be identical
1074                         assert!(split_package.is_malleable());
1075                         assert_eq!(split_package.soonest_conf_deadline, package_one.soonest_conf_deadline);
1076                         assert_eq!(split_package.aggregable, package_one.aggregable);
1077                         assert_eq!(split_package.feerate_previous, package_one.feerate_previous);
1078                         assert_eq!(split_package.height_timer, package_one.height_timer);
1079                         assert_eq!(split_package.height_original, package_one.height_original);
1080                 } else { panic!(); }
1081                 assert_eq!(package_one.outpoints().len(), 2);
1082         }
1083
1084         #[test]
1085         fn test_package_split_untractable() {
1086                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1087                 let htlc_outp_one = dumb_htlc_output!();
1088
1089                 let mut package_one = PackageTemplate::build_package(txid, 0, htlc_outp_one, 1000, true, 100);
1090                 let ret_split = package_one.split_package(&BitcoinOutPoint { txid, vout: 0});
1091                 assert!(ret_split.is_none());
1092         }
1093
1094         #[test]
1095         fn test_package_timer() {
1096                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1097                 let secp_ctx = Secp256k1::new();
1098                 let revk_outp = dumb_revk_output!(secp_ctx);
1099
1100                 let mut package = PackageTemplate::build_package(txid, 0, revk_outp, 1000, true, 100);
1101                 let timer_none = package.timer();
1102                 assert!(timer_none.is_none());
1103                 package.set_timer(Some(100));
1104                 if let Some(timer_some) = package.timer() {
1105                         assert_eq!(timer_some, 100);
1106                 } else { panic!() }
1107         }
1108
1109         #[test]
1110         fn test_package_amounts() {
1111                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1112                 let secp_ctx = Secp256k1::new();
1113                 let counterparty_outp = dumb_counterparty_output!(secp_ctx, 1_000_000, false);
1114
1115                 let package = PackageTemplate::build_package(txid, 0, counterparty_outp, 1000, true, 100);
1116                 assert_eq!(package.package_amount(), 1000);
1117         }
1118
1119         #[test]
1120         fn test_package_weight() {
1121                 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1122                 let secp_ctx = Secp256k1::new();
1123
1124                 // (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)
1125                 let weight_sans_output = (4 + 4 + 1 + 36 + 4 + 1 + 1 + 8 + 1) * WITNESS_SCALE_FACTOR + 2;
1126
1127                 {
1128                         let revk_outp = dumb_revk_output!(secp_ctx);
1129                         let package = PackageTemplate::build_package(txid, 0, revk_outp, 0, true, 100);
1130                         assert_eq!(package.package_weight(&Script::new()),  weight_sans_output + WEIGHT_REVOKED_OUTPUT as usize);
1131                 }
1132
1133                 {
1134                         for &opt_anchors in [false, true].iter() {
1135                                 let counterparty_outp = dumb_counterparty_output!(secp_ctx, 1_000_000, opt_anchors);
1136                                 let package = PackageTemplate::build_package(txid, 0, counterparty_outp, 1000, true, 100);
1137                                 assert_eq!(package.package_weight(&Script::new()), weight_sans_output + weight_received_htlc(opt_anchors) as usize);
1138                         }
1139                 }
1140
1141                 {
1142                         for &opt_anchors in [false, true].iter() {
1143                                 let counterparty_outp = dumb_counterparty_offered_output!(secp_ctx, 1_000_000, opt_anchors);
1144                                 let package = PackageTemplate::build_package(txid, 0, counterparty_outp, 1000, true, 100);
1145                                 assert_eq!(package.package_weight(&Script::new()), weight_sans_output + weight_offered_htlc(opt_anchors) as usize);
1146                         }
1147                 }
1148         }
1149 }