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