Module bdk::wallet::coin_selection[][src]

Expand description

Coin selection

This module provides the trait CoinSelectionAlgorithm that can be implemented to define custom coin selection algorithms.

You can specify a custom coin selection algorithm through the coin_selection method on TxBuilder. DefaultCoinSelectionAlgorithm aliases the coin selection algorithm that will be used if it is not explicitly set.


struct AlwaysSpendEverything;

impl<D: Database> CoinSelectionAlgorithm<D> for AlwaysSpendEverything {
    fn coin_select(
        database: &D,
        required_utxos: Vec<WeightedUtxo>,
        optional_utxos: Vec<WeightedUtxo>,
        fee_rate: FeeRate,
        amount_needed: u64,
        fee_amount: u64,
    ) -> Result<CoinSelectionResult, bdk::Error> {
        let mut selected_amount = 0;
        let mut additional_weight = 0;
        let all_utxos_selected = required_utxos
                (&mut selected_amount, &mut additional_weight),
                |(selected_amount, additional_weight), weighted_utxo| {
                    **selected_amount += weighted_utxo.utxo.txout().value;
                    **additional_weight += TXIN_BASE_WEIGHT + weighted_utxo.satisfaction_weight;
        let additional_fees = fee_rate.fee_wu(additional_weight);
        let amount_needed_with_fees = (fee_amount + additional_fees) + amount_needed;
        if amount_needed_with_fees > selected_amount {
            return Err(bdk::Error::InsufficientFunds {
                needed: amount_needed_with_fees,
                available: selected_amount,

        Ok(CoinSelectionResult {
            selected: all_utxos_selected,
            fee_amount: fee_amount + additional_fees,

// create wallet, sync, ...

let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap();
let (psbt, details) = {
    let mut builder = wallet.build_tx().coin_selection(AlwaysSpendEverything);
    builder.add_recipient(to_address.script_pubkey(), 50_000);

// inspect, sign, broadcast, ...


Branch and bound coin selection

Result of a successful coin selection

Simple and dumb coin selection


Trait for generalized coin selection algorithms

Type Definitions

Default coin selection algorithm used by TxBuilder if not overridden