Bitcoin Core  0.20.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  if (best_waste == 0) {
110  break;
111  }
112  }
113  curr_waste -= (curr_value - actual_target); // Remove the excess value as we will be selecting different coins now
114  backtrack = true;
115  }
116 
117  // Backtracking, moving backwards
118  if (backtrack) {
119  // Walk backwards to find the last included UTXO that still needs to have its omission branch traversed.
120  while (!curr_selection.empty() && !curr_selection.back()) {
121  curr_selection.pop_back();
122  curr_available_value += utxo_pool.at(curr_selection.size()).effective_value;
123  }
124 
125  if (curr_selection.empty()) { // We have walked back to the first utxo and no branch is untraversed. All solutions searched
126  break;
127  }
128 
129  // Output was included on previous iterations, try excluding now.
130  curr_selection.back() = false;
131  OutputGroup& utxo = utxo_pool.at(curr_selection.size() - 1);
132  curr_value -= utxo.effective_value;
133  curr_waste -= utxo.fee - utxo.long_term_fee;
134  } else { // Moving forwards, continuing down this branch
135  OutputGroup& utxo = utxo_pool.at(curr_selection.size());
136 
137  // Remove this utxo from the curr_available_value utxo amount
138  curr_available_value -= utxo.effective_value;
139 
140  // Avoid searching a branch if the previous UTXO has the same value and same waste and was excluded. Since the ratio of fee to
141  // 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.
142  if (!curr_selection.empty() && !curr_selection.back() &&
143  utxo.effective_value == utxo_pool.at(curr_selection.size() - 1).effective_value &&
144  utxo.fee == utxo_pool.at(curr_selection.size() - 1).fee) {
145  curr_selection.push_back(false);
146  } else {
147  // Inclusion branch first (Largest First Exploration)
148  curr_selection.push_back(true);
149  curr_value += utxo.effective_value;
150  curr_waste += utxo.fee - utxo.long_term_fee;
151  }
152  }
153  }
154 
155  // Check for solution
156  if (best_selection.empty()) {
157  return false;
158  }
159 
160  // Set output set
161  value_ret = 0;
162  for (size_t i = 0; i < best_selection.size(); ++i) {
163  if (best_selection.at(i)) {
164  util::insert(out_set, utxo_pool.at(i).m_outputs);
165  value_ret += utxo_pool.at(i).m_value;
166  }
167  }
168 
169  return true;
170 }
171 
172 static void ApproximateBestSubset(const std::vector<OutputGroup>& groups, const CAmount& nTotalLower, const CAmount& nTargetValue,
173  std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
174 {
175  std::vector<char> vfIncluded;
176 
177  vfBest.assign(groups.size(), true);
178  nBest = nTotalLower;
179 
180  FastRandomContext insecure_rand;
181 
182  for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
183  {
184  vfIncluded.assign(groups.size(), false);
185  CAmount nTotal = 0;
186  bool fReachedTarget = false;
187  for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
188  {
189  for (unsigned int i = 0; i < groups.size(); i++)
190  {
191  //The solver here uses a randomized algorithm,
192  //the randomness serves no real security purpose but is just
193  //needed to prevent degenerate behavior and it is important
194  //that the rng is fast. We do not use a constant random sequence,
195  //because there may be some privacy improvement by making
196  //the selection random.
197  if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
198  {
199  nTotal += groups[i].m_value;
200  vfIncluded[i] = true;
201  if (nTotal >= nTargetValue)
202  {
203  fReachedTarget = true;
204  if (nTotal < nBest)
205  {
206  nBest = nTotal;
207  vfBest = vfIncluded;
208  }
209  nTotal -= groups[i].m_value;
210  vfIncluded[i] = false;
211  }
212  }
213  }
214  }
215  }
216 }
217 
218 bool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet)
219 {
220  setCoinsRet.clear();
221  nValueRet = 0;
222 
223  // List of values less than target
224  Optional<OutputGroup> lowest_larger;
225  std::vector<OutputGroup> applicable_groups;
226  CAmount nTotalLower = 0;
227 
228  Shuffle(groups.begin(), groups.end(), FastRandomContext());
229 
230  for (const OutputGroup& group : groups) {
231  if (group.m_value == nTargetValue) {
232  util::insert(setCoinsRet, group.m_outputs);
233  nValueRet += group.m_value;
234  return true;
235  } else if (group.m_value < nTargetValue + MIN_CHANGE) {
236  applicable_groups.push_back(group);
237  nTotalLower += group.m_value;
238  } else if (!lowest_larger || group.m_value < lowest_larger->m_value) {
239  lowest_larger = group;
240  }
241  }
242 
243  if (nTotalLower == nTargetValue) {
244  for (const auto& group : applicable_groups) {
245  util::insert(setCoinsRet, group.m_outputs);
246  nValueRet += group.m_value;
247  }
248  return true;
249  }
250 
251  if (nTotalLower < nTargetValue) {
252  if (!lowest_larger) return false;
253  util::insert(setCoinsRet, lowest_larger->m_outputs);
254  nValueRet += lowest_larger->m_value;
255  return true;
256  }
257 
258  // Solve subset sum by stochastic approximation
259  std::sort(applicable_groups.begin(), applicable_groups.end(), descending);
260  std::vector<char> vfBest;
261  CAmount nBest;
262 
263  ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue, vfBest, nBest);
264  if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE) {
265  ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
266  }
267 
268  // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
269  // or the next bigger coin is closer), return the bigger coin
270  if (lowest_larger &&
271  ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || lowest_larger->m_value <= nBest)) {
272  util::insert(setCoinsRet, lowest_larger->m_outputs);
273  nValueRet += lowest_larger->m_value;
274  } else {
275  for (unsigned int i = 0; i < applicable_groups.size(); i++) {
276  if (vfBest[i]) {
277  util::insert(setCoinsRet, applicable_groups[i].m_outputs);
278  nValueRet += applicable_groups[i].m_value;
279  }
280  }
281 
283  LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: "); /* Continued */
284  for (unsigned int i = 0; i < applicable_groups.size(); i++) {
285  if (vfBest[i]) {
286  LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(applicable_groups[i].m_value)); /* Continued */
287  }
288  }
289  LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
290  }
291  }
292 
293  return true;
294 }
295 
296 /******************************************************************************
297 
298  OutputGroup
299 
300  ******************************************************************************/
301 
302 void OutputGroup::Insert(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants) {
303  m_outputs.push_back(output);
304  m_from_me &= from_me;
305  m_value += output.effective_value;
306  m_depth = std::min(m_depth, depth);
307  // ancestors here express the number of ancestors the new coin will end up having, which is
308  // the sum, rather than the max; this will overestimate in the cases where multiple inputs
309  // have common ancestors
310  m_ancestors += ancestors;
311  // descendants is the count as seen from the top ancestor, not the descendants as seen from the
312  // coin itself; thus, this value is counted as the max, not the sum
313  m_descendants = std::max(m_descendants, descendants);
315 }
316 
317 std::vector<CInputCoin>::iterator OutputGroup::Discard(const CInputCoin& output) {
318  auto it = m_outputs.begin();
319  while (it != m_outputs.end() && it->outpoint != output.outpoint) ++it;
320  if (it == m_outputs.end()) return it;
321  m_value -= output.effective_value;
323  return m_outputs.erase(it);
324 }
325 
326 bool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const
327 {
328  return m_depth >= (m_from_me ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs)
329  && m_ancestors <= eligibility_filter.max_ancestors
330  && m_descendants <= eligibility_filter.max_descendants;
331 }
#define LogPrint(category,...)
Definition: logging.h:182
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:423
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
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:119
CAmount m_value
Definition: coinselection.h:71
static bool LogAcceptCategory(BCLog::LogFlags category)
Return true if log accepts specified category.
Definition: logging.h:153
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:231
bool EligibleForSpending(const CoinEligibilityFilter &eligibility_filter) const
CAmount effective_value
Definition: coinselection.h:75
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:211
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)
struct @14 descending
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
auto it
Definition: validation.cpp:384