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