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