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