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