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