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