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