Skip to content
Closed
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
44 changes: 28 additions & 16 deletions src/metrics/lowest_fee.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
use crate::{float::Ordf32, BnbMetric, CoinSelector, Drain, DrainWeights, FeeRate};
use crate::{
float::{Ordf32, Ordf64},
BnbMetric, Candidate, CoinSelector, Drain, DrainWeights, FeeRate,
};

/// [`Candidate::effective_value`] in `f64`, so it stays exact for large values.
fn effective_value_f64(candidate: Candidate, feerate: FeeRate) -> f64 {
candidate.value as f64 - candidate.weight as f64 * feerate.spwu() as f64
}

/// Metric that aims to minimize transaction fees. The future fee for spending the change output is
/// included in this calculation.
Expand Down Expand Up @@ -199,17 +207,17 @@ impl BnbMetric for LowestFee {
//
// In the perfect scenario, no additional fee would be required to pay for rounding up when converting from weight units to
// vbytes and so all fee calculations below are performed on weight units directly.
let rate_excess = cs.rate_excess_wu(Drain::NONE) as f32;
let mut scale = Ordf32(0.0);
let rate_excess = cs.rate_excess_wu(Drain::NONE) as f64;
let mut scale = Ordf64(0.0);

if rate_excess < 0.0 {
let remaining_value_to_reach_feerate = rate_excess.abs();
let effective_value_of_resized_input =
to_resize.effective_value(cs.target().fee.rate);
effective_value_f64(to_resize, cs.target().fee.rate);
if effective_value_of_resized_input > 0.0 {
let feerate_scale =
remaining_value_to_reach_feerate / effective_value_of_resized_input;
scale = scale.max(Ordf32(feerate_scale));
scale = scale.max(Ordf64(feerate_scale));
} else {
return None; // we can never satisfy the constraint
}
Expand All @@ -218,15 +226,15 @@ impl BnbMetric for LowestFee {
// We can use the same approach for replacement we just have to use the
// incremental_relay_feerate.
if let Some(replace) = cs.target().fee.replace {
let replace_excess = cs.replacement_excess_wu(Drain::NONE) as f32;
let replace_excess = cs.replacement_excess_wu(Drain::NONE) as f64;
if replace_excess < 0.0 {
let remaining_value_to_reach_feerate = replace_excess.abs();
let effective_value_of_resized_input =
to_resize.effective_value(replace.incremental_relay_feerate);
effective_value_f64(to_resize, replace.incremental_relay_feerate);
if effective_value_of_resized_input > 0.0 {
let replace_scale =
remaining_value_to_reach_feerate / effective_value_of_resized_input;
scale = scale.max(Ordf32(replace_scale));
scale = scale.max(Ordf64(replace_scale));
} else {
return None; // we can never satisfy the constraint
}
Expand All @@ -235,12 +243,12 @@ impl BnbMetric for LowestFee {
// Handle absolute fee constraint. Unlike feerate and replacement, the
// absolute fee is a fixed amount (not weight-proportional), so we just
// need enough raw value to cover the gap.
let absolute_excess = cs.absolute_excess(Drain::NONE) as f32;
let absolute_excess = cs.absolute_excess(Drain::NONE) as f64;
if absolute_excess < 0.0 {
let remaining = absolute_excess.abs();
if to_resize.value > 0 {
let absolute_scale = remaining / to_resize.value as f32;
scale = scale.max(Ordf32(absolute_scale));
let absolute_scale = remaining / to_resize.value as f64;
scale = scale.max(Ordf64(absolute_scale));
} else {
return None; // we can never satisfy the constraint
}
Expand All @@ -253,20 +261,24 @@ impl BnbMetric for LowestFee {
// fractional relaxation, so it never prunes a branch with an (integer) within-cap
// solution.
if let Some(max_weight) = cs.target().max_weight {
if cs.weight(DrainWeights::NONE) as f32 + scale.0 * to_resize.weight as f32
> max_weight as f32
if cs.weight(DrainWeights::NONE) as f64 + scale.0 * to_resize.weight as f64
> max_weight as f64
{
return None;
}
}

// `scale` could be 0 even if `is_funded` is `false` due to the latter being based on
// rounded-up vbytes.
let ideal_fee = scale.0 * to_resize.value as f32 + cs.selected_value() as f32
- cs.target().value() as f32;
//
// The arithmetic is done in `f64` (subtracting the integers first) so that it stays
// exact at large values. Casting to `f32` at the end keeps the bound admissible: the
// cast is monotonic, and `fee_score` casts the true fee the same way.
let ideal_fee = scale.0 * to_resize.value as f64
+ (cs.selected_value() as i64 - cs.target().value() as i64) as f64;
assert!(ideal_fee >= 0.0);

Some(Ordf32(ideal_fee))
Some(Ordf32(ideal_fee as f32))
}
}

Expand Down
158 changes: 158 additions & 0 deletions tests/large_values.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
//! BnB with `LowestFee` must find the same optimum as brute force when values are large.
use bdk_coin_select::{
metrics::LowestFee, BnbMetric, Candidate, CoinSelector, DrainWeights, FeeRate, Target,
TargetFee, TargetOutputs,
};

/// Small deterministic random number generator, so every run tests the same cases.
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
self.0 >> 11
}
fn range(&mut self, lo: u64, hi: u64) -> u64 {
lo + self.next() % (hi - lo)
}
}

/// Exact (integer) long-term fee of a selection, or `None` if it isn't a valid solution.
fn exact_score(metric: &mut LowestFee, cs: &CoinSelector<'_>) -> Option<u64> {
if !cs.is_funded() {
return None;
}
let drain = metric.drain(cs);
if !cs.is_within_max_weight(drain.weights) {
return None;
}
Some(cs.fee(drain.value) as u64 + drain.weights.spend_fee(metric.long_term_feerate))
}

/// Runs `cases` random scenarios and returns (suboptimal, panics, solvable).
fn run(
min_value: u64,
max_value: u64,
max_feerate: u64,
absolute: bool,
cases: u64,
) -> (u64, u64, u64) {
let (mut mismatches, mut panics, mut solved) = (0, 0, 0);
for seed in 0..cases {
let mut rng = Lcg(seed.wrapping_mul(0x9E3779B97F4A7C15) ^ max_value);
let n = rng.range(2, 11) as usize;
let candidates: Vec<Candidate> = (0..n)
.map(|_| Candidate {
value: rng.range(min_value, max_value),
weight: rng.range(160, 600),
input_count: 1,
})
.collect();
let total: u64 = candidates.iter().map(|c| c.value).sum();
let target = Target {
outputs: TargetOutputs {
value_sum: rng.range(total / 10, total),
weight_sum: rng.range(100, 1000),
n_outputs: 1,
},
fee: TargetFee {
absolute: if absolute {
rng.range(min_value, total / 10 + min_value + 1)
} else {
0
},
..TargetFee::from_feerate(FeeRate::from_sat_per_vb(
rng.range(1, max_feerate + 1) as f32
))
},
max_weight: None,
};
let mut metric = LowestFee {
long_term_feerate: FeeRate::from_sat_per_vb(rng.range(1, max_feerate + 1) as f32),
dust_relay_feerate: FeeRate::from_sat_per_vb(3.0),
drain_weights: DrainWeights::TR_KEYSPEND,
};

// Brute force: try every subset of candidates and keep the cheapest.
let mut best: Option<u64> = None;
for mask in 1u32..(1 << n) {
let mut cs = CoinSelector::new(&candidates, target);
for i in 0..n {
if mask & (1 << i) != 0 {
cs.select(i);
}
}
if let Some(s) = exact_score(&mut metric, &cs) {
best = Some(best.map_or(s, |b| b.min(s)));
}
}
let best = match best {
Some(b) => b,
None => continue,
};
solved += 1;

// Branch and bound must find the same fee, without panicking.
let res = std::panic::catch_unwind(|| {
let mut cs = CoinSelector::new(&candidates, target);
let mut m = metric;
cs.run_bnb(metric, usize::MAX).ok()?;
exact_score(&mut m, &cs)
});
match res {
Err(_) => panics += 1,
Ok(got) if got != Some(best) => {
if mismatches < 3 {
println!(
"seed {seed}: bnb={got:?} brute_force={best} (diff {:?})",
got.map(|g| g as i64 - best as i64)
);
}
mismatches += 1
}
Ok(_) => {}
}
}
(mismatches, panics, solved)
}

macro_rules! case {
($name:ident, $min:expr, $max:expr, $fr:expr, $abs:expr) => {
#[test]
fn $name() {
let (mismatches, panics, solved) = run($min, $max, $fr, $abs, 20_000);
println!(
"{}: {solved} solvable, {mismatches} suboptimal, {panics} panics",
stringify!($name)
);
assert_eq!((mismatches, panics), (0, 0));
}
};
}

// name, min UTXO value, max UTXO value (sats), max feerate (sat/vB), use absolute fee
case!(small_values, 1_000, 500_000, 100, false);
// around 1 BTC per UTXO
case!(one_btc, 50_000_000, 200_000_000, 100, false);
case!(one_btc_low_feerate, 50_000_000, 200_000_000, 2, false);
// 0.2 BTC .. 20 BTC per UTXO
case!(large_values, 20_000_000, 2_000_000_000, 100, false);
case!(
large_values_low_feerate,
20_000_000,
2_000_000_000,
2,
false
);
// up to 500 BTC per UTXO
case!(
huge_values_low_feerate,
20_000_000,
50_000_000_000,
2,
false
);
// large absolute fee (> 2^24 sats), the #82 scenario
case!(large_absolute_fee, 20_000_000, 2_000_000_000, 100, true);