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