Coverage Report

Created: 2024-11-15 12:18

/root/bitcoin/src/wallet/coinselection.h
Line
Count
Source (jump to first uncovered line)
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
#ifndef BITCOIN_WALLET_COINSELECTION_H
6
#define BITCOIN_WALLET_COINSELECTION_H
7
8
#include <consensus/amount.h>
9
#include <consensus/consensus.h>
10
#include <outputtype.h>
11
#include <policy/feerate.h>
12
#include <primitives/transaction.h>
13
#include <random.h>
14
#include <util/check.h>
15
#include <util/insert.h>
16
#include <util/result.h>
17
18
#include <optional>
19
20
21
namespace wallet {
22
//! lower bound for randomly-chosen target change amount
23
static constexpr CAmount CHANGE_LOWER{50000};
24
//! upper bound for randomly-chosen target change amount
25
static constexpr CAmount CHANGE_UPPER{1000000};
26
27
/** A UTXO under consideration for use in funding a new transaction. */
28
struct COutput {
29
private:
30
    /** The output's value minus fees required to spend it and bump its unconfirmed ancestors to the target feerate. */
31
    std::optional<CAmount> effective_value;
32
33
    /** The fee required to spend this output at the transaction's target feerate and to bump its unconfirmed ancestors to the target feerate. */
34
    std::optional<CAmount> fee;
35
36
public:
37
    /** The outpoint identifying this UTXO */
38
    COutPoint outpoint;
39
40
    /** The output itself */
41
    CTxOut txout;
42
43
    /**
44
     * Depth in block chain.
45
     * If > 0: the tx is on chain and has this many confirmations.
46
     * If = 0: the tx is waiting confirmation.
47
     * If < 0: a conflicting tx is on chain and has this many confirmations. */
48
    int depth;
49
50
    /** Pre-computed estimated size of this output as a fully-signed input in a transaction. Can be -1 if it could not be calculated */
51
    int input_bytes;
52
53
    /** Whether we have the private keys to spend this output */
54
    bool spendable;
55
56
    /** Whether we know how to spend this output, ignoring the lack of keys */
57
    bool solvable;
58
59
    /**
60
     * Whether this output is considered safe to spend. Unconfirmed transactions
61
     * from outside keys and unconfirmed replacement transactions are considered
62
     * unsafe and will not be used to fund new spending transactions.
63
     */
64
    bool safe;
65
66
    /** The time of the transaction containing this output as determined by CWalletTx::nTimeSmart */
67
    int64_t time;
68
69
    /** Whether the transaction containing this output is sent from the owning wallet */
70
    bool from_me;
71
72
    /** The fee required to spend this output at the consolidation feerate. */
73
    CAmount long_term_fee{0};
74
75
    /** The fee necessary to bump this UTXO's ancestor transactions to the target feerate */
76
    CAmount ancestor_bump_fees{0};
77
78
    COutput(const COutPoint& outpoint, const CTxOut& txout, int depth, int input_bytes, bool spendable, bool solvable, bool safe, int64_t time, bool from_me, const std::optional<CFeeRate> feerate = std::nullopt)
79
0
        : outpoint{outpoint},
80
0
          txout{txout},
81
0
          depth{depth},
82
0
          input_bytes{input_bytes},
83
0
          spendable{spendable},
84
0
          solvable{solvable},
85
0
          safe{safe},
86
0
          time{time},
87
0
          from_me{from_me}
88
0
    {
89
0
        if (feerate) {
90
            // base fee without considering potential unconfirmed ancestors
91
0
            fee = input_bytes < 0 ? 0 : feerate.value().GetFee(input_bytes);
92
0
            effective_value = txout.nValue - fee.value();
93
0
        }
94
0
    }
95
96
    COutput(const COutPoint& outpoint, const CTxOut& txout, int depth, int input_bytes, bool spendable, bool solvable, bool safe, int64_t time, bool from_me, const CAmount fees)
97
        : COutput(outpoint, txout, depth, input_bytes, spendable, solvable, safe, time, from_me)
98
0
    {
99
0
        // if input_bytes is unknown, then fees should be 0, if input_bytes is known, then the fees should be a positive integer or 0 (input_bytes known and fees = 0 only happens in the tests)
100
0
        assert((input_bytes < 0 && fees == 0) || (input_bytes > 0 && fees >= 0));
101
0
        fee = fees;
102
0
        effective_value = txout.nValue - fee.value();
103
0
    }
104
105
    std::string ToString() const;
106
107
    bool operator<(const COutput& rhs) const
108
0
    {
109
0
        return outpoint < rhs.outpoint;
110
0
    }
111
112
    void ApplyBumpFee(CAmount bump_fee)
113
0
    {
114
0
        assert(bump_fee >= 0);
115
0
        ancestor_bump_fees = bump_fee;
116
0
        assert(fee);
117
0
        *fee += bump_fee;
118
        // Note: assert(effective_value - bump_fee == nValue - fee.value());
119
0
        effective_value = txout.nValue - fee.value();
120
0
    }
121
122
    CAmount GetFee() const
123
0
    {
124
0
        assert(fee.has_value());
125
0
        return fee.value();
126
0
    }
127
128
    CAmount GetEffectiveValue() const
129
0
    {
130
0
        assert(effective_value.has_value());
131
0
        return effective_value.value();
132
0
    }
133
134
0
    bool HasEffectiveValue() const { return effective_value.has_value(); }
135
};
136
137
/** Parameters for one iteration of Coin Selection. */
138
struct CoinSelectionParams {
139
    /** Randomness to use in the context of coin selection. */
140
    FastRandomContext& rng_fast;
141
    /** Size of a change output in bytes, determined by the output type. */
142
    int change_output_size = 0;
143
    /** Size of the input to spend a change output in virtual bytes. */
144
    int change_spend_size = 0;
145
    /** Mininmum change to target in Knapsack solver and CoinGrinder:
146
     * select coins to cover the payment and at least this value of change. */
147
    CAmount m_min_change_target{0};
148
    /** Minimum amount for creating a change output.
149
     * If change budget is smaller than min_change then we forgo creation of change output.
150
     */
151
    CAmount min_viable_change{0};
152
    /** Cost of creating the change output. */
153
    CAmount m_change_fee{0};
154
    /** Cost of creating the change output + cost of spending the change output in the future. */
155
    CAmount m_cost_of_change{0};
156
    /** The targeted feerate of the transaction being built. */
157
    CFeeRate m_effective_feerate;
158
    /** The feerate estimate used to estimate an upper bound on what should be sufficient to spend
159
     * the change output sometime in the future. */
160
    CFeeRate m_long_term_feerate;
161
    /** If the cost to spend a change output at the discard feerate exceeds its value, drop it to fees. */
162
    CFeeRate m_discard_feerate;
163
    /** Size of the transaction before coin selection, consisting of the header and recipient
164
     * output(s), excluding the inputs and change output(s). */
165
    int tx_noinputs_size = 0;
166
    /** Indicate that we are subtracting the fee from outputs */
167
    bool m_subtract_fee_outputs = false;
168
    /** When true, always spend all (up to OUTPUT_GROUP_MAX_ENTRIES) or none of the outputs
169
     * associated with the same address. This helps reduce privacy leaks resulting from address
170
     * reuse. Dust outputs are not eligible to be added to output groups and thus not considered. */
171
    bool m_avoid_partial_spends = false;
172
    /**
173
     * When true, allow unsafe coins to be selected during Coin Selection. This may spend unconfirmed outputs:
174
     * 1) Received from other wallets, 2) replacing other txs, 3) that have been replaced.
175
     */
176
    bool m_include_unsafe_inputs = false;
177
    /** The maximum weight for this transaction. */
178
    std::optional<int> m_max_tx_weight{std::nullopt};
179
180
    CoinSelectionParams(FastRandomContext& rng_fast, int change_output_size, int change_spend_size,
181
                        CAmount min_change_target, CFeeRate effective_feerate,
182
                        CFeeRate long_term_feerate, CFeeRate discard_feerate, int tx_noinputs_size, bool avoid_partial,
183
                        std::optional<int> max_tx_weight = std::nullopt)
184
        : rng_fast{rng_fast},
185
          change_output_size(change_output_size),
186
          change_spend_size(change_spend_size),
187
          m_min_change_target(min_change_target),
188
          m_effective_feerate(effective_feerate),
189
          m_long_term_feerate(long_term_feerate),
190
          m_discard_feerate(discard_feerate),
191
          tx_noinputs_size(tx_noinputs_size),
192
          m_avoid_partial_spends(avoid_partial),
193
          m_max_tx_weight(max_tx_weight)
194
0
    {
195
0
    }
196
    CoinSelectionParams(FastRandomContext& rng_fast)
197
0
        : rng_fast{rng_fast} {}
198
};
199
200
/** Parameters for filtering which OutputGroups we may use in coin selection.
201
 * We start by being very selective and requiring multiple confirmations and
202
 * then get more permissive if we cannot fund the transaction. */
203
struct CoinEligibilityFilter
204
{
205
    /** Minimum number of confirmations for outputs that we sent to ourselves.
206
     * We may use unconfirmed UTXOs sent from ourselves, e.g. change outputs. */
207
    const int conf_mine;
208
    /** Minimum number of confirmations for outputs received from a different wallet. */
209
    const int conf_theirs;
210
    /** Maximum number of unconfirmed ancestors aggregated across all UTXOs in an OutputGroup. */
211
    const uint64_t max_ancestors;
212
    /** Maximum number of descendants that a single UTXO in the OutputGroup may have. */
213
    const uint64_t max_descendants;
214
    /** When avoid_reuse=true and there are full groups (OUTPUT_GROUP_MAX_ENTRIES), whether or not to use any partial groups.*/
215
    const bool m_include_partial_groups{false};
216
217
    CoinEligibilityFilter() = delete;
218
0
    CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_ancestors) {}
219
0
    CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors, uint64_t max_descendants) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_descendants) {}
220
0
    CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors, uint64_t max_descendants, bool include_partial) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_descendants), m_include_partial_groups(include_partial) {}
221
222
0
    bool operator<(const CoinEligibilityFilter& other) const {
223
0
        return std::tie(conf_mine, conf_theirs, max_ancestors, max_descendants, m_include_partial_groups)
224
0
               < std::tie(other.conf_mine, other.conf_theirs, other.max_ancestors, other.max_descendants, other.m_include_partial_groups);
225
0
    }
226
};
227
228
/** A group of UTXOs paid to the same output script. */
229
struct OutputGroup
230
{
231
    /** The list of UTXOs contained in this output group. */
232
    std::vector<std::shared_ptr<COutput>> m_outputs;
233
    /** Whether the UTXOs were sent by the wallet to itself. This is relevant because we may want at
234
     * least a certain number of confirmations on UTXOs received from outside wallets while trusting
235
     * our own UTXOs more. */
236
    bool m_from_me{true};
237
    /** The total value of the UTXOs in sum. */
238
    CAmount m_value{0};
239
    /** The minimum number of confirmations the UTXOs in the group have. Unconfirmed is 0. */
240
    int m_depth{999};
241
    /** The aggregated count of unconfirmed ancestors of all UTXOs in this
242
     * group. Not deduplicated and may overestimate when ancestors are shared. */
243
    size_t m_ancestors{0};
244
    /** The maximum count of descendants of a single UTXO in this output group. */
245
    size_t m_descendants{0};
246
    /** The value of the UTXOs after deducting the cost of spending them at the effective feerate. */
247
    CAmount effective_value{0};
248
    /** The fee to spend these UTXOs at the effective feerate. */
249
    CAmount fee{0};
250
    /** The fee to spend these UTXOs at the long term feerate. */
251
    CAmount long_term_fee{0};
252
    /** The feerate for spending a created change output eventually (i.e. not urgently, and thus at
253
     * a lower feerate). Calculated using long term fee estimate. This is used to decide whether
254
     * it could be economical to create a change output. */
255
    CFeeRate m_long_term_feerate{0};
256
    /** Indicate that we are subtracting the fee from outputs.
257
     * When true, the value that is used for coin selection is the UTXO's real value rather than effective value */
258
    bool m_subtract_fee_outputs{false};
259
    /** Total weight of the UTXOs in this group. */
260
    int m_weight{0};
261
262
    OutputGroup() = default;
263
    OutputGroup(const CoinSelectionParams& params) :
264
0
        m_long_term_feerate(params.m_long_term_feerate),
265
0
        m_subtract_fee_outputs(params.m_subtract_fee_outputs)
266
0
    {}
267
268
    void Insert(const std::shared_ptr<COutput>& output, size_t ancestors, size_t descendants);
269
    bool EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const;
270
    CAmount GetSelectionAmount() const;
271
};
272
273
struct Groups {
274
    // Stores 'OutputGroup' containing only positive UTXOs (value > 0).
275
    std::vector<OutputGroup> positive_group;
276
    // Stores 'OutputGroup' which may contain both positive and negative UTXOs.
277
    std::vector<OutputGroup> mixed_group;
278
};
279
280
/** Stores several 'Groups' whose were mapped by output type. */
281
struct OutputGroupTypeMap
282
{
283
    // Maps output type to output groups.
284
    std::map<OutputType, Groups> groups_by_type;
285
    // All inserted groups, no type distinction.
286
    Groups all_groups;
287
288
    // Based on the insert flag; appends group to the 'mixed_group' and, if value > 0, to the 'positive_group'.
289
    // This affects both; the groups filtered by type and the overall groups container.
290
    void Push(const OutputGroup& group, OutputType type, bool insert_positive, bool insert_mixed);
291
    // Different output types count
292
0
    size_t TypesCount() { return groups_by_type.size(); }
293
};
294
295
typedef std::map<CoinEligibilityFilter, OutputGroupTypeMap> FilteredOutputGroups;
296
297
/** Choose a random change target for each transaction to make it harder to fingerprint the Core
298
 * wallet based on the change output values of transactions it creates.
299
 * Change target covers at least change fees and adds a random value on top of it.
300
 * The random value is between 50ksat and min(2 * payment_value, 1milsat)
301
 * When payment_value <= 25ksat, the value is just 50ksat.
302
 *
303
 * Making change amounts similar to the payment value may help disguise which output(s) are payments
304
 * are which ones are change. Using double the payment value may increase the number of inputs
305
 * needed (and thus be more expensive in fees), but breaks analysis techniques which assume the
306
 * coins selected are just sufficient to cover the payment amount ("unnecessary input" heuristic).
307
 *
308
 * @param[in]   payment_value   Average payment value of the transaction output(s).
309
 * @param[in]   change_fee      Fee for creating a change output.
310
 */
311
[[nodiscard]] CAmount GenerateChangeTarget(const CAmount payment_value, const CAmount change_fee, FastRandomContext& rng);
312
313
enum class SelectionAlgorithm : uint8_t
314
{
315
    BNB = 0,
316
    KNAPSACK = 1,
317
    SRD = 2,
318
    CG = 3,
319
    MANUAL = 4,
320
};
321
322
std::string GetAlgorithmName(const SelectionAlgorithm algo);
323
324
struct SelectionResult
325
{
326
private:
327
    /** Set of inputs selected by the algorithm to use in the transaction */
328
    std::set<std::shared_ptr<COutput>> m_selected_inputs;
329
    /** The target the algorithm selected for. Equal to the recipient amount plus non-input fees */
330
    CAmount m_target;
331
    /** The algorithm used to produce this result */
332
    SelectionAlgorithm m_algo;
333
    /** Whether the input values for calculations should be the effective value (true) or normal value (false) */
334
    bool m_use_effective{false};
335
    /** The computed waste */
336
    std::optional<CAmount> m_waste;
337
    /** False if algorithm was cut short by hitting limit of attempts and solution is non-optimal */
338
    bool m_algo_completed{true};
339
    /** The count of selections that were evaluated by this coin selection attempt */
340
    size_t m_selections_evaluated;
341
    /** Total weight of the selected inputs */
342
    int m_weight{0};
343
    /** How much individual inputs overestimated the bump fees for the shared ancestry */
344
    CAmount bump_fee_group_discount{0};
345
346
    template<typename T>
347
    void InsertInputs(const T& inputs)
348
0
    {
349
        // Store sum of combined input sets to check that the results have no shared UTXOs
350
0
        const size_t expected_count = m_selected_inputs.size() + inputs.size();
351
0
        util::insert(m_selected_inputs, inputs);
352
0
        if (m_selected_inputs.size() != expected_count) {
353
0
            throw std::runtime_error(STR_INTERNAL_BUG("Shared UTXOs among selection results"));
354
0
        }
355
0
    }
Unexecuted instantiation: _ZN6wallet15SelectionResult12InsertInputsISt6vectorISt10shared_ptrINS_7COutputEESaIS5_EEEEvRKT_
Unexecuted instantiation: _ZN6wallet15SelectionResult12InsertInputsISt3setISt10shared_ptrINS_7COutputEESt4lessIS5_ESaIS5_EEEEvRKT_
356
357
public:
358
    explicit SelectionResult(const CAmount target, SelectionAlgorithm algo)
359
0
        : m_target(target), m_algo(algo) {}
360
361
    SelectionResult() = delete;
362
363
    /** Get the sum of the input values */
364
    [[nodiscard]] CAmount GetSelectedValue() const;
365
366
    [[nodiscard]] CAmount GetSelectedEffectiveValue() const;
367
368
    [[nodiscard]] CAmount GetTotalBumpFees() const;
369
370
    void Clear();
371
372
    void AddInput(const OutputGroup& group);
373
    void AddInputs(const std::set<std::shared_ptr<COutput>>& inputs, bool subtract_fee_outputs);
374
375
    /** How much individual inputs overestimated the bump fees for shared ancestries */
376
    void SetBumpFeeDiscount(const CAmount discount);
377
378
    /** Calculates and stores the waste for this result given the cost of change
379
     * and the opportunity cost of spending these inputs now vs in the future.
380
     * If change exists, waste = change_cost + inputs * (effective_feerate - long_term_feerate) - bump_fee_group_discount
381
     * If no change, waste = excess + inputs * (effective_feerate - long_term_feerate) - bump_fee_group_discount
382
     * where excess = selected_effective_value - target
383
     * change_cost = effective_feerate * change_output_size + long_term_feerate * change_spend_size
384
     *
385
     * @param[in] min_viable_change The minimum amount necessary to make a change output economic
386
     * @param[in] change_cost       The cost of creating a change output and spending it in the future. Only
387
     *                              used if there is change, in which case it must be non-negative.
388
     * @param[in] change_fee        The fee for creating a change output
389
     */
390
    void RecalculateWaste(const CAmount min_viable_change, const CAmount change_cost, const CAmount change_fee);
391
    [[nodiscard]] CAmount GetWaste() const;
392
393
    /** Tracks that algorithm was able to exhaustively search the entire combination space before hitting limit of tries */
394
    void SetAlgoCompleted(bool algo_completed);
395
396
    /** Get m_algo_completed */
397
    bool GetAlgoCompleted() const;
398
399
    /** Record the number of selections that were evaluated */
400
    void SetSelectionsEvaluated(size_t attempts);
401
402
    /** Get selections_evaluated */
403
    size_t GetSelectionsEvaluated() const ;
404
405
    /**
406
     * Combines the @param[in] other selection result into 'this' selection result.
407
     *
408
     * Important note:
409
     * There must be no shared 'COutput' among the two selection results being combined.
410
     */
411
    void Merge(const SelectionResult& other);
412
413
    /** Get m_selected_inputs */
414
    const std::set<std::shared_ptr<COutput>>& GetInputSet() const;
415
    /** Get the vector of COutputs that will be used to fill in a CTransaction's vin */
416
    std::vector<std::shared_ptr<COutput>> GetShuffledInputVector() const;
417
418
    bool operator<(SelectionResult other) const;
419
420
    /** Get the amount for the change output after paying needed fees.
421
     *
422
     * The change amount is not 100% precise due to discrepancies in fee calculation.
423
     * The final change amount (if any) should be corrected after calculating the final tx fees.
424
     * When there is a discrepancy, most of the time the final change would be slightly bigger than estimated.
425
     *
426
     * Following are the possible factors of discrepancy:
427
     *  + non-input fees always include segwit flags
428
     *  + input fee estimation always include segwit stack size
429
     *  + input fees are rounded individually and not collectively, which leads to small rounding errors
430
     *  - input counter size is always assumed to be 1vbyte
431
     *
432
     * @param[in]  min_viable_change  Minimum amount for change output, if change would be less then we forgo change
433
     * @param[in]  change_fee         Fees to include change output in the tx
434
     * @returns Amount for change output, 0 when there is no change.
435
     *
436
     */
437
    CAmount GetChange(const CAmount min_viable_change, const CAmount change_fee) const;
438
439
0
    CAmount GetTarget() const { return m_target; }
440
441
0
    SelectionAlgorithm GetAlgo() const { return m_algo; }
442
443
0
    int GetWeight() const { return m_weight; }
444
};
445
446
util::Result<SelectionResult> SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, const CAmount& cost_of_change,
447
                                             int max_selection_weight);
448
449
util::Result<SelectionResult> CoinGrinder(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, CAmount change_target, int max_selection_weight);
450
451
/** Select coins by Single Random Draw. OutputGroups are selected randomly from the eligible
452
 * outputs until the target is satisfied
453
 *
454
 * @param[in]  utxo_pool    The positive effective value OutputGroups eligible for selection
455
 * @param[in]  target_value The target value to select for
456
 * @param[in]  rng The randomness source to shuffle coins
457
 * @param[in]  max_selection_weight The maximum allowed weight for a selection result to be valid
458
 * @returns If successful, a valid SelectionResult, otherwise, util::Error
459
 */
460
util::Result<SelectionResult> SelectCoinsSRD(const std::vector<OutputGroup>& utxo_pool, CAmount target_value, CAmount change_fee, FastRandomContext& rng,
461
                                             int max_selection_weight);
462
463
// Original coin selection algorithm as a fallback
464
util::Result<SelectionResult> KnapsackSolver(std::vector<OutputGroup>& groups, const CAmount& nTargetValue,
465
                                             CAmount change_target, FastRandomContext& rng, int max_selection_weight);
466
} // namespace wallet
467
468
#endif // BITCOIN_WALLET_COINSELECTION_H