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