008da5d265e5e4c5d38d188d025e12328d7d7db5
[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, HTLC_OUTPUT_IN_COMMITMENT_SIZE};
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 std::cmp;
35 use std::mem;
36 use std::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!(RevokedOutput, 33*3 + 32 + 8 + 8 + 2, {
90         per_commitment_point,
91         counterparty_delayed_payment_base_key,
92         counterparty_htlc_base_key,
93         per_commitment_key,
94         weight,
95         amount,
96         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!(RevokedHTLCOutput, 33*3 + 32 + 8 + 8 + HTLC_OUTPUT_IN_COMMITMENT_SIZE, {
134         per_commitment_point,
135         counterparty_delayed_payment_base_key,
136         counterparty_htlc_base_key,
137         per_commitment_key,
138         weight,
139         amount,
140         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!(CounterpartyOfferedHTLCOutput, 33*3 + 32 + HTLC_OUTPUT_IN_COMMITMENT_SIZE, {
171         per_commitment_point,
172         counterparty_delayed_payment_base_key,
173         counterparty_htlc_base_key,
174         preimage,
175         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!(CounterpartyReceivedHTLCOutput, 33*3 + HTLC_OUTPUT_IN_COMMITMENT_SIZE, {
202         per_commitment_point,
203         counterparty_delayed_payment_base_key,
204         counterparty_htlc_base_key,
205         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!(HolderHTLCOutput, 0, {
228         preimage,
229         amount
230 });
231
232 /// A struct to describe the channel output on the funding transaction.
233 ///
234 /// witnessScript is used as part of the witness redeeming the funding utxo.
235 #[derive(Clone, PartialEq)]
236 pub(crate) struct HolderFundingOutput {
237         funding_redeemscript: Script,
238 }
239
240 impl HolderFundingOutput {
241         pub(crate) fn build(funding_redeemscript: Script) -> Self {
242                 HolderFundingOutput {
243                         funding_redeemscript,
244                 }
245         }
246 }
247
248 impl_writeable!(HolderFundingOutput, 0, {
249         funding_redeemscript
250 });
251
252 /// A wrapper encapsulating all in-protocol differing outputs types.
253 ///
254 /// The generic API offers access to an outputs common attributes or allow transformation such as
255 /// finalizing an input claiming the output.
256 #[derive(Clone, PartialEq)]
257 pub(crate) enum PackageSolvingData {
258         RevokedOutput(RevokedOutput),
259         RevokedHTLCOutput(RevokedHTLCOutput),
260         CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput),
261         CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput),
262         HolderHTLCOutput(HolderHTLCOutput),
263         HolderFundingOutput(HolderFundingOutput),
264 }
265
266 impl PackageSolvingData {
267         fn amount(&self) -> u64 {
268                 let amt = match self {
269                         PackageSolvingData::RevokedOutput(ref outp) => { outp.amount },
270                         PackageSolvingData::RevokedHTLCOutput(ref outp) => { outp.amount },
271                         PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => { outp.htlc.amount_msat / 1000 },
272                         PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => { outp.htlc.amount_msat / 1000 },
273                         // Note: Currently, amounts of holder outputs spending witnesses aren't used
274                         // as we can't malleate spending package to increase their feerate. This
275                         // should change with the remaining anchor output patchset.
276                         PackageSolvingData::HolderHTLCOutput(..) => { 0 },
277                         PackageSolvingData::HolderFundingOutput(..) => { 0 },
278                 };
279                 amt
280         }
281         fn weight(&self) -> usize {
282                 let weight = match self {
283                         PackageSolvingData::RevokedOutput(ref outp) => { outp.weight as usize },
284                         PackageSolvingData::RevokedHTLCOutput(ref outp) => { outp.weight as usize },
285                         PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { WEIGHT_OFFERED_HTLC as usize },
286                         PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { WEIGHT_RECEIVED_HTLC as usize },
287                         // Note: Currently, weights of holder outputs spending witnesses aren't used
288                         // as we can't malleate spending package to increase their feerate. This
289                         // should change with the remaining anchor output patchset.
290                         PackageSolvingData::HolderHTLCOutput(..) => { debug_assert!(false); 0 },
291                         PackageSolvingData::HolderFundingOutput(..) => { debug_assert!(false); 0 },
292                 };
293                 weight
294         }
295         fn is_compatible(&self, input: &PackageSolvingData) -> bool {
296                 match self {
297                         PackageSolvingData::RevokedOutput(..) => {
298                                 match input {
299                                         PackageSolvingData::RevokedHTLCOutput(..) => { true },
300                                         PackageSolvingData::RevokedOutput(..) => { true },
301                                         _ => { false }
302                                 }
303                         },
304                         PackageSolvingData::RevokedHTLCOutput(..) => {
305                                 match input {
306                                         PackageSolvingData::RevokedOutput(..) => { true },
307                                         PackageSolvingData::RevokedHTLCOutput(..) => { true },
308                                         _ => { false }
309                                 }
310                         },
311                         _ => { mem::discriminant(self) == mem::discriminant(&input) }
312                 }
313         }
314         fn finalize_input<Signer: Sign>(&self, bumped_tx: &mut Transaction, i: usize, onchain_handler: &mut OnchainTxHandler<Signer>) -> bool {
315                 match self {
316                         PackageSolvingData::RevokedOutput(ref outp) => {
317                                 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) {
318                                         let witness_script = chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, outp.on_counterparty_tx_csv, &chan_keys.broadcaster_delayed_payment_key);
319                                         //TODO: should we panic on signer failure ?
320                                         if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_output(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &onchain_handler.secp_ctx) {
321                                                 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
322                                                 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
323                                                 bumped_tx.input[i].witness.push(vec!(1));
324                                                 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
325                                         } else { return false; }
326                                 }
327                         },
328                         PackageSolvingData::RevokedHTLCOutput(ref outp) => {
329                                 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) {
330                                         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);
331                                         //TODO: should we panic on signer failure ?
332                                         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) {
333                                                 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
334                                                 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
335                                                 bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
336                                                 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
337                                         } else { return false; }
338                                 }
339                         },
340                         PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => {
341                                 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) {
342                                         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);
343
344                                         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) {
345                                                 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
346                                                 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
347                                                 bumped_tx.input[i].witness.push(outp.preimage.0.to_vec());
348                                                 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
349                                         }
350                                 }
351                         },
352                         PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => {
353                                 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) {
354                                         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);
355
356                                         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
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                                                 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
361                                                 bumped_tx.input[i].witness.push(vec![]);
362                                                 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
363                                         }
364                                 }
365                         },
366                         _ => { panic!("API Error!"); }
367                 }
368                 true
369         }
370         fn get_finalized_tx<Signer: Sign>(&self, outpoint: &BitcoinOutPoint, onchain_handler: &mut OnchainTxHandler<Signer>) -> Option<Transaction> {
371                 match self {
372                         PackageSolvingData::HolderHTLCOutput(ref outp) => { return onchain_handler.get_fully_signed_htlc_tx(outpoint, &outp.preimage); }
373                         PackageSolvingData::HolderFundingOutput(ref outp) => { return Some(onchain_handler.get_fully_signed_holder_tx(&outp.funding_redeemscript)); }
374                         _ => { panic!("API Error!"); }
375                 }
376         }
377 }
378
379 impl Writeable for PackageSolvingData {
380         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
381                 match self {
382                         PackageSolvingData::RevokedOutput(ref revoked_outp) => {
383                                 0u8.write(writer)?;
384                                 revoked_outp.write(writer)?;
385                         },
386                         PackageSolvingData::RevokedHTLCOutput(ref revoked_outp) => {
387                                 1u8.write(writer)?;
388                                 revoked_outp.write(writer)?;
389                         },
390                         PackageSolvingData::CounterpartyOfferedHTLCOutput(ref counterparty_outp) => {
391                                 2u8.write(writer)?;
392                                 counterparty_outp.write(writer)?;
393                         },
394                         PackageSolvingData::CounterpartyReceivedHTLCOutput(ref counterparty_outp) => {
395                                 3u8.write(writer)?;
396                                 counterparty_outp.write(writer)?;
397                         },
398                         PackageSolvingData::HolderHTLCOutput(ref holder_outp) => {
399                                 4u8.write(writer)?;
400                                 holder_outp.write(writer)?;
401                         },
402                         PackageSolvingData::HolderFundingOutput(ref funding_outp) => {
403                                 5u8.write(writer)?;
404                                 funding_outp.write(writer)?;
405                         }
406                 }
407                 Ok(())
408         }
409 }
410
411 impl Readable for PackageSolvingData {
412         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
413                 let byte = <u8 as Readable>::read(reader)?;
414                 let solving_data = match byte {
415                         0 => {
416                                 PackageSolvingData::RevokedOutput(Readable::read(reader)?)
417                         },
418                         1 => {
419                                 PackageSolvingData::RevokedHTLCOutput(Readable::read(reader)?)
420                         },
421                         2 => {
422                                 PackageSolvingData::CounterpartyOfferedHTLCOutput(Readable::read(reader)?)
423                         },
424                         3 => {
425                                 PackageSolvingData::CounterpartyReceivedHTLCOutput(Readable::read(reader)?)
426                         },
427                         4 => {
428                                 PackageSolvingData::HolderHTLCOutput(Readable::read(reader)?)
429                         },
430                         5 => {
431                                 PackageSolvingData::HolderFundingOutput(Readable::read(reader)?)
432                         }
433                         _ => return Err(DecodeError::UnknownVersion)
434                 };
435                 Ok(solving_data)
436         }
437 }
438
439 /// A malleable package might be aggregated with other packages to save on fees.
440 /// A untractable package has been counter-signed and aggregable will break cached counterparty
441 /// signatures.
442 #[derive(Clone, PartialEq)]
443 pub(crate) enum PackageMalleability {
444         Malleable,
445         Untractable,
446 }
447
448 /// A structure to describe a package content that is generated by ChannelMonitor and
449 /// used by OnchainTxHandler to generate and broadcast transactions settling onchain claims.
450 ///
451 /// A package is defined as one or more transactions claiming onchain outputs in reaction
452 /// to confirmation of a channel transaction. Those packages might be aggregated to save on
453 /// fees, if satisfaction of outputs's witnessScript let's us do so.
454 ///
455 /// As packages are time-sensitive, we fee-bump and rebroadcast them at scheduled intervals.
456 /// Failing to confirm a package translate as a loss of funds for the user.
457 #[derive(Clone, PartialEq)]
458 pub struct PackageTemplate {
459         // List of onchain outputs and solving data to generate satisfying witnesses.
460         inputs: Vec<(BitcoinOutPoint, PackageSolvingData)>,
461         // Packages are deemed as malleable if we have local knwoledge of at least one set of
462         // private keys yielding a satisfying witnesses. Malleability implies that we can aggregate
463         // packages among them to save on fees or rely on RBF to bump their feerates.
464         // Untractable packages have been counter-signed and thus imply that we can't aggregate
465         // them without breaking signatures. Fee-bumping strategy will also rely on CPFP.
466         malleability: PackageMalleability,
467         // Block height after which the earlier-output belonging to this package is mature for a
468         // competing claim by the counterparty. As our chain tip becomes nearer from the timelock,
469         // the fee-bumping frequency will increase. See `OnchainTxHandler::get_height_timer`.
470         soonest_conf_deadline: u32,
471         // Determines if this package can be aggregated.
472         // Timelocked outputs belonging to the same transaction might have differing
473         // satisfying heights. Picking up the later height among the output set would be a valid
474         // aggregable strategy but it comes with at least 2 trade-offs :
475         // * earlier-output fund are going to take longer to come back
476         // * CLTV delta backing up a corresponding HTLC on an upstream channel could be swallowed
477         // by the requirement of the later-output part of the set
478         // For now, we mark such timelocked outputs as non-aggregable, though we might introduce
479         // smarter aggregable strategy in the future.
480         aggregable: bool,
481         // Cache of package feerate committed at previous (re)broadcast. If bumping resources
482         // (either claimed output value or external utxo), it will keep increasing until holder
483         // or counterparty successful claim.
484         feerate_previous: u64,
485         // Cache of next height at which fee-bumping and rebroadcast will be attempted. In
486         // the future, we might abstract it to an observed mempool fluctuation.
487         height_timer: Option<u32>,
488         // Confirmation height of the claimed outputs set transaction. In case of reorg reaching
489         // it, we wipe out and forget the package.
490         height_original: u32,
491 }
492
493 impl PackageTemplate {
494         pub(crate) fn is_malleable(&self) -> bool {
495                 self.malleability == PackageMalleability::Malleable
496         }
497         pub(crate) fn timelock(&self) -> u32 {
498                 self.soonest_conf_deadline
499         }
500         pub(crate) fn aggregable(&self) -> bool {
501                 self.aggregable
502         }
503         pub(crate) fn feerate(&self) -> u64 {
504                 self.feerate_previous
505         }
506         pub(crate) fn set_feerate(&mut self, new_feerate: u64) {
507                 self.feerate_previous = new_feerate;
508         }
509         pub(crate) fn timer(&self) -> Option<u32> {
510                 if let Some(ref timer) = self.height_timer {
511                         return Some(*timer);
512                 }
513                 None
514         }
515         pub(crate) fn set_timer(&mut self, new_timer: Option<u32>) {
516                 self.height_timer = new_timer;
517         }
518         pub(crate) fn outpoints(&self) -> Vec<&BitcoinOutPoint> {
519                 self.inputs.iter().map(|(o, _)| o).collect()
520         }
521         pub(crate) fn split_package(&mut self, split_outp: &BitcoinOutPoint) -> Option<PackageTemplate> {
522                 match self.malleability {
523                         PackageMalleability::Malleable => {
524                                 let mut split_package = None;
525                                 let timelock = self.soonest_conf_deadline;
526                                 let aggregable = self.aggregable;
527                                 let feerate_previous = self.feerate_previous;
528                                 let height_timer = self.height_timer;
529                                 let height_original = self.height_original;
530                                 self.inputs.retain(|outp| {
531                                         if *split_outp == outp.0 {
532                                                 split_package = Some(PackageTemplate {
533                                                         inputs: vec![(outp.0, outp.1.clone())],
534                                                         malleability: PackageMalleability::Malleable,
535                                                         soonest_conf_deadline: timelock,
536                                                         aggregable,
537                                                         feerate_previous,
538                                                         height_timer,
539                                                         height_original,
540                                                 });
541                                                 return false;
542                                         }
543                                         return true;
544                                 });
545                                 return split_package;
546                         },
547                         _ => {
548                                 // Note, we may try to split on remote transaction for
549                                 // which we don't have a competing one (HTLC-Success before
550                                 // timelock expiration). This explain we don't panic!
551                                 // We should refactor OnchainTxHandler::block_connected to
552                                 // only test equality on competing claims.
553                                 return None;
554                         }
555                 }
556         }
557         pub(crate) fn merge_package(&mut self, mut merge_from: PackageTemplate) {
558                 assert_eq!(self.height_original, merge_from.height_original);
559                 if self.malleability == PackageMalleability::Untractable || merge_from.malleability == PackageMalleability::Untractable {
560                         panic!("Merging template on untractable packages");
561                 }
562                 if !self.aggregable || !merge_from.aggregable {
563                         panic!("Merging non aggregatable packages");
564                 }
565                 if let Some((_, lead_input)) = self.inputs.first() {
566                         for (_, v) in merge_from.inputs.iter() {
567                                 if !lead_input.is_compatible(v) { panic!("Merging outputs from differing types !"); }
568                         }
569                 } else { panic!("Merging template on an empty package"); }
570                 for (k, v) in merge_from.inputs.drain(..) {
571                         self.inputs.push((k, v));
572                 }
573                 //TODO: verify coverage and sanity?
574                 if self.soonest_conf_deadline > merge_from.soonest_conf_deadline {
575                         self.soonest_conf_deadline = merge_from.soonest_conf_deadline;
576                 }
577                 if self.feerate_previous > merge_from.feerate_previous {
578                         self.feerate_previous = merge_from.feerate_previous;
579                 }
580                 self.height_timer = cmp::min(self.height_timer, merge_from.height_timer);
581         }
582         pub(crate) fn package_amount(&self) -> u64 {
583                 let mut amounts = 0;
584                 for (_, outp) in self.inputs.iter() {
585                         amounts += outp.amount();
586                 }
587                 amounts
588         }
589         pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
590                 let mut inputs_weight = 0;
591                 let mut witnesses_weight = 2; // count segwit flags
592                 for (_, outp) in self.inputs.iter() {
593                         // previous_out_point: 36 bytes ; var_int: 1 byte ; sequence: 4 bytes
594                         inputs_weight += 41 * WITNESS_SCALE_FACTOR;
595                         witnesses_weight += outp.weight();
596                 }
597                 // version: 4 bytes ; count_tx_in: 1 byte ; count_tx_out: 1 byte ; lock_time: 4 bytes
598                 let transaction_weight = 10 * WITNESS_SCALE_FACTOR;
599                 // value: 8 bytes ; var_int: 1 byte ; pk_script: `destination_script.len()`
600                 let output_weight = (8 + 1 + destination_script.len()) * WITNESS_SCALE_FACTOR;
601                 inputs_weight + witnesses_weight + transaction_weight + output_weight
602         }
603         pub(crate) fn finalize_package<L: Deref, Signer: Sign>(&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L) -> Option<Transaction>
604                 where L::Target: Logger,
605         {
606                 match self.malleability {
607                         PackageMalleability::Malleable => {
608                                 let mut bumped_tx = Transaction {
609                                         version: 2,
610                                         lock_time: 0,
611                                         input: vec![],
612                                         output: vec![TxOut {
613                                                 script_pubkey: destination_script,
614                                                 value,
615                                         }],
616                                 };
617                                 for (outpoint, _) in self.inputs.iter() {
618                                         bumped_tx.input.push(TxIn {
619                                                 previous_output: *outpoint,
620                                                 script_sig: Script::new(),
621                                                 sequence: 0xfffffffd,
622                                                 witness: Vec::new(),
623                                         });
624                                 }
625                                 for (i, (outpoint, out)) in self.inputs.iter().enumerate() {
626                                         log_trace!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
627                                         if !out.finalize_input(&mut bumped_tx, i, onchain_handler) { return None; }
628                                 }
629                                 log_trace!(logger, "Finalized transaction {} ready to broadcast", bumped_tx.txid());
630                                 return Some(bumped_tx);
631                         },
632                         PackageMalleability::Untractable => {
633                                 if let Some((outpoint, outp)) = self.inputs.first() {
634                                         if let Some(final_tx) = outp.get_finalized_tx(outpoint, onchain_handler) {
635                                                 log_trace!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
636                                                 log_trace!(logger, "Finalized transaction {} ready to broadcast", final_tx.txid());
637                                                 return Some(final_tx);
638                                         }
639                                         return None;
640                                 } else { panic!("API Error: Package must not be inputs empty"); }
641                         },
642                 }
643         }
644         /// In LN, output claimed are time-sensitive, which means we have to spend them before reaching some timelock expiration. At in-channel
645         /// 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
646         /// height that once reached we should generate a new bumped "version" of the claim tx to be sure that we safely claim outputs before
647         /// that our counterparty can do so. If timelock expires soon, height timer is going to be scaled down in consequence to increase
648         /// frequency of the bump and so increase our bets of success.
649         pub(crate) fn get_height_timer(&self, current_height: u32) -> u32 {
650                 if self.soonest_conf_deadline <= current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL {
651                         return current_height + HIGH_FREQUENCY_BUMP_INTERVAL
652                 } else if self.soonest_conf_deadline - current_height <= LOW_FREQUENCY_BUMP_INTERVAL {
653                         return current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL
654                 }
655                 current_height + LOW_FREQUENCY_BUMP_INTERVAL
656         }
657         pub (crate) fn build_package(txid: Txid, vout: u32, input_solving_data: PackageSolvingData, soonest_conf_deadline: u32, aggregable: bool, height_original: u32) -> Self {
658                 let malleability = match input_solving_data {
659                         PackageSolvingData::RevokedOutput(..) => { PackageMalleability::Malleable },
660                         PackageSolvingData::RevokedHTLCOutput(..) => { PackageMalleability::Malleable },
661                         PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { PackageMalleability::Malleable },
662                         PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { PackageMalleability::Malleable },
663                         PackageSolvingData::HolderHTLCOutput(..) => { PackageMalleability::Untractable },
664                         PackageSolvingData::HolderFundingOutput(..) => { PackageMalleability::Untractable },
665                 };
666                 let mut inputs = Vec::with_capacity(1);
667                 inputs.push((BitcoinOutPoint { txid, vout }, input_solving_data));
668                 PackageTemplate {
669                         inputs,
670                         malleability,
671                         soonest_conf_deadline,
672                         aggregable,
673                         feerate_previous: 0,
674                         height_timer: None,
675                         height_original,
676                 }
677         }
678 }
679
680 impl Writeable for PackageTemplate {
681         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
682                 writer.write_all(&byte_utils::be64_to_array(self.inputs.len() as u64))?;
683                 for (ref outpoint, ref rev_outp) in self.inputs.iter() {
684                         outpoint.write(writer)?;
685                         rev_outp.write(writer)?;
686                 }
687                 self.soonest_conf_deadline.write(writer)?;
688                 self.feerate_previous.write(writer)?;
689                 self.height_timer.write(writer)?;
690                 self.height_original.write(writer)?;
691                 Ok(())
692         }
693 }
694
695 impl Readable for PackageTemplate {
696         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
697                 let inputs_count = <u64 as Readable>::read(reader)?;
698                 let mut inputs: Vec<(BitcoinOutPoint, PackageSolvingData)> = Vec::with_capacity(cmp::min(inputs_count as usize, MAX_ALLOC_SIZE / 128));
699                 for _ in 0..inputs_count {
700                         let outpoint = Readable::read(reader)?;
701                         let rev_outp = Readable::read(reader)?;
702                         inputs.push((outpoint, rev_outp));
703                 }
704                 let (malleability, aggregable) = if let Some((_, lead_input)) = inputs.first() {
705                         match lead_input {
706                                 PackageSolvingData::RevokedOutput(..) => { (PackageMalleability::Malleable, true) },
707                                 PackageSolvingData::RevokedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
708                                 PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
709                                 PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { (PackageMalleability::Malleable, false) },
710                                 PackageSolvingData::HolderHTLCOutput(..) => { (PackageMalleability::Untractable, false) },
711                                 PackageSolvingData::HolderFundingOutput(..) => { (PackageMalleability::Untractable, false) },
712                         }
713                 } else { return Err(DecodeError::InvalidValue); };
714                 let soonest_conf_deadline = Readable::read(reader)?;
715                 let feerate_previous = Readable::read(reader)?;
716                 let height_timer = Readable::read(reader)?;
717                 let height_original = Readable::read(reader)?;
718                 Ok(PackageTemplate {
719                         inputs,
720                         malleability,
721                         soonest_conf_deadline,
722                         aggregable,
723                         feerate_previous,
724                         height_timer,
725                         height_original,
726                 })
727         }
728 }
729
730 /// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
731 /// weight. We start with the highest priority feerate returned by the node's fee estimator then
732 /// fall-back to lower priorities until we have enough value available to suck from.
733 ///
734 /// If the proposed fee is less than the available spent output's values, we return the proposed
735 /// fee and the corresponding updated feerate. If the proposed fee is equal or more than the
736 /// available spent output's values, we return nothing
737 fn compute_fee_from_spent_amounts<F: Deref, L: Deref>(input_amounts: u64, predicted_weight: usize, fee_estimator: &F, logger: &L) -> Option<(u64, u64)>
738         where F::Target: FeeEstimator,
739               L::Target: Logger,
740 {
741         let mut updated_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) as u64;
742         let mut fee = updated_feerate * (predicted_weight as u64) / 1000;
743         if input_amounts <= fee {
744                 updated_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) as u64;
745                 fee = updated_feerate * (predicted_weight as u64) / 1000;
746                 if input_amounts <= fee {
747                         updated_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background) as u64;
748                         fee = updated_feerate * (predicted_weight as u64) / 1000;
749                         if input_amounts <= fee {
750                                 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)",
751                                         fee, input_amounts);
752                                 None
753                         } else {
754                                 log_warn!(logger, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
755                                         input_amounts);
756                                 Some((fee, updated_feerate))
757                         }
758                 } else {
759                         log_warn!(logger, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
760                                 input_amounts);
761                         Some((fee, updated_feerate))
762                 }
763         } else {
764                 Some((fee, updated_feerate))
765         }
766 }
767
768 /// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
769 /// weight. If feerates proposed by the fee-estimator have been increasing since last fee-bumping
770 /// attempt, use them. Otherwise, blindly bump the feerate by 25% of the previous feerate. We also
771 /// verify that those bumping heuristics respect BIP125 rules 3) and 4) and if required adjust
772 /// the new fee to meet the RBF policy requirement.
773 fn feerate_bump<F: Deref, L: Deref>(predicted_weight: usize, input_amounts: u64, previous_feerate: u64, fee_estimator: &F, logger: &L) -> Option<(u64, u64)>
774         where F::Target: FeeEstimator,
775               L::Target: Logger,
776 {
777         // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
778         let new_fee = if let Some((new_fee, _)) = compute_fee_from_spent_amounts(input_amounts, predicted_weight, fee_estimator, logger) {
779                 let updated_feerate = new_fee / (predicted_weight as u64 * 1000);
780                 if updated_feerate > previous_feerate {
781                         new_fee
782                 } else {
783                         // ...else just increase the previous feerate by 25% (because that's a nice number)
784                         let new_fee = previous_feerate * (predicted_weight as u64) / 750;
785                         if input_amounts <= new_fee {
786                                 log_trace!(logger, "Can't 25% bump new claiming tx, amount {} is too small", input_amounts);
787                                 return None;
788                         }
789                         new_fee
790                 }
791         } else {
792                 log_trace!(logger, "Can't new-estimation bump new claiming tx, amount {} is too small", input_amounts);
793                 return None;
794         };
795
796         let previous_fee = previous_feerate * (predicted_weight as u64) / 1000;
797         let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * (predicted_weight as u64) / 1000;
798         // BIP 125 Opt-in Full Replace-by-Fee Signaling
799         //      * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
800         //      * 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.
801         let new_fee = if new_fee < previous_fee + min_relay_fee {
802                 new_fee + previous_fee + min_relay_fee - new_fee
803         } else {
804                 new_fee
805         };
806         Some((new_fee, new_fee * 1000 / (predicted_weight as u64)))
807 }
808
809 /// Deduce a new proposed fee from the claiming transaction output value.
810 /// If the new proposed fee is superior to the consumed outpoint's value, burn everything in miner's
811 /// fee to deter counterparties attacker.
812 pub(crate) fn compute_output_value<F: Deref, L: Deref>(predicted_weight: usize, input_amounts: u64, previous_feerate: u64, fee_estimator: &F, logger: &L) -> Option<(u64, u64)>
813         where F::Target: FeeEstimator,
814               L::Target: Logger,
815 {
816         // If old feerate is 0, first iteration of this claim, use normal fee calculation
817         if previous_feerate != 0 {
818                 if let Some((new_fee, feerate)) = feerate_bump(predicted_weight, input_amounts, previous_feerate, fee_estimator, logger) {
819                         // If new computed fee is superior at the whole claimable amount burn all in fees
820                         if new_fee > input_amounts {
821                                 return Some((0, feerate));
822                         } else {
823                                 return Some((input_amounts - new_fee, feerate));
824                         }
825                 }
826         } else {
827                 if let Some((new_fee, feerate)) = compute_fee_from_spent_amounts(input_amounts, predicted_weight, fee_estimator, logger) {
828                                 return Some((input_amounts - new_fee, feerate));
829                 }
830         }
831         None
832 }
833