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