Bitcoin Core  26.1.0
P2P Digital Currency
coinselection.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2022 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 <common/system.h>
8 #include <consensus/amount.h>
9 #include <consensus/consensus.h>
10 #include <interfaces/chain.h>
11 #include <logging.h>
12 #include <policy/feerate.h>
13 #include <util/check.h>
14 #include <util/moneystr.h>
15 
16 #include <numeric>
17 #include <optional>
18 #include <queue>
19 
20 namespace wallet {
21 // Common selection error across the algorithms
23 {
24  return util::Error{_("The inputs size exceeds the maximum weight. "
25  "Please try sending a smaller amount or manually consolidating your wallet's UTXOs")};
26 }
27 
28 // Descending order comparator
29 struct {
30  bool operator()(const OutputGroup& a, const OutputGroup& b) const
31  {
32  return a.GetSelectionAmount() > b.GetSelectionAmount();
33  }
34 } descending;
35 
36 /*
37  * This is the Branch and Bound Coin Selection algorithm designed by Murch. It searches for an input
38  * set that can pay for the spending target and does not exceed the spending target by more than the
39  * cost of creating and spending a change output. The algorithm uses a depth-first search on a binary
40  * tree. In the binary tree, each node corresponds to the inclusion or the omission of a UTXO. UTXOs
41  * are sorted by their effective values and the tree is explored deterministically per the inclusion
42  * branch first. At each node, the algorithm checks whether the selection is within the target range.
43  * While the selection has not reached the target range, more UTXOs are included. When a selection's
44  * value exceeds the target range, the complete subtree deriving from this selection can be omitted.
45  * At that point, the last included UTXO is deselected and the corresponding omission branch explored
46  * instead. The search ends after the complete tree has been searched or after a limited number of tries.
47  *
48  * The search continues to search for better solutions after one solution has been found. The best
49  * solution is chosen by minimizing the waste metric. The waste metric is defined as the cost to
50  * spend the current inputs at the given fee rate minus the long term expected cost to spend the
51  * inputs, plus the amount by which the selection exceeds the spending target:
52  *
53  * waste = selectionTotal - target + inputs × (currentFeeRate - longTermFeeRate)
54  *
55  * The algorithm uses two additional optimizations. A lookahead keeps track of the total value of
56  * the unexplored UTXOs. A subtree is not explored if the lookahead indicates that the target range
57  * cannot be reached. Further, it is unnecessary to test equivalent combinations. This allows us
58  * to skip testing the inclusion of UTXOs that match the effective value and waste of an omitted
59  * predecessor.
60  *
61  * The Branch and Bound algorithm is described in detail in Murch's Master Thesis:
62  * https://murch.one/wp-content/uploads/2016/11/erhardt2016coinselection.pdf
63  *
64  * @param const std::vector<OutputGroup>& utxo_pool The set of UTXO groups that we are choosing from.
65  * These UTXO groups will be sorted in descending order by effective value and the OutputGroups'
66  * values are their effective values.
67  * @param const CAmount& selection_target This is the value that we want to select. It is the lower
68  * bound of the range.
69  * @param const CAmount& cost_of_change This is the cost of creating and spending a change output.
70  * This plus selection_target is the upper bound of the range.
71  * @returns The result of this coin selection algorithm, or std::nullopt
72  */
73 
74 static const size_t TOTAL_TRIES = 100000;
75 
76 util::Result<SelectionResult> SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, const CAmount& cost_of_change,
77  int max_weight)
78 {
79  SelectionResult result(selection_target, SelectionAlgorithm::BNB);
80  CAmount curr_value = 0;
81  std::vector<size_t> curr_selection; // selected utxo indexes
82  int curr_selection_weight = 0; // sum of selected utxo weight
83 
84  // Calculate curr_available_value
85  CAmount curr_available_value = 0;
86  for (const OutputGroup& utxo : utxo_pool) {
87  // Assert that this utxo is not negative. It should never be negative,
88  // effective value calculation should have removed it
89  assert(utxo.GetSelectionAmount() > 0);
90  curr_available_value += utxo.GetSelectionAmount();
91  }
92  if (curr_available_value < selection_target) {
93  return util::Error();
94  }
95 
96  // Sort the utxo_pool
97  std::sort(utxo_pool.begin(), utxo_pool.end(), descending);
98 
99  CAmount curr_waste = 0;
100  std::vector<size_t> best_selection;
101  CAmount best_waste = MAX_MONEY;
102 
103  bool is_feerate_high = utxo_pool.at(0).fee > utxo_pool.at(0).long_term_fee;
104  bool max_tx_weight_exceeded = false;
105 
106  // Depth First search loop for choosing the UTXOs
107  for (size_t curr_try = 0, utxo_pool_index = 0; curr_try < TOTAL_TRIES; ++curr_try, ++utxo_pool_index) {
108  // Conditions for starting a backtrack
109  bool backtrack = false;
110  if (curr_value + curr_available_value < selection_target || // Cannot possibly reach target with the amount remaining in the curr_available_value.
111  curr_value > selection_target + cost_of_change || // Selected value is out of range, go back and try other branch
112  (curr_waste > best_waste && is_feerate_high)) { // Don't select things which we know will be more wasteful if the waste is increasing
113  backtrack = true;
114  } else if (curr_selection_weight > max_weight) { // Exceeding weight for standard tx, cannot find more solutions by adding more inputs
115  max_tx_weight_exceeded = true; // at least one selection attempt exceeded the max weight
116  backtrack = true;
117  } else if (curr_value >= selection_target) { // Selected value is within range
118  curr_waste += (curr_value - selection_target); // This is the excess value which is added to the waste for the below comparison
119  // Adding another UTXO after this check could bring the waste down if the long term fee is higher than the current fee.
120  // However we are not going to explore that because this optimization for the waste is only done when we have hit our target
121  // value. Adding any more UTXOs will be just burning the UTXO; it will go entirely to fees. Thus we aren't going to
122  // explore any more UTXOs to avoid burning money like that.
123  if (curr_waste <= best_waste) {
124  best_selection = curr_selection;
125  best_waste = curr_waste;
126  }
127  curr_waste -= (curr_value - selection_target); // Remove the excess value as we will be selecting different coins now
128  backtrack = true;
129  }
130 
131  if (backtrack) { // Backtracking, moving backwards
132  if (curr_selection.empty()) { // We have walked back to the first utxo and no branch is untraversed. All solutions searched
133  break;
134  }
135 
136  // Add omitted UTXOs back to lookahead before traversing the omission branch of last included UTXO.
137  for (--utxo_pool_index; utxo_pool_index > curr_selection.back(); --utxo_pool_index) {
138  curr_available_value += utxo_pool.at(utxo_pool_index).GetSelectionAmount();
139  }
140 
141  // Output was included on previous iterations, try excluding now.
142  assert(utxo_pool_index == curr_selection.back());
143  OutputGroup& utxo = utxo_pool.at(utxo_pool_index);
144  curr_value -= utxo.GetSelectionAmount();
145  curr_waste -= utxo.fee - utxo.long_term_fee;
146  curr_selection_weight -= utxo.m_weight;
147  curr_selection.pop_back();
148  } else { // Moving forwards, continuing down this branch
149  OutputGroup& utxo = utxo_pool.at(utxo_pool_index);
150 
151  // Remove this utxo from the curr_available_value utxo amount
152  curr_available_value -= utxo.GetSelectionAmount();
153 
154  if (curr_selection.empty() ||
155  // The previous index is included and therefore not relevant for exclusion shortcut
156  (utxo_pool_index - 1) == curr_selection.back() ||
157  // Avoid searching a branch if the previous UTXO has the same value and same waste and was excluded.
158  // Since the ratio of fee to 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.
159  utxo.GetSelectionAmount() != utxo_pool.at(utxo_pool_index - 1).GetSelectionAmount() ||
160  utxo.fee != utxo_pool.at(utxo_pool_index - 1).fee)
161  {
162  // Inclusion branch first (Largest First Exploration)
163  curr_selection.push_back(utxo_pool_index);
164  curr_value += utxo.GetSelectionAmount();
165  curr_waste += utxo.fee - utxo.long_term_fee;
166  curr_selection_weight += utxo.m_weight;
167  }
168  }
169  }
170 
171  // Check for solution
172  if (best_selection.empty()) {
173  return max_tx_weight_exceeded ? ErrorMaxWeightExceeded() : util::Error();
174  }
175 
176  // Set output set
177  for (const size_t& i : best_selection) {
178  result.AddInput(utxo_pool.at(i));
179  }
180  result.ComputeAndSetWaste(cost_of_change, cost_of_change, CAmount{0});
181  assert(best_waste == result.GetWaste());
182 
183  return result;
184 }
185 
187 {
188 public:
189  int operator() (const OutputGroup& group1, const OutputGroup& group2) const
190  {
191  return group1.GetSelectionAmount() > group2.GetSelectionAmount();
192  }
193 };
194 
195 util::Result<SelectionResult> SelectCoinsSRD(const std::vector<OutputGroup>& utxo_pool, CAmount target_value, CAmount change_fee, FastRandomContext& rng,
196  int max_weight)
197 {
198  SelectionResult result(target_value, SelectionAlgorithm::SRD);
199  std::priority_queue<OutputGroup, std::vector<OutputGroup>, MinOutputGroupComparator> heap;
200 
201  // Include change for SRD as we want to avoid making really small change if the selection just
202  // barely meets the target. Just use the lower bound change target instead of the randomly
203  // generated one, since SRD will result in a random change amount anyway; avoid making the
204  // target needlessly large.
205  target_value += CHANGE_LOWER + change_fee;
206 
207  std::vector<size_t> indexes;
208  indexes.resize(utxo_pool.size());
209  std::iota(indexes.begin(), indexes.end(), 0);
210  Shuffle(indexes.begin(), indexes.end(), rng);
211 
212  CAmount selected_eff_value = 0;
213  int weight = 0;
214  bool max_tx_weight_exceeded = false;
215  for (const size_t i : indexes) {
216  const OutputGroup& group = utxo_pool.at(i);
217  Assume(group.GetSelectionAmount() > 0);
218 
219  // Add group to selection
220  heap.push(group);
221  selected_eff_value += group.GetSelectionAmount();
222  weight += group.m_weight;
223 
224  // If the selection weight exceeds the maximum allowed size, remove the least valuable inputs until we
225  // are below max weight.
226  if (weight > max_weight) {
227  max_tx_weight_exceeded = true; // mark it in case we don't find any useful result.
228  do {
229  const OutputGroup& to_remove_group = heap.top();
230  selected_eff_value -= to_remove_group.GetSelectionAmount();
231  weight -= to_remove_group.m_weight;
232  heap.pop();
233  } while (!heap.empty() && weight > max_weight);
234  }
235 
236  // Now check if we are above the target
237  if (selected_eff_value >= target_value) {
238  // Result found, add it.
239  while (!heap.empty()) {
240  result.AddInput(heap.top());
241  heap.pop();
242  }
243  return result;
244  }
245  }
246  return max_tx_weight_exceeded ? ErrorMaxWeightExceeded() : util::Error();
247 }
248 
260 static void ApproximateBestSubset(FastRandomContext& insecure_rand, const std::vector<OutputGroup>& groups,
261  const CAmount& nTotalLower, const CAmount& nTargetValue,
262  std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
263 {
264  std::vector<char> vfIncluded;
265 
266  // Worst case "best" approximation is just all of the groups.
267  vfBest.assign(groups.size(), true);
268  nBest = nTotalLower;
269 
270  for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
271  {
272  vfIncluded.assign(groups.size(), false);
273  CAmount nTotal = 0;
274  bool fReachedTarget = false;
275  for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
276  {
277  for (unsigned int i = 0; i < groups.size(); i++)
278  {
279  //The solver here uses a randomized algorithm,
280  //the randomness serves no real security purpose but is just
281  //needed to prevent degenerate behavior and it is important
282  //that the rng is fast. We do not use a constant random sequence,
283  //because there may be some privacy improvement by making
284  //the selection random.
285  if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
286  {
287  nTotal += groups[i].GetSelectionAmount();
288  vfIncluded[i] = true;
289  if (nTotal >= nTargetValue)
290  {
291  fReachedTarget = true;
292  // If the total is between nTargetValue and nBest, it's our new best
293  // approximation.
294  if (nTotal < nBest)
295  {
296  nBest = nTotal;
297  vfBest = vfIncluded;
298  }
299  nTotal -= groups[i].GetSelectionAmount();
300  vfIncluded[i] = false;
301  }
302  }
303  }
304  }
305  }
306 }
307 
308 util::Result<SelectionResult> KnapsackSolver(std::vector<OutputGroup>& groups, const CAmount& nTargetValue,
309  CAmount change_target, FastRandomContext& rng, int max_weight)
310 {
311  SelectionResult result(nTargetValue, SelectionAlgorithm::KNAPSACK);
312 
313  // List of values less than target
314  std::optional<OutputGroup> lowest_larger;
315  // Groups with selection amount smaller than the target and any change we might produce.
316  // Don't include groups larger than this, because they will only cause us to overshoot.
317  std::vector<OutputGroup> applicable_groups;
318  CAmount nTotalLower = 0;
319 
320  Shuffle(groups.begin(), groups.end(), rng);
321 
322  for (const OutputGroup& group : groups) {
323  if (group.GetSelectionAmount() == nTargetValue) {
324  result.AddInput(group);
325  return result;
326  } else if (group.GetSelectionAmount() < nTargetValue + change_target) {
327  applicable_groups.push_back(group);
328  nTotalLower += group.GetSelectionAmount();
329  } else if (!lowest_larger || group.GetSelectionAmount() < lowest_larger->GetSelectionAmount()) {
330  lowest_larger = group;
331  }
332  }
333 
334  if (nTotalLower == nTargetValue) {
335  for (const auto& group : applicable_groups) {
336  result.AddInput(group);
337  }
338  return result;
339  }
340 
341  if (nTotalLower < nTargetValue) {
342  if (!lowest_larger) return util::Error();
343  result.AddInput(*lowest_larger);
344  return result;
345  }
346 
347  // Solve subset sum by stochastic approximation
348  std::sort(applicable_groups.begin(), applicable_groups.end(), descending);
349  std::vector<char> vfBest;
350  CAmount nBest;
351 
352  ApproximateBestSubset(rng, applicable_groups, nTotalLower, nTargetValue, vfBest, nBest);
353  if (nBest != nTargetValue && nTotalLower >= nTargetValue + change_target) {
354  ApproximateBestSubset(rng, applicable_groups, nTotalLower, nTargetValue + change_target, vfBest, nBest);
355  }
356 
357  // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
358  // or the next bigger coin is closer), return the bigger coin
359  if (lowest_larger &&
360  ((nBest != nTargetValue && nBest < nTargetValue + change_target) || lowest_larger->GetSelectionAmount() <= nBest)) {
361  result.AddInput(*lowest_larger);
362  } else {
363  for (unsigned int i = 0; i < applicable_groups.size(); i++) {
364  if (vfBest[i]) {
365  result.AddInput(applicable_groups[i]);
366  }
367  }
368 
369  // If the result exceeds the maximum allowed size, return closest UTXO above the target
370  if (result.GetWeight() > max_weight) {
371  // No coin above target, nothing to do.
372  if (!lowest_larger) return ErrorMaxWeightExceeded();
373 
374  // Return closest UTXO above target
375  result.Clear();
376  result.AddInput(*lowest_larger);
377  }
378 
380  std::string log_message{"Coin selection best subset: "};
381  for (unsigned int i = 0; i < applicable_groups.size(); i++) {
382  if (vfBest[i]) {
383  log_message += strprintf("%s ", FormatMoney(applicable_groups[i].m_value));
384  }
385  }
386  LogPrint(BCLog::SELECTCOINS, "%stotal %s\n", log_message, FormatMoney(nBest));
387  }
388  }
389 
390  return result;
391 }
392 
393 /******************************************************************************
394 
395  OutputGroup
396 
397  ******************************************************************************/
398 
399 void OutputGroup::Insert(const std::shared_ptr<COutput>& output, size_t ancestors, size_t descendants) {
400  m_outputs.push_back(output);
401  auto& coin = *m_outputs.back();
402 
403  fee += coin.GetFee();
404 
405  coin.long_term_fee = coin.input_bytes < 0 ? 0 : m_long_term_feerate.GetFee(coin.input_bytes);
406  long_term_fee += coin.long_term_fee;
407 
408  effective_value += coin.GetEffectiveValue();
409 
410  m_from_me &= coin.from_me;
411  m_value += coin.txout.nValue;
412  m_depth = std::min(m_depth, coin.depth);
413  // ancestors here express the number of ancestors the new coin will end up having, which is
414  // the sum, rather than the max; this will overestimate in the cases where multiple inputs
415  // have common ancestors
416  m_ancestors += ancestors;
417  // descendants is the count as seen from the top ancestor, not the descendants as seen from the
418  // coin itself; thus, this value is counted as the max, not the sum
419  m_descendants = std::max(m_descendants, descendants);
420 
421  if (output->input_bytes > 0) {
422  m_weight += output->input_bytes * WITNESS_SCALE_FACTOR;
423  }
424 }
425 
426 bool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const
427 {
428  return m_depth >= (m_from_me ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs)
429  && m_ancestors <= eligibility_filter.max_ancestors
430  && m_descendants <= eligibility_filter.max_descendants;
431 }
432 
434 {
436 }
437 
438 void OutputGroupTypeMap::Push(const OutputGroup& group, OutputType type, bool insert_positive, bool insert_mixed)
439 {
440  if (group.m_outputs.empty()) return;
441 
442  Groups& groups = groups_by_type[type];
443  if (insert_positive && group.GetSelectionAmount() > 0) {
444  groups.positive_group.emplace_back(group);
445  all_groups.positive_group.emplace_back(group);
446  }
447  if (insert_mixed) {
448  groups.mixed_group.emplace_back(group);
449  all_groups.mixed_group.emplace_back(group);
450  }
451 }
452 
453 CAmount SelectionResult::GetSelectionWaste(CAmount change_cost, CAmount target, bool use_effective_value)
454 {
455  // This function should not be called with empty inputs as that would mean the selection failed
456  assert(!m_selected_inputs.empty());
457 
458  // Always consider the cost of spending an input now vs in the future.
459  CAmount waste = 0;
460  for (const auto& coin_ptr : m_selected_inputs) {
461  const COutput& coin = *coin_ptr;
462  waste += coin.GetFee() - coin.long_term_fee;
463  }
464  // Bump fee of whole selection may diverge from sum of individual bump fees
465  waste -= bump_fee_group_discount;
466 
467  if (change_cost) {
468  // Consider the cost of making change and spending it in the future
469  // If we aren't making change, the caller should've set change_cost to 0
470  assert(change_cost > 0);
471  waste += change_cost;
472  } else {
473  // When we are not making change (change_cost == 0), consider the excess we are throwing away to fees
474  CAmount selected_effective_value = use_effective_value ? GetSelectedEffectiveValue() : GetSelectedValue();
475  assert(selected_effective_value >= target);
476  waste += selected_effective_value - target;
477  }
478 
479  return waste;
480 }
481 
482 CAmount GenerateChangeTarget(const CAmount payment_value, const CAmount change_fee, FastRandomContext& rng)
483 {
484  if (payment_value <= CHANGE_LOWER / 2) {
485  return change_fee + CHANGE_LOWER;
486  } else {
487  // random value between 50ksat and min (payment_value * 2, 1milsat)
488  const auto upper_bound = std::min(payment_value * 2, CHANGE_UPPER);
489  return change_fee + rng.randrange(upper_bound - CHANGE_LOWER) + CHANGE_LOWER;
490  }
491 }
492 
494 {
495  // Overlapping ancestry can only lower the fees, not increase them
496  assert (discount >= 0);
497  bump_fee_group_discount = discount;
498 }
499 
500 
501 void SelectionResult::ComputeAndSetWaste(const CAmount min_viable_change, const CAmount change_cost, const CAmount change_fee)
502 {
503  const CAmount change = GetChange(min_viable_change, change_fee);
504 
505  if (change > 0) {
507  } else {
509  }
510 }
511 
513 {
514  return *Assert(m_waste);
515 }
516 
518 {
519  return std::accumulate(m_selected_inputs.cbegin(), m_selected_inputs.cend(), CAmount{0}, [](CAmount sum, const auto& coin) { return sum + coin->txout.nValue; });
520 }
521 
523 {
524  return std::accumulate(m_selected_inputs.cbegin(), m_selected_inputs.cend(), CAmount{0}, [](CAmount sum, const auto& coin) { return sum + coin->GetEffectiveValue(); }) + bump_fee_group_discount;
525 }
526 
528 {
529  return std::accumulate(m_selected_inputs.cbegin(), m_selected_inputs.cend(), CAmount{0}, [](CAmount sum, const auto& coin) { return sum + coin->ancestor_bump_fees; }) - bump_fee_group_discount;
530 }
531 
533 {
534  m_selected_inputs.clear();
535  m_waste.reset();
536  m_weight = 0;
537 }
538 
540 {
541  // As it can fail, combine inputs first
542  InsertInputs(group.m_outputs);
543  m_use_effective = !group.m_subtract_fee_outputs;
544 
545  m_weight += group.m_weight;
546 }
547 
548 void SelectionResult::AddInputs(const std::set<std::shared_ptr<COutput>>& inputs, bool subtract_fee_outputs)
549 {
550  // As it can fail, combine inputs first
551  InsertInputs(inputs);
552  m_use_effective = !subtract_fee_outputs;
553 
554  m_weight += std::accumulate(inputs.cbegin(), inputs.cend(), 0, [](int sum, const auto& coin) {
555  return sum + std::max(coin->input_bytes, 0) * WITNESS_SCALE_FACTOR;
556  });
557 }
558 
560 {
561  // As it can fail, combine inputs first
563 
564  m_target += other.m_target;
567  m_algo = other.m_algo;
568  }
569 
570  m_weight += other.m_weight;
571 }
572 
573 const std::set<std::shared_ptr<COutput>>& SelectionResult::GetInputSet() const
574 {
575  return m_selected_inputs;
576 }
577 
578 std::vector<std::shared_ptr<COutput>> SelectionResult::GetShuffledInputVector() const
579 {
580  std::vector<std::shared_ptr<COutput>> coins(m_selected_inputs.begin(), m_selected_inputs.end());
581  Shuffle(coins.begin(), coins.end(), FastRandomContext());
582  return coins;
583 }
584 
586 {
587  Assert(m_waste.has_value());
588  Assert(other.m_waste.has_value());
589  // As this operator is only used in std::min_element, we want the result that has more inputs when waste are equal.
590  return *m_waste < *other.m_waste || (*m_waste == *other.m_waste && m_selected_inputs.size() > other.m_selected_inputs.size());
591 }
592 
593 std::string COutput::ToString() const
594 {
595  return strprintf("COutput(%s, %d, %d) [%s]", outpoint.hash.ToString(), outpoint.n, depth, FormatMoney(txout.nValue));
596 }
597 
598 std::string GetAlgorithmName(const SelectionAlgorithm algo)
599 {
600  switch (algo)
601  {
602  case SelectionAlgorithm::BNB: return "bnb";
603  case SelectionAlgorithm::KNAPSACK: return "knapsack";
604  case SelectionAlgorithm::SRD: return "srd";
605  case SelectionAlgorithm::MANUAL: return "manual";
606  // No default case to allow for compiler to warn
607  }
608  assert(false);
609 }
610 
611 CAmount SelectionResult::GetChange(const CAmount min_viable_change, const CAmount change_fee) const
612 {
613  // change = SUM(inputs) - SUM(outputs) - fees
614  // 1) With SFFO we don't pay any fees
615  // 2) Otherwise we pay all the fees:
616  // - input fees are covered by GetSelectedEffectiveValue()
617  // - non_input_fee is included in m_target
618  // - change_fee
619  const CAmount change = m_use_effective
620  ? GetSelectedEffectiveValue() - m_target - change_fee
622 
623  if (change < min_viable_change) {
624  return 0;
625  }
626 
627  return change;
628 }
629 
630 } // namespace wallet
CAmount nValue
Definition: transaction.h:160
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
util::Result< SelectionResult > SelectCoinsSRD(const std::vector< OutputGroup > &utxo_pool, CAmount target_value, CAmount change_fee, FastRandomContext &rng, int max_weight)
Select coins by Single Random Draw.
COutPoint outpoint
The outpoint identifying this UTXO.
Definition: coinselection.h:38
CAmount GetWaste() const
CAmount m_value
The total value of the UTXOs in sum.
std::map< OutputType, Groups > groups_by_type
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
struct wallet::@16 descending
#define LogPrint(category,...)
Definition: logging.h:246
assert(!tx.IsCoinBase())
CAmount fee
The fee to spend these UTXOs at the effective feerate.
const uint64_t max_descendants
Maximum number of descendants that a single UTXO in the OutputGroup may have.
size_t m_ancestors
The aggregated count of unconfirmed ancestors of all UTXOs in this group.
void AddInput(const OutputGroup &group)
util::Result< SelectionResult > SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &selection_target, const CAmount &cost_of_change, int max_weight)
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
const uint64_t max_ancestors
Maximum number of unconfirmed ancestors aggregated across all UTXOs in an OutputGroup.
void AddInputs(const std::set< std::shared_ptr< COutput >> &inputs, bool subtract_fee_outputs)
int m_weight
Total weight of the UTXOs in this group.
static constexpr CAmount CHANGE_LOWER
lower bound for randomly-chosen target change amount
Definition: coinselection.h:23
bool operator<(SelectionResult other) const
bool m_use_effective
Whether the input values for calculations should be the effective value (true) or normal value (false...
CAmount GetChange(const CAmount min_viable_change, const CAmount change_fee) const
Get the amount for the change output after paying needed fees.
OutputType
Definition: outputtype.h:17
CAmount effective_value
The value of the UTXOs after deducting the cost of spending them at the effective feerate...
void Push(const OutputGroup &group, OutputType type, bool insert_positive, bool insert_mixed)
SelectionAlgorithm
CTxOut txout
The output itself.
Definition: coinselection.h:41
volatile double sum
Definition: examples.cpp:10
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
CAmount bump_fee_group_discount
How much individual inputs overestimated the bump fees for the shared ancestry.
std::string ToString() const
CAmount long_term_fee
The fee required to spend this output at the consolidation feerate.
Definition: coinselection.h:73
CAmount GetTotalBumpFees() const
bool EligibleForSpending(const CoinEligibilityFilter &eligibility_filter) const
static util::Result< SelectionResult > ErrorMaxWeightExceeded()
size_t m_descendants
The maximum count of descendants of a single UTXO in this output group.
std::vector< OutputGroup > positive_group
CAmount GetSelectedEffectiveValue() const
std::set< std::shared_ptr< COutput > > m_selected_inputs
Set of inputs selected by the algorithm to use in the transaction.
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:74
std::optional< CAmount > m_waste
The computed waste.
int depth
Depth in block chain.
Definition: coinselection.h:48
Fast randomness source.
Definition: random.h:143
const std::set< std::shared_ptr< COutput > > & GetInputSet() const
Get m_selected_inputs.
CAmount GetSelectionWaste(CAmount change_cost, CAmount target, bool use_effective_value=true)
Compute the waste for this result given the cost of change and the opportunity cost of spending these...
CFeeRate m_long_term_feerate
The feerate for spending a created change output eventually (i.e.
uint32_t n
Definition: transaction.h:39
static const size_t TOTAL_TRIES
static void ApproximateBestSubset(FastRandomContext &insecure_rand, const std::vector< OutputGroup > &groups, const CAmount &nTotalLower, const CAmount &nTargetValue, std::vector< char > &vfBest, CAmount &nBest, int iterations=1000)
Find a subset of the OutputGroups that is at least as large as, but as close as possible to...
util::Result< SelectionResult > KnapsackSolver(std::vector< OutputGroup > &groups, const CAmount &nTargetValue, CAmount change_target, FastRandomContext &rng, int max_weight)
CAmount GetSelectionAmount() const
SelectionAlgorithm m_algo
The algorithm used to produce this result.
std::string ToString() const
Definition: uint256.cpp:55
A group of UTXOs paid to the same output script.
void ComputeAndSetWaste(const CAmount min_viable_change, const CAmount change_cost, const CAmount change_fee)
Calculates and stores the waste for this selection via GetSelectionWaste.
void InsertInputs(const T &inputs)
#define Assume(val)
Assume is the identity function.
Definition: check.h:85
int m_weight
Total weight of the selected inputs.
std::vector< std::shared_ptr< COutput > > m_outputs
The list of UTXOs contained in this output group.
Parameters for filtering which OutputGroups we may use in coin selection.
std::vector< OutputGroup > mixed_group
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:16
const int conf_mine
Minimum number of confirmations for outputs that we sent to ourselves.
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:264
int m_depth
The minimum number of confirmations the UTXOs in the group have.
std::string GetAlgorithmName(const SelectionAlgorithm algo)
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
bool randbool() noexcept
Generate a random boolean.
Definition: random.h:227
int operator()(const OutputGroup &group1, const OutputGroup &group2) const
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
Definition: feerate.cpp:23
void Insert(const std::shared_ptr< COutput > &output, size_t ancestors, size_t descendants)
CAmount GetFee() const
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:207
CAmount GetSelectedValue() const
Get the sum of the input values.
CAmount long_term_fee
The fee to spend these UTXOs at the long term feerate.
static constexpr CAmount CHANGE_UPPER
upper bound for randomly-chosen target change amount
Definition: coinselection.h:25
bool m_from_me
Whether the UTXOs were sent by the wallet to itself.
A UTXO under consideration for use in funding a new transaction.
Definition: coinselection.h:28
std::vector< std::shared_ptr< COutput > > GetShuffledInputVector() const
Get the vector of COutputs that will be used to fill in a CTransaction&#39;s vin.
CAmount GenerateChangeTarget(const CAmount payment_value, const CAmount change_fee, FastRandomContext &rng)
Choose a random change target for each transaction to make it harder to fingerprint the Core wallet b...
const int conf_theirs
Minimum number of confirmations for outputs received from a different wallet.
void SetBumpFeeDiscount(const CAmount discount)
How much individual inputs overestimated the bump fees for shared ancestries.
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:202
void Merge(const SelectionResult &other)
Combines the.
CAmount m_target
The target the algorithm selected for.
#define Assert(val)
Identity function.
Definition: check.h:73
uint256 hash
Definition: transaction.h:38