From 5c38bb580e7dd98c5ec8837742f2b5514e90b76d Mon Sep 17 00:00:00 2001 From: yancy Date: Wed, 6 Dec 2023 21:27:11 +0100 Subject: [PATCH] Implement BnB search algorithm --- Cargo.toml | 14 +- README.md | 13 + benches/coin_selection.rs | 47 +++ src/branch_and_bound.rs | 817 +++++++++++++++++++++++++++++++------- src/lib.rs | 34 +- 5 files changed, 767 insertions(+), 158 deletions(-) create mode 100644 benches/coin_selection.rs diff --git a/Cargo.toml b/Cargo.toml index e89b909..66a06ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ keywords = ["crypto", "bitcoin"] readme = "README.md" [dependencies] -bitcoin = { git="https://github.com/yancyribbens/rust-bitcoin", branch = "add-effective-value-calculation" } +bitcoin = { git="https://github.com/yancyribbens/rust-bitcoin", rev="254fafdf71b30ae9156b43d57b336cf4a251ed33" } rand = {version = "0.8.5", default-features = false, optional = true} [dev-dependencies] @@ -23,7 +23,11 @@ rust-bitcoin-coin-selection = {path = ".", features = ["rand"]} rand = "0.8.5" [patch.crates-io] -bitcoin_hashes = { git = "https://github.com/yancyribbens/rust-bitcoin", branch = "add-effective-value-calculation" } -bitcoin-io = { git = "https://github.com/yancyribbens/rust-bitcoin", branch = "add-effective-value-calculation" } -bitcoin-units = { git = "https://github.com/yancyribbens/rust-bitcoin", branch = "add-effective-value-calculation" } -bitcoin-internals = { git = "https://github.com/yancyribbens/rust-bitcoin", branch = "add-effective-value-calculation" } +bitcoin_hashes = { git = "https://github.com/yancyribbens/rust-bitcoin", rev="254fafdf71b30ae9156b43d57b336cf4a251ed33" } +bitcoin-io = { git = "https://github.com/yancyribbens/rust-bitcoin", rev="254fafdf71b30ae9156b43d57b336cf4a251ed33" } +bitcoin-units = { git = "https://github.com/yancyribbens/rust-bitcoin", rev="254fafdf71b30ae9156b43d57b336cf4a251ed33" } +bitcoin-internals = { git = "https://github.com/yancyribbens/rust-bitcoin", rev="254fafdf71b30ae9156b43d57b336cf4a251ed33" } + +[[bench]] +name = "coin_selection" +harness = false diff --git a/README.md b/README.md index a97cbdb..5fc88c4 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,20 @@ As discussed in the literature above, ideally we want to choose a selection from ## Benchmarks +<<<<<<< HEAD To run the benchmarks use: `RUSTFLAGS='--cfg=bench' cargo +nightly bench`. +======= +To run the benchmarks use: `cargo bench`. + +### performance comparison + +A basic performance comparison between this current [Rust BnB](https://github.com/p2pderivatives/rust-bitcoin-coin-selection/pull/28/files#diff-9098d62be93e83524a8371395c973d761a95000d1c295f600a8c808e917c16d9R122) implementation and the [Bitcoin Core](https://github.com/bitcoin/bitcoin/blob/4b1196a9855dcd188a24f393aa2fa21e2d61f061/src/wallet/coinselection.cpp#L76) version using commodity hardware (My rather old laptop). + +|implementation|pool size|ns/iter| +|-------------:|---------|-------| +| Rust BnB| 1,000|823,680| +| C++ Core BnB| 1,000|816,374| +>>>>>>> 4ede8d5 (Add cost of change param) ## Minimum Supported Rust Version (MSRV) diff --git a/benches/coin_selection.rs b/benches/coin_selection.rs new file mode 100644 index 0000000..fa5ff5c --- /dev/null +++ b/benches/coin_selection.rs @@ -0,0 +1,47 @@ +use criterion::{black_box, criterion_group, criterion_main, Criterion}; + +use bitcoin::Amount; +use bitcoin::FeeRate; +use bitcoin::ScriptBuf; +use bitcoin::TxOut; +use bitcoin::Weight; +use rust_bitcoin_coin_selection::select_coins_bnb; +use rust_bitcoin_coin_selection::WeightedUtxo; + +pub fn criterion_benchmark(c: &mut Criterion) { + // https://github.com/bitcoin/bitcoin/blob/f3bc1a72825fe2b51f4bc20e004cef464f05b965/src/wallet/coinselection.h#L18 + let cost_of_change = Amount::from_sat(50_000); + + let one = WeightedUtxo { + satisfaction_weight: Weight::ZERO, + utxo: TxOut { value: Amount::from_sat(1_000), script_pubkey: ScriptBuf::new() }, + }; + + let two = WeightedUtxo { + satisfaction_weight: Weight::ZERO, + utxo: TxOut { value: Amount::from_sat(3), script_pubkey: ScriptBuf::new() }, + }; + + let target = Amount::from_sat(1_003); + let mut utxo_pool = vec![one; 1000]; + utxo_pool.push(two); + + c.bench_function("bnb 1000", |b| { + b.iter(|| { + let result = select_coins_bnb( + black_box(target), + black_box(cost_of_change), + black_box(FeeRate::ZERO), + black_box(FeeRate::ZERO), + black_box(&mut utxo_pool), + ) + .unwrap(); + assert_eq!(2, result.len()); + assert_eq!(Amount::from_sat(1_000), result[0].utxo.value); + assert_eq!(Amount::from_sat(3), result[1].utxo.value); + }) + }); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/src/branch_and_bound.rs b/src/branch_and_bound.rs index db7750f..088a44e 100644 --- a/src/branch_and_bound.rs +++ b/src/branch_and_bound.rs @@ -1,222 +1,743 @@ -use crate::Utxo; -use std::cmp::Reverse; - -/// Select coins using BnB algorithm similar to what is done in bitcoin -/// core see: -/// Returns None if BnB doesn't find a solution. -pub fn select_coins_bnb( - target: u64, - cost_of_change: u64, - utxo_pool: &mut [T], -) -> Option> { - let solution = find_solution(target, cost_of_change, utxo_pool)?; - Some( - solution - .into_iter() - .zip(utxo_pool.iter()) - .filter_map(|(include, utxo)| if include { Some(utxo.clone()) } else { None }) - .collect::>(), - ) -} +// SPDX-License-Identifier: CC0-1.0 +// +//! Bitcoin Branch and Bound Selection. +//! +//! This module introduces the Branch and Bound Coin Selection Algorithm. + +use crate::WeightedUtxo; +use bitcoin::amount::CheckedSum; +use bitcoin::Amount; +use bitcoin::FeeRate; +use bitcoin::SignedAmount; + +/// Select coins bnb performs a depth first branch and bound search on binary tree. +/// +/// See also core: +/// +/// Returns a collection of `WeightedUtxo` that meet or exceed the target `Amount` when summed. +/// The collection returned seeks to minimize the waste, which is the difference between the target +/// `Amount` and sum of the `WeightedUtxo` collection. If no match can be found, an empty +/// collection is returned wrapped by the option type. However, if an un-expected error was +/// encountered, `None` is returned. +/// +/// # Returns +/// * `Some(Vec)` where `Vec` is not empty on match. +/// * `Some(vec![])` if no match could be fouund. +/// * `None` if some un-expected behavior occurred such as an overflow. +/// +/// # Arguments +/// * target: Target spend `Amount` +/// * cost_of_change: The `Amount` needed to produce a change output +/// * fee_rate: `FeeRate` used to calculate each effective_value output value +/// * weighted_utxos: The candidate Weighted UTXOs from which to choose a selection from + +// This search can be thought of as exploring a binary tree where the left branch is the inclusion +// of a node and the right branch is the exclusion. For example, if the utxo set consist of a +// list of utxos: [4,3,2,1], and the target is 5, the selection process works as follows: +// +// Start at 4 and try including 4 in the total the first loop. We therefore have a tree with only +// one root node that is less than the total, so the next iteration occurs. The second iteration +// examines a tree where 4 is the root and the left branch is 3. +// o +// / +// 4 +// / +// 3 +// +// At this point, the total is determined to be 7 which exceeds the target of 5. We therefore +// remove 3 from the left branch and it becomes the right branch since 3 is now excluded +// (backtrack). +// o +// / +// 4 +// / \ +// 3 +// +// We next try including 2 on the left branch of 3 (add 2 to the inclusion branch). +// o +// / +// 4 +// / \ +// 3 +// / +// 2 +// +// The sum is now 6, since the sum of the right branch totals 6. Once again, we find the total +// exceeds 5, so we explore the exclusion branch of 2. +// o +// / +// 4 +// / \ +// 3 +// / \ +// 2 +// +// Finally, we add 1 to the inclusion branch. This ends our depth first search by matching two +// conditions, it is both the leaf node (end of the list) and matches our search criteria of +// matching 5. Both 4 and 1 are on the left inclusion branch. We therefore record our solution +// and backtrack to next try the exclusion branch of our root node 4. +// o +// / \ +// 4 +// / \ +// 3 +// / \ +// 2 +// / +// 1 +// +// We try excluding 4 now +// o +// / \ +// 4 +// / \ +// 3 +// +// 3 is less than our target, so we next add 2 to our inclusion branch +// o +// / \ +// 4 +// / \ +// 3 +// / +// 2 +// +// We now stop our search again noticing that 3 and 2 equals our target as 5, and since this +// solution was found last, then [3, 2] overwrites the previously found solution [4, 1]. We next +// backtrack and exclude our root node of this sub tree 3. Since our new sub tree starting at 2 +// doesn't have enough value left to meet the target, we conclude our search at [3, 2]. +// +// * Waste Calculation * +// Waste, like value, is a bound used to track when a search path is no longer advantageous. +// The waste total is accumulated and stored in a variable called current_waste. If the +// iteration adds a new node to the inclusion branch, besides incrementing the accumulated +// value for the node, the waste is also added to the current_waste. Note that unlike value, +// waste can actually be negative. This happens if there is a low fee environment such that +// fee is less than long_term_fee. Therefore, the only case where a solution becomes more +// wasteful, and we may bound our search because a better waste score is not longer possible +// is a) if we have already found a target and recorded a best_value and b) if the it's a high +// fee environment such that adding more utxos will increase current_waste to be greater +// than best_waste. +pub fn select_coins_bnb( + target: Amount, + cost_of_change: Amount, + fee_rate: FeeRate, + long_term_fee_rate: FeeRate, + weighted_utxos: &mut [WeightedUtxo], +) -> Option> { + // Total_Tries in Core: + // https://github.com/bitcoin/bitcoin/blob/1d9da8da309d1dbf9aef15eb8dc43b4a2dc3d309/src/wallet/coinselection.cpp#L74 + const ITERATION_LIMIT: i32 = 100_000; + + let mut iteration = 0; + let mut index = 0; + let mut backtrack; + let mut backtrack_subtree; + + let mut value = Amount::ZERO; + + let mut current_waste: SignedAmount = SignedAmount::ZERO; + let mut best_waste = SignedAmount::MAX_MONEY; + + let mut index_selection: Vec = vec![]; + let mut best_selection: Option> = None; + + let upper_bound = target.checked_add(cost_of_change)?; + + // Create a tuple of (effective_value, waste, weighted_utxo) + // * filter out effective values and wastes that are None (error). + // * filter out negative effective values. + let mut w_utxos: Vec<(Amount, SignedAmount, &WeightedUtxo)> = weighted_utxos + .iter() + // calculate effective_value and waste for each w_utxo. + .map(|wu| (wu.effective_value(fee_rate), wu.waste(fee_rate, long_term_fee_rate), wu)) + // remove utxos that either had an error in the effective_value or waste calculation. + .filter(|(eff_val, waste, _)| !eff_val.is_none() && !waste.is_none()) + // unwrap the option type since we know they are not NONE (see previous step). + .map(|(eff_val, waste, wu)| (eff_val.unwrap(), waste.unwrap(), wu)) + // filter out all effective_values that are negative. + .filter(|(eff_val, _, _)| eff_val.is_positive()) + // all utxo effective_values are now positive (see previous step) - cast to unsigned. + .map(|(eff_val, waste, wu)| (eff_val.to_unsigned().unwrap(), waste, wu)) + .collect(); + + w_utxos.sort_by_key(|u| u.0); + w_utxos.reverse(); + + let mut available_value = w_utxos.clone().into_iter().map(|(ev, _, _)| ev).checked_sum()?; + + if available_value < target { + return Some(Vec::new()); + } -fn find_solution( - target: u64, - cost_of_change: u64, - utxo_pool: &mut [T], -) -> Option> { - let utxo_sum = utxo_pool.iter().fold(0u64, |mut s, u| { - s += u.get_value(); - s - }); + while iteration < ITERATION_LIMIT { + // There are two conditions for backtracking: + // + // 1_ Not enough value to make it to target. + // This condition happens before reaching a leaf node. + // Looking for a leaf node condition should not make a difference. + // This backtrack removes more than one node and instead starts + // the exploration of a new subtree. + // + // From: + // o + // / \ + // 4 + // / \ + // 3 + // / \ + // 2 + // / + // 1 + // + // To: + // o + // / \ + // 4 + // / \ + // 3 + // + // + // 2_ value meets or exceeded target. + // In this condition, we only backtrack one node + // + // From: + // o + // / + // 4 + // / + // 3 + // + // To: + // o + // / + // 4 + // / \ + // 3 + + // Set initial loop state + backtrack = false; + backtrack_subtree = false; + + // * not enough value to make it to the target. + // Therefore, explore a new new subtree. + // + // unchecked_add is used here for performance. Before entering the search loop, all + // utxos are summed and checked for overflow. Since there was no overflow then, any + // subset of addition will not overflow. + if available_value.unchecked_add(value) < target { + backtrack_subtree = true; + } + // This optimization provides an upper bound on the amount of waste that is acceptable. + // Since value is lost when we create a change output due to increasing the size of the + // transaction by an output, we accept solutions that may be larger than the target as + // if they are exactly equal to the target and consider the overage waste or a throw + // away amount. However we do not consider values greater than value + cost_of_change. + // + // This effectively creates a range of possible solution where; + // range = (target, target + cost_of_change] + // + // That is, the range includes solutions that exactly equal the target up to but not + // including values greater than target + cost_of_change. + // + // if current_waste > best_waste, then backtrack. However, only backtrack if + // it's high fee_rate environment. During low fee environments, a utxo may + // have negative waste, therefore adding more utxos in such an environment + // may still result in reduced waste. + else if value > upper_bound || current_waste > best_waste && fee_rate > long_term_fee_rate + { + backtrack = true; + } + // * value meets or exceeds the target. + // Record the solution and the waste then continue. + else if value >= target { + backtrack = true; + + let v = value.to_signed().ok()?; + let t = target.to_signed().ok()?; + let waste: SignedAmount = v.checked_sub(t)?; + current_waste = current_waste.checked_add(waste)?; + + // Check if index_selection is better than the previous known best, and + // update best_selection accordingly. + if current_waste <= best_waste { + best_selection = Some(index_selection.clone()); + best_waste = current_waste; + } - let utxo_pool_length = utxo_pool.len(); - utxo_pool.sort_by_key(|u| Reverse(u.get_value())); + current_waste = current_waste.checked_sub(waste)?; + } - let mut curr_selection: Vec = vec![false; utxo_pool_length]; - let mut best_selection = None; - let mut remainder = utxo_sum; + // * Backtrack + if backtrack { + let last_index = index_selection.pop().unwrap(); + let (eff_value, utxo_waste, _) = w_utxos[last_index]; - let lower_bound = target; - let upper_bound = cost_of_change + lower_bound; + current_waste = current_waste.checked_sub(utxo_waste)?; + value = value.checked_sub(eff_value)?; + index -= 1; + assert_eq!(index, last_index); + } + // * Backtrack to new tree + else if backtrack_subtree { + // No new subtree left to explore. + if index_selection.is_empty() { + return index_to_utxo_list(best_selection, w_utxos); + } - if utxo_sum < lower_bound { - return None; - } + // Anchor the new subtree at the next available index. + // The next iteration, the index will be incremented by one. + index = index_selection[0]; - for m in 0..utxo_pool_length { - let mut curr_sum = 0; - let mut slice_remainder = remainder; + // Reset waste counter since we are starting a new search branch. + current_waste = SignedAmount::ZERO; - for n in m..utxo_pool_length { - if slice_remainder + curr_sum < lower_bound { - break; + // The available value of the next iteration. This should never overflow + // since the value is always less than the last available_value calculation. + available_value = w_utxos[index + 1..].iter().map(|&(v, _, _)| v).sum(); + + // If the new subtree does not have enough value, we are done searching. + if available_value < target { + return index_to_utxo_list(best_selection, w_utxos); } - let utxo_value = utxo_pool[n].get_value(); - curr_sum += utxo_value; - curr_selection[n] = true; + // Start a new selection and add the root of the new subtree to the index selection. + index_selection.clear(); + value = Amount::ZERO; + } + // * Add next node to the inclusion branch. + else { + let (eff_value, utxo_waste, _) = w_utxos[index]; + current_waste = current_waste.checked_add(utxo_waste)?; - if curr_sum >= lower_bound { - if curr_sum <= upper_bound { - best_selection = Some(curr_selection.clone()); - } + index_selection.push(index); - curr_selection[n] = false; - curr_sum -= utxo_value; - } + // unchecked add is used her for performance. since the sum of all utxo values + // did not overflow, then any positive subset of the sum will not overflow. + value = value.unchecked_add(eff_value); - slice_remainder -= utxo_value; + // unchecked sub is used her for performance. + // The bounds for available_value are at most the sum of utxos + // and at least zero. + available_value = available_value.unchecked_sub(eff_value); } - remainder -= utxo_pool[m].get_value(); - curr_selection[m] = false; + // no overflow is possible since the iteration count is bounded. + index += 1; + iteration += 1; } - best_selection + index_to_utxo_list(best_selection, w_utxos) +} + +//TODO this should return iter still and likewise the coin-selection algo. +fn index_to_utxo_list( + index_list: Option>, + effective_values: Vec<(Amount, SignedAmount, &WeightedUtxo)>, +) -> Option> { + index_list.map(|i_list| i_list.iter().map(|i: &usize| effective_values[*i].2).collect()) } #[cfg(test)] mod tests { - use crate::*; - use crate::branch_and_bound::find_solution; - - const ONE_BTC: u64 = 100000000; - const TWO_BTC: u64 = 2 * 100000000; - const THREE_BTC: u64 = 3 * 100000000; - const FOUR_BTC: u64 = 4 * 100000000; - - const UTXO_POOL: [MinimalUtxo; 4] = [ - MinimalUtxo { value: ONE_BTC }, - MinimalUtxo { value: TWO_BTC }, - MinimalUtxo { value: THREE_BTC }, - MinimalUtxo { value: FOUR_BTC }, - ]; - - const COST_OF_CHANGE: u64 = 50000000; + use super::*; + use crate::WeightedUtxo; + use bitcoin::Amount; + use bitcoin::ScriptBuf; + use bitcoin::SignedAmount; + use bitcoin::TxOut; + use bitcoin::Weight; + use core::str::FromStr; + + fn create_weighted_utxos(fee: Amount) -> Vec { + let amts = [ + Amount::from_str("1 cBTC").unwrap() + fee, + Amount::from_str("2 cBTC").unwrap() + fee, + Amount::from_str("3 cBTC").unwrap() + fee, + Amount::from_str("4 cBTC").unwrap() + fee, + ]; + + amts.iter() + .map(|amt| WeightedUtxo { + satisfaction_weight: Weight::ZERO, + utxo: TxOut { value: *amt, script_pubkey: ScriptBuf::new() }, + }) + .collect() + } - #[derive(Clone, Debug, Eq, PartialEq)] - struct MinimalUtxo { - value: u64, + #[test] + fn select_coins_bnb_one() { + let target = Amount::from_str("1 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].utxo.value, Amount::from_str("1 cBTC").unwrap()); } - impl Utxo for MinimalUtxo { - fn get_value(&self) -> u64 { - self.value - } + #[test] + fn select_coins_bnb_two() { + let target = Amount::from_str("2 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].utxo.value, Amount::from_str("2 cBTC").unwrap()); } #[test] - fn find_solution_1_btc() { - let utxo_match = find_solution(ONE_BTC, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![false, false, false, true]; - assert_eq!(expected_bool_vec, utxo_match); + + fn select_coins_bnb_three() { + let target = Amount::from_str("3 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[0].utxo.value, Amount::from_str("2 cBTC").unwrap()); + assert_eq!(list[1].utxo.value, Amount::from_str("1 cBTC").unwrap()); } #[test] - fn find_solution_2_btc() { - let utxo_match = find_solution(TWO_BTC, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![false, false, true, false]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_four() { + let target = Amount::from_str("4 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[0].utxo.value, Amount::from_str("3 cBTC").unwrap()); + assert_eq!(list[1].utxo.value, Amount::from_str("1 cBTC").unwrap()); } #[test] - fn find_solution_3_btc() { - let utxo_match = find_solution(THREE_BTC, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![false, false, true, true]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_five() { + let target = Amount::from_str("5 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[0].utxo.value, Amount::from_str("3 cBTC").unwrap()); + assert_eq!(list[1].utxo.value, Amount::from_str("2 cBTC").unwrap()); } #[test] - fn find_solution_4_btc() { - let utxo_match = find_solution(FOUR_BTC, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![false, true, false, true]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_six() { + let target = Amount::from_str("6 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 3); + assert_eq!(list[0].utxo.value, Amount::from_str("3 cBTC").unwrap()); + assert_eq!(list[1].utxo.value, Amount::from_str("2 cBTC").unwrap()); + assert_eq!(list[2].utxo.value, Amount::from_str("1 cBTC").unwrap()); } #[test] - fn find_solution_5_btc() { - let five_btc = FOUR_BTC + ONE_BTC; - let utxo_match = find_solution(five_btc, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![false, true, true, false]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_seven() { + let target = Amount::from_str("7 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 3); + assert_eq!(list[0].utxo.value, Amount::from_str("4 cBTC").unwrap()); + assert_eq!(list[1].utxo.value, Amount::from_str("2 cBTC").unwrap()); + assert_eq!(list[2].utxo.value, Amount::from_str("1 cBTC").unwrap()); } #[test] - fn find_solution_6_btc() { - let six_btc = FOUR_BTC + TWO_BTC; - let utxo_match = find_solution(six_btc, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![false, true, true, true]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_eight() { + let target = Amount::from_str("8 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 3); + assert_eq!(list[0].utxo.value, Amount::from_str("4 cBTC").unwrap()); + assert_eq!(list[1].utxo.value, Amount::from_str("3 cBTC").unwrap()); + assert_eq!(list[2].utxo.value, Amount::from_str("1 cBTC").unwrap()); } #[test] - fn find_solution_7_btc() { - let seven_btc = FOUR_BTC + THREE_BTC; - let utxo_match = find_solution(seven_btc, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![true, false, true, true]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_nine() { + let target = Amount::from_str("9 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 3); + assert_eq!(list[0].utxo.value, Amount::from_str("4 cBTC").unwrap()); + assert_eq!(list[1].utxo.value, Amount::from_str("3 cBTC").unwrap()); + assert_eq!(list[2].utxo.value, Amount::from_str("2 cBTC").unwrap()); } #[test] - fn find_solution_8_btc() { - let seven_btc = FOUR_BTC + THREE_BTC + ONE_BTC; - let utxo_match = find_solution(seven_btc, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![true, true, false, true]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_ten() { + let target = Amount::from_str("10 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert_eq!(list.len(), 4); + assert_eq!(list[0].utxo.value, Amount::from_str("4 cBTC").unwrap()); + assert_eq!(list[1].utxo.value, Amount::from_str("3 cBTC").unwrap()); + assert_eq!(list[2].utxo.value, Amount::from_str("2 cBTC").unwrap()); + assert_eq!(list[3].utxo.value, Amount::from_str("1 cBTC").unwrap()); } #[test] - fn find_solution_9_btc() { - let seven_btc = FOUR_BTC + THREE_BTC + TWO_BTC; - let utxo_match = find_solution(seven_btc, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![true, true, true, false]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_cost_of_change() { + let target = Amount::from_str("1 cBTC").unwrap(); + + // Since cost of change here is one, we accept any solution + // between 1 and 2. Range = (1, 2] + let cost_of_change = target; + + let weighted_utxos = vec![WeightedUtxo { + satisfaction_weight: Weight::ZERO, + utxo: TxOut { + value: Amount::from_str("1.5 cBTC").unwrap(), + script_pubkey: ScriptBuf::new(), + }, + }]; + + let mut wu = weighted_utxos.clone(); + + let list = select_coins_bnb(target, cost_of_change, FeeRate::ZERO, FeeRate::ZERO, &mut wu) + .unwrap(); + + assert_eq!(list.len(), 1); + assert_eq!(list[0].utxo.value, Amount::from_str("1.5 cBTC").unwrap()); + + let index_list = + select_coins_bnb(target, Amount::ZERO, FeeRate::ZERO, FeeRate::ZERO, &mut wu); + assert_eq!(index_list, None); } #[test] - fn find_solution_10_btc() { - let ten_btc = ONE_BTC + TWO_BTC + THREE_BTC + FOUR_BTC; - let utxo_match = find_solution(ten_btc, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![true, true, true, true]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_effective_value() { + let target = Amount::from_str("1 cBTC").unwrap(); + let fee_rate = FeeRate::from_sat_per_kwu(10); + let satisfaction_weight = Weight::from_wu(204); + + let weighted_utxos = vec![WeightedUtxo { + satisfaction_weight, + utxo: TxOut { + // This would be a match using value, however since effective_value is used + // the effective_value is calculated, this will fall short of the target. + value: Amount::from_str("1 cBTC").unwrap(), + script_pubkey: ScriptBuf::new(), + }, + }]; + + let mut wu = weighted_utxos.clone(); + let index_list = + select_coins_bnb(target, Amount::ZERO, fee_rate, fee_rate, &mut wu).unwrap(); + assert!(index_list.is_empty()); } #[test] - fn find_solution_11_btc_not_possible() { - let ten_btc = ONE_BTC + TWO_BTC + THREE_BTC + FOUR_BTC; - let utxo_match = find_solution(ten_btc + ONE_BTC, COST_OF_CHANGE, &mut UTXO_POOL.clone()); - assert_eq!(None, utxo_match); + fn select_coins_bnb_skip_effective_negative_effective_value() { + let target = Amount::from_str("1 cBTC").unwrap(); + let fee_rate = FeeRate::from_sat_per_kwu(10); + let satisfaction_weight = Weight::from_wu(204); + + // Since cost of change here is one, we accept any solution + // between 1 and 2. Range = (1, 2] + let cost_of_change = target; + + let weighted_utxos = vec![ + WeightedUtxo { + satisfaction_weight: Weight::ZERO, + utxo: TxOut { + value: Amount::from_str("1.5 cBTC").unwrap(), + script_pubkey: ScriptBuf::new(), + }, + }, + WeightedUtxo { + satisfaction_weight, + utxo: TxOut { + // If this had no fee, a 1 sat utxo would be included since + // there would be less waste. However, since there is a weight + // and fee to spend it, the effective value is negative, so + // it will not be included. + value: Amount::from_str("1 sat").unwrap(), + script_pubkey: ScriptBuf::new(), + }, + }, + ]; + + let mut wu = weighted_utxos.clone(); + let list = select_coins_bnb(target, cost_of_change, fee_rate, fee_rate, &mut wu).unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].utxo.value, Amount::from_str("1.5 cBTC").unwrap()); } #[test] - fn find_solution_with_large_cost_of_change() { - let utxo_match = - find_solution(ONE_BTC * 9 / 10, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); - let expected_bool_vec = vec![false, false, false, true]; - assert_eq!(expected_bool_vec, utxo_match); + fn select_coins_bnb_target_greater_than_value() { + let target = Amount::from_str("11 cBTC").unwrap(); + let mut weighted_utxos = create_weighted_utxos(Amount::ZERO); + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ) + .unwrap(); + assert!(list.is_empty()); } #[test] - fn find_solution_with_no_cost_of_change() { - let utxo_match = find_solution(ONE_BTC * 9 / 10, 0, &mut UTXO_POOL.clone()); - assert_eq!(None, utxo_match); + fn select_coins_bnb_consume_more_inputs_when_cheap() { + let target = Amount::from_str("6 cBTC").unwrap(); + let fee = Amount::from_str("2 sats").unwrap(); + let mut weighted_utxos = create_weighted_utxos(fee); + + let fee_rate = FeeRate::from_sat_per_kwu(10); + let lt_fee_rate = FeeRate::from_sat_per_kwu(20); + + // the possible combinations are 2,4 or 1,2,3 + // fees are cheap, so use 1,2,3 + let list = + select_coins_bnb(target, Amount::ZERO, fee_rate, lt_fee_rate, &mut weighted_utxos) + .unwrap(); + assert_eq!(list.len(), 3); + assert_eq!(list[0].utxo.value, Amount::from_str("3 cBTC").unwrap() + fee); + assert_eq!(list[1].utxo.value, Amount::from_str("2 cBTC").unwrap() + fee); + assert_eq!(list[2].utxo.value, Amount::from_str("1 cBTC").unwrap() + fee); } #[test] - fn find_solution_with_not_input_fee() { - let utxo_match = find_solution(ONE_BTC + 1, COST_OF_CHANGE, &mut UTXO_POOL.clone()); - assert_eq!(None, utxo_match); + fn select_coins_bnb_consume_less_inputs_when_expensive() { + let target = Amount::from_str("6 cBTC").unwrap(); + let fee = Amount::from_str("4 sats").unwrap(); + let mut weighted_utxos = create_weighted_utxos(fee); + + let fee_rate = FeeRate::from_sat_per_kwu(20); + let lt_fee_rate = FeeRate::from_sat_per_kwu(10); + + // the possible combinations are 2,4 or 1,2,3 + // fees are expensive, so use 2,4 + let list = + select_coins_bnb(target, Amount::ZERO, fee_rate, lt_fee_rate, &mut weighted_utxos) + .unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[0].utxo.value, Amount::from_str("4 cBTC").unwrap() + fee); + assert_eq!(list[1].utxo.value, Amount::from_str("2 cBTC").unwrap() + fee); } #[test] - fn select_coins_bnb_with_match() { - select_coins_bnb(ONE_BTC, COST_OF_CHANGE, &mut UTXO_POOL.clone()).unwrap(); + fn select_coins_bnb_utxo_pool_sum_overflow() { + let target = Amount::from_str("1 cBTC").unwrap(); + let satisfaction_weight = Weight::from_wu(204); + let value = SignedAmount::MAX.to_unsigned().unwrap(); + let mut weighted_utxos = vec![ + WeightedUtxo { + satisfaction_weight, + utxo: TxOut { value, script_pubkey: ScriptBuf::new() }, + }, + WeightedUtxo { + satisfaction_weight, + utxo: TxOut { value, script_pubkey: ScriptBuf::new() }, + }, + ]; + let list = select_coins_bnb( + target, + Amount::ZERO, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ); + assert!(list.is_none()); } #[test] - fn select_coins_bnb_with_no_match() { - let utxo_match = select_coins_bnb(1, COST_OF_CHANGE, &mut UTXO_POOL.clone()); - assert_eq!(None, utxo_match); + fn select_coins_bnb_upper_bound_overflow() { + // the upper_bound is target + cost_of_change. + // adding these two together returns NONE on overflow. + let target = Amount::MAX; + let cost_of_change = Amount::MAX; + + let satisfaction_weight = Weight::from_wu(204); + let mut weighted_utxos = vec![WeightedUtxo { + satisfaction_weight, + utxo: TxOut { value: target, script_pubkey: ScriptBuf::new() }, + }]; + + let list = select_coins_bnb( + target, + cost_of_change, + FeeRate::ZERO, + FeeRate::ZERO, + &mut weighted_utxos, + ); + assert!(list.is_none()); } } diff --git a/src/lib.rs b/src/lib.rs index 731ca92..ed2076c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,11 +21,13 @@ mod single_random_draw; use bitcoin::Amount; use bitcoin::FeeRate; +use bitcoin::SignedAmount; use bitcoin::TxOut; use bitcoin::Weight; use crate::branch_and_bound::select_coins_bnb; use crate::single_random_draw::select_coins_srd; +use bitcoin::blockdata::transaction::TxIn; use rand::thread_rng; /// Trait that a UTXO struct must implement to be used as part of the coin selection @@ -43,6 +45,7 @@ const CHANGE_LOWER: Amount = Amount::from_sat(50_000); /// The idea of using a WeightUtxo type was inspired by the BDK implementation: /// #[derive(Clone, Debug, PartialEq)] +// note, change this to private? No good reason to be public. pub struct WeightedUtxo { /// The satisfaction_weight is the size of the required params to satisfy the UTXO. pub satisfaction_weight: Weight, @@ -50,6 +53,24 @@ pub struct WeightedUtxo { pub utxo: TxOut, } +impl WeightedUtxo { + fn effective_value(&self, fee_rate: FeeRate) -> Option { + let signed_input_fee = self.calculate_fee(fee_rate)?.to_signed().ok()?; + self.utxo.value.to_signed().ok()?.checked_sub(signed_input_fee) + } + + fn calculate_fee(&self, fee_rate: FeeRate) -> Option { + let weight = self.satisfaction_weight.checked_add(TxIn::BASE_WEIGHT)?; + fee_rate.checked_mul_by_weight(weight) + } + + fn waste(&self, fee_rate: FeeRate, long_term_fee_rate: FeeRate) -> Option { + let fee: SignedAmount = self.calculate_fee(fee_rate)?.to_signed().ok()?; + let lt_fee: SignedAmount = self.calculate_fee(long_term_fee_rate)?.to_signed().ok()?; + fee.checked_sub(lt_fee) + } +} + /// Select coins first using BnB algorithm similar to what is done in bitcoin /// core see: , /// and falls back on a random UTXO selection. Returns none if the target cannot @@ -59,13 +80,16 @@ pub struct WeightedUtxo { #[cfg_attr(docsrs, doc(cfg(feature = "rand")))] pub fn select_coins( target: Amount, - cost_of_change: u64, + cost_of_change: Amount, fee_rate: FeeRate, + long_term_fee_rate: FeeRate, weighted_utxos: &mut [WeightedUtxo], - utxo_pool: &mut [T], ) -> Option> { - match select_coins_bnb(target.to_sat(), cost_of_change, utxo_pool) { - Some(_res) => Some(Vec::new()), - None => select_coins_srd(target, fee_rate, weighted_utxos, &mut thread_rng()), + if let Some(coins) = + select_coins_bnb(target, cost_of_change, fee_rate, long_term_fee_rate, weighted_utxos) + { + Some(coins.into_iter().cloned().collect()) + } else { + select_coins_srd(target, fee_rate, weighted_utxos, &mut thread_rng()) } }