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