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