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