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