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