|
| 1 | +use bdk_coin_select::metrics::{Changeless, LowestFee}; |
| 2 | +use bdk_coin_select::{ |
| 3 | + Candidate as BdkCandidate, ChangePolicy, CoinSelector, DrainWeights, FeeRate, |
| 4 | + Target as BdkTarget, TargetFee, TargetOutputs, |
| 5 | +}; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | + |
| 8 | +use crate::WalletError; |
| 9 | + |
| 10 | +/// Candidate input for wallet coin selection. |
| 11 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 12 | +pub struct Candidate { |
| 13 | + /// Candidate value in satoshis. |
| 14 | + pub value: u64, |
| 15 | + /// Estimated satisfaction weight in weight units. |
| 16 | + pub satisfaction_weight: u64, |
| 17 | + /// Whether spending this candidate uses segwit witness data. |
| 18 | + pub is_segwit: bool, |
| 19 | +} |
| 20 | + |
| 21 | +impl Candidate { |
| 22 | + /// Converts into the upstream selector candidate type. |
| 23 | + #[must_use] |
| 24 | + pub fn to_bdk(self) -> BdkCandidate { |
| 25 | + BdkCandidate::new(self.value, self.satisfaction_weight, self.is_segwit) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +/// Funding target for coin selection. |
| 30 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 31 | +pub struct Target { |
| 32 | + /// Output value that must be funded. |
| 33 | + pub value: u64, |
| 34 | + /// Minimum absolute fee in satoshis. |
| 35 | + pub minimum_fee: u64, |
| 36 | + /// Target feerate for input-weight-aware selection. |
| 37 | + pub fee_rate: FeeRate, |
| 38 | +} |
| 39 | + |
| 40 | +impl Target { |
| 41 | + /// Creates a target from value, minimum fee, and feerate. |
| 42 | + #[must_use] |
| 43 | + pub const fn new(value: u64, minimum_fee: u64, fee_rate: FeeRate) -> Self { |
| 44 | + Self { |
| 45 | + value, |
| 46 | + minimum_fee, |
| 47 | + fee_rate, |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + fn to_bdk(self) -> Result<BdkTarget, WalletError> { |
| 52 | + let value_sum = self |
| 53 | + .value |
| 54 | + .checked_add(self.minimum_fee) |
| 55 | + .ok_or_else(|| WalletError::Psbt("target value overflow".to_owned()))?; |
| 56 | + Ok(BdkTarget { |
| 57 | + fee: TargetFee::from_feerate(self.fee_rate), |
| 58 | + outputs: TargetOutputs { |
| 59 | + value_sum, |
| 60 | + weight_sum: 0, |
| 61 | + n_outputs: 1, |
| 62 | + }, |
| 63 | + }) |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +/// Coin selection strategy. |
| 68 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 69 | +pub enum SelectStrategy { |
| 70 | + /// Branch-and-bound changeless-first selection. |
| 71 | + BnB, |
| 72 | + /// Greedy knapsack-style selection. |
| 73 | + Knapsack, |
| 74 | + /// Waste metric selection using long-term feerate accounting. |
| 75 | + WasteMetric, |
| 76 | +} |
| 77 | + |
| 78 | +/// Selected input set. |
| 79 | +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 80 | +pub struct Selection { |
| 81 | + /// Indices selected from the candidate slice. |
| 82 | + pub selected_indices: Vec<usize>, |
| 83 | + /// Sum of selected candidate values. |
| 84 | + pub selected_value: u64, |
| 85 | + /// Fee implied by selected value minus target output value. |
| 86 | + pub fee: u64, |
| 87 | +} |
| 88 | + |
| 89 | +/// Selects coins with the requested strategy. |
| 90 | +pub fn select_coins( |
| 91 | + target: &Target, |
| 92 | + candidates: &[Candidate], |
| 93 | + strategy: SelectStrategy, |
| 94 | +) -> Result<Selection, WalletError> { |
| 95 | + let bdk_candidates: Vec<BdkCandidate> = |
| 96 | + candidates.iter().copied().map(Candidate::to_bdk).collect(); |
| 97 | + let bdk_target = target.to_bdk()?; |
| 98 | + let mut selector = CoinSelector::new(&bdk_candidates); |
| 99 | + |
| 100 | + match strategy { |
| 101 | + SelectStrategy::BnB => select_bnb(&mut selector, bdk_target)?, |
| 102 | + SelectStrategy::Knapsack => select_knapsack(&mut selector, bdk_target)?, |
| 103 | + SelectStrategy::WasteMetric => select_waste(&mut selector, bdk_target)?, |
| 104 | + } |
| 105 | + |
| 106 | + to_selection(&selector, target) |
| 107 | +} |
| 108 | + |
| 109 | +fn select_bnb(selector: &mut CoinSelector<'_>, target: BdkTarget) -> Result<(), WalletError> { |
| 110 | + let change_policy = ChangePolicy::min_value(DrainWeights::TR_KEYSPEND, 0); |
| 111 | + selector.sort_candidates_by_descending_value_pwu(); |
| 112 | + let metric = Changeless { |
| 113 | + target, |
| 114 | + change_policy, |
| 115 | + }; |
| 116 | + if selector.run_bnb(metric, 100_000).is_ok() { |
| 117 | + return Ok(()); |
| 118 | + } |
| 119 | + selector |
| 120 | + .select_until_target_met(target) |
| 121 | + .map_err(|error| WalletError::InsufficientFunds { |
| 122 | + missing: error.missing, |
| 123 | + }) |
| 124 | +} |
| 125 | + |
| 126 | +fn select_knapsack(selector: &mut CoinSelector<'_>, target: BdkTarget) -> Result<(), WalletError> { |
| 127 | + selector.sort_candidates_by_key(|(_index, candidate)| core::cmp::Reverse(candidate.value)); |
| 128 | + selector |
| 129 | + .select_until_target_met(target) |
| 130 | + .map_err(|error| WalletError::InsufficientFunds { |
| 131 | + missing: error.missing, |
| 132 | + }) |
| 133 | +} |
| 134 | + |
| 135 | +fn select_waste(selector: &mut CoinSelector<'_>, target: BdkTarget) -> Result<(), WalletError> { |
| 136 | + selector.sort_candidates_by_descending_value_pwu(); |
| 137 | + let change_policy = ChangePolicy::min_value_and_waste( |
| 138 | + DrainWeights::TR_KEYSPEND, |
| 139 | + 0, |
| 140 | + target.fee.rate, |
| 141 | + FeeRate::DEFAULT_MIN_RELAY, |
| 142 | + ); |
| 143 | + let metric = LowestFee { |
| 144 | + target, |
| 145 | + long_term_feerate: FeeRate::DEFAULT_MIN_RELAY, |
| 146 | + change_policy, |
| 147 | + }; |
| 148 | + if let Err(error) = selector.run_bnb(metric, 100_000) { |
| 149 | + selector.select_until_target_met(target).map_err(|funds| { |
| 150 | + WalletError::InsufficientFunds { |
| 151 | + missing: funds.missing, |
| 152 | + } |
| 153 | + })?; |
| 154 | + if !selector.is_target_met(target) { |
| 155 | + return Err(WalletError::NoBnbSolution { |
| 156 | + rounds: error.rounds, |
| 157 | + max_rounds: error.max_rounds, |
| 158 | + }); |
| 159 | + } |
| 160 | + } |
| 161 | + Ok(()) |
| 162 | +} |
| 163 | + |
| 164 | +fn to_selection(selector: &CoinSelector<'_>, target: &Target) -> Result<Selection, WalletError> { |
| 165 | + let selected_value = selector.selected_value(); |
| 166 | + let target_with_fee = target |
| 167 | + .value |
| 168 | + .checked_add(target.minimum_fee) |
| 169 | + .ok_or_else(|| WalletError::Psbt("target value overflow".to_owned()))?; |
| 170 | + if selected_value < target_with_fee { |
| 171 | + return Err(WalletError::InsufficientFunds { |
| 172 | + missing: target_with_fee - selected_value, |
| 173 | + }); |
| 174 | + } |
| 175 | + Ok(Selection { |
| 176 | + selected_indices: selector.selected_indices().iter().copied().collect(), |
| 177 | + selected_value, |
| 178 | + fee: selected_value - target.value, |
| 179 | + }) |
| 180 | +} |
0 commit comments