Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Unreleased

- **Breaking:** Every transaction is now priced as segwit, and `Candidate::is_segwit` is removed. `Candidate::weight` is the input's segwit-serialized weight (`TxIn::segwit_weight`), so legacy inputs include their 1 WU empty witness. A transaction that spends only legacy inputs is overestimated by 2 WU plus 1 WU per input, and never undershoots the target feerate. The same margin applies to `Target::max_weight`, so such a selection close to the cap can be rejected even though the real transaction fits. This fixes `CoinSelector::input_weight` undercounting candidates that group several legacy inputs in a segwit transaction.
- **Breaking:** `Candidate::new(value, satisfaction_weight, is_segwit)` is now `Candidate::new(value, satisfaction_weight)`, and `satisfaction_weight` now means the weight over an unsatisfied `TxIn::default()`, which is what miniscript's `Descriptor::max_weight_to_satisfy` returns for every script type. Previously it was documented as including the `scriptSig` length and the `scriptWitness` stack item count. To migrate, pass `max_weight_to_satisfy()?.to_wu()` directly. If you compute it by hand, it is the satisfied input's `TxIn::segwit_weight()` minus `TxIn::default().segwit_weight()`.
- **Breaking:** Public weight constants changed value without changing type. `TXIN_BASE_WEIGHT` is now 165 (was 164) and includes the stack item count of an empty `scriptWitness`. `TX_FIXED_FIELD_WEIGHT` is now 34 (was 32) and includes the segwit `marker` and `flag`. `TR_KEYSPEND_SATISFACTION_WEIGHT` is now 65 (was 66) and excludes the `scriptWitness` stack item count. `TR_KEYSPEND_TXIN_WEIGHT` is unchanged at 230.
- **Breaking:** `CoinSelector` now owns its `Target`. `CoinSelector::new(candidates, target)` takes it and `CoinSelector::target()` returns it, and it is fixed for the life of the selector. Every method that took a `target: Target` argument no longer does, including `excess`, `missing`, `rate_excess`, `implied_fee`, `is_funded`, `is_within_max_weight`, `drain`, `select_until_target_met`, `select_srd`, `run_bnb`, and `bnb_solutions`. The same goes for arguments that merely restated part of the target: `weight` and `implied_feerate` no longer take `TargetOutputs`, `fee` no longer takes `target_value`, and `effective_value` and `select_all_effective` no longer take a `FeeRate`. `BnbMetric`'s methods read the target from the `CoinSelector` they are given — they are now `fn score(&mut self, cs: &CoinSelector<'_>) -> Option<Ordf32>`, `fn bound(&mut self, cs: &CoinSelector<'_>) -> Option<Ordf32>` and `fn drain(&mut self, cs: &CoinSelector<'_>) -> Drain` — so `LowestFee` and `Changeless` no longer store a `target` field. This removes the target that `Changeless<M>` previously had to keep in sync with its inner metric. To measure a selection against a second target, use `CoinSelector::with_target(target)`, which copies the selection, the bans and the candidate order over to the new target; `CoinSelector::new` starts from an empty selection.
- **Breaking:** `BnbMetric` metrics now decide the change output themselves. The trait gains a `drain(&mut self, cs) -> Drain` method; call it on a branch-and-bound solution (or the `LowestFee` metric directly) to get the change output the metric optimized against, instead of computing a separate `ChangePolicy`.
- **Breaking:** `CoinSelector::run_bnb` now returns `(Ordf32, Drain)` instead of just `Ordf32`, handing back the change output the metric decided on for the winning selection.
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ std = []
rand = "0.9"
proptest = "1.7"
bitcoin = "0.32"
miniscript = "12"
criterion = "0.5"

[[bench]]
Expand Down
13 changes: 4 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,18 @@ let candidates = vec![
input_count: 1,
// the value of the input
value: 1_000_000,
// the total weight of the input(s) including their witness/scriptSig
// you may need to use miniscript to figure out the correct value here.
// the total weight of the input(s) as serialized in a segwit tx, i.e.
// `TxIn::segwit_weight`. Legacy inputs include their 1 WU empty witness.
// `Candidate::new(value, descriptor.max_weight_to_satisfy()?.to_wu())`
// computes this for you.
weight: TR_KEYSPEND_TXIN_WEIGHT,
// wether it's a segwit input. Needed so we know whether to include the
// segwit header in total weight calculations.
is_segwit: true
},
Candidate {
// A candidate can represent multiple inputs in the case where you
// always want some inputs to be spent together.
input_count: 2,
weight: 2*TR_KEYSPEND_TXIN_WEIGHT,
value: 3_000_000,
is_segwit: true
}
];

Expand Down Expand Up @@ -108,19 +106,16 @@ let candidates = [
input_count: 1,
value: 400_000,
weight: TR_KEYSPEND_TXIN_WEIGHT,
is_segwit: true
},
Candidate {
input_count: 1,
value: 200_000,
weight: TR_KEYSPEND_TXIN_WEIGHT,
is_segwit: true
},
Candidate {
input_count: 1,
value: 11_000,
weight: TR_KEYSPEND_TXIN_WEIGHT,
is_segwit: true
}
];
let drain_weights = bdk_coin_select::DrainWeights::default();
Expand Down
1 change: 0 additions & 1 deletion benches/coin_selector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ fn make_candidates(n: usize) -> Vec<Candidate> {
value,
weight: TXIN_BASE_WEIGHT + P2WPKH_SAT_W,
input_count: 1,
is_segwit: true,
}
})
.collect()
Expand Down
8 changes: 5 additions & 3 deletions src/bnb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,14 @@ impl<'a, M: BnbMetric> BnbIter<'a, M> {
inclusion_cs.select(next_index);
self.consider_adding_to_queue(&inclusion_cs, false);

// for the exclusion branch, we keep banning if candidates have the same weight and value
// for the exclusion branch, we keep banning identical candidates since selecting any one of
// them is equivalent to selecting another. This relies on the sort placing identical
// candidates next to each other.
let mut is_first_ban = true;
let mut exclusion_cs = cs.clone();
let to_ban = (next.value, next.weight);
let to_ban = next;
for (next_index, next) in cs.unselected() {
if (next.value, next.weight) != to_ban {
if next != to_ban {
break;
}
let (_index, _candidate) = exclusion_cs
Expand Down
72 changes: 33 additions & 39 deletions src/coin_selector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,29 +183,15 @@ impl<'a> CoinSelector<'a> {
self.selected.is_empty()
}

/// The weight of the inputs including the witness header and the varint for the number of
/// inputs.
/// The weight of the inputs including the varint for the number of inputs.
///
/// Inputs are priced as segwit, so each legacy input is overestimated by its 1 WU empty
/// witness when no segwit input is selected (see [`Candidate::weight`]).
pub fn input_weight(&self) -> u64 {
let is_segwit_tx = self.selected().any(|(_, wv)| wv.is_segwit);
let witness_header_extra_weight = is_segwit_tx as u64 * 2;

let input_count = self.selected().map(|(_, wv)| wv.input_count).sum::<usize>();
let input_varint_weight = varint_size(input_count) * 4;

let selected_weight: u64 = self
.selected()
.map(|(_, candidate)| {
let mut weight = candidate.weight;
if is_segwit_tx && !candidate.is_segwit {
// non-segwit candidates do not have the witness length field included in their
// weight field so we need to add 1 here if it's in a segwit tx.
weight += 1;
}
weight
})
.sum();

input_varint_weight + selected_weight + witness_header_extra_weight
let selected_weight: u64 = self.selected().map(|(_, wv)| wv.weight).sum();
input_varint_weight + selected_weight
}

/// Absolute value sum of all selected inputs.
Expand Down Expand Up @@ -403,11 +389,13 @@ impl<'a> CoinSelector<'a> {
self.sort_candidates_by(|a, b| key_fn(a).cmp(&key_fn(b)))
}

/// Sorts the candidates by descending value per weight unit, tie-breaking with value.
/// Sorts the candidates by descending value per weight unit, tie-breaking with [`Candidate`]'s
/// `Ord`.
///
/// Tie-breaking on the whole candidate keeps identical candidates next to each other, which
/// branch and bound relies on to exclude them together.
pub fn sort_candidates_by_descending_value_pwu(&mut self) {
self.sort_candidates_by_key(|(_, wv)| {
core::cmp::Reverse((Ordf32(wv.value_pwu()), wv.value))
});
self.sort_candidates_by_key(|(_, wv)| core::cmp::Reverse((Ordf32(wv.value_pwu()), wv)));
}

/// Shuffle the candidates with Fisher-Yates algorithm.
Expand Down Expand Up @@ -917,38 +905,44 @@ impl std::error::Error for NoBnbSolution {}
/// A `Candidate` represents an input candidate for [`CoinSelector`].
///
/// This can either be a single UTXO, or a group of UTXOs that should be spent together.
#[derive(Debug, Clone, Copy)]
///
/// The derived `Ord` compares fields in declaration order and has no meaning beyond grouping
/// identical candidates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Candidate {
/// Total value of the UTXO(s) that this [`Candidate`] represents.
pub value: u64,
/// Total weight of including this/these UTXO(s).
/// `txin` fields: `prevout`, `nSequence`, `scriptSigLen`, `scriptSig`, `scriptWitnessLen`,
/// `scriptWitness` should all be included.
/// Total weight of the input(s) as serialized in a segwit transaction, i.e. the sum of
/// `TxIn::segwit_weight` from rust-bitcoin. That is `prevout`, `scriptSig` and its length,
/// `nSequence`, and `scriptWitness` with its stack item count. A legacy input's empty
/// `scriptWitness` still serializes its stack item count (1 WU) in a segwit transaction.
///
/// [`CoinSelector`] always prices the transaction as segwit. A transaction that spends only
/// legacy inputs has no witness section, so its weight is overestimated by 2 WU plus 1 WU per
/// input. This never undershoots the target feerate, but such a selection within that margin of
/// [`Target::max_weight`] is rejected even though the real transaction would fit.
pub weight: u64,
/// Total number of inputs; so we can calculate extra `varint` weight due to `vin` len changes.
pub input_count: usize,
/// Whether this [`Candidate`] contains at least one segwit spend.
pub is_segwit: bool,
}

impl Candidate {
/// Create a [`Candidate`] input that spends a single taproot keyspend output.
pub fn new_tr_keyspend(value: u64) -> Self {
let weight = TR_KEYSPEND_SATISFACTION_WEIGHT;
Self::new(value, weight, true)
Self::new(value, TR_KEYSPEND_SATISFACTION_WEIGHT)
}

/// Create a new [`Candidate`] that represents a single input.
/// Create a new [`Candidate`] that represents a single input of any script type.
///
/// `satisfaction_weight` is the weight of `scriptSigLen + scriptSig + scriptWitnessLen +
/// scriptWitness`.
pub fn new(value: u64, satisfaction_weight: u64, is_segwit: bool) -> Candidate {
let weight = TXIN_BASE_WEIGHT + satisfaction_weight;
/// `satisfaction_weight` is the weight the input adds over an unsatisfied `TxIn::default()`,
/// which is exactly what miniscript's `Descriptor::max_weight_to_satisfy()?.to_wu()` returns.
/// It excludes the 1-byte `scriptSig` length and the 1-byte `scriptWitness` stack item count,
/// which [`TXIN_BASE_WEIGHT`] covers.
pub fn new(value: u64, satisfaction_weight: u64) -> Candidate {
Candidate {
value,
weight,
weight: TXIN_BASE_WEIGHT + satisfaction_weight,
input_count: 1,
is_segwit,
}
}

Expand Down
20 changes: 13 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@ pub use target::*;
mod drain;
pub use drain::*;

/// Txin "base" fields include `outpoint` (32+4) and `nSequence` (4) and 1 byte for the scriptSig
/// length.
pub const TXIN_BASE_WEIGHT: u64 = (32 + 4 + 4 + 1) * 4;
/// The weight of an unsatisfied txin: the non-discounted `prevout` (32+4), `nSequence` (4) and
/// empty `scriptSig` length (1), plus the discounted empty `scriptWitness` stack item count (1).
pub const TXIN_BASE_WEIGHT: u64 =
(32 + 4 /* prevout */ + 4 /* nSequence */ + 1 /* scriptSig length */) * 4 + 1 /* stack item count */;

/// The weight of a TXOUT with a zero length `scriptPubKey`
#[allow(clippy::identity_op)]
Expand All @@ -41,11 +42,16 @@ pub const TXOUT_BASE_WEIGHT: u64 =
// The spk length
+ (4 * 1);

/// The weight of the `nVersion` and `nLockTime` transaction fields
pub const TX_FIXED_FIELD_WEIGHT: u64 = (4 /* nVersion */ + 4/* nLockTime */) * 4;
/// The weight of the non-discounted `nVersion`, `nLockTime` fields and the discounted segwit
/// `marker` and `flag`.
pub const TX_FIXED_FIELD_WEIGHT: u64 = (4 /* nVersion */ + 4/* nLockTime */) * 4 + 2;

/// The weight of a taproot keyspend witness
pub const TR_KEYSPEND_SATISFACTION_WEIGHT: u64 = 1 /*witness_len*/ + 1 /*item len*/ + 64 /*signature*/;
/// The weight of a taproot keyspend `scriptWitness`, excluding the stack item count that
/// [`TXIN_BASE_WEIGHT`] covers.
///
/// This assumes a 64-byte `SIGHASH_DEFAULT` signature. miniscript's `max_weight_to_satisfy` assumes
/// the worst case, a 65-byte signature with an explicit sighash byte, and so returns 1 WU more.
pub const TR_KEYSPEND_SATISFACTION_WEIGHT: u64 = 1 /* stack item length */ + 64 /* signature */;

/// The weight of a segwit `v1` (taproot) script pubkey in an output. This does not include the weight of
/// the `TxOut` itself or the script pubkey length field.
Expand Down
14 changes: 4 additions & 10 deletions tests/bnb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,13 @@ use proptest::{prelude::*, proptest, test_runner::*};
fn test_wv(mut rng: impl RngCore) -> impl Iterator<Item = Candidate> {
core::iter::repeat_with(move || {
let value = rng.random_range(0..1_000);
let mut candidate = Candidate {
let candidate = Candidate {
value,
weight: 100,
input_count: rng.random_range(1..2),
is_segwit: rng.random_bool(0.5),
};
// HACK: set is_segwit = true for all these tests because you can't actually lower bound
// things easily with how segwit inputs interfere with their weights. We can't modify the
// above since that would change what we pull from rng.
candidate.is_segwit = true;
// This used to draw `is_segwit`. Keep drawing so the rng stream stays the same.
let _ = rng.random_bool(0.5);
candidate
})
}
Expand Down Expand Up @@ -62,10 +59,7 @@ fn bnb_finds_an_exact_solution_in_n_iter() {
let num_additional_canidates = 12;

let mut rng = TestRng::deterministic_rng(RngAlgorithm::ChaCha);
let mut wv = test_wv(&mut rng).map(|mut candidate| {
candidate.is_segwit = true;
candidate
});
let mut wv = test_wv(&mut rng);

let solution: Vec<Candidate> = (0..solution_len).map(|_| wv.next().unwrap()).collect();
let target_value = solution.iter().map(|c| c.value).sum();
Expand Down
1 change: 0 additions & 1 deletion tests/changeless.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ fn test_wv(mut rng: impl RngCore) -> impl Iterator<Item = Candidate> {
value,
weight: rng.random_range(0..100),
input_count: rng.random_range(1..2),
is_segwit: false,
}
})
}
Expand Down
4 changes: 2 additions & 2 deletions tests/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,13 +264,13 @@ pub fn gen_candidates(n: usize) -> Vec<Candidate> {
let value = rng.random_range(1..500_001);
let weight = rng.random_range(1..2001);
let input_count = rng.random_range(1..3);
let is_segwit = rng.random_bool(0.01);
// This used to draw `is_segwit`. Keep drawing so the rng stream stays the same.
let _ = rng.random_bool(0.01);

Candidate {
value,
weight,
input_count,
is_segwit,
}
})
.take(n)
Expand Down
42 changes: 33 additions & 9 deletions tests/lowest_fee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ mod common;
use bdk_coin_select::metrics::{Changeless, LowestFee};
use bdk_coin_select::{
BnbMetric, Candidate, ChangePolicy, CoinSelector, Drain, DrainWeights, FeeRate, NoBnbSolution,
Replace, Target, TargetFee, TargetOutputs, TX_FIXED_FIELD_WEIGHT,
Replace, Target, TargetFee, TargetOutputs, TXIN_BASE_WEIGHT, TXOUT_BASE_WEIGHT,
TX_FIXED_FIELD_WEIGHT,
};
use proptest::prelude::*;

Expand Down Expand Up @@ -84,9 +85,8 @@ proptest! {
let candidates = vec![
Candidate {
value: 20_000,
weight: (32 + 4 + 4 + 1) * 4 + 64 + 32,
weight: TXIN_BASE_WEIGHT + 64 + 32,
input_count: 1,
is_segwit: true,
};
params.n_candidates
];
Expand Down Expand Up @@ -237,20 +237,17 @@ fn does_not_create_change_below_spend_cost() {
value: 100_000,
weight: 100,
input_count: 1,
is_segwit: true,
},
Candidate {
value: 50_000,
weight: 100,
input_count: 1,
is_segwit: true,
},
// NOTE: this input has negative effective value
Candidate {
value: 10,
weight: 100,
input_count: 1,
is_segwit: true,
},
];

Expand Down Expand Up @@ -315,13 +312,11 @@ fn zero_fee_tx() {
value: 100_000,
weight: 100,
input_count: 1,
is_segwit: true,
},
Candidate {
value: 50_000,
weight: 100,
input_count: 1,
is_segwit: true,
},
];

Expand All @@ -347,7 +342,6 @@ fn err_candidate(value: u64) -> Candidate {
value,
weight: 272, // ~1 P2WPKH input
input_count: 1,
is_segwit: true,
}
}

Expand Down Expand Up @@ -426,3 +420,33 @@ fn run_bnb_reports_round_limit() {
},
);
}

/// Branch and bound excludes identical candidates together, which relies on the sort placing them
/// next to each other. Candidates that differ only in `input_count` are not identical, so the sort
/// must not interleave them with each other, or nothing gets excluded together and the search blows
/// up: without the tie-break this takes 35,749 rounds.
#[test]
fn identical_candidates_are_excluded_together_when_interleaved() {
// Equal value and weight, alternating input count.
let candidates = (0..16)
.map(|i| Candidate {
value: 10_000,
weight: 400,
input_count: 1 + i % 2,
})
.collect::<Vec<_>>();
let target = Target {
outputs: TargetOutputs::fund_outputs([(TXOUT_BASE_WEIGHT + 22 * 4, 78_000)]),
fee: TargetFee::from_feerate(FeeRate::from_sat_per_vb(10.0)),
max_weight: None,
};
let metric = LowestFee {
long_term_feerate: FeeRate::from_sat_per_vb(10.0),
dust_relay_feerate: FeeRate::from_sat_per_vb(1.0),
drain_weights: DrainWeights::TR_KEYSPEND,
};
let rounds = CoinSelector::new(&candidates, target)
.bnb_solutions(metric)
.count();
assert!(rounds <= 100, "took {} rounds", rounds);
}
Loading
Loading