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