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