Skip to content

Commit

Permalink
Check if max_weight is exceeded
Browse files Browse the repository at this point in the history
  • Loading branch information
yancyribbens committed Jan 8, 2025
1 parent 1264fb2 commit 2c44712
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions src/coin_grinder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,16 @@ fn build_lookahead<Utxo: WeightedUtxo>(lookahead: Vec<(Amount, &Utxo)>, availabl

// Creates a tuple of (effective_value, weighted_utxo)
fn calc_effective_values<Utxo: WeightedUtxo>(weighted_utxos: &[Utxo], fee_rate: FeeRate) -> Vec<(Amount, &Utxo)> {
//println!("calc effective values");

//for wu in weighted_utxos {
//println!("val: {:?} weight: {:?}", wu.value(), wu.weight());
//println!("eff val: {:?}", wu.effective_value(fee_rate));
//}

weighted_utxos
.iter()
// calculate effective_value and waste for each w_utxo.
// calculate effective_value for each w_utxo.
.map(|wu| (wu.effective_value(fee_rate), wu))
// remove utxos that either had an error in the effective_value calculation.
.filter(|(eff_val, _)| eff_val.is_some())
Expand Down Expand Up @@ -124,6 +131,7 @@ pub fn select_coins<Utxo: WeightedUtxo>(
weighted_utxos: &[Utxo],
) -> Option<std::vec::IntoIter<&Utxo>> {
let mut w_utxos = calc_effective_values::<Utxo>(weighted_utxos, fee_rate);

let available_value = w_utxos.clone().into_iter().map(|(ev, _)| ev).checked_sum()?;

// descending sort by effective_value using weight as tie breaker.
Expand Down Expand Up @@ -152,7 +160,7 @@ pub fn select_coins<Utxo: WeightedUtxo>(
let mut weight_sum: Weight = Weight::ZERO;
let mut best_weight_sum: Weight = max_selection_weight;

let _tx_weight_exceeded = false;
let mut max_tx_weight_exceeded = false;

let mut next_utxo_index = 0;

Expand All @@ -175,6 +183,9 @@ pub fn select_coins<Utxo: WeightedUtxo>(
if amount_sum + lookahead[tail] < total_target {
cut = true;
} else if weight_sum > best_weight_sum {
if weight_sum > max_selection_weight {
max_tx_weight_exceeded = true;
}
// check if a better solution could exist. IE there exists a utxo with a better
// weight along the current branch
if w_utxos[tail].1.weight() <= min_tail_weight[tail] {
Expand Down Expand Up @@ -384,4 +395,23 @@ mod tests {

assert_coin_select_params(&params, None);
}

#[test]
fn max_weight_exceeded () {
let mut wu = Vec::new();
for i in 0..10 {
wu.push("1 BTC/272");
wu.push("2 BTC/272");
}

let params = ParamsStr {
target: "29.5 BTC",
change_target: "1000000 sats",
max_weight: "3000",
fee_rate: "5",
weighted_utxos: wu
};

assert_coin_select_params(&params, None);
}
}

0 comments on commit 2c44712

Please sign in to comment.