Skip to content

Commit bc39da6

Browse files
committed
Provide a default CoinSelectionSource implementation via a new trait
Certain users may not care how their UTXOs are selected, or their wallet may not expose enough controls to fully implement the `CoinSelectionSource` trait. As an alternative, we introduce another trait `WalletSource` they could opt to implement instead, which is much simpler as it just returns the set of confirmed UTXOs that may be used. This trait implementation is then consumed into a wrapper `Wallet` which implements the `CoinSelectionSource` trait using a "smallest above-dust-after-spend first" coin selection algorithm.
1 parent d4b6f8c commit bc39da6

File tree

1 file changed

+145
-1
lines changed

1 file changed

+145
-1
lines changed

lightning/src/events/bump_transaction.rs

+145-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ use crate::ln::chan_utils::{
2424
};
2525
use crate::events::Event;
2626
use crate::prelude::HashMap;
27+
use crate::sync::Mutex;
2728
use crate::util::logger::Logger;
2829

2930
use bitcoin::{OutPoint, PackedLockTime, PubkeyHash, Sequence, Script, Transaction, Txid, TxIn, TxOut, Witness, WPubkeyHash};
@@ -368,7 +369,8 @@ pub struct CoinSelection {
368369

369370
/// An abstraction over a bitcoin wallet that can perform coin selection over a set of UTXOs and can
370371
/// sign for them. The coin selection method aims to mimic Bitcoin Core's `fundrawtransaction` RPC,
371-
/// which most wallets should be able to satisfy.
372+
/// which most wallets should be able to satisfy. Otherwise, consider implementing [`WalletSource`],
373+
/// which can provide a default implementation of this trait when used with [`Wallet`].
372374
pub trait CoinSelectionSource {
373375
/// Performs coin selection of a set of UTXOs, with at least 1 confirmation each, that are
374376
/// available to spend. Implementations are free to pick their coin selection algorithm of
@@ -405,6 +407,148 @@ pub trait CoinSelectionSource {
405407
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()>;
406408
}
407409

410+
/// An alternative to [`CoinSelectionSource`] that can be implemented and used along [`Wallet`] to
411+
/// provide a default implementation to [`CoinSelectionSource`].
412+
pub trait WalletSource {
413+
/// Returns all UTXOs, with at least 1 confirmation each, that are available to spend.
414+
fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()>;
415+
/// Returns a script to use for change above dust resulting from a successful coin selection
416+
/// attempt.
417+
fn get_change_script(&self) -> Result<Script, ()>;
418+
/// Signs and provides the full [`TxIn::script_sig`] and [`TxIn::witness`] for all inputs within
419+
/// the transaction known to the wallet (i.e., any provided via
420+
/// [`WalletSource::list_confirmed_utxos`]).
421+
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()>;
422+
}
423+
424+
/// A wrapper over [`WalletSource`] that implements [`CoinSelection`] by preferring UTXOs that would
425+
/// avoid conflicting double spends. If not enough UTXOs are available to do so, conflicting double
426+
/// spends may happen.
427+
pub struct Wallet<W: Deref> where W::Target: WalletSource {
428+
source: W,
429+
// TODO: Do we care about cleaning this up once the UTXOs have a confirmed spend? We can do so
430+
// by checking whether any UTXOs that exist in the map are no longer returned in
431+
// `list_confirmed_utxos`.
432+
locked_utxos: Mutex<HashMap<OutPoint, ClaimId>>,
433+
}
434+
435+
impl<W: Deref> Wallet<W> where W::Target: WalletSource {
436+
/// Returns a new instance backed by the given [`WalletSource`] that serves as an implementation
437+
/// of [`CoinSelectionSource`].
438+
pub fn new(source: W) -> Self {
439+
Self { source, locked_utxos: Mutex::new(HashMap::new()) }
440+
}
441+
442+
/// Performs coin selection on the set of UTXOs obtained from
443+
/// [`WalletSource::list_confirmed_utxos`]. Its algorithm can be described as "smallest
444+
/// above-dust-after-spend first", with a slight twist: we may skip UTXOs that are above dust at
445+
/// the target feerate after having spent them in a separate claim transaction if
446+
/// `force_conflicting_utxo_spend` is unset to avoid producing conflicting transactions. If
447+
/// `tolerate_high_network_feerates` is set, we'll attempt to spend UTXOs that contribute at
448+
/// least 1 satoshi at the current feerate, otherwise, we'll only attempt to spend those which
449+
/// contribute at least twice their fee.
450+
fn select_confirmed_utxos_internal(
451+
&self, utxos: &[Utxo], claim_id: ClaimId, force_conflicting_utxo_spend: bool,
452+
tolerate_high_network_feerates: bool, target_feerate_sat_per_1000_weight: u32,
453+
preexisting_tx_weight: u64, target_amount_sat: u64,
454+
) -> Result<CoinSelection, ()> {
455+
let mut locked_utxos = self.locked_utxos.lock().unwrap();
456+
let mut eligible_utxos = utxos.iter().filter_map(|utxo| {
457+
if let Some(utxo_claim_id) = locked_utxos.get(&utxo.outpoint) {
458+
if *utxo_claim_id != claim_id && !force_conflicting_utxo_spend {
459+
return None;
460+
}
461+
}
462+
let fee_to_spend_utxo = fee_for_weight(
463+
target_feerate_sat_per_1000_weight, BASE_INPUT_WEIGHT as u64 + utxo.satisfaction_weight,
464+
);
465+
let should_spend = if tolerate_high_network_feerates {
466+
utxo.output.value > fee_to_spend_utxo
467+
} else {
468+
utxo.output.value >= fee_to_spend_utxo * 2
469+
};
470+
if should_spend {
471+
Some((utxo, fee_to_spend_utxo))
472+
} else {
473+
None
474+
}
475+
}).collect::<Vec<_>>();
476+
eligible_utxos.sort_unstable_by_key(|(utxo, _)| utxo.output.value);
477+
478+
let mut selected_amount = 0;
479+
let mut total_fees = fee_for_weight(target_feerate_sat_per_1000_weight, preexisting_tx_weight);
480+
let mut selected_utxos = Vec::new();
481+
for (utxo, fee_to_spend_utxo) in eligible_utxos {
482+
if selected_amount >= target_amount_sat + total_fees {
483+
break;
484+
}
485+
selected_amount += utxo.output.value;
486+
total_fees += fee_to_spend_utxo;
487+
selected_utxos.push(utxo.clone());
488+
}
489+
if selected_amount < target_amount_sat + total_fees {
490+
return Err(());
491+
}
492+
for utxo in &selected_utxos {
493+
locked_utxos.insert(utxo.outpoint, claim_id);
494+
}
495+
core::mem::drop(locked_utxos);
496+
497+
let remaining_amount = selected_amount - target_amount_sat - total_fees;
498+
let change_script = self.source.get_change_script()?;
499+
let change_output_fee = fee_for_weight(
500+
target_feerate_sat_per_1000_weight,
501+
(8 /* value */ + change_script.consensus_encode(&mut sink()).unwrap() as u64) *
502+
WITNESS_SCALE_FACTOR as u64,
503+
);
504+
let change_output_amount = remaining_amount.saturating_sub(change_output_fee);
505+
let change_output = if change_output_amount < change_script.dust_value().to_sat() {
506+
None
507+
} else {
508+
Some(TxOut { script_pubkey: change_script, value: change_output_amount })
509+
};
510+
511+
Ok(CoinSelection {
512+
confirmed_utxos: selected_utxos,
513+
change_output,
514+
})
515+
}
516+
}
517+
518+
impl<W: Deref> CoinSelectionSource for Wallet<W> where W::Target: WalletSource {
519+
fn select_confirmed_utxos(
520+
&self, claim_id: ClaimId, must_spend: &[Input], must_pay_to: &[TxOut],
521+
target_feerate_sat_per_1000_weight: u32,
522+
) -> Result<CoinSelection, ()> {
523+
let utxos = self.source.list_confirmed_utxos()?;
524+
// TODO: Use fee estimation utils when we upgrade to bitcoin v0.30.0.
525+
const BASE_TX_SIZE: u64 = 4 /* version */ + 1 /* input count */ + 1 /* output count */ + 4 /* locktime */;
526+
let total_output_size: u64 = must_pay_to.iter().map(|output|
527+
8 /* value */ + 1 /* script len */ + output.script_pubkey.len() as u64
528+
).sum();
529+
let total_satisfaction_weight: u64 = must_spend.iter().map(|input| input.satisfaction_weight).sum();
530+
let total_input_weight = (BASE_INPUT_WEIGHT * must_spend.len() as u64) + total_satisfaction_weight;
531+
532+
let preexisting_tx_weight = 2 /* segwit marker & flag */ + total_input_weight +
533+
((BASE_TX_SIZE + total_output_size) * WITNESS_SCALE_FACTOR as u64);
534+
let target_amount_sat = must_pay_to.iter().map(|output| output.value).sum();
535+
let do_coin_selection = |force_conflicting_utxo_spend: bool, tolerate_high_network_feerates: bool| {
536+
self.select_confirmed_utxos_internal(
537+
&utxos, claim_id, force_conflicting_utxo_spend, tolerate_high_network_feerates,
538+
target_feerate_sat_per_1000_weight, preexisting_tx_weight, target_amount_sat,
539+
)
540+
};
541+
do_coin_selection(false, false)
542+
.or_else(|_| do_coin_selection(false, true))
543+
.or_else(|_| do_coin_selection(true, false))
544+
.or_else(|_| do_coin_selection(true, true))
545+
}
546+
547+
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()> {
548+
self.source.sign_tx(tx)
549+
}
550+
}
551+
408552
/// A handler for [`Event::BumpTransaction`] events that sources confirmed UTXOs from a
409553
/// [`CoinSelectionSource`] to fee bump transactions via Child-Pays-For-Parent (CPFP) or
410554
/// Replace-By-Fee (RBF).

0 commit comments

Comments
 (0)