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