Bitcoin Core  21.99.0
P2P Digital Currency
coinselection.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <wallet/coinselection.h>
6 
7 #include <policy/feerate.h>
8 #include <util/system.h>
9 #include <util/moneystr.h>
10 
11 #include <optional>
12 
13 // Descending order comparator
14 struct {
15  bool operator()(const OutputGroup& a, const OutputGroup& b) const
16  {
17  return a.effective_value > b.effective_value;
18  }
19 } descending;
20 
21 /*
22  * This is the Branch and Bound Coin Selection algorithm designed by Murch. It searches for an input
23  * set that can pay for the spending target and does not exceed the spending target by more than the
24  * cost of creating and spending a change output. The algorithm uses a depth-first search on a binary
25  * tree. In the binary tree, each node corresponds to the inclusion or the omission of a UTXO. UTXOs
26  * are sorted by their effective values and the trees is explored deterministically per the inclusion
27  * branch first. At each node, the algorithm checks whether the selection is within the target range.
28  * While the selection has not reached the target range, more UTXOs are included. When a selection's
29  * value exceeds the target range, the complete subtree deriving from this selection can be omitted.
30  * At that point, the last included UTXO is deselected and the corresponding omission branch explored
31  * instead. The search ends after the complete tree has been searched or after a limited number of tries.
32  *
33  * The search continues to search for better solutions after one solution has been found. The best
34  * solution is chosen by minimizing the waste metric. The waste metric is defined as the cost to
35  * spend the current inputs at the given fee rate minus the long term expected cost to spend the
36  * inputs, plus the amount the selection exceeds the spending target:
37  *
38  * waste = selectionTotal - target + inputs × (currentFeeRate - longTermFeeRate)
39  *
40  * The algorithm uses two additional optimizations. A lookahead keeps track of the total value of
41  * the unexplored UTXOs. A subtree is not explored if the lookahead indicates that the target range
42  * cannot be reached. Further, it is unnecessary to test equivalent combinations. This allows us
43  * to skip testing the inclusion of UTXOs that match the effective value and waste of an omitted
44  * predecessor.
45  *
46  * The Branch and Bound algorithm is described in detail in Murch's Master Thesis:
47  * https://murch.one/wp-content/uploads/2016/11/erhardt2016coinselection.pdf
48  *
49  * @param const std::vector<CInputCoin>& utxo_pool The set of UTXOs that we are choosing from.
50  * These UTXOs will be sorted in descending order by effective value and the CInputCoins'
51  * values are their effective values.
52  * @param const CAmount& target_value This is the value that we want to select. It is the lower
53  * bound of the range.
54  * @param const CAmount& cost_of_change This is the cost of creating and spending a change output.
55  * This plus target_value is the upper bound of the range.
56  * @param std::set<CInputCoin>& out_set -> This is an output parameter for the set of CInputCoins
57  * that have been selected.
58  * @param CAmount& value_ret -> This is an output parameter for the total value of the CInputCoins
59  * that were selected.
60  * @param CAmount not_input_fees -> The fees that need to be paid for the outputs and fixed size
61  * overhead (version, locktime, marker and flag)
62  */
63 
64 static const size_t TOTAL_TRIES = 100000;
65 
66 bool SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees)
67 {
68  out_set.clear();
69  CAmount curr_value = 0;
70 
71  std::vector<bool> curr_selection; // select the utxo at this index
72  curr_selection.reserve(utxo_pool.size());
73  CAmount actual_target = not_input_fees + target_value;
74 
75  // Calculate curr_available_value
76  CAmount curr_available_value = 0;
77  for (const OutputGroup& utxo : utxo_pool) {
78  // Assert that this utxo is not negative. It should never be negative, effective value calculation should have removed it
79  assert(utxo.effective_value > 0);
80  curr_available_value += utxo.effective_value;
81  }
82  if (curr_available_value < actual_target) {
83  return false;
84  }
85 
86  // Sort the utxo_pool
87  std::sort(utxo_pool.begin(), utxo_pool.end(), descending);
88 
89  CAmount curr_waste = 0;
90  std::vector<bool> best_selection;
91  CAmount best_waste = MAX_MONEY;
92 
93  // Depth First search loop for choosing the UTXOs
94  for (size_t i = 0; i < TOTAL_TRIES; ++i) {
95  // Conditions for starting a backtrack
96  bool backtrack = false;
97  if (curr_value + curr_available_value < actual_target || // Cannot possibly reach target with the amount remaining in the curr_available_value.
98  curr_value > actual_target + cost_of_change || // Selected value is out of range, go back and try other branch
99  (curr_waste > best_waste && (utxo_pool.at(0).fee - utxo_pool.at(0).long_term_fee) > 0)) { // Don't select things which we know will be more wasteful if the waste is increasing
100  backtrack = true;
101  } else if (curr_value >= actual_target) { // Selected value is within range
102  curr_waste += (curr_value - actual_target); // This is the excess value which is added to the waste for the below comparison
103  // Adding another UTXO after this check could bring the waste down if the long term fee is higher than the current fee.
104  // However we are not going to explore that because this optimization for the waste is only done when we have hit our target
105  // value. Adding any more UTXOs will be just burning the UTXO; it will go entirely to fees. Thus we aren't going to
106  // explore any more UTXOs to avoid burning money like that.
107  if (curr_waste <= best_waste) {
108  best_selection = curr_selection;
109  best_selection.resize(utxo_pool.size());
110  best_waste = curr_waste;
111  if (best_waste == 0) {
112  break;
113  }
114  }
115  curr_waste -= (curr_value - actual_target); // Remove the excess value as we will be selecting different coins now
116  backtrack = true;
117  }
118 
119  // Backtracking, moving backwards
120  if (backtrack) {
121  // Walk backwards to find the last included UTXO that still needs to have its omission branch traversed.
122  while (!curr_selection.empty() && !curr_selection.back()) {
123  curr_selection.pop_back();
124  curr_available_value += utxo_pool.at(curr_selection.size()).effective_value;
125  }
126 
127  if (curr_selection.empty()) { // We have walked back to the first utxo and no branch is untraversed. All solutions searched
128  break;
129  }
130 
131  // Output was included on previous iterations, try excluding now.
132  curr_selection.back() = false;
133  OutputGroup& utxo = utxo_pool.at(curr_selection.size() - 1);
134  curr_value -= utxo.effective_value;
135  curr_waste -= utxo.fee - utxo.long_term_fee;
136  } else { // Moving forwards, continuing down this branch
137  OutputGroup& utxo = utxo_pool.at(curr_selection.size());
138 
139  // Remove this utxo from the curr_available_value utxo amount
140  curr_available_value -= utxo.effective_value;
141 
142  // Avoid searching a branch if the previous UTXO has the same value and same waste and was excluded. Since the ratio of fee to
143  // long term fee is the same, we only need to check if one of those values match in order to know that the waste is the same.
144  if (!curr_selection.empty() && !curr_selection.back() &&
145  utxo.effective_value == utxo_pool.at(curr_selection.size() - 1).effective_value &&
146  utxo.fee == utxo_pool.at(curr_selection.size() - 1).fee) {
147  curr_selection.push_back(false);
148  } else {
149  // Inclusion branch first (Largest First Exploration)
150  curr_selection.push_back(true);
151  curr_value += utxo.effective_value;
152  curr_waste += utxo.fee - utxo.long_term_fee;
153  }
154  }
155  }
156 
157  // Check for solution
158  if (best_selection.empty()) {
159  return false;
160  }
161 
162  // Set output set
163  value_ret = 0;
164  for (size_t i = 0; i < best_selection.size(); ++i) {
165  if (best_selection.at(i)) {
166  util::insert(out_set, utxo_pool.at(i).m_outputs);
167  value_ret += utxo_pool.at(i).m_value;
168  }
169  }
170 
171  return true;
172 }
173 
174 static void ApproximateBestSubset(const std::vector<OutputGroup>& groups, const CAmount& nTotalLower, const CAmount& nTargetValue,
175  std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
176 {
177  std::vector<char> vfIncluded;
178 
179  vfBest.assign(groups.size(), true);
180  nBest = nTotalLower;
181 
182  FastRandomContext insecure_rand;
183 
184  for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
185  {
186  vfIncluded.assign(groups.size(), false);
187  CAmount nTotal = 0;
188  bool fReachedTarget = false;
189  for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
190  {
191  for (unsigned int i = 0; i < groups.size(); i++)
192  {
193  //The solver here uses a randomized algorithm,
194  //the randomness serves no real security purpose but is just
195  //needed to prevent degenerate behavior and it is important
196  //that the rng is fast. We do not use a constant random sequence,
197  //because there may be some privacy improvement by making
198  //the selection random.
199  if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
200  {
201  nTotal += groups[i].m_value;
202  vfIncluded[i] = true;
203  if (nTotal >= nTargetValue)
204  {
205  fReachedTarget = true;
206  if (nTotal < nBest)
207  {
208  nBest = nTotal;
209  vfBest = vfIncluded;
210  }
211  nTotal -= groups[i].m_value;
212  vfIncluded[i] = false;
213  }
214  }
215  }
216  }
217  }
218 }
219 
220 bool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet)
221 {
222  setCoinsRet.clear();
223  nValueRet = 0;
224 
225  // List of values less than target
226  std::optional<OutputGroup> lowest_larger;
227  std::vector<OutputGroup> applicable_groups;
228  CAmount nTotalLower = 0;
229 
230  Shuffle(groups.begin(), groups.end(), FastRandomContext());
231 
232  for (const OutputGroup& group : groups) {
233  if (group.m_value == nTargetValue) {
234  util::insert(setCoinsRet, group.m_outputs);
235  nValueRet += group.m_value;
236  return true;
237  } else if (group.m_value < nTargetValue + MIN_CHANGE) {
238  applicable_groups.push_back(group);
239  nTotalLower += group.m_value;
240  } else if (!lowest_larger || group.m_value < lowest_larger->m_value) {
241  lowest_larger = group;
242  }
243  }
244 
245  if (nTotalLower == nTargetValue) {
246  for (const auto& group : applicable_groups) {
247  util::insert(setCoinsRet, group.m_outputs);
248  nValueRet += group.m_value;
249  }
250  return true;
251  }
252 
253  if (nTotalLower < nTargetValue) {
254  if (!lowest_larger) return false;
255  util::insert(setCoinsRet, lowest_larger->m_outputs);
256  nValueRet += lowest_larger->m_value;
257  return true;
258  }
259 
260  // Solve subset sum by stochastic approximation
261  std::sort(applicable_groups.begin(), applicable_groups.end(), descending);
262  std::vector<char> vfBest;
263  CAmount nBest;
264 
265  ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue, vfBest, nBest);
266  if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE) {
267  ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
268  }
269 
270  // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
271  // or the next bigger coin is closer), return the bigger coin
272  if (lowest_larger &&
273  ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || lowest_larger->m_value <= nBest)) {
274  util::insert(setCoinsRet, lowest_larger->m_outputs);
275  nValueRet += lowest_larger->m_value;
276  } else {
277  for (unsigned int i = 0; i < applicable_groups.size(); i++) {
278  if (vfBest[i]) {
279  util::insert(setCoinsRet, applicable_groups[i].m_outputs);
280  nValueRet += applicable_groups[i].m_value;
281  }
282  }
283 
285  LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: "); /* Continued */
286  for (unsigned int i = 0; i < applicable_groups.size(); i++) {
287  if (vfBest[i]) {
288  LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(applicable_groups[i].m_value)); /* Continued */
289  }
290  }
291  LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
292  }
293  }
294 
295  return true;
296 }
297 
298 /******************************************************************************
299 
300  OutputGroup
301 
302  ******************************************************************************/
303 
304 void OutputGroup::Insert(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants, bool positive_only) {
305  // Compute the effective value first
306  const CAmount coin_fee = output.m_input_bytes < 0 ? 0 : m_effective_feerate.GetFee(output.m_input_bytes);
307  const CAmount ev = output.txout.nValue - coin_fee;
308 
309  // Filter for positive only here before adding the coin
310  if (positive_only && ev <= 0) return;
311 
312  m_outputs.push_back(output);
313  CInputCoin& coin = m_outputs.back();
314 
315  coin.m_fee = coin_fee;
316  fee += coin.m_fee;
317 
320 
321  coin.effective_value = ev;
323 
324  m_from_me &= from_me;
325  m_value += output.txout.nValue;
326  m_depth = std::min(m_depth, depth);
327  // ancestors here express the number of ancestors the new coin will end up having, which is
328  // the sum, rather than the max; this will overestimate in the cases where multiple inputs
329  // have common ancestors
330  m_ancestors += ancestors;
331  // descendants is the count as seen from the top ancestor, not the descendants as seen from the
332  // coin itself; thus, this value is counted as the max, not the sum
333  m_descendants = std::max(m_descendants, descendants);
334 }
335 
336 bool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const
337 {
338  return m_depth >= (m_from_me ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs)
339  && m_ancestors <= eligibility_filter.max_ancestors
340  && m_descendants <= eligibility_filter.max_descendants;
341 }
OutputGroup::Insert
void Insert(const CInputCoin &output, int depth, bool from_me, size_t ancestors, size_t descendants, bool positive_only)
Definition: coinselection.cpp:304
OutputGroup::m_depth
int m_depth
Definition: coinselection.h:77
feerate.h
CFeeRate::GetFee
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:21
CoinEligibilityFilter::max_descendants
const uint64_t max_descendants
Definition: coinselection.h:64
MIN_CHANGE
static constexpr CAmount MIN_CHANGE
target minimum change amount
Definition: coinselection.h:14
OutputGroup
Definition: coinselection.h:72
moneystr.h
CoinEligibilityFilter::conf_theirs
const int conf_theirs
Definition: coinselection.h:62
FastRandomContext::randbool
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:211
OutputGroup::m_long_term_feerate
CFeeRate m_long_term_feerate
Definition: coinselection.h:84
CoinEligibilityFilter::max_ancestors
const uint64_t max_ancestors
Definition: coinselection.h:63
OutputGroup::effective_value
CAmount effective_value
Definition: coinselection.h:80
CInputCoin::effective_value
CAmount effective_value
Definition: coinselection.h:39
CInputCoin::m_fee
CAmount m_fee
Definition: coinselection.h:40
CoinEligibilityFilter
Definition: coinselection.h:59
SelectCoinsBnB
bool SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &target_value, const CAmount &cost_of_change, std::set< CInputCoin > &out_set, CAmount &value_ret, CAmount not_input_fees)
Definition: coinselection.cpp:66
OutputGroup::m_outputs
std::vector< CInputCoin > m_outputs
Definition: coinselection.h:74
ApproximateBestSubset
static void ApproximateBestSubset(const std::vector< OutputGroup > &groups, const CAmount &nTotalLower, const CAmount &nTargetValue, std::vector< char > &vfBest, CAmount &nBest, int iterations=1000)
Definition: coinselection.cpp:174
OutputGroup::m_effective_feerate
CFeeRate m_effective_feerate
Definition: coinselection.h:82
CTxOut::nValue
CAmount nValue
Definition: transaction.h:131
coinselection.h
OutputGroup::long_term_fee
CAmount long_term_fee
Definition: coinselection.h:83
TOTAL_TRIES
static const size_t TOTAL_TRIES
Definition: coinselection.cpp:64
CInputCoin::txout
CTxOut txout
Definition: coinselection.h:38
OutputGroup::m_value
CAmount m_value
Definition: coinselection.h:76
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
KnapsackSolver
bool KnapsackSolver(const CAmount &nTargetValue, std::vector< OutputGroup > &groups, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet)
Definition: coinselection.cpp:220
CInputCoin::m_input_bytes
int m_input_bytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: coinselection.h:44
Shuffle
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:231
LogPrint
#define LogPrint(category,...)
Definition: logging.h:187
OutputGroup::fee
CAmount fee
Definition: coinselection.h:81
CInputCoin
Definition: coinselection.h:18
system.h
LogAcceptCategory
static bool LogAcceptCategory(BCLog::LogFlags category)
Return true if log accepts specified category.
Definition: logging.h:156
CoinEligibilityFilter::conf_mine
const int conf_mine
Definition: coinselection.h:61
util::insert
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
Definition: system.h:516
MAX_MONEY
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:25
BCLog::SELECTCOINS
@ SELECTCOINS
Definition: logging.h:48
OutputGroup::m_from_me
bool m_from_me
Definition: coinselection.h:75
OutputGroup::m_descendants
size_t m_descendants
Definition: coinselection.h:79
descending
struct @15 descending
OutputGroup::m_ancestors
size_t m_ancestors
Definition: coinselection.h:78
assert
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
CInputCoin::m_long_term_fee
CAmount m_long_term_fee
Definition: coinselection.h:41
FastRandomContext
Fast randomness source.
Definition: random.h:119
OutputGroup::EligibleForSpending
bool EligibleForSpending(const CoinEligibilityFilter &eligibility_filter) const
Definition: coinselection.cpp:336
FormatMoney
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:12