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