LCOV - code coverage report
Current view: top level - src/wallet - coinselection.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 254 264 96.2 %
Date: 2022-04-21 14:51:19 Functions: 19 20 95.0 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 129 134 96.3 %

           Branch data     Line data    Source code
#       1                 :            : // Copyright (c) 2017-2021 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 <consensus/amount.h>
#       8                 :            : #include <policy/feerate.h>
#       9                 :            : #include <util/check.h>
#      10                 :            : #include <util/system.h>
#      11                 :            : #include <util/moneystr.h>
#      12                 :            : 
#      13                 :            : #include <numeric>
#      14                 :            : #include <optional>
#      15                 :            : 
#      16                 :            : namespace wallet {
#      17                 :            : // Descending order comparator
#      18                 :            : struct {
#      19                 :            :     bool operator()(const OutputGroup& a, const OutputGroup& b) const
#      20                 :    3452904 :     {
#      21                 :    3452904 :         return a.GetSelectionAmount() > b.GetSelectionAmount();
#      22                 :    3452904 :     }
#      23                 :            : } descending;
#      24                 :            : 
#      25                 :            : /*
#      26                 :            :  * This is the Branch and Bound Coin Selection algorithm designed by Murch. It searches for an input
#      27                 :            :  * set that can pay for the spending target and does not exceed the spending target by more than the
#      28                 :            :  * cost of creating and spending a change output. The algorithm uses a depth-first search on a binary
#      29                 :            :  * tree. In the binary tree, each node corresponds to the inclusion or the omission of a UTXO. UTXOs
#      30                 :            :  * are sorted by their effective values and the tree is explored deterministically per the inclusion
#      31                 :            :  * branch first. At each node, the algorithm checks whether the selection is within the target range.
#      32                 :            :  * While the selection has not reached the target range, more UTXOs are included. When a selection's
#      33                 :            :  * value exceeds the target range, the complete subtree deriving from this selection can be omitted.
#      34                 :            :  * At that point, the last included UTXO is deselected and the corresponding omission branch explored
#      35                 :            :  * instead. The search ends after the complete tree has been searched or after a limited number of tries.
#      36                 :            :  *
#      37                 :            :  * The search continues to search for better solutions after one solution has been found. The best
#      38                 :            :  * solution is chosen by minimizing the waste metric. The waste metric is defined as the cost to
#      39                 :            :  * spend the current inputs at the given fee rate minus the long term expected cost to spend the
#      40                 :            :  * inputs, plus the amount by which the selection exceeds the spending target:
#      41                 :            :  *
#      42                 :            :  * waste = selectionTotal - target + inputs × (currentFeeRate - longTermFeeRate)
#      43                 :            :  *
#      44                 :            :  * The algorithm uses two additional optimizations. A lookahead keeps track of the total value of
#      45                 :            :  * the unexplored UTXOs. A subtree is not explored if the lookahead indicates that the target range
#      46                 :            :  * cannot be reached. Further, it is unnecessary to test equivalent combinations. This allows us
#      47                 :            :  * to skip testing the inclusion of UTXOs that match the effective value and waste of an omitted
#      48                 :            :  * predecessor.
#      49                 :            :  *
#      50                 :            :  * The Branch and Bound algorithm is described in detail in Murch's Master Thesis:
#      51                 :            :  * https://murch.one/wp-content/uploads/2016/11/erhardt2016coinselection.pdf
#      52                 :            :  *
#      53                 :            :  * @param const std::vector<OutputGroup>& utxo_pool The set of UTXO groups that we are choosing from.
#      54                 :            :  *        These UTXO groups will be sorted in descending order by effective value and the OutputGroups'
#      55                 :            :  *        values are their effective values.
#      56                 :            :  * @param const CAmount& selection_target This is the value that we want to select. It is the lower
#      57                 :            :  *        bound of the range.
#      58                 :            :  * @param const CAmount& cost_of_change This is the cost of creating and spending a change output.
#      59                 :            :  *        This plus selection_target is the upper bound of the range.
#      60                 :            :  * @returns The result of this coin selection algorithm, or std::nullopt
#      61                 :            :  */
#      62                 :            : 
#      63                 :            : static const size_t TOTAL_TRIES = 100000;
#      64                 :            : 
#      65                 :            : std::optional<SelectionResult> SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, const CAmount& cost_of_change)
#      66                 :       7989 : {
#      67                 :       7989 :     SelectionResult result(selection_target);
#      68                 :       7989 :     CAmount curr_value = 0;
#      69                 :       7989 :     std::vector<size_t> curr_selection; // selected utxo indexes
#      70                 :            : 
#      71                 :            :     // Calculate curr_available_value
#      72                 :       7989 :     CAmount curr_available_value = 0;
#      73         [ +  + ]:     304748 :     for (const OutputGroup& utxo : utxo_pool) {
#      74                 :            :         // Assert that this utxo is not negative. It should never be negative,
#      75                 :            :         // effective value calculation should have removed it
#      76                 :     304748 :         assert(utxo.GetSelectionAmount() > 0);
#      77                 :          0 :         curr_available_value += utxo.GetSelectionAmount();
#      78                 :     304748 :     }
#      79         [ +  + ]:       7989 :     if (curr_available_value < selection_target) {
#      80                 :       2876 :         return std::nullopt;
#      81                 :       2876 :     }
#      82                 :            : 
#      83                 :            :     // Sort the utxo_pool
#      84                 :       5113 :     std::sort(utxo_pool.begin(), utxo_pool.end(), descending);
#      85                 :            : 
#      86                 :       5113 :     CAmount curr_waste = 0;
#      87                 :       5113 :     std::vector<size_t> best_selection;
#      88                 :       5113 :     CAmount best_waste = MAX_MONEY;
#      89                 :            : 
#      90                 :            :     // Depth First search loop for choosing the UTXOs
#      91         [ +  + ]:    2817543 :     for (size_t curr_try = 0, utxo_pool_index = 0; curr_try < TOTAL_TRIES; ++curr_try, ++utxo_pool_index) {
#      92                 :            :         // Conditions for starting a backtrack
#      93                 :    2817528 :         bool backtrack = false;
#      94         [ +  + ]:    2817528 :         if (curr_value + curr_available_value < selection_target || // Cannot possibly reach target with the amount remaining in the curr_available_value.
#      95         [ +  + ]:    2817528 :             curr_value > selection_target + cost_of_change || // Selected value is out of range, go back and try other branch
#      96 [ +  + ][ -  + ]:    2817528 :             (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
#      97                 :    1074651 :             backtrack = true;
#      98         [ +  + ]:    1742877 :         } else if (curr_value >= selection_target) {       // Selected value is within range
#      99                 :        252 :             curr_waste += (curr_value - selection_target); // This is the excess value which is added to the waste for the below comparison
#     100                 :            :             // Adding another UTXO after this check could bring the waste down if the long term fee is higher than the current fee.
#     101                 :            :             // However we are not going to explore that because this optimization for the waste is only done when we have hit our target
#     102                 :            :             // value. Adding any more UTXOs will be just burning the UTXO; it will go entirely to fees. Thus we aren't going to
#     103                 :            :             // explore any more UTXOs to avoid burning money like that.
#     104         [ +  - ]:        252 :             if (curr_waste <= best_waste) {
#     105                 :        252 :                 best_selection = curr_selection;
#     106                 :        252 :                 best_waste = curr_waste;
#     107         [ +  + ]:        252 :                 if (best_waste == 0) {
#     108                 :        122 :                     break;
#     109                 :        122 :                 }
#     110                 :        252 :             }
#     111                 :        130 :             curr_waste -= (curr_value - selection_target); // Remove the excess value as we will be selecting different coins now
#     112                 :        130 :             backtrack = true;
#     113                 :        130 :         }
#     114                 :            : 
#     115         [ +  + ]:    2817406 :         if (backtrack) { // Backtracking, moving backwards
#     116         [ +  + ]:    1074781 :             if (curr_selection.empty()) { // We have walked back to the first utxo and no branch is untraversed. All solutions searched
#     117                 :       4976 :                 break;
#     118                 :       4976 :             }
#     119                 :            : 
#     120                 :            :             // Add omitted UTXOs back to lookahead before traversing the omission branch of last included UTXO.
#     121         [ +  + ]:    2521617 :             for (--utxo_pool_index; utxo_pool_index > curr_selection.back(); --utxo_pool_index) {
#     122                 :    1451812 :                 curr_available_value += utxo_pool.at(utxo_pool_index).GetSelectionAmount();
#     123                 :    1451812 :             }
#     124                 :            : 
#     125                 :            :             // Output was included on previous iterations, try excluding now.
#     126                 :    1069805 :             assert(utxo_pool_index == curr_selection.back());
#     127                 :          0 :             OutputGroup& utxo = utxo_pool.at(utxo_pool_index);
#     128                 :    1069805 :             curr_value -= utxo.GetSelectionAmount();
#     129                 :    1069805 :             curr_waste -= utxo.fee - utxo.long_term_fee;
#     130                 :    1069805 :             curr_selection.pop_back();
#     131                 :    1742625 :         } else { // Moving forwards, continuing down this branch
#     132                 :    1742625 :             OutputGroup& utxo = utxo_pool.at(utxo_pool_index);
#     133                 :            : 
#     134                 :            :             // Remove this utxo from the curr_available_value utxo amount
#     135                 :    1742625 :             curr_available_value -= utxo.GetSelectionAmount();
#     136                 :            : 
#     137         [ +  + ]:    1742625 :             if (curr_selection.empty() ||
#     138                 :            :                 // The previous index is included and therefore not relevant for exclusion shortcut
#     139         [ +  + ]:    1742625 :                 (utxo_pool_index - 1) == curr_selection.back() ||
#     140                 :            :                 // Avoid searching a branch if the previous UTXO has the same value and same waste and was excluded.
#     141                 :            :                 // 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.
#     142         [ +  + ]:    1742625 :                 utxo.GetSelectionAmount() != utxo_pool.at(utxo_pool_index - 1).GetSelectionAmount() ||
#     143         [ -  + ]:    1742625 :                 utxo.fee != utxo_pool.at(utxo_pool_index - 1).fee)
#     144                 :    1095142 :             {
#     145                 :            :                 // Inclusion branch first (Largest First Exploration)
#     146                 :    1095142 :                 curr_selection.push_back(utxo_pool_index);
#     147                 :    1095142 :                 curr_value += utxo.GetSelectionAmount();
#     148                 :    1095142 :                 curr_waste += utxo.fee - utxo.long_term_fee;
#     149                 :    1095142 :             }
#     150                 :    1742625 :         }
#     151                 :    2817406 :     }
#     152                 :            : 
#     153                 :            :     // Check for solution
#     154         [ +  + ]:       5113 :     if (best_selection.empty()) {
#     155                 :       4887 :         return std::nullopt;
#     156                 :       4887 :     }
#     157                 :            : 
#     158                 :            :     // Set output set
#     159         [ +  + ]:      26401 :     for (const size_t& i : best_selection) {
#     160                 :      26401 :         result.AddInput(utxo_pool.at(i));
#     161                 :      26401 :     }
#     162                 :        226 :     result.ComputeAndSetWaste(CAmount{0});
#     163                 :        226 :     assert(best_waste == result.GetWaste());
#     164                 :            : 
#     165                 :          0 :     return result;
#     166                 :       5113 : }
#     167                 :            : 
#     168                 :            : std::optional<SelectionResult> SelectCoinsSRD(const std::vector<OutputGroup>& utxo_pool, CAmount target_value, FastRandomContext& rng)
#     169                 :       7874 : {
#     170                 :       7874 :     SelectionResult result(target_value);
#     171                 :            : 
#     172                 :       7874 :     std::vector<size_t> indexes;
#     173                 :       7874 :     indexes.resize(utxo_pool.size());
#     174                 :       7874 :     std::iota(indexes.begin(), indexes.end(), 0);
#     175                 :       7874 :     Shuffle(indexes.begin(), indexes.end(), rng);
#     176                 :            : 
#     177                 :       7874 :     CAmount selected_eff_value = 0;
#     178         [ +  + ]:      63848 :     for (const size_t i : indexes) {
#     179                 :      63848 :         const OutputGroup& group = utxo_pool.at(i);
#     180                 :      63848 :         Assume(group.GetSelectionAmount() > 0);
#     181                 :      63848 :         selected_eff_value += group.GetSelectionAmount();
#     182                 :      63848 :         result.AddInput(group);
#     183         [ +  + ]:      63848 :         if (selected_eff_value >= target_value) {
#     184                 :       4892 :             return result;
#     185                 :       4892 :         }
#     186                 :      63848 :     }
#     187                 :       2982 :     return std::nullopt;
#     188                 :       7874 : }
#     189                 :            : 
#     190                 :            : /** Find a subset of the OutputGroups that is at least as large as, but as close as possible to, the
#     191                 :            :  * target amount; solve subset sum.
#     192                 :            :  * param@[in]   groups          OutputGroups to choose from, sorted by value in descending order.
#     193                 :            :  * param@[in]   nTotalLower     Total (effective) value of the UTXOs in groups.
#     194                 :            :  * param@[in]   nTargetValue    Subset sum target, not including change.
#     195                 :            :  * param@[out]  vfBest          Boolean vector representing the subset chosen that is closest to
#     196                 :            :  *                              nTargetValue, with indices corresponding to groups. If the ith
#     197                 :            :  *                              entry is true, that means the ith group in groups was selected.
#     198                 :            :  * param@[out]  nBest           Total amount of subset chosen that is closest to nTargetValue.
#     199                 :            :  * param@[in]   iterations      Maximum number of tries.
#     200                 :            :  */
#     201                 :            : static void ApproximateBestSubset(FastRandomContext& insecure_rand, const std::vector<OutputGroup>& groups,
#     202                 :            :                                   const CAmount& nTotalLower, const CAmount& nTargetValue,
#     203                 :            :                                   std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
#     204                 :       5899 : {
#     205                 :       5899 :     std::vector<char> vfIncluded;
#     206                 :            : 
#     207                 :            :     // Worst case "best" approximation is just all of the groups.
#     208                 :       5899 :     vfBest.assign(groups.size(), true);
#     209                 :       5899 :     nBest = nTotalLower;
#     210                 :            : 
#     211 [ +  + ][ +  + ]:    4714736 :     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
#     212                 :    4708837 :     {
#     213                 :    4708837 :         vfIncluded.assign(groups.size(), false);
#     214                 :    4708837 :         CAmount nTotal = 0;
#     215                 :    4708837 :         bool fReachedTarget = false;
#     216 [ +  + ][ +  + ]:   11576502 :         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
#     217                 :    6867665 :         {
#     218         [ +  + ]:  407552801 :             for (unsigned int i = 0; i < groups.size(); i++)
#     219                 :  400685136 :             {
#     220                 :            :                 //The solver here uses a randomized algorithm,
#     221                 :            :                 //the randomness serves no real security purpose but is just
#     222                 :            :                 //needed to prevent degenerate behavior and it is important
#     223                 :            :                 //that the rng is fast. We do not use a constant random sequence,
#     224                 :            :                 //because there may be some privacy improvement by making
#     225                 :            :                 //the selection random.
#     226 [ +  + ][ +  + ]:  400685136 :                 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
#     227                 :  201527795 :                 {
#     228                 :  201527795 :                     nTotal += groups[i].GetSelectionAmount();
#     229                 :  201527795 :                     vfIncluded[i] = true;
#     230         [ +  + ]:  201527795 :                     if (nTotal >= nTargetValue)
#     231                 :  173736011 :                     {
#     232                 :  173736011 :                         fReachedTarget = true;
#     233                 :            :                         // If the total is between nTargetValue and nBest, it's our new best
#     234                 :            :                         // approximation.
#     235         [ +  + ]:  173736011 :                         if (nTotal < nBest)
#     236                 :      28827 :                         {
#     237                 :      28827 :                             nBest = nTotal;
#     238                 :      28827 :                             vfBest = vfIncluded;
#     239                 :      28827 :                         }
#     240                 :  173736011 :                         nTotal -= groups[i].GetSelectionAmount();
#     241                 :  173736011 :                         vfIncluded[i] = false;
#     242                 :  173736011 :                     }
#     243                 :  201527795 :                 }
#     244                 :  400685136 :             }
#     245                 :    6867665 :         }
#     246                 :    4708837 :     }
#     247                 :       5899 : }
#     248                 :            : 
#     249                 :            : std::optional<SelectionResult> KnapsackSolver(std::vector<OutputGroup>& groups, const CAmount& nTargetValue,
#     250                 :            :                                               CAmount change_target, FastRandomContext& rng)
#     251                 :      13475 : {
#     252                 :      13475 :     SelectionResult result(nTargetValue);
#     253                 :            : 
#     254                 :            :     // List of values less than target
#     255                 :      13475 :     std::optional<OutputGroup> lowest_larger;
#     256                 :            :     // Groups with selection amount smaller than the target and any change we might produce.
#     257                 :            :     // Don't include groups larger than this, because they will only cause us to overshoot.
#     258                 :      13475 :     std::vector<OutputGroup> applicable_groups;
#     259                 :      13475 :     CAmount nTotalLower = 0;
#     260                 :            : 
#     261                 :      13475 :     Shuffle(groups.begin(), groups.end(), rng);
#     262                 :            : 
#     263         [ +  + ]:     733047 :     for (const OutputGroup& group : groups) {
#     264         [ +  + ]:     733047 :         if (group.GetSelectionAmount() == nTargetValue) {
#     265                 :       1100 :             result.AddInput(group);
#     266                 :       1100 :             return result;
#     267         [ +  + ]:     731947 :         } else if (group.GetSelectionAmount() < nTargetValue + change_target) {
#     268                 :     362663 :             applicable_groups.push_back(group);
#     269                 :     362663 :             nTotalLower += group.GetSelectionAmount();
#     270 [ +  + ][ +  + ]:     369284 :         } else if (!lowest_larger || group.GetSelectionAmount() < lowest_larger->GetSelectionAmount()) {
#     271                 :      12646 :             lowest_larger = group;
#     272                 :      12646 :         }
#     273                 :     733047 :     }
#     274                 :            : 
#     275         [ +  + ]:      12375 :     if (nTotalLower == nTargetValue) {
#     276         [ +  + ]:       1902 :         for (const auto& group : applicable_groups) {
#     277                 :       1902 :             result.AddInput(group);
#     278                 :       1902 :         }
#     279                 :        501 :         return result;
#     280                 :        501 :     }
#     281                 :            : 
#     282         [ +  + ]:      11874 :     if (nTotalLower < nTargetValue) {
#     283         [ +  + ]:       8374 :         if (!lowest_larger) return std::nullopt;
#     284                 :       4807 :         result.AddInput(*lowest_larger);
#     285                 :       4807 :         return result;
#     286                 :       8374 :     }
#     287                 :            : 
#     288                 :            :     // Solve subset sum by stochastic approximation
#     289                 :       3500 :     std::sort(applicable_groups.begin(), applicable_groups.end(), descending);
#     290                 :       3500 :     std::vector<char> vfBest;
#     291                 :       3500 :     CAmount nBest;
#     292                 :            : 
#     293                 :       3500 :     ApproximateBestSubset(rng, applicable_groups, nTotalLower, nTargetValue, vfBest, nBest);
#     294 [ +  + ][ +  + ]:       3500 :     if (nBest != nTargetValue && nTotalLower >= nTargetValue + change_target) {
#     295                 :       2399 :         ApproximateBestSubset(rng, applicable_groups, nTotalLower, nTargetValue + change_target, vfBest, nBest);
#     296                 :       2399 :     }
#     297                 :            : 
#     298                 :            :     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
#     299                 :            :     //                                   or the next bigger coin is closer), return the bigger coin
#     300         [ +  + ]:       3500 :     if (lowest_larger &&
#     301 [ +  + ][ +  + ]:       3500 :         ((nBest != nTargetValue && nBest < nTargetValue + change_target) || lowest_larger->GetSelectionAmount() <= nBest)) {
#                 [ +  + ]
#     302                 :        316 :         result.AddInput(*lowest_larger);
#     303                 :       3184 :     } else {
#     304         [ +  + ]:     346607 :         for (unsigned int i = 0; i < applicable_groups.size(); i++) {
#     305         [ +  + ]:     343423 :             if (vfBest[i]) {
#     306                 :     130037 :                 result.AddInput(applicable_groups[i]);
#     307                 :     130037 :             }
#     308                 :     343423 :         }
#     309                 :            : 
#     310         [ +  - ]:       3184 :         if (LogAcceptCategory(BCLog::SELECTCOINS)) {
#     311                 :       3184 :             std::string log_message{"Coin selection best subset: "};
#     312         [ +  + ]:     346607 :             for (unsigned int i = 0; i < applicable_groups.size(); i++) {
#     313         [ +  + ]:     343423 :                 if (vfBest[i]) {
#     314                 :     130037 :                     log_message += strprintf("%s ", FormatMoney(applicable_groups[i].m_value));
#     315                 :     130037 :                 }
#     316                 :     343423 :             }
#     317         [ +  - ]:       3184 :             LogPrint(BCLog::SELECTCOINS, "%stotal %s\n", log_message, FormatMoney(nBest));
#     318                 :       3184 :         }
#     319                 :       3184 :     }
#     320                 :            : 
#     321                 :       3500 :     return result;
#     322                 :      11874 : }
#     323                 :            : 
#     324                 :            : /******************************************************************************
#     325                 :            : 
#     326                 :            :  OutputGroup
#     327                 :            : 
#     328                 :            :  ******************************************************************************/
#     329                 :            : 
#     330                 :    1671844 : void OutputGroup::Insert(const COutput& output, size_t ancestors, size_t descendants, bool positive_only) {
#     331                 :            :     // Compute the effective value first
#     332         [ +  + ]:    1671844 :     const CAmount coin_fee = output.input_bytes < 0 ? 0 : m_effective_feerate.GetFee(output.input_bytes);
#     333                 :    1671844 :     const CAmount ev = output.txout.nValue - coin_fee;
#     334                 :            : 
#     335                 :            :     // Filter for positive only here before adding the coin
#     336 [ +  + ][ +  + ]:    1671844 :     if (positive_only && ev <= 0) return;
#     337                 :            : 
#     338                 :    1671822 :     m_outputs.push_back(output);
#     339                 :    1671822 :     COutput& coin = m_outputs.back();
#     340                 :            : 
#     341                 :    1671822 :     coin.fee = coin_fee;
#     342                 :    1671822 :     fee += coin.fee;
#     343                 :            : 
#     344         [ +  + ]:    1671822 :     coin.long_term_fee = coin.input_bytes < 0 ? 0 : m_long_term_feerate.GetFee(coin.input_bytes);
#     345                 :    1671822 :     long_term_fee += coin.long_term_fee;
#     346                 :            : 
#     347                 :    1671822 :     coin.effective_value = ev;
#     348                 :    1671822 :     effective_value += coin.effective_value;
#     349                 :            : 
#     350                 :    1671822 :     m_from_me &= coin.from_me;
#     351                 :    1671822 :     m_value += coin.txout.nValue;
#     352                 :    1671822 :     m_depth = std::min(m_depth, coin.depth);
#     353                 :            :     // ancestors here express the number of ancestors the new coin will end up having, which is
#     354                 :            :     // the sum, rather than the max; this will overestimate in the cases where multiple inputs
#     355                 :            :     // have common ancestors
#     356                 :    1671822 :     m_ancestors += ancestors;
#     357                 :            :     // descendants is the count as seen from the top ancestor, not the descendants as seen from the
#     358                 :            :     // coin itself; thus, this value is counted as the max, not the sum
#     359                 :    1671822 :     m_descendants = std::max(m_descendants, descendants);
#     360                 :    1671822 : }
#     361                 :            : 
#     362                 :            : bool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const
#     363                 :    1192403 : {
#     364 [ +  + ][ +  + ]:    1192403 :     return m_depth >= (m_from_me ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs)
#     365         [ +  + ]:    1192403 :         && m_ancestors <= eligibility_filter.max_ancestors
#     366         [ +  + ]:    1192403 :         && m_descendants <= eligibility_filter.max_descendants;
#     367                 :    1192403 : }
#     368                 :            : 
#     369                 :            : CAmount OutputGroup::GetSelectionAmount() const
#     370                 :  393830462 : {
#     371         [ +  + ]:  393830462 :     return m_subtract_fee_outputs ? m_value : effective_value;
#     372                 :  393830462 : }
#     373                 :            : 
#     374                 :            : CAmount GetSelectionWaste(const std::set<COutput>& inputs, CAmount change_cost, CAmount target, bool use_effective_value)
#     375                 :      10035 : {
#     376                 :            :     // This function should not be called with empty inputs as that would mean the selection failed
#     377                 :      10035 :     assert(!inputs.empty());
#     378                 :            : 
#     379                 :            :     // Always consider the cost of spending an input now vs in the future.
#     380                 :          0 :     CAmount waste = 0;
#     381                 :      10035 :     CAmount selected_effective_value = 0;
#     382         [ +  + ]:     167723 :     for (const COutput& coin : inputs) {
#     383                 :     167723 :         waste += coin.fee - coin.long_term_fee;
#     384         [ +  + ]:     167723 :         selected_effective_value += use_effective_value ? coin.effective_value : coin.txout.nValue;
#     385                 :     167723 :     }
#     386                 :            : 
#     387         [ +  + ]:      10035 :     if (change_cost) {
#     388                 :            :         // Consider the cost of making change and spending it in the future
#     389                 :            :         // If we aren't making change, the caller should've set change_cost to 0
#     390                 :       9603 :         assert(change_cost > 0);
#     391                 :          0 :         waste += change_cost;
#     392                 :       9603 :     } else {
#     393                 :            :         // When we are not making change (change_cost == 0), consider the excess we are throwing away to fees
#     394                 :        432 :         assert(selected_effective_value >= target);
#     395                 :          0 :         waste += selected_effective_value - target;
#     396                 :        432 :     }
#     397                 :            : 
#     398                 :          0 :     return waste;
#     399                 :      10035 : }
#     400                 :            : 
#     401                 :            : CAmount GenerateChangeTarget(CAmount payment_value, FastRandomContext& rng)
#     402                 :       5447 : {
#     403         [ +  + ]:       5447 :     if (payment_value <= CHANGE_LOWER / 2) {
#     404                 :        140 :         return CHANGE_LOWER;
#     405                 :       5307 :     } else {
#     406                 :            :         // random value between 50ksat and min (payment_value * 2, 1milsat)
#     407                 :       5307 :         const auto upper_bound = std::min(payment_value * 2, CHANGE_UPPER);
#     408                 :       5307 :         return rng.randrange(upper_bound - CHANGE_LOWER) + CHANGE_LOWER;
#     409                 :       5307 :     }
#     410                 :       5447 : }
#     411                 :            : 
#     412                 :            : void SelectionResult::ComputeAndSetWaste(CAmount change_cost)
#     413                 :      10025 : {
#     414                 :      10025 :     m_waste = GetSelectionWaste(m_selected_inputs, change_cost, m_target, m_use_effective);
#     415                 :      10025 : }
#     416                 :            : 
#     417                 :            : CAmount SelectionResult::GetWaste() const
#     418                 :        226 : {
#     419                 :        226 :     return *Assert(m_waste);
#     420                 :        226 : }
#     421                 :            : 
#     422                 :            : CAmount SelectionResult::GetSelectedValue() const
#     423                 :       8161 : {
#     424                 :     137294 :     return std::accumulate(m_selected_inputs.cbegin(), m_selected_inputs.cend(), CAmount{0}, [](CAmount sum, const auto& coin) { return sum + coin.txout.nValue; });
#     425                 :       8161 : }
#     426                 :            : 
#     427                 :            : void SelectionResult::Clear()
#     428                 :          8 : {
#     429                 :          8 :     m_selected_inputs.clear();
#     430                 :          8 :     m_waste.reset();
#     431                 :          8 : }
#     432                 :            : 
#     433                 :            : void SelectionResult::AddInput(const OutputGroup& group)
#     434                 :     233880 : {
#     435                 :     233880 :     util::insert(m_selected_inputs, group.m_outputs);
#     436                 :     233880 :     m_use_effective = !group.m_subtract_fee_outputs;
#     437                 :     233880 : }
#     438                 :            : 
#     439                 :            : const std::set<COutput>& SelectionResult::GetInputSet() const
#     440                 :       6423 : {
#     441                 :       6423 :     return m_selected_inputs;
#     442                 :       6423 : }
#     443                 :            : 
#     444                 :            : std::vector<COutput> SelectionResult::GetShuffledInputVector() const
#     445                 :       5352 : {
#     446                 :       5352 :     std::vector<COutput> coins(m_selected_inputs.begin(), m_selected_inputs.end());
#     447                 :       5352 :     Shuffle(coins.begin(), coins.end(), FastRandomContext());
#     448                 :       5352 :     return coins;
#     449                 :       5352 : }
#     450                 :            : 
#     451                 :            : bool SelectionResult::operator<(SelectionResult other) const
#     452                 :       5015 : {
#     453                 :       5015 :     Assert(m_waste.has_value());
#     454                 :       5015 :     Assert(other.m_waste.has_value());
#     455                 :            :     // As this operator is only used in std::min_element, we want the result that has more inputs when waste are equal.
#     456 [ +  + ][ +  + ]:       5015 :     return *m_waste < *other.m_waste || (*m_waste == *other.m_waste && m_selected_inputs.size() > other.m_selected_inputs.size());
#                 [ +  + ]
#     457                 :       5015 : }
#     458                 :            : 
#     459                 :            : std::string COutput::ToString() const
#     460                 :          0 : {
#     461                 :          0 :     return strprintf("COutput(%s, %d, %d) [%s]", outpoint.hash.ToString(), outpoint.n, depth, FormatMoney(txout.nValue));
#     462                 :          0 : }
#     463                 :            : } // namespace wallet

Generated by: LCOV version 0-eol-96201-ge66f56f4af6a