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