Skip to content

Commit ee0ff68

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 8973cbd commit ee0ff68

File tree

1 file changed

+138
-1
lines changed

1 file changed

+138
-1
lines changed

lightning/src/events/bump_transaction.rs

+138-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, Sequence, Script, Transaction, Txid, TxIn, TxOut, Witness};
@@ -303,7 +304,8 @@ pub struct CoinSelection {
303304

304305
/// An abstraction over a bitcoin wallet that can perform coin selection over a set of UTXOs and can
305306
/// sign for them. The coin selection method aims to mimic Bitcoin Core's `fundrawtransaction` RPC,
306-
/// which most wallets should be able to satisfy.
307+
/// which most wallets should be able to satisfy. Otherwise, consider implementing [`WalletSource`],
308+
/// which can provide a default implementation of this trait when used with [`Wallet`].
307309
pub trait CoinSelectionSource {
308310
/// Performs coin selection of a set of UTXOs, with at least 1 confirmation each, that are
309311
/// available to spend. Implementations are free to pick their coin selection algorithm of
@@ -339,6 +341,141 @@ pub trait CoinSelectionSource {
339341
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()>;
340342
}
341343

344+
/// An alternative to [`CoinSelectionSource`] that can be implemented and used along [`Wallet`] to
345+
/// provide a default implementation to [`CoinSelectionSource`].
346+
pub trait WalletSource {
347+
/// Returns all UTXOs, with at least 1 confirmation each, that are available to spend.
348+
fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()>;
349+
/// Returns a script to use for change above dust resulting from a successful coin selection
350+
/// attempt.
351+
fn change_script(&self) -> Result<Script, ()>;
352+
/// Signs and provides the full witness for all inputs within the transaction known to the
353+
/// wallet (i.e., any provided via [`WalletSource::list_confirmed_utxos`]).
354+
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()>;
355+
}
356+
357+
/// A wrapper over [`WalletSource`] that implements [`CoinSelection`] by preferring UTXOs that would
358+
/// avoid conflicting double spends. If not enough UTXOs are available to do so, conflicting double
359+
/// spends may happen.
360+
pub struct Wallet<W: Deref> where W::Target: WalletSource {
361+
source: W,
362+
// TODO: Do we care about cleaning this up once the UTXOs have a confirmed spend? We can do so
363+
// by checking whether any UTXOs that exist in the map are no longer returned in
364+
// `list_confirmed_utxos`.
365+
locked_utxos: Mutex<HashMap<OutPoint, ClaimId>>,
366+
}
367+
368+
impl<W: Deref> Wallet<W> where W::Target: WalletSource {
369+
/// Returns a new instance backed by the given [`WalletSource`] that serves as an implementation
370+
/// of [`CoinSelectionSource`].
371+
pub fn new(source: W) -> Self {
372+
Self { source, locked_utxos: Mutex::new(HashMap::new()) }
373+
}
374+
375+
/// Performs coin selection on the set of UTXOs obtained from
376+
/// [`WalletSource::list_confirmed_utxos`]. Its algorithm can be described as "smallest
377+
/// above-dust-after-spend first", with a slight twist: we may skip UTXOs that are above dust
378+
/// after spending them at the target feerate if `force_conflicting_utxo_spend` is unset to
379+
/// avoid producing conflicting transactions.
380+
fn select_confirmed_utxos_internal(
381+
&self, claim_id: ClaimId, force_conflicting_utxo_spend: bool,
382+
target_feerate_sat_per_1000_weight: u32, preexisting_tx_weight: u64, target_amount: u64,
383+
) -> Result<CoinSelection, ()> {
384+
let mut utxos = self.source.list_confirmed_utxos()?;
385+
utxos.sort_unstable_by_key(|utxo| utxo.output.value);
386+
387+
let mut selected_amount = 0;
388+
let mut fee_amount = preexisting_tx_weight * target_feerate_sat_per_1000_weight as u64;
389+
let selected_utxos = {
390+
let mut locked_utxos = self.locked_utxos.lock().unwrap();
391+
let selected_utxos = utxos.into_iter().scan(
392+
(&mut selected_amount, &mut fee_amount), |(selected_amount, fee_amount), utxo| {
393+
if let Some(utxo_claim_id) = locked_utxos.get(&utxo.outpoint) {
394+
if *utxo_claim_id != claim_id && !force_conflicting_utxo_spend {
395+
return None;
396+
}
397+
}
398+
let need_more_inputs = **selected_amount < target_amount + **fee_amount;
399+
if need_more_inputs {
400+
let fee_to_spend_utxo = target_feerate_sat_per_1000_weight as u64 *
401+
((41 * WITNESS_SCALE_FACTOR) as u64 + utxo.witness_weight);
402+
let utxo_value_after_fee = utxo.output.value.saturating_sub(fee_to_spend_utxo);
403+
if utxo_value_after_fee > 0 {
404+
**selected_amount += utxo.output.value;
405+
**fee_amount += fee_to_spend_utxo;
406+
Some(utxo)
407+
} else {
408+
None
409+
}
410+
} else {
411+
None
412+
}
413+
}
414+
).collect::<Vec<_>>();
415+
let need_more_inputs = selected_amount < target_amount + fee_amount;
416+
if need_more_inputs {
417+
return Err(());
418+
}
419+
for utxo in &selected_utxos {
420+
locked_utxos.insert(utxo.outpoint, claim_id);
421+
}
422+
selected_utxos
423+
};
424+
425+
let remaining_amount = selected_amount - target_amount - fee_amount;
426+
let change_script = self.source.change_script()?;
427+
let change_output_fee = target_feerate_sat_per_1000_weight as u64
428+
* (8 + change_script.consensus_encode(&mut sink()).unwrap() as u64);
429+
let change_output_amount = remaining_amount.saturating_sub(change_output_fee);
430+
let change_output = if change_output_amount < change_script.dust_value().to_sat() {
431+
None
432+
} else {
433+
Some(TxOut { script_pubkey: change_script, value: change_output_amount })
434+
};
435+
436+
Ok(CoinSelection {
437+
confirmed_utxos: selected_utxos,
438+
change_output,
439+
})
440+
}
441+
}
442+
443+
impl<W: Deref> CoinSelectionSource for Wallet<W> where W::Target: WalletSource {
444+
fn select_confirmed_utxos(
445+
&self, claim_id: ClaimId, must_spend: Vec<Input>, must_pay_to: Vec<TxOut>,
446+
target_feerate_sat_per_1000_weight: u32,
447+
) -> Result<CoinSelection, ()> {
448+
// TODO: Use fee estimation utils when we upgrade to bitcoin v0.30.0.
449+
let base_tx_weight = 4 /* version */ + 1 /* input count */ + 1 /* output count */ + 4 /* locktime */;
450+
let total_input_weight = must_spend.len() *
451+
(32 /* txid */ + 4 /* vout */ + 4 /* sequence */ + 1 /* script sig */);
452+
let total_output_weight: usize = must_pay_to.iter().map(|output|
453+
8 /* value */ + 1 /* script len */ + output.script_pubkey.len()
454+
).sum();
455+
let total_non_witness_weight = base_tx_weight + total_input_weight + total_output_weight;
456+
let total_witness_weight: u64 = must_spend.iter().map(|input| input.witness_weight).sum();
457+
458+
let preexisting_tx_weight = 2 /* segwit marker & flag */ + total_witness_weight +
459+
(total_non_witness_weight * WITNESS_SCALE_FACTOR) as u64;
460+
let target_amount = must_pay_to.iter().map(|output| output.value).sum();
461+
let do_coin_selection = |force_conflicting_utxo_spend: bool| {
462+
self.select_confirmed_utxos_internal(
463+
claim_id, force_conflicting_utxo_spend, target_feerate_sat_per_1000_weight,
464+
preexisting_tx_weight, target_amount,
465+
)
466+
};
467+
do_coin_selection(false).or_else(|_| do_coin_selection(true))
468+
}
469+
470+
fn change_script(&self) -> Result<Script, ()> {
471+
self.source.change_script()
472+
}
473+
474+
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()> {
475+
self.source.sign_tx(tx)
476+
}
477+
}
478+
342479
/// A handler for [`Event::BumpTransaction`] events that sources confirmed UTXOs from a
343480
/// [`CoinSelectionSource`] to fee bump transactions via Child-Pays-For-Parent (CPFP) or
344481
/// Replace-By-Fee (RBF).

0 commit comments

Comments
 (0)