Move HTLCDescriptor to sign module
[rust-lightning] / lightning / src / events / bump_transaction.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 //! Utilities for bumping transactions originating from [`Event`]s.
11 //!
12 //! [`Event`]: crate::events::Event
13
14 use alloc::collections::BTreeMap;
15 use core::ops::Deref;
16
17 use crate::chain::chaininterface::{BroadcasterInterface, fee_for_weight};
18 use crate::chain::ClaimId;
19 use crate::io_extras::sink;
20 use crate::ln::channel::ANCHOR_OUTPUT_VALUE_SATOSHI;
21 use crate::ln::chan_utils;
22 use crate::ln::chan_utils::{
23         ANCHOR_INPUT_WITNESS_WEIGHT, HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT,
24         HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT, HTLCOutputInCommitment
25 };
26 use crate::prelude::*;
27 use crate::sign::{
28         ChannelDerivationParameters, HTLCDescriptor, EcdsaChannelSigner, SignerProvider,
29         WriteableEcdsaChannelSigner, P2WPKH_WITNESS_WEIGHT
30 };
31 use crate::sync::Mutex;
32 use crate::util::logger::Logger;
33
34 use bitcoin::{OutPoint, PackedLockTime, PubkeyHash, Sequence, Script, Transaction, TxIn, TxOut, Witness, WPubkeyHash};
35 use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
36 use bitcoin::consensus::Encodable;
37 use bitcoin::secp256k1;
38 use bitcoin::secp256k1::Secp256k1;
39 use bitcoin::secp256k1::ecdsa::Signature;
40
41 const EMPTY_SCRIPT_SIG_WEIGHT: u64 = 1 /* empty script_sig */ * WITNESS_SCALE_FACTOR as u64;
42
43 const BASE_INPUT_SIZE: u64 = 32 /* txid */ + 4 /* vout */ + 4 /* sequence */;
44
45 const BASE_INPUT_WEIGHT: u64 = BASE_INPUT_SIZE * WITNESS_SCALE_FACTOR as u64;
46
47 /// A descriptor used to sign for a commitment transaction's anchor output.
48 #[derive(Clone, Debug, PartialEq, Eq)]
49 pub struct AnchorDescriptor {
50         /// The parameters required to derive the signer for the anchor input.
51         pub channel_derivation_parameters: ChannelDerivationParameters,
52         /// The transaction input's outpoint corresponding to the commitment transaction's anchor
53         /// output.
54         pub outpoint: OutPoint,
55 }
56
57 impl AnchorDescriptor {
58         /// Returns the UTXO to be spent by the anchor input, which can be obtained via
59         /// [`Self::unsigned_tx_input`].
60         pub fn previous_utxo(&self) -> TxOut {
61                 TxOut {
62                         script_pubkey: self.witness_script().to_v0_p2wsh(),
63                         value: ANCHOR_OUTPUT_VALUE_SATOSHI,
64                 }
65         }
66
67         /// Returns the unsigned transaction input spending the anchor output in the commitment
68         /// transaction.
69         pub fn unsigned_tx_input(&self) -> TxIn {
70                 TxIn {
71                         previous_output: self.outpoint.clone(),
72                         script_sig: Script::new(),
73                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
74                         witness: Witness::new(),
75                 }
76         }
77
78         /// Returns the witness script of the anchor output in the commitment transaction.
79         pub fn witness_script(&self) -> Script {
80                 let channel_params = self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
81                 chan_utils::get_anchor_redeemscript(&channel_params.broadcaster_pubkeys().funding_pubkey)
82         }
83
84         /// Returns the fully signed witness required to spend the anchor output in the commitment
85         /// transaction.
86         pub fn tx_input_witness(&self, signature: &Signature) -> Witness {
87                 let channel_params = self.channel_derivation_parameters.transaction_parameters.as_holder_broadcastable();
88                 chan_utils::build_anchor_input_witness(&channel_params.broadcaster_pubkeys().funding_pubkey, signature)
89         }
90
91         /// Derives the channel signer required to sign the anchor input.
92         pub fn derive_channel_signer<S: WriteableEcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
93         where
94                 SP::Target: SignerProvider<Signer = S>
95         {
96                 let mut signer = signer_provider.derive_channel_signer(
97                         self.channel_derivation_parameters.value_satoshis,
98                         self.channel_derivation_parameters.keys_id,
99                 );
100                 signer.provide_channel_parameters(&self.channel_derivation_parameters.transaction_parameters);
101                 signer
102         }
103 }
104
105 /// Represents the different types of transactions, originating from LDK, to be bumped.
106 #[derive(Clone, Debug, PartialEq, Eq)]
107 pub enum BumpTransactionEvent {
108         /// Indicates that a channel featuring anchor outputs is to be closed by broadcasting the local
109         /// commitment transaction. Since commitment transactions have a static feerate pre-agreed upon,
110         /// they may need additional fees to be attached through a child transaction using the popular
111         /// [Child-Pays-For-Parent](https://bitcoinops.org/en/topics/cpfp) fee bumping technique. This
112         /// child transaction must include the anchor input described within `anchor_descriptor` along
113         /// with additional inputs to meet the target feerate. Failure to meet the target feerate
114         /// decreases the confirmation odds of the transaction package (which includes the commitment
115         /// and child anchor transactions), possibly resulting in a loss of funds. Once the transaction
116         /// is constructed, it must be fully signed for and broadcast by the consumer of the event
117         /// along with the `commitment_tx` enclosed. Note that the `commitment_tx` must always be
118         /// broadcast first, as the child anchor transaction depends on it.
119         ///
120         /// The consumer should be able to sign for any of the additional inputs included within the
121         /// child anchor transaction. To sign its anchor input, an [`EcdsaChannelSigner`] should be
122         /// re-derived through [`AnchorDescriptor::derive_channel_signer`]. The anchor input signature
123         /// can be computed with [`EcdsaChannelSigner::sign_holder_anchor_input`], which can then be
124         /// provided to [`build_anchor_input_witness`] along with the `funding_pubkey` to obtain the
125         /// full witness required to spend.
126         ///
127         /// It is possible to receive more than one instance of this event if a valid child anchor
128         /// transaction is never broadcast or is but not with a sufficient fee to be mined. Care should
129         /// be taken by the consumer of the event to ensure any future iterations of the child anchor
130         /// transaction adhere to the [Replace-By-Fee
131         /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
132         /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
133         /// these events is not user-controlled, users may ignore/drop the event if they are no longer
134         /// able to commit external confirmed funds to the child anchor transaction.
135         ///
136         /// The set of `pending_htlcs` on the commitment transaction to be broadcast can be inspected to
137         /// determine whether a significant portion of the channel's funds are allocated to HTLCs,
138         /// enabling users to make their own decisions regarding the importance of the commitment
139         /// transaction's confirmation. Note that this is not required, but simply exists as an option
140         /// for users to override LDK's behavior. On commitments with no HTLCs (indicated by those with
141         /// an empty `pending_htlcs`), confirmation of the commitment transaction can be considered to
142         /// be not urgent.
143         ///
144         /// [`EcdsaChannelSigner`]: crate::sign::EcdsaChannelSigner
145         /// [`EcdsaChannelSigner::sign_holder_anchor_input`]: crate::sign::EcdsaChannelSigner::sign_holder_anchor_input
146         /// [`build_anchor_input_witness`]: crate::ln::chan_utils::build_anchor_input_witness
147         ChannelClose {
148                 /// The unique identifier for the claim of the anchor output in the commitment transaction.
149                 ///
150                 /// The identifier must map to the set of external UTXOs assigned to the claim, such that
151                 /// they can be reused when a new claim with the same identifier needs to be made, resulting
152                 /// in a fee-bumping attempt.
153                 claim_id: ClaimId,
154                 /// The target feerate that the transaction package, which consists of the commitment
155                 /// transaction and the to-be-crafted child anchor transaction, must meet.
156                 package_target_feerate_sat_per_1000_weight: u32,
157                 /// The channel's commitment transaction to bump the fee of. This transaction should be
158                 /// broadcast along with the anchor transaction constructed as a result of consuming this
159                 /// event.
160                 commitment_tx: Transaction,
161                 /// The absolute fee in satoshis of the commitment transaction. This can be used along the
162                 /// with weight of the commitment transaction to determine its feerate.
163                 commitment_tx_fee_satoshis: u64,
164                 /// The descriptor to sign the anchor input of the anchor transaction constructed as a
165                 /// result of consuming this event.
166                 anchor_descriptor: AnchorDescriptor,
167                 /// The set of pending HTLCs on the commitment transaction that need to be resolved once the
168                 /// commitment transaction confirms.
169                 pending_htlcs: Vec<HTLCOutputInCommitment>,
170         },
171         /// Indicates that a channel featuring anchor outputs has unilaterally closed on-chain by a
172         /// holder commitment transaction and its HTLC(s) need to be resolved on-chain. With the
173         /// zero-HTLC-transaction-fee variant of anchor outputs, the pre-signed HTLC
174         /// transactions have a zero fee, thus requiring additional inputs and/or outputs to be attached
175         /// for a timely confirmation within the chain. These additional inputs and/or outputs must be
176         /// appended to the resulting HTLC transaction to meet the target feerate. Failure to meet the
177         /// target feerate decreases the confirmation odds of the transaction, possibly resulting in a
178         /// loss of funds. Once the transaction meets the target feerate, it must be signed for and
179         /// broadcast by the consumer of the event.
180         ///
181         /// The consumer should be able to sign for any of the non-HTLC inputs added to the resulting
182         /// HTLC transaction. To sign HTLC inputs, an [`EcdsaChannelSigner`] should be re-derived
183         /// through [`HTLCDescriptor::derive_channel_signer`]. Each HTLC input's signature can be
184         /// computed with [`EcdsaChannelSigner::sign_holder_htlc_transaction`], which can then be
185         /// provided to [`HTLCDescriptor::tx_input_witness`] to obtain the fully signed witness required
186         /// to spend.
187         ///
188         /// It is possible to receive more than one instance of this event if a valid HTLC transaction
189         /// is never broadcast or is but not with a sufficient fee to be mined. Care should be taken by
190         /// the consumer of the event to ensure any future iterations of the HTLC transaction adhere to
191         /// the [Replace-By-Fee
192         /// rules](https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md)
193         /// for fee bumps to be accepted into the mempool, and eventually the chain. As the frequency of
194         /// these events is not user-controlled, users may ignore/drop the event if either they are no
195         /// longer able to commit external confirmed funds to the HTLC transaction or the fee committed
196         /// to the HTLC transaction is greater in value than the HTLCs being claimed.
197         ///
198         /// [`EcdsaChannelSigner`]: crate::sign::EcdsaChannelSigner
199         /// [`EcdsaChannelSigner::sign_holder_htlc_transaction`]: crate::sign::EcdsaChannelSigner::sign_holder_htlc_transaction
200         HTLCResolution {
201                 /// The unique identifier for the claim of the HTLCs in the confirmed commitment
202                 /// transaction.
203                 ///
204                 /// The identifier must map to the set of external UTXOs assigned to the claim, such that
205                 /// they can be reused when a new claim with the same identifier needs to be made, resulting
206                 /// in a fee-bumping attempt.
207                 claim_id: ClaimId,
208                 /// The target feerate that the resulting HTLC transaction must meet.
209                 target_feerate_sat_per_1000_weight: u32,
210                 /// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
211                 /// by the same transaction.
212                 htlc_descriptors: Vec<HTLCDescriptor>,
213                 /// The locktime required for the resulting HTLC transaction.
214                 tx_lock_time: PackedLockTime,
215         },
216 }
217
218 /// An input that must be included in a transaction when performing coin selection through
219 /// [`CoinSelectionSource::select_confirmed_utxos`]. It is guaranteed to be a SegWit input, so it
220 /// must have an empty [`TxIn::script_sig`] when spent.
221 #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
222 pub struct Input {
223         /// The unique identifier of the input.
224         pub outpoint: OutPoint,
225         /// The UTXO being spent by the input.
226         pub previous_utxo: TxOut,
227         /// The upper-bound weight consumed by the input's full [`TxIn::script_sig`] and
228         /// [`TxIn::witness`], each with their lengths included, required to satisfy the output's
229         /// script.
230         pub satisfaction_weight: u64,
231 }
232
233 /// An unspent transaction output that is available to spend resulting from a successful
234 /// [`CoinSelection`] attempt.
235 #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
236 pub struct Utxo {
237         /// The unique identifier of the output.
238         pub outpoint: OutPoint,
239         /// The output to spend.
240         pub output: TxOut,
241         /// The upper-bound weight consumed by the input's full [`TxIn::script_sig`] and [`TxIn::witness`], each
242         /// with their lengths included, required to satisfy the output's script. The weight consumed by
243         /// the input's `script_sig` must account for [`WITNESS_SCALE_FACTOR`].
244         pub satisfaction_weight: u64,
245 }
246
247 impl Utxo {
248         /// Returns a `Utxo` with the `satisfaction_weight` estimate for a legacy P2PKH output.
249         pub fn new_p2pkh(outpoint: OutPoint, value: u64, pubkey_hash: &PubkeyHash) -> Self {
250                 let script_sig_size = 1 /* script_sig length */ +
251                         1 /* OP_PUSH73 */ +
252                         73 /* sig including sighash flag */ +
253                         1 /* OP_PUSH33 */ +
254                         33 /* pubkey */;
255                 Self {
256                         outpoint,
257                         output: TxOut {
258                                 value,
259                                 script_pubkey: Script::new_p2pkh(pubkey_hash),
260                         },
261                         satisfaction_weight: script_sig_size * WITNESS_SCALE_FACTOR as u64 + 1 /* empty witness */,
262                 }
263         }
264
265         /// Returns a `Utxo` with the `satisfaction_weight` estimate for a P2WPKH nested in P2SH output.
266         pub fn new_nested_p2wpkh(outpoint: OutPoint, value: u64, pubkey_hash: &WPubkeyHash) -> Self {
267                 let script_sig_size = 1 /* script_sig length */ +
268                         1 /* OP_0 */ +
269                         1 /* OP_PUSH20 */ +
270                         20 /* pubkey_hash */;
271                 Self {
272                         outpoint,
273                         output: TxOut {
274                                 value,
275                                 script_pubkey: Script::new_p2sh(&Script::new_v0_p2wpkh(pubkey_hash).script_hash()),
276                         },
277                         satisfaction_weight: script_sig_size * WITNESS_SCALE_FACTOR as u64 + P2WPKH_WITNESS_WEIGHT,
278                 }
279         }
280
281         /// Returns a `Utxo` with the `satisfaction_weight` estimate for a SegWit v0 P2WPKH output.
282         pub fn new_v0_p2wpkh(outpoint: OutPoint, value: u64, pubkey_hash: &WPubkeyHash) -> Self {
283                 Self {
284                         outpoint,
285                         output: TxOut {
286                                 value,
287                                 script_pubkey: Script::new_v0_p2wpkh(pubkey_hash),
288                         },
289                         satisfaction_weight: EMPTY_SCRIPT_SIG_WEIGHT + P2WPKH_WITNESS_WEIGHT,
290                 }
291         }
292 }
293
294 /// The result of a successful coin selection attempt for a transaction requiring additional UTXOs
295 /// to cover its fees.
296 #[derive(Clone, Debug)]
297 pub struct CoinSelection {
298         /// The set of UTXOs (with at least 1 confirmation) to spend and use within a transaction
299         /// requiring additional fees.
300         pub confirmed_utxos: Vec<Utxo>,
301         /// An additional output tracking whether any change remained after coin selection. This output
302         /// should always have a value above dust for its given `script_pubkey`. It should not be
303         /// spent until the transaction it belongs to confirms to ensure mempool descendant limits are
304         /// not met. This implies no other party should be able to spend it except us.
305         pub change_output: Option<TxOut>,
306 }
307
308 /// An abstraction over a bitcoin wallet that can perform coin selection over a set of UTXOs and can
309 /// sign for them. The coin selection method aims to mimic Bitcoin Core's `fundrawtransaction` RPC,
310 /// which most wallets should be able to satisfy. Otherwise, consider implementing [`WalletSource`],
311 /// which can provide a default implementation of this trait when used with [`Wallet`].
312 pub trait CoinSelectionSource {
313         /// Performs coin selection of a set of UTXOs, with at least 1 confirmation each, that are
314         /// available to spend. Implementations are free to pick their coin selection algorithm of
315         /// choice, as long as the following requirements are met:
316         ///
317         /// 1. `must_spend` contains a set of [`Input`]s that must be included in the transaction
318         ///    throughout coin selection, but must not be returned as part of the result.
319         /// 2. `must_pay_to` contains a set of [`TxOut`]s that must be included in the transaction
320         ///    throughout coin selection. In some cases, like when funding an anchor transaction, this
321         ///    set is empty. Implementations should ensure they handle this correctly on their end,
322         ///    e.g., Bitcoin Core's `fundrawtransaction` RPC requires at least one output to be
323         ///    provided, in which case a zero-value empty OP_RETURN output can be used instead.
324         /// 3. Enough inputs must be selected/contributed for the resulting transaction (including the
325         ///    inputs and outputs noted above) to meet `target_feerate_sat_per_1000_weight`.
326         ///
327         /// Implementations must take note that [`Input::satisfaction_weight`] only tracks the weight of
328         /// the input's `script_sig` and `witness`. Some wallets, like Bitcoin Core's, may require
329         /// providing the full input weight. Failing to do so may lead to underestimating fee bumps and
330         /// delaying block inclusion.
331         ///
332         /// The `claim_id` must map to the set of external UTXOs assigned to the claim, such that they
333         /// can be re-used within new fee-bumped iterations of the original claiming transaction,
334         /// ensuring that claims don't double spend each other. If a specific `claim_id` has never had a
335         /// transaction associated with it, and all of the available UTXOs have already been assigned to
336         /// other claims, implementations must be willing to double spend their UTXOs. The choice of
337         /// which UTXOs to double spend is left to the implementation, but it must strive to keep the
338         /// set of other claims being double spent to a minimum.
339         fn select_confirmed_utxos(
340                 &self, claim_id: ClaimId, must_spend: Vec<Input>, must_pay_to: &[TxOut],
341                 target_feerate_sat_per_1000_weight: u32,
342         ) -> Result<CoinSelection, ()>;
343         /// Signs and provides the full witness for all inputs within the transaction known to the
344         /// trait (i.e., any provided via [`CoinSelectionSource::select_confirmed_utxos`]).
345         fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()>;
346 }
347
348 /// An alternative to [`CoinSelectionSource`] that can be implemented and used along [`Wallet`] to
349 /// provide a default implementation to [`CoinSelectionSource`].
350 pub trait WalletSource {
351         /// Returns all UTXOs, with at least 1 confirmation each, that are available to spend.
352         fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()>;
353         /// Returns a script to use for change above dust resulting from a successful coin selection
354         /// attempt.
355         fn get_change_script(&self) -> Result<Script, ()>;
356         /// Signs and provides the full [`TxIn::script_sig`] and [`TxIn::witness`] for all inputs within
357         /// the transaction known to the wallet (i.e., any provided via
358         /// [`WalletSource::list_confirmed_utxos`]).
359         fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()>;
360 }
361
362 /// A wrapper over [`WalletSource`] that implements [`CoinSelection`] by preferring UTXOs that would
363 /// avoid conflicting double spends. If not enough UTXOs are available to do so, conflicting double
364 /// spends may happen.
365 pub struct Wallet<W: Deref, L: Deref>
366 where
367         W::Target: WalletSource,
368         L::Target: Logger
369 {
370         source: W,
371         logger: L,
372         // TODO: Do we care about cleaning this up once the UTXOs have a confirmed spend? We can do so
373         // by checking whether any UTXOs that exist in the map are no longer returned in
374         // `list_confirmed_utxos`.
375         locked_utxos: Mutex<HashMap<OutPoint, ClaimId>>,
376 }
377
378 impl<W: Deref, L: Deref> Wallet<W, L>
379 where
380         W::Target: WalletSource,
381         L::Target: Logger
382 {
383         /// Returns a new instance backed by the given [`WalletSource`] that serves as an implementation
384         /// of [`CoinSelectionSource`].
385         pub fn new(source: W, logger: L) -> Self {
386                 Self { source, logger, locked_utxos: Mutex::new(HashMap::new()) }
387         }
388
389         /// Performs coin selection on the set of UTXOs obtained from
390         /// [`WalletSource::list_confirmed_utxos`]. Its algorithm can be described as "smallest
391         /// above-dust-after-spend first", with a slight twist: we may skip UTXOs that are above dust at
392         /// the target feerate after having spent them in a separate claim transaction if
393         /// `force_conflicting_utxo_spend` is unset to avoid producing conflicting transactions. If
394         /// `tolerate_high_network_feerates` is set, we'll attempt to spend UTXOs that contribute at
395         /// least 1 satoshi at the current feerate, otherwise, we'll only attempt to spend those which
396         /// contribute at least twice their fee.
397         fn select_confirmed_utxos_internal(
398                 &self, utxos: &[Utxo], claim_id: ClaimId, force_conflicting_utxo_spend: bool,
399                 tolerate_high_network_feerates: bool, target_feerate_sat_per_1000_weight: u32,
400                 preexisting_tx_weight: u64, input_amount_sat: u64, target_amount_sat: u64,
401         ) -> Result<CoinSelection, ()> {
402                 let mut locked_utxos = self.locked_utxos.lock().unwrap();
403                 let mut eligible_utxos = utxos.iter().filter_map(|utxo| {
404                         if let Some(utxo_claim_id) = locked_utxos.get(&utxo.outpoint) {
405                                 if *utxo_claim_id != claim_id && !force_conflicting_utxo_spend {
406                                         log_trace!(self.logger, "Skipping UTXO {} to prevent conflicting spend", utxo.outpoint);
407                                         return None;
408                                 }
409                         }
410                         let fee_to_spend_utxo = fee_for_weight(
411                                 target_feerate_sat_per_1000_weight, BASE_INPUT_WEIGHT as u64 + utxo.satisfaction_weight,
412                         );
413                         let should_spend = if tolerate_high_network_feerates {
414                                 utxo.output.value > fee_to_spend_utxo
415                         } else {
416                                 utxo.output.value >= fee_to_spend_utxo * 2
417                         };
418                         if should_spend {
419                                 Some((utxo, fee_to_spend_utxo))
420                         } else {
421                                 log_trace!(self.logger, "Skipping UTXO {} due to dust proximity after spend", utxo.outpoint);
422                                 None
423                         }
424                 }).collect::<Vec<_>>();
425                 eligible_utxos.sort_unstable_by_key(|(utxo, _)| utxo.output.value);
426
427                 let mut selected_amount = input_amount_sat;
428                 let mut total_fees = fee_for_weight(target_feerate_sat_per_1000_weight, preexisting_tx_weight);
429                 let mut selected_utxos = Vec::new();
430                 for (utxo, fee_to_spend_utxo) in eligible_utxos {
431                         if selected_amount >= target_amount_sat + total_fees {
432                                 break;
433                         }
434                         selected_amount += utxo.output.value;
435                         total_fees += fee_to_spend_utxo;
436                         selected_utxos.push(utxo.clone());
437                 }
438                 if selected_amount < target_amount_sat + total_fees {
439                         log_debug!(self.logger, "Insufficient funds to meet target feerate {} sat/kW",
440                                 target_feerate_sat_per_1000_weight);
441                         return Err(());
442                 }
443                 for utxo in &selected_utxos {
444                         locked_utxos.insert(utxo.outpoint, claim_id);
445                 }
446                 core::mem::drop(locked_utxos);
447
448                 let remaining_amount = selected_amount - target_amount_sat - total_fees;
449                 let change_script = self.source.get_change_script()?;
450                 let change_output_fee = fee_for_weight(
451                         target_feerate_sat_per_1000_weight,
452                         (8 /* value */ + change_script.consensus_encode(&mut sink()).unwrap() as u64) *
453                                 WITNESS_SCALE_FACTOR as u64,
454                 );
455                 let change_output_amount = remaining_amount.saturating_sub(change_output_fee);
456                 let change_output = if change_output_amount < change_script.dust_value().to_sat() {
457                         log_debug!(self.logger, "Coin selection attempt did not yield change output");
458                         None
459                 } else {
460                         Some(TxOut { script_pubkey: change_script, value: change_output_amount })
461                 };
462
463                 Ok(CoinSelection {
464                         confirmed_utxos: selected_utxos,
465                         change_output,
466                 })
467         }
468 }
469
470 impl<W: Deref, L: Deref> CoinSelectionSource for Wallet<W, L>
471 where
472         W::Target: WalletSource,
473         L::Target: Logger
474 {
475         fn select_confirmed_utxos(
476                 &self, claim_id: ClaimId, must_spend: Vec<Input>, must_pay_to: &[TxOut],
477                 target_feerate_sat_per_1000_weight: u32,
478         ) -> Result<CoinSelection, ()> {
479                 let utxos = self.source.list_confirmed_utxos()?;
480                 // TODO: Use fee estimation utils when we upgrade to bitcoin v0.30.0.
481                 const BASE_TX_SIZE: u64 = 4 /* version */ + 1 /* input count */ + 1 /* output count */ + 4 /* locktime */;
482                 let total_output_size: u64 = must_pay_to.iter().map(|output|
483                         8 /* value */ + 1 /* script len */ + output.script_pubkey.len() as u64
484                 ).sum();
485                 let total_satisfaction_weight: u64 = must_spend.iter().map(|input| input.satisfaction_weight).sum();
486                 let total_input_weight = (BASE_INPUT_WEIGHT * must_spend.len() as u64) + total_satisfaction_weight;
487
488                 let preexisting_tx_weight = 2 /* segwit marker & flag */ + total_input_weight +
489                         ((BASE_TX_SIZE + total_output_size) * WITNESS_SCALE_FACTOR as u64);
490                 let input_amount_sat: u64 = must_spend.iter().map(|input| input.previous_utxo.value).sum();
491                 let target_amount_sat = must_pay_to.iter().map(|output| output.value).sum();
492                 let do_coin_selection = |force_conflicting_utxo_spend: bool, tolerate_high_network_feerates: bool| {
493                         log_debug!(self.logger, "Attempting coin selection targeting {} sat/kW (force_conflicting_utxo_spend = {}, tolerate_high_network_feerates = {})",
494                                 target_feerate_sat_per_1000_weight, force_conflicting_utxo_spend, tolerate_high_network_feerates);
495                         self.select_confirmed_utxos_internal(
496                                 &utxos, claim_id, force_conflicting_utxo_spend, tolerate_high_network_feerates,
497                                 target_feerate_sat_per_1000_weight, preexisting_tx_weight, input_amount_sat, target_amount_sat,
498                         )
499                 };
500                 do_coin_selection(false, false)
501                         .or_else(|_| do_coin_selection(false, true))
502                         .or_else(|_| do_coin_selection(true, false))
503                         .or_else(|_| do_coin_selection(true, true))
504         }
505
506         fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
507                 self.source.sign_tx(tx)
508         }
509 }
510
511 /// A handler for [`Event::BumpTransaction`] events that sources confirmed UTXOs from a
512 /// [`CoinSelectionSource`] to fee bump transactions via Child-Pays-For-Parent (CPFP) or
513 /// Replace-By-Fee (RBF).
514 ///
515 /// [`Event::BumpTransaction`]: crate::events::Event::BumpTransaction
516 pub struct BumpTransactionEventHandler<B: Deref, C: Deref, SP: Deref, L: Deref>
517 where
518         B::Target: BroadcasterInterface,
519         C::Target: CoinSelectionSource,
520         SP::Target: SignerProvider,
521         L::Target: Logger,
522 {
523         broadcaster: B,
524         utxo_source: C,
525         signer_provider: SP,
526         logger: L,
527         secp: Secp256k1<secp256k1::All>,
528 }
529
530 impl<B: Deref, C: Deref, SP: Deref, L: Deref> BumpTransactionEventHandler<B, C, SP, L>
531 where
532         B::Target: BroadcasterInterface,
533         C::Target: CoinSelectionSource,
534         SP::Target: SignerProvider,
535         L::Target: Logger,
536 {
537         /// Returns a new instance capable of handling [`Event::BumpTransaction`] events.
538         ///
539         /// [`Event::BumpTransaction`]: crate::events::Event::BumpTransaction
540         pub fn new(broadcaster: B, utxo_source: C, signer_provider: SP, logger: L) -> Self {
541                 Self {
542                         broadcaster,
543                         utxo_source,
544                         signer_provider,
545                         logger,
546                         secp: Secp256k1::new(),
547                 }
548         }
549
550         /// Updates a transaction with the result of a successful coin selection attempt.
551         fn process_coin_selection(&self, tx: &mut Transaction, mut coin_selection: CoinSelection) {
552                 for utxo in coin_selection.confirmed_utxos.drain(..) {
553                         tx.input.push(TxIn {
554                                 previous_output: utxo.outpoint,
555                                 script_sig: Script::new(),
556                                 sequence: Sequence::ZERO,
557                                 witness: Witness::new(),
558                         });
559                 }
560                 if let Some(change_output) = coin_selection.change_output.take() {
561                         tx.output.push(change_output);
562                 } else if tx.output.is_empty() {
563                         // We weren't provided a change output, likely because the input set was a perfect
564                         // match, but we still need to have at least one output in the transaction for it to be
565                         // considered standard. We choose to go with an empty OP_RETURN as it is the cheapest
566                         // way to include a dummy output.
567                         log_debug!(self.logger, "Including dummy OP_RETURN output since an output is needed and a change output was not provided");
568                         tx.output.push(TxOut {
569                                 value: 0,
570                                 script_pubkey: Script::new_op_return(&[]),
571                         });
572                 }
573         }
574
575         /// Handles a [`BumpTransactionEvent::ChannelClose`] event variant by producing a fully-signed
576         /// transaction spending an anchor output of the commitment transaction to bump its fee and
577         /// broadcasts them to the network as a package.
578         fn handle_channel_close(
579                 &self, claim_id: ClaimId, package_target_feerate_sat_per_1000_weight: u32,
580                 commitment_tx: &Transaction, commitment_tx_fee_sat: u64, anchor_descriptor: &AnchorDescriptor,
581         ) -> Result<(), ()> {
582                 // Our commitment transaction already has fees allocated to it, so we should take them into
583                 // account. We do so by pretending the commitment tranasction's fee and weight are part of
584                 // the anchor input.
585                 let mut anchor_utxo = anchor_descriptor.previous_utxo();
586                 anchor_utxo.value += commitment_tx_fee_sat;
587                 let must_spend = vec![Input {
588                         outpoint: anchor_descriptor.outpoint,
589                         previous_utxo: anchor_utxo,
590                         satisfaction_weight: commitment_tx.weight() as u64 + ANCHOR_INPUT_WITNESS_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT,
591                 }];
592                 #[cfg(debug_assertions)]
593                 let must_spend_amount = must_spend.iter().map(|input| input.previous_utxo.value).sum::<u64>();
594
595                 log_debug!(self.logger, "Peforming coin selection for commitment package (commitment and anchor transaction) targeting {} sat/kW",
596                         package_target_feerate_sat_per_1000_weight);
597                 let coin_selection = self.utxo_source.select_confirmed_utxos(
598                         claim_id, must_spend, &[], package_target_feerate_sat_per_1000_weight,
599                 )?;
600
601                 let mut anchor_tx = Transaction {
602                         version: 2,
603                         lock_time: PackedLockTime::ZERO, // TODO: Use next best height.
604                         input: vec![anchor_descriptor.unsigned_tx_input()],
605                         output: vec![],
606                 };
607
608                 #[cfg(debug_assertions)]
609                 let total_satisfaction_weight = ANCHOR_INPUT_WITNESS_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT +
610                         coin_selection.confirmed_utxos.iter().map(|utxo| utxo.satisfaction_weight).sum::<u64>();
611                 #[cfg(debug_assertions)]
612                 let total_input_amount = must_spend_amount +
613                         coin_selection.confirmed_utxos.iter().map(|utxo| utxo.output.value).sum::<u64>();
614
615                 self.process_coin_selection(&mut anchor_tx, coin_selection);
616                 let anchor_txid = anchor_tx.txid();
617
618                 debug_assert_eq!(anchor_tx.output.len(), 1);
619                 #[cfg(debug_assertions)]
620                 let unsigned_tx_weight = anchor_tx.weight() as u64 - (anchor_tx.input.len() as u64 * EMPTY_SCRIPT_SIG_WEIGHT);
621
622                 log_debug!(self.logger, "Signing anchor transaction {}", anchor_txid);
623                 anchor_tx = self.utxo_source.sign_tx(anchor_tx)?;
624
625                 let signer = anchor_descriptor.derive_channel_signer(&self.signer_provider);
626                 let anchor_sig = signer.sign_holder_anchor_input(&anchor_tx, 0, &self.secp)?;
627                 anchor_tx.input[0].witness = anchor_descriptor.tx_input_witness(&anchor_sig);
628
629                 #[cfg(debug_assertions)] {
630                         let signed_tx_weight = anchor_tx.weight() as u64;
631                         let expected_signed_tx_weight = unsigned_tx_weight + total_satisfaction_weight;
632                         // Our estimate should be within a 1% error margin of the actual weight and we should
633                         // never underestimate.
634                         assert!(expected_signed_tx_weight >= signed_tx_weight &&
635                                 expected_signed_tx_weight - (expected_signed_tx_weight / 100) <= signed_tx_weight);
636
637                         let expected_package_fee = fee_for_weight(package_target_feerate_sat_per_1000_weight,
638                                 signed_tx_weight + commitment_tx.weight() as u64);
639                         let package_fee = total_input_amount -
640                                 anchor_tx.output.iter().map(|output| output.value).sum::<u64>();
641                         // Our fee should be within a 5% error margin of the expected fee based on the
642                         // feerate and transaction weight and we should never pay less than required.
643                         let fee_error_margin = expected_package_fee * 5 / 100;
644                         assert!(package_fee >= expected_package_fee &&
645                                 package_fee - fee_error_margin <= expected_package_fee);
646                 }
647
648                 log_info!(self.logger, "Broadcasting anchor transaction {} to bump channel close with txid {}",
649                         anchor_txid, commitment_tx.txid());
650                 self.broadcaster.broadcast_transactions(&[&commitment_tx, &anchor_tx]);
651                 Ok(())
652         }
653
654         /// Handles a [`BumpTransactionEvent::HTLCResolution`] event variant by producing a
655         /// fully-signed, fee-bumped HTLC transaction that is broadcast to the network.
656         fn handle_htlc_resolution(
657                 &self, claim_id: ClaimId, target_feerate_sat_per_1000_weight: u32,
658                 htlc_descriptors: &[HTLCDescriptor], tx_lock_time: PackedLockTime,
659         ) -> Result<(), ()> {
660                 let mut htlc_tx = Transaction {
661                         version: 2,
662                         lock_time: tx_lock_time,
663                         input: vec![],
664                         output: vec![],
665                 };
666                 let mut must_spend = Vec::with_capacity(htlc_descriptors.len());
667                 for htlc_descriptor in htlc_descriptors {
668                         let htlc_input = htlc_descriptor.unsigned_tx_input();
669                         must_spend.push(Input {
670                                 outpoint: htlc_input.previous_output.clone(),
671                                 previous_utxo: htlc_descriptor.previous_utxo(&self.secp),
672                                 satisfaction_weight: EMPTY_SCRIPT_SIG_WEIGHT + if htlc_descriptor.preimage.is_some() {
673                                         HTLC_SUCCESS_INPUT_ANCHOR_WITNESS_WEIGHT
674                                 } else {
675                                         HTLC_TIMEOUT_INPUT_ANCHOR_WITNESS_WEIGHT
676                                 },
677                         });
678                         htlc_tx.input.push(htlc_input);
679                         let htlc_output = htlc_descriptor.tx_output(&self.secp);
680                         htlc_tx.output.push(htlc_output);
681                 }
682
683                 log_debug!(self.logger, "Peforming coin selection for HTLC transaction targeting {} sat/kW",
684                         target_feerate_sat_per_1000_weight);
685
686                 #[cfg(debug_assertions)]
687                 let must_spend_satisfaction_weight =
688                         must_spend.iter().map(|input| input.satisfaction_weight).sum::<u64>();
689                 #[cfg(debug_assertions)]
690                 let must_spend_amount = must_spend.iter().map(|input| input.previous_utxo.value).sum::<u64>();
691
692                 let coin_selection = self.utxo_source.select_confirmed_utxos(
693                         claim_id, must_spend, &htlc_tx.output, target_feerate_sat_per_1000_weight,
694                 )?;
695
696                 #[cfg(debug_assertions)]
697                 let total_satisfaction_weight = must_spend_satisfaction_weight +
698                         coin_selection.confirmed_utxos.iter().map(|utxo| utxo.satisfaction_weight).sum::<u64>();
699                 #[cfg(debug_assertions)]
700                 let total_input_amount = must_spend_amount +
701                         coin_selection.confirmed_utxos.iter().map(|utxo| utxo.output.value).sum::<u64>();
702
703                 self.process_coin_selection(&mut htlc_tx, coin_selection);
704
705                 #[cfg(debug_assertions)]
706                 let unsigned_tx_weight = htlc_tx.weight() as u64 - (htlc_tx.input.len() as u64 * EMPTY_SCRIPT_SIG_WEIGHT);
707
708                 log_debug!(self.logger, "Signing HTLC transaction {}", htlc_tx.txid());
709                 htlc_tx = self.utxo_source.sign_tx(htlc_tx)?;
710
711                 let mut signers = BTreeMap::new();
712                 for (idx, htlc_descriptor) in htlc_descriptors.iter().enumerate() {
713                         let signer = signers.entry(htlc_descriptor.channel_derivation_parameters.keys_id)
714                                 .or_insert_with(|| htlc_descriptor.derive_channel_signer(&self.signer_provider));
715                         let htlc_sig = signer.sign_holder_htlc_transaction(&htlc_tx, idx, htlc_descriptor, &self.secp)?;
716                         let witness_script = htlc_descriptor.witness_script(&self.secp);
717                         htlc_tx.input[idx].witness = htlc_descriptor.tx_input_witness(&htlc_sig, &witness_script);
718                 }
719
720                 #[cfg(debug_assertions)] {
721                         let signed_tx_weight = htlc_tx.weight() as u64;
722                         let expected_signed_tx_weight = unsigned_tx_weight + total_satisfaction_weight;
723                         // Our estimate should be within a 1% error margin of the actual weight and we should
724                         // never underestimate.
725                         assert!(expected_signed_tx_weight >= signed_tx_weight &&
726                                 expected_signed_tx_weight - (expected_signed_tx_weight / 100) <= signed_tx_weight);
727
728                         let expected_signed_tx_fee = fee_for_weight(target_feerate_sat_per_1000_weight, signed_tx_weight);
729                         let signed_tx_fee = total_input_amount -
730                                 htlc_tx.output.iter().map(|output| output.value).sum::<u64>();
731                         // Our fee should be within a 5% error margin of the expected fee based on the
732                         // feerate and transaction weight and we should never pay less than required.
733                         let fee_error_margin = expected_signed_tx_fee * 5 / 100;
734                         assert!(signed_tx_fee >= expected_signed_tx_fee &&
735                                 signed_tx_fee - fee_error_margin <= expected_signed_tx_fee);
736                 }
737
738                 log_info!(self.logger, "Broadcasting {}", log_tx!(htlc_tx));
739                 self.broadcaster.broadcast_transactions(&[&htlc_tx]);
740                 Ok(())
741         }
742
743         /// Handles all variants of [`BumpTransactionEvent`].
744         pub fn handle_event(&self, event: &BumpTransactionEvent) {
745                 match event {
746                         BumpTransactionEvent::ChannelClose {
747                                 claim_id, package_target_feerate_sat_per_1000_weight, commitment_tx,
748                                 commitment_tx_fee_satoshis, anchor_descriptor, ..
749                         } => {
750                                 log_info!(self.logger, "Handling channel close bump (claim_id = {}, commitment_txid = {})",
751                                         log_bytes!(claim_id.0), commitment_tx.txid());
752                                 if let Err(_) = self.handle_channel_close(
753                                         *claim_id, *package_target_feerate_sat_per_1000_weight, commitment_tx,
754                                         *commitment_tx_fee_satoshis, anchor_descriptor,
755                                 ) {
756                                         log_error!(self.logger, "Failed bumping commitment transaction fee for {}",
757                                                 commitment_tx.txid());
758                                 }
759                         }
760                         BumpTransactionEvent::HTLCResolution {
761                                 claim_id, target_feerate_sat_per_1000_weight, htlc_descriptors, tx_lock_time,
762                         } => {
763                                 log_info!(self.logger, "Handling HTLC bump (claim_id = {}, htlcs_to_claim = {})",
764                                         log_bytes!(claim_id.0), log_iter!(htlc_descriptors.iter().map(|d| d.outpoint())));
765                                 if let Err(_) = self.handle_htlc_resolution(
766                                         *claim_id, *target_feerate_sat_per_1000_weight, htlc_descriptors, *tx_lock_time,
767                                 ) {
768                                         log_error!(self.logger, "Failed bumping HTLC transaction fee for commitment {}",
769                                                 htlc_descriptors[0].commitment_txid);
770                                 }
771                         }
772                 }
773         }
774 }