@@ -24,6 +24,7 @@ use crate::ln::chan_utils::{
24
24
} ;
25
25
use crate :: events:: Event ;
26
26
use crate :: prelude:: HashMap ;
27
+ use crate :: sync:: Mutex ;
27
28
use crate :: util:: logger:: Logger ;
28
29
29
30
use bitcoin:: { OutPoint , PackedLockTime , Sequence , Script , Transaction , Txid , TxIn , TxOut , Witness } ;
@@ -348,7 +349,8 @@ pub struct CoinSelection {
348
349
349
350
/// An abstraction over a bitcoin wallet that can perform coin selection over a set of UTXOs and can
350
351
/// sign for them. The coin selection method aims to mimic Bitcoin Core's `fundrawtransaction` RPC,
351
- /// which most wallets should be able to satisfy.
352
+ /// which most wallets should be able to satisfy. Otherwise, consider implementing [`WalletSource`],
353
+ /// which can provide a default implementation of this trait when used with [`Wallet`].
352
354
pub trait CoinSelectionSource {
353
355
/// Performs coin selection of a set of UTXOs, with at least 1 confirmation each, that are
354
356
/// available to spend. Implementations are free to pick their coin selection algorithm of
@@ -385,6 +387,149 @@ pub trait CoinSelectionSource {
385
387
fn sign_tx ( & self , tx : & mut Transaction ) -> Result < ( ) , ( ) > ;
386
388
}
387
389
390
+ /// An alternative to [`CoinSelectionSource`] that can be implemented and used along [`Wallet`] to
391
+ /// provide a default implementation to [`CoinSelectionSource`].
392
+ pub trait WalletSource {
393
+ /// Returns all UTXOs, with at least 1 confirmation each, that are available to spend.
394
+ fn list_confirmed_utxos ( & self ) -> Result < Vec < Utxo > , ( ) > ;
395
+ /// Returns a script to use for change above dust resulting from a successful coin selection
396
+ /// attempt.
397
+ fn get_change_script ( & self ) -> Result < Script , ( ) > ;
398
+ /// Signs and provides the full witness for all inputs within the transaction known to the
399
+ /// wallet (i.e., any provided via [`WalletSource::list_confirmed_utxos`]).
400
+ fn sign_tx ( & self , tx : & mut Transaction ) -> Result < ( ) , ( ) > ;
401
+ }
402
+
403
+ /// A wrapper over [`WalletSource`] that implements [`CoinSelection`] by preferring UTXOs that would
404
+ /// avoid conflicting double spends. If not enough UTXOs are available to do so, conflicting double
405
+ /// spends may happen.
406
+ pub struct Wallet < W : Deref > where W :: Target : WalletSource {
407
+ source : W ,
408
+ // TODO: Do we care about cleaning this up once the UTXOs have a confirmed spend? We can do so
409
+ // by checking whether any UTXOs that exist in the map are no longer returned in
410
+ // `list_confirmed_utxos`.
411
+ locked_utxos : Mutex < HashMap < OutPoint , ClaimId > > ,
412
+ }
413
+
414
+ impl < W : Deref > Wallet < W > where W :: Target : WalletSource {
415
+ /// Returns a new instance backed by the given [`WalletSource`] that serves as an implementation
416
+ /// of [`CoinSelectionSource`].
417
+ pub fn new ( source : W ) -> Self {
418
+ Self { source, locked_utxos : Mutex :: new ( HashMap :: new ( ) ) }
419
+ }
420
+
421
+ /// Performs coin selection on the set of UTXOs obtained from
422
+ /// [`WalletSource::list_confirmed_utxos`]. Its algorithm can be described as "smallest
423
+ /// above-dust-after-spend first", with a slight twist: we may skip UTXOs that are above dust at
424
+ /// the target feerate after having spent them in a separate claim transaction if
425
+ /// `force_conflicting_utxo_spend` is unset to avoid producing conflicting transactions. If
426
+ /// `tolerate_high_feerates` is set, we'll attempt to spend UTXOs that contribute at least 1
427
+ /// satoshi at the current feerate, otherwise, we'll only attempt to spend those which
428
+ /// contribute at least twice their fee.
429
+ fn select_confirmed_utxos_internal (
430
+ & self , utxos : & [ Utxo ] , claim_id : ClaimId , force_conflicting_utxo_spend : bool ,
431
+ tolerate_high_feerates : bool , target_feerate_sat_per_1000_weight : u32 ,
432
+ preexisting_tx_weight : u64 , target_amount : u64 ,
433
+ ) -> Result < CoinSelection , ( ) > {
434
+ let mut locked_utxos = self . locked_utxos . lock ( ) . unwrap ( ) ;
435
+ let mut eligible_utxos = utxos. iter ( ) . filter_map ( |utxo| {
436
+ if let Some ( utxo_claim_id) = locked_utxos. get ( & utxo. outpoint ) {
437
+ if * utxo_claim_id != claim_id && !force_conflicting_utxo_spend {
438
+ return None ;
439
+ }
440
+ }
441
+ let fee_to_spend_utxo = target_feerate_sat_per_1000_weight as u64 *
442
+ ( ( 40 * WITNESS_SCALE_FACTOR ) as u64 + utxo. satisfaction_weight ) / 1000 ;
443
+ let should_spend = if tolerate_high_feerates {
444
+ utxo. output . value > fee_to_spend_utxo
445
+ } else {
446
+ utxo. output . value >= fee_to_spend_utxo * 2
447
+ } ;
448
+ if should_spend {
449
+ Some ( ( utxo, fee_to_spend_utxo) )
450
+ } else {
451
+ None
452
+ }
453
+ } ) . collect :: < Vec < _ > > ( ) ;
454
+ eligible_utxos. sort_unstable_by_key ( |( utxo, _) | utxo. output . value ) ;
455
+
456
+ let mut selected_amount = 0 ;
457
+ let mut total_fees = preexisting_tx_weight * target_feerate_sat_per_1000_weight as u64 ;
458
+ let selected_utxos = eligible_utxos. into_iter ( ) . scan (
459
+ ( & mut selected_amount, & mut total_fees) , |( selected_amount, total_fees) , ( utxo, fee_to_spend_utxo) | {
460
+ let need_more_inputs = * * selected_amount < target_amount + * * total_fees;
461
+ if need_more_inputs {
462
+ * * selected_amount += utxo. output . value ;
463
+ * * total_fees += fee_to_spend_utxo;
464
+ Some ( utxo. clone ( ) )
465
+ } else {
466
+ None
467
+ }
468
+ }
469
+ ) . collect :: < Vec < _ > > ( ) ;
470
+ let need_more_inputs = selected_amount < target_amount + total_fees;
471
+ if need_more_inputs {
472
+ return Err ( ( ) ) ;
473
+ }
474
+ for utxo in & selected_utxos {
475
+ locked_utxos. insert ( utxo. outpoint , claim_id) ;
476
+ }
477
+ core:: mem:: drop ( locked_utxos) ;
478
+
479
+ let remaining_amount = selected_amount - target_amount - total_fees;
480
+ let change_script = self . source . get_change_script ( ) ?;
481
+ let change_output_fee = target_feerate_sat_per_1000_weight as u64
482
+ * ( 8 + change_script. consensus_encode ( & mut sink ( ) ) . unwrap ( ) as u64 ) ;
483
+ let change_output_amount = remaining_amount. saturating_sub ( change_output_fee) ;
484
+ let change_output = if change_output_amount < change_script. dust_value ( ) . to_sat ( ) {
485
+ None
486
+ } else {
487
+ Some ( TxOut { script_pubkey : change_script, value : change_output_amount } )
488
+ } ;
489
+
490
+ Ok ( CoinSelection {
491
+ confirmed_utxos : selected_utxos,
492
+ change_output,
493
+ } )
494
+ }
495
+ }
496
+
497
+ impl < W : Deref > CoinSelectionSource for Wallet < W > where W :: Target : WalletSource {
498
+ fn select_confirmed_utxos (
499
+ & self , claim_id : ClaimId , must_spend : & [ Input ] , must_pay_to : & [ TxOut ] ,
500
+ target_feerate_sat_per_1000_weight : u32 ,
501
+ ) -> Result < CoinSelection , ( ) > {
502
+ let utxos = self . source . list_confirmed_utxos ( ) ?;
503
+ // TODO: Use fee estimation utils when we upgrade to bitcoin v0.30.0.
504
+ let base_tx_weight = 4 /* version */ + 1 /* input count */ + 1 /* output count */ + 4 /* locktime */ ;
505
+ let total_input_weight = must_spend. len ( ) *
506
+ ( 32 /* txid */ + 4 /* vout */ + 4 /* sequence */ + 1 /* script sig */ ) ;
507
+ let total_output_weight: usize = must_pay_to. iter ( ) . map ( |output|
508
+ 8 /* value */ + 1 /* script len */ + output. script_pubkey . len ( )
509
+ ) . sum ( ) ;
510
+ let total_non_witness_weight = base_tx_weight + total_input_weight + total_output_weight;
511
+ let total_witness_weight: u64 = must_spend. iter ( ) . map ( |input| input. witness_weight ) . sum ( ) ;
512
+
513
+ let preexisting_tx_weight = 2 /* segwit marker & flag */ + total_witness_weight +
514
+ ( total_non_witness_weight * WITNESS_SCALE_FACTOR ) as u64 ;
515
+ let target_amount = must_pay_to. iter ( ) . map ( |output| output. value ) . sum ( ) ;
516
+ let do_coin_selection = |force_conflicting_utxo_spend : bool , tolerate_high_feerates : bool | {
517
+ self . select_confirmed_utxos_internal (
518
+ & utxos, claim_id, force_conflicting_utxo_spend, tolerate_high_feerates,
519
+ target_feerate_sat_per_1000_weight, preexisting_tx_weight, target_amount,
520
+ )
521
+ } ;
522
+ do_coin_selection ( false , false )
523
+ . or_else ( |_| do_coin_selection ( false , true ) )
524
+ . or_else ( |_| do_coin_selection ( true , false ) )
525
+ . or_else ( |_| do_coin_selection ( true , true ) )
526
+ }
527
+
528
+ fn sign_tx ( & self , tx : & mut Transaction ) -> Result < ( ) , ( ) > {
529
+ self . source . sign_tx ( tx)
530
+ }
531
+ }
532
+
388
533
/// A handler for [`Event::BumpTransaction`] events that sources confirmed UTXOs from a
389
534
/// [`CoinSelectionSource`] to fee bump transactions via Child-Pays-For-Parent (CPFP) or
390
535
/// Replace-By-Fee (RBF).
0 commit comments