Bitcoin Core Fuzz Coverage Report

Coverage Report

Created: 2026-03-24 13:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/wallet/spend.cpp
Line
Count
Source
1
// Copyright (c) 2021-present 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 <algorithm>
6
#include <common/args.h>
7
#include <common/messages.h>
8
#include <common/system.h>
9
#include <consensus/amount.h>
10
#include <consensus/validation.h>
11
#include <interfaces/chain.h>
12
#include <node/types.h>
13
#include <numeric>
14
#include <policy/policy.h>
15
#include <policy/truc_policy.h>
16
#include <primitives/transaction.h>
17
#include <primitives/transaction_identifier.h>
18
#include <script/script.h>
19
#include <script/signingprovider.h>
20
#include <script/solver.h>
21
#include <util/check.h>
22
#include <util/moneystr.h>
23
#include <util/rbf.h>
24
#include <util/trace.h>
25
#include <util/translation.h>
26
#include <wallet/coincontrol.h>
27
#include <wallet/fees.h>
28
#include <wallet/receive.h>
29
#include <wallet/spend.h>
30
#include <wallet/transaction.h>
31
#include <wallet/wallet.h>
32
33
#include <cmath>
34
35
using common::StringForFeeReason;
36
using common::TransactionErrorString;
37
using interfaces::FoundBlock;
38
using node::TransactionError;
39
40
TRACEPOINT_SEMAPHORE(coin_selection, selected_coins);
41
TRACEPOINT_SEMAPHORE(coin_selection, normal_create_tx_internal);
42
TRACEPOINT_SEMAPHORE(coin_selection, attempting_aps_create_tx);
43
TRACEPOINT_SEMAPHORE(coin_selection, aps_create_tx_internal);
44
45
namespace wallet {
46
static constexpr size_t OUTPUT_GROUP_MAX_ENTRIES{100};
47
48
/** Whether the descriptor represents, directly or not, a witness program. */
49
0
static bool IsSegwit(const Descriptor& desc) {
50
0
    if (const auto typ = desc.GetOutputType()) return *typ != OutputType::LEGACY;
51
0
    return false;
52
0
}
53
54
/** Whether to assume ECDSA signatures' will be high-r. */
55
0
static bool UseMaxSig(const std::optional<CTxIn>& txin, const CCoinControl* coin_control) {
56
    // Use max sig if watch only inputs were used or if this particular input is an external input
57
    // to ensure a sufficient fee is attained for the requested feerate.
58
0
    return coin_control && txin && coin_control->IsExternalSelected(txin->prevout);
59
0
}
60
61
/** Get the size of an input (in witness units) once it's signed.
62
 *
63
 * @param desc The output script descriptor of the coin spent by this input.
64
 * @param txin Optionally the txin to estimate the size of. Used to determine the size of ECDSA signatures.
65
 * @param coin_control Information about the context to determine the size of ECDSA signatures.
66
 * @param tx_is_segwit Whether the transaction has at least a single input spending a segwit coin.
67
 * @param can_grind_r Whether the signer will be able to grind the R of the signature.
68
 */
69
static std::optional<int64_t> MaxInputWeight(const Descriptor& desc, const std::optional<CTxIn>& txin,
70
                                             const CCoinControl* coin_control, const bool tx_is_segwit,
71
0
                                             const bool can_grind_r) {
72
0
    if (const auto sat_weight = desc.MaxSatisfactionWeight(!can_grind_r || UseMaxSig(txin, coin_control))) {
73
0
        if (const auto elems_count = desc.MaxSatisfactionElems()) {
74
0
            const bool is_segwit = IsSegwit(desc);
75
            // Account for the size of the scriptsig and the number of elements on the witness stack. Note
76
            // that if any input in the transaction is spending a witness program, we need to specify the
77
            // witness stack size for every input regardless of whether it is segwit itself.
78
            // NOTE: this also works in case of mixed scriptsig-and-witness such as in p2sh-wrapped segwit v0
79
            // outputs. In this case the size of the scriptsig length will always be one (since the redeemScript
80
            // is always a push of the witness program in this case, which is smaller than 253 bytes).
81
0
            const int64_t scriptsig_len = is_segwit ? 1 : GetSizeOfCompactSize(*sat_weight / WITNESS_SCALE_FACTOR);
82
0
            const int64_t witstack_len = is_segwit ? GetSizeOfCompactSize(*elems_count) : (tx_is_segwit ? 1 : 0);
83
            // previous txid + previous vout + sequence + scriptsig len + witstack size + scriptsig or witness
84
            // NOTE: sat_weight already accounts for the witness discount accordingly.
85
0
            return (32 + 4 + 4 + scriptsig_len) * WITNESS_SCALE_FACTOR + witstack_len + *sat_weight;
86
0
        }
87
0
    }
88
89
0
    return {};
90
0
}
91
92
int CalculateMaximumSignedInputSize(const CTxOut& txout, const COutPoint outpoint, const SigningProvider* provider, bool can_grind_r, const CCoinControl* coin_control)
93
0
{
94
0
    if (!provider) return -1;
95
96
0
    if (const auto desc = InferDescriptor(txout.scriptPubKey, *provider)) {
97
0
        if (const auto weight = MaxInputWeight(*desc, {}, coin_control, true, can_grind_r)) {
98
0
            return static_cast<int>(GetVirtualTransactionSize(*weight, 0, 0));
99
0
        }
100
0
    }
101
102
0
    return -1;
103
0
}
104
105
int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, const CCoinControl* coin_control)
106
0
{
107
0
    const std::unique_ptr<SigningProvider> provider = wallet->GetSolvingProvider(txout.scriptPubKey);
108
0
    return CalculateMaximumSignedInputSize(txout, COutPoint(), provider.get(), wallet->CanGrindR(), coin_control);
109
0
}
110
111
/** Infer a descriptor for the given output script. */
112
static std::unique_ptr<Descriptor> GetDescriptor(const CWallet* wallet, const CCoinControl* coin_control,
113
                                                 const CScript script_pubkey)
114
0
{
115
0
    MultiSigningProvider providers;
116
0
    for (const auto spkman: wallet->GetScriptPubKeyMans(script_pubkey)) {
117
0
        providers.AddProvider(spkman->GetSolvingProvider(script_pubkey));
118
0
    }
119
0
    if (coin_control) {
120
0
        providers.AddProvider(std::make_unique<FlatSigningProvider>(coin_control->m_external_provider));
121
0
    }
122
0
    return InferDescriptor(script_pubkey, providers);
123
0
}
124
125
/** Infer the maximum size of this input after it will be signed. */
126
static std::optional<int64_t> GetSignedTxinWeight(const CWallet* wallet, const CCoinControl* coin_control,
127
                                                  const CTxIn& txin, const CTxOut& txo, const bool tx_is_segwit,
128
                                                  const bool can_grind_r)
129
0
{
130
    // If weight was provided, use that.
131
0
    std::optional<int64_t> weight;
132
0
    if (coin_control && (weight = coin_control->GetInputWeight(txin.prevout))) {
133
0
        return weight.value();
134
0
    }
135
136
    // Otherwise, use the maximum satisfaction size provided by the descriptor.
137
0
    std::unique_ptr<Descriptor> desc{GetDescriptor(wallet, coin_control, txo.scriptPubKey)};
138
0
    if (desc) return MaxInputWeight(*desc, {txin}, coin_control, tx_is_segwit, can_grind_r);
139
140
0
    return {};
141
0
}
142
143
// txouts needs to be in the order of tx.vin
144
TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, const CCoinControl* coin_control)
145
0
{
146
    // version + nLockTime + input count + output count
147
0
    int64_t weight = (4 + 4 + GetSizeOfCompactSize(tx.vin.size()) + GetSizeOfCompactSize(tx.vout.size())) * WITNESS_SCALE_FACTOR;
148
    // Whether any input spends a witness program. Necessary to run before the next loop over the
149
    // inputs in order to accurately compute the compactSize length for the witness data per input.
150
0
    bool is_segwit = std::any_of(txouts.begin(), txouts.end(), [&](const CTxOut& txo) {
151
0
        std::unique_ptr<Descriptor> desc{GetDescriptor(wallet, coin_control, txo.scriptPubKey)};
152
0
        if (desc) return IsSegwit(*desc);
153
0
        return false;
154
0
    });
155
    // Segwit marker and flag
156
0
    if (is_segwit) weight += 2;
157
158
    // Add the size of the transaction outputs.
159
0
    for (const auto& txo : tx.vout) weight += GetSerializeSize(txo) * WITNESS_SCALE_FACTOR;
160
161
    // Add the size of the transaction inputs as if they were signed.
162
0
    for (uint32_t i = 0; i < txouts.size(); i++) {
163
0
        const auto txin_weight = GetSignedTxinWeight(wallet, coin_control, tx.vin[i], txouts[i], is_segwit, wallet->CanGrindR());
164
0
        if (!txin_weight) return TxSize{-1, -1};
165
0
        assert(*txin_weight > -1);
166
0
        weight += *txin_weight;
167
0
    }
168
169
    // It's ok to use 0 as the number of sigops since we never create any pathological transaction.
170
0
    return TxSize{GetVirtualTransactionSize(weight, 0, 0), weight};
171
0
}
172
173
TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const CCoinControl* coin_control)
174
0
{
175
0
    std::vector<CTxOut> txouts;
176
    // Look up the inputs. The inputs are either in the wallet, or in coin_control.
177
0
    for (const CTxIn& input : tx.vin) {
178
0
        const auto mi = wallet->mapWallet.find(input.prevout.hash);
179
        // Can not estimate size without knowing the input details
180
0
        if (mi != wallet->mapWallet.end()) {
181
0
            assert(input.prevout.n < mi->second.tx->vout.size());
182
0
            txouts.emplace_back(mi->second.tx->vout.at(input.prevout.n));
183
0
        } else if (coin_control) {
184
0
            const auto& txout{coin_control->GetExternalOutput(input.prevout)};
185
0
            if (!txout) return TxSize{-1, -1};
186
0
            txouts.emplace_back(*txout);
187
0
        } else {
188
0
            return TxSize{-1, -1};
189
0
        }
190
0
    }
191
0
    return CalculateMaximumSignedTxSize(tx, wallet, txouts, coin_control);
192
0
}
193
194
size_t CoinsResult::Size() const
195
0
{
196
0
    size_t size{0};
197
0
    for (const auto& it : coins) {
198
0
        size += it.second.size();
199
0
    }
200
0
    return size;
201
0
}
202
203
std::vector<COutput> CoinsResult::All() const
204
0
{
205
0
    std::vector<COutput> all;
206
0
    all.reserve(Size());
207
0
    for (const auto& it : coins) {
208
0
        all.insert(all.end(), it.second.begin(), it.second.end());
209
0
    }
210
0
    return all;
211
0
}
212
213
0
void CoinsResult::Clear() {
214
0
    coins.clear();
215
0
}
216
217
void CoinsResult::Erase(const std::unordered_set<COutPoint, SaltedOutpointHasher>& coins_to_remove)
218
0
{
219
0
    for (auto& [type, vec] : coins) {
220
0
        auto remove_it = std::remove_if(vec.begin(), vec.end(), [&](const COutput& coin) {
221
            // remove it if it's on the set
222
0
            if (!coins_to_remove.contains(coin.outpoint)) return false;
223
224
            // update cached amounts
225
0
            total_amount -= coin.txout.nValue;
226
0
            if (coin.HasEffectiveValue() && total_effective_amount.has_value()) total_effective_amount = *total_effective_amount - coin.GetEffectiveValue();
227
0
            return true;
228
0
        });
229
0
        vec.erase(remove_it, vec.end());
230
0
    }
231
0
}
232
233
void CoinsResult::Shuffle(FastRandomContext& rng_fast)
234
0
{
235
0
    for (auto& it : coins) {
236
0
        std::shuffle(it.second.begin(), it.second.end(), rng_fast);
237
0
    }
238
0
}
239
240
void CoinsResult::Add(OutputType type, const COutput& out)
241
0
{
242
0
    coins[type].emplace_back(out);
243
0
    total_amount += out.txout.nValue;
244
0
    if (out.HasEffectiveValue()) {
245
0
        total_effective_amount = total_effective_amount.has_value() ?
246
0
                *total_effective_amount + out.GetEffectiveValue() : out.GetEffectiveValue();
247
0
    }
248
0
}
249
250
static OutputType GetOutputType(TxoutType type, bool is_from_p2sh)
251
0
{
252
0
    switch (type) {
253
0
        case TxoutType::WITNESS_V1_TAPROOT:
254
0
            return OutputType::BECH32M;
255
0
        case TxoutType::WITNESS_V0_KEYHASH:
256
0
        case TxoutType::WITNESS_V0_SCRIPTHASH:
257
0
            if (is_from_p2sh) return OutputType::P2SH_SEGWIT;
258
0
            else return OutputType::BECH32;
259
0
        case TxoutType::SCRIPTHASH:
260
0
        case TxoutType::PUBKEYHASH:
261
0
            return OutputType::LEGACY;
262
0
        default:
263
0
            return OutputType::UNKNOWN;
264
0
    }
265
0
}
266
267
// Fetch and validate the coin control selected inputs.
268
// Coins could be internal (from the wallet) or external.
269
util::Result<CoinsResult> FetchSelectedInputs(const CWallet& wallet, const CCoinControl& coin_control,
270
                                            const CoinSelectionParams& coin_selection_params)
271
0
{
272
0
    CoinsResult result;
273
0
    const bool can_grind_r = wallet.CanGrindR();
274
0
    std::map<COutPoint, CAmount> map_of_bump_fees = wallet.chain().calculateIndividualBumpFees(coin_control.ListSelected(), coin_selection_params.m_effective_feerate);
275
0
    for (const COutPoint& outpoint : coin_control.ListSelected()) {
276
0
        int64_t input_bytes = coin_control.GetInputWeight(outpoint).value_or(-1);
277
0
        if (input_bytes != -1) {
278
0
            input_bytes = GetVirtualTransactionSize(input_bytes, 0, 0);
279
0
        }
280
0
        CTxOut txout;
281
0
        if (auto txo = wallet.GetTXO(outpoint)) {
282
0
            txout = txo->GetTxOut();
283
0
            if (input_bytes == -1) {
284
0
                input_bytes = CalculateMaximumSignedInputSize(txout, &wallet, &coin_control);
285
0
            }
286
0
            const CWalletTx& parent_tx = txo->GetWalletTx();
287
0
            if (wallet.GetTxDepthInMainChain(parent_tx) == 0) {
288
0
                if (parent_tx.tx->version == TRUC_VERSION && coin_control.m_version != TRUC_VERSION) {
289
0
                    return util::Error{strprintf(_("Can't spend unconfirmed version 3 pre-selected input with a version %d tx"), coin_control.m_version)};
Line
Count
Source
1172
0
#define strprintf tfm::format
290
0
                } else if (coin_control.m_version == TRUC_VERSION && parent_tx.tx->version != TRUC_VERSION) {
291
0
                    return util::Error{strprintf(_("Can't spend unconfirmed version %d pre-selected input with a version 3 tx"), parent_tx.tx->version)};
Line
Count
Source
1172
0
#define strprintf tfm::format
292
0
                }
293
0
            }
294
0
        } else {
295
            // The input is external. We did not find the tx in mapWallet.
296
0
            const auto out{coin_control.GetExternalOutput(outpoint)};
297
0
            if (!out) {
298
0
                return util::Error{strprintf(_("Not found pre-selected input %s"), outpoint.ToString())};
Line
Count
Source
1172
0
#define strprintf tfm::format
299
0
            }
300
301
0
            txout = *out;
302
0
        }
303
304
0
        if (input_bytes == -1) {
305
0
            input_bytes = CalculateMaximumSignedInputSize(txout, outpoint, &coin_control.m_external_provider, can_grind_r, &coin_control);
306
0
        }
307
308
0
        if (input_bytes == -1) {
309
0
            return util::Error{strprintf(_("Not solvable pre-selected input %s"), outpoint.ToString())}; // Not solvable, can't estimate size for fee
Line
Count
Source
1172
0
#define strprintf tfm::format
310
0
        }
311
312
        /* Set some defaults for depth, solvable, safe, time, and from_me as these don't matter for preset inputs since no selection is being done. */
313
0
        COutput output(outpoint, txout, /*depth=*/0, input_bytes, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/false, coin_selection_params.m_effective_feerate);
314
0
        output.ApplyBumpFee(map_of_bump_fees.at(output.outpoint));
315
0
        result.Add(OutputType::UNKNOWN, output);
316
0
    }
317
0
    return result;
318
0
}
319
320
CoinsResult AvailableCoins(const CWallet& wallet,
321
                           const CCoinControl* coinControl,
322
                           std::optional<CFeeRate> feerate,
323
                           const CoinFilterParams& params)
324
0
{
325
0
    AssertLockHeld(wallet.cs_wallet);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
326
327
0
    CoinsResult result;
328
    // track unconfirmed truc outputs separately if we are tracking trucness
329
0
    std::vector<std::pair<OutputType, COutput>> unconfirmed_truc_coins;
330
0
    std::unordered_map<Txid, CAmount, SaltedTxidHasher> truc_txid_by_value;
331
    // Either the WALLET_FLAG_AVOID_REUSE flag is not set (in which case we always allow), or we default to avoiding, and only in the case where
332
    // a coin control object is provided, and has the avoid address reuse flag set to false, do we allow already used addresses
333
0
    bool allow_used_addresses = !wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE) || (coinControl && !coinControl->m_avoid_address_reuse);
334
0
    const int min_depth = {coinControl ? coinControl->m_min_depth : DEFAULT_MIN_DEPTH};
335
0
    const int max_depth = {coinControl ? coinControl->m_max_depth : DEFAULT_MAX_DEPTH};
336
0
    const bool only_safe = {coinControl ? !coinControl->m_include_unsafe_inputs : true};
337
0
    const bool can_grind_r = wallet.CanGrindR();
338
0
    std::vector<COutPoint> outpoints;
339
340
0
    std::set<Txid> trusted_parents;
341
    // Cache for whether each tx passes the tx level checks (first bool), and whether the transaction is "safe" (second bool)
342
0
    std::unordered_map<Txid, std::pair<bool, bool>, SaltedTxidHasher> tx_safe_cache;
343
0
    for (const auto& [outpoint, txo] : wallet.GetTXOs()) {
344
0
        const CWalletTx& wtx = txo.GetWalletTx();
345
0
        const CTxOut& output = txo.GetTxOut();
346
347
0
        if (tx_safe_cache.contains(outpoint.hash) && !tx_safe_cache.at(outpoint.hash).first) {
348
0
            continue;
349
0
        }
350
351
0
        int nDepth = wallet.GetTxDepthInMainChain(wtx);
352
353
        // Perform tx level checks if we haven't already come across outputs from this tx before.
354
0
        if (!tx_safe_cache.contains(outpoint.hash)) {
355
0
            tx_safe_cache[outpoint.hash] = {false, false};
356
357
0
            if (wallet.IsTxImmatureCoinBase(wtx) && !params.include_immature_coinbase)
358
0
                continue;
359
360
0
            if (nDepth < 0)
361
0
                continue;
362
363
            // We should not consider coins which aren't at least in our mempool
364
            // It's possible for these to be conflicted via ancestors which we may never be able to detect
365
0
            if (nDepth == 0 && !wtx.InMempool())
366
0
                continue;
367
368
0
            bool safeTx = CachedTxIsTrusted(wallet, wtx, trusted_parents);
369
370
            // We should not consider coins from transactions that are replacing
371
            // other transactions.
372
            //
373
            // Example: There is a transaction A which is replaced by bumpfee
374
            // transaction B. In this case, we want to prevent creation of
375
            // a transaction B' which spends an output of B.
376
            //
377
            // Reason: If transaction A were initially confirmed, transactions B
378
            // and B' would no longer be valid, so the user would have to create
379
            // a new transaction C to replace B'. However, in the case of a
380
            // one-block reorg, transactions B' and C might BOTH be accepted,
381
            // when the user only wanted one of them. Specifically, there could
382
            // be a 1-block reorg away from the chain where transactions A and C
383
            // were accepted to another chain where B, B', and C were all
384
            // accepted.
385
0
            if (nDepth == 0 && wtx.mapValue.contains("replaces_txid")) {
386
0
                safeTx = false;
387
0
            }
388
389
            // Similarly, we should not consider coins from transactions that
390
            // have been replaced. In the example above, we would want to prevent
391
            // creation of a transaction A' spending an output of A, because if
392
            // transaction B were initially confirmed, conflicting with A and
393
            // A', we wouldn't want to the user to create a transaction D
394
            // intending to replace A', but potentially resulting in a scenario
395
            // where A, A', and D could all be accepted (instead of just B and
396
            // D, or just A and A' like the user would want).
397
0
            if (nDepth == 0 && wtx.mapValue.contains("replaced_by_txid")) {
398
0
                safeTx = false;
399
0
            }
400
401
0
            if (nDepth == 0 && params.check_version_trucness) {
402
0
                if (coinControl->m_version == TRUC_VERSION) {
403
0
                    if (wtx.tx->version != TRUC_VERSION) continue;
404
                    // this unconfirmed v3 transaction already has a child
405
0
                    if (wtx.truc_child_in_mempool.has_value()) continue;
406
407
                    // this unconfirmed v3 transaction has a parent: spending would create a third generation
408
0
                    size_t ancestors, unused_cluster_count;
409
0
                    wallet.chain().getTransactionAncestry(wtx.tx->GetHash(), ancestors, unused_cluster_count);
410
0
                    if (ancestors > 1) continue;
411
0
                } else {
412
0
                    if (wtx.tx->version == TRUC_VERSION) continue;
413
0
                }
414
0
            }
415
416
0
            if (only_safe && !safeTx) {
417
0
                continue;
418
0
            }
419
420
0
            if (nDepth < min_depth || nDepth > max_depth) {
421
0
                continue;
422
0
            }
423
424
0
            tx_safe_cache[outpoint.hash] = {true, safeTx};
425
0
        }
426
0
        const auto& [tx_ok, tx_safe] = tx_safe_cache.at(outpoint.hash);
427
0
        if (!Assume(tx_ok)) {
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
428
0
            continue;
429
0
        }
430
431
0
        if (output.nValue < params.min_amount || output.nValue > params.max_amount)
432
0
            continue;
433
434
        // Skip manually selected coins (the caller can fetch them directly)
435
0
        if (coinControl && coinControl->HasSelected() && coinControl->IsSelected(outpoint))
436
0
            continue;
437
438
0
        if (wallet.IsLockedCoin(outpoint) && params.skip_locked)
439
0
            continue;
440
441
0
        if (wallet.IsSpent(outpoint))
442
0
            continue;
443
444
0
        if (!allow_used_addresses && wallet.IsSpentKey(output.scriptPubKey)) {
445
0
            continue;
446
0
        }
447
448
0
        bool tx_from_me = CachedTxIsFromMe(wallet, wtx);
449
450
0
        std::unique_ptr<SigningProvider> provider = wallet.GetSolvingProvider(output.scriptPubKey);
451
452
0
        int input_bytes = CalculateMaximumSignedInputSize(output, COutPoint(), provider.get(), can_grind_r, coinControl);
453
        // Because CalculateMaximumSignedInputSize infers a solvable descriptor to get the satisfaction size,
454
        // it is safe to assume that this input is solvable if input_bytes is greater than -1.
455
0
        bool solvable = input_bytes > -1;
456
457
        // Obtain script type
458
0
        std::vector<std::vector<uint8_t>> script_solutions;
459
0
        TxoutType type = Solver(output.scriptPubKey, script_solutions);
460
461
        // If the output is P2SH and solvable, we want to know if it is
462
        // a P2SH (legacy) or one of P2SH-P2WPKH, P2SH-P2WSH (P2SH-Segwit). We can determine
463
        // this from the redeemScript. If the output is not solvable, it will be classified
464
        // as a P2SH (legacy), since we have no way of knowing otherwise without the redeemScript
465
0
        bool is_from_p2sh{false};
466
0
        if (type == TxoutType::SCRIPTHASH && solvable) {
467
0
            CScript script;
468
0
            if (!provider->GetCScript(CScriptID(uint160(script_solutions[0])), script)) continue;
469
0
            type = Solver(script, script_solutions);
470
0
            is_from_p2sh = true;
471
0
        }
472
473
0
        auto available_output_type = GetOutputType(type, is_from_p2sh);
474
0
        auto available_output = COutput(outpoint, output, nDepth, input_bytes, solvable, tx_safe, wtx.GetTxTime(), tx_from_me, feerate);
475
0
        if (wtx.tx->version == TRUC_VERSION && nDepth == 0 && params.check_version_trucness) {
476
0
            unconfirmed_truc_coins.emplace_back(available_output_type, available_output);
477
0
            auto [it, _] = truc_txid_by_value.try_emplace(wtx.tx->GetHash(), 0);
478
0
            it->second += output.nValue;
479
0
        } else {
480
0
            result.Add(available_output_type, available_output);
481
0
        }
482
483
0
        outpoints.push_back(outpoint);
484
485
        // Checks the sum amount of all UTXO's.
486
0
        if (params.min_sum_amount != MAX_MONEY) {
487
0
            if (result.GetTotalAmount() >= params.min_sum_amount) {
488
0
                return result;
489
0
            }
490
0
        }
491
492
        // Checks the maximum number of UTXO's.
493
0
        if (params.max_count > 0 && result.Size() >= params.max_count) {
494
0
            return result;
495
0
        }
496
0
    }
497
498
    // Return all the coins from one TRUC transaction, that have the highest value.
499
    // This could be improved in the future by encoding these restrictions in
500
    // the coin selection itself so that we don't have to filter out
501
    // other unconfirmed TRUC coins beforehand.
502
0
    if (params.check_version_trucness && unconfirmed_truc_coins.size() > 0) {
503
0
        auto highest_value_truc_tx = std::max_element(truc_txid_by_value.begin(), truc_txid_by_value.end(), [](const auto& tx1, const auto& tx2){
504
0
                return tx1.second < tx2.second;
505
0
                });
506
507
0
        const Txid& truc_txid = highest_value_truc_tx->first;
508
0
        for (const auto& [type, output] : unconfirmed_truc_coins) {
509
0
            if (output.outpoint.hash == truc_txid) {
510
0
                    result.Add(type, output);
511
0
            }
512
0
        }
513
0
    }
514
515
0
    if (feerate.has_value()) {
516
0
        std::map<COutPoint, CAmount> map_of_bump_fees = wallet.chain().calculateIndividualBumpFees(outpoints, feerate.value());
517
518
0
        for (auto& [_, outputs] : result.coins) {
519
0
            for (auto& output : outputs) {
520
0
                output.ApplyBumpFee(map_of_bump_fees.at(output.outpoint));
521
0
            }
522
0
        }
523
0
    }
524
525
0
    return result;
526
0
}
527
528
const CTxOut& FindNonChangeParentOutput(const CWallet& wallet, const COutPoint& outpoint)
529
0
{
530
0
    AssertLockHeld(wallet.cs_wallet);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
531
0
    const CWalletTx* wtx{Assert(wallet.GetWalletTx(outpoint.hash))};
Line
Count
Source
113
0
#define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val)
532
533
0
    const CTransaction* ptx = wtx->tx.get();
534
0
    int n = outpoint.n;
535
0
    while (OutputIsChange(wallet, ptx->vout[n]) && ptx->vin.size() > 0) {
536
0
        const COutPoint& prevout = ptx->vin[0].prevout;
537
0
        const CWalletTx* it = wallet.GetWalletTx(prevout.hash);
538
0
        if (!it || it->tx->vout.size() <= prevout.n ||
539
0
            !wallet.IsMine(it->tx->vout[prevout.n])) {
540
0
            break;
541
0
        }
542
0
        ptx = it->tx.get();
543
0
        n = prevout.n;
544
0
    }
545
0
    return ptx->vout[n];
546
0
}
547
548
std::map<CTxDestination, std::vector<COutput>> ListCoins(const CWallet& wallet)
549
0
{
550
0
    AssertLockHeld(wallet.cs_wallet);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
551
552
0
    std::map<CTxDestination, std::vector<COutput>> result;
553
554
0
    CCoinControl coin_control;
555
0
    CoinFilterParams coins_params;
556
0
    coins_params.skip_locked = false;
557
0
    for (const COutput& coin : AvailableCoins(wallet, &coin_control, /*feerate=*/std::nullopt, coins_params).All()) {
558
0
        CTxDestination address;
559
0
        if (!ExtractDestination(FindNonChangeParentOutput(wallet, coin.outpoint).scriptPubKey, address)) {
560
            // For backwards compatibility, we convert P2PK output scripts into PKHash destinations
561
0
            if (auto pk_dest = std::get_if<PubKeyDestination>(&address)) {
562
0
                address = PKHash(pk_dest->GetPubKey());
563
0
            } else {
564
0
                continue;
565
0
            }
566
0
        }
567
0
        result[address].emplace_back(coin);
568
0
    }
569
0
    return result;
570
0
}
571
572
FilteredOutputGroups GroupOutputs(const CWallet& wallet,
573
                          const CoinsResult& coins,
574
                          const CoinSelectionParams& coin_sel_params,
575
                          const std::vector<SelectionFilter>& filters,
576
                          std::vector<OutputGroup>& ret_discarded_groups)
577
0
{
578
0
    FilteredOutputGroups filtered_groups;
579
580
0
    if (!coin_sel_params.m_avoid_partial_spends) {
581
        // Allowing partial spends means no grouping. Each COutput gets its own OutputGroup
582
0
        for (const auto& [type, outputs] : coins.coins) {
583
0
            for (const COutput& output : outputs) {
584
                // Get mempool info
585
0
                size_t ancestors, cluster_count;
586
0
                wallet.chain().getTransactionAncestry(output.outpoint.hash, ancestors, cluster_count);
587
588
                // Create a new group per output and add it to the all groups vector
589
0
                OutputGroup group(coin_sel_params);
590
0
                group.Insert(std::make_shared<COutput>(output), ancestors, cluster_count);
591
592
                // Each filter maps to a different set of groups
593
0
                bool accepted = false;
594
0
                for (const auto& sel_filter : filters) {
595
0
                    const auto& filter = sel_filter.filter;
596
0
                    if (!group.EligibleForSpending(filter)) continue;
597
0
                    filtered_groups[filter].Push(group, type, /*insert_positive=*/true, /*insert_mixed=*/true);
598
0
                    accepted = true;
599
0
                }
600
0
                if (!accepted) ret_discarded_groups.emplace_back(group);
601
0
            }
602
0
        }
603
0
        return filtered_groups;
604
0
    }
605
606
    // We want to combine COutputs that have the same scriptPubKey into single OutputGroups
607
    // except when there are more than OUTPUT_GROUP_MAX_ENTRIES COutputs grouped in an OutputGroup.
608
    // To do this, we maintain a map where the key is the scriptPubKey and the value is a vector of OutputGroups.
609
    // For each COutput, we check if the scriptPubKey is in the map, and if it is, the COutput is added
610
    // to the last OutputGroup in the vector for the scriptPubKey. When the last OutputGroup has
611
    // OUTPUT_GROUP_MAX_ENTRIES COutputs, a new OutputGroup is added to the end of the vector.
612
0
    typedef std::map<std::pair<CScript, OutputType>, std::vector<OutputGroup>> ScriptPubKeyToOutgroup;
613
0
    const auto& insert_output = [&](
614
0
            const std::shared_ptr<COutput>& output, OutputType type, size_t ancestors, size_t cluster_count,
615
0
            ScriptPubKeyToOutgroup& groups_map) {
616
0
        std::vector<OutputGroup>& groups = groups_map[std::make_pair(output->txout.scriptPubKey,type)];
617
618
0
        if (groups.size() == 0) {
619
            // No OutputGroups for this scriptPubKey yet, add one
620
0
            groups.emplace_back(coin_sel_params);
621
0
        }
622
623
        // Get the last OutputGroup in the vector so that we can add the COutput to it
624
        // A pointer is used here so that group can be reassigned later if it is full.
625
0
        OutputGroup* group = &groups.back();
626
627
        // Check if this OutputGroup is full. We limit to OUTPUT_GROUP_MAX_ENTRIES when using -avoidpartialspends
628
        // to avoid surprising users with very high fees.
629
0
        if (group->m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
630
            // The last output group is full, add a new group to the vector and use that group for the insertion
631
0
            groups.emplace_back(coin_sel_params);
632
0
            group = &groups.back();
633
0
        }
634
635
0
        group->Insert(output, ancestors, cluster_count);
636
0
    };
637
638
0
    ScriptPubKeyToOutgroup spk_to_groups_map;
639
0
    ScriptPubKeyToOutgroup spk_to_positive_groups_map;
640
0
    for (const auto& [type, outs] : coins.coins) {
641
0
        for (const COutput& output : outs) {
642
0
            size_t ancestors, cluster_count;
643
0
            wallet.chain().getTransactionAncestry(output.outpoint.hash, ancestors, cluster_count);
644
645
0
            const auto& shared_output = std::make_shared<COutput>(output);
646
            // Filter for positive only before adding the output
647
0
            if (output.GetEffectiveValue() > 0) {
648
0
                insert_output(shared_output, type, ancestors, cluster_count, spk_to_positive_groups_map);
649
0
            }
650
651
            // 'All' groups
652
0
            insert_output(shared_output, type, ancestors, cluster_count, spk_to_groups_map);
653
0
        }
654
0
    }
655
656
    // Now we go through the entire maps and pull out the OutputGroups
657
0
    const auto& push_output_groups = [&](const ScriptPubKeyToOutgroup& groups_map, bool positive_only) {
658
0
        for (const auto& [script, groups] : groups_map) {
659
            // Go through the vector backwards. This allows for the first item we deal with being the partial group.
660
0
            for (auto group_it = groups.rbegin(); group_it != groups.rend(); group_it++) {
661
0
                const OutputGroup& group = *group_it;
662
663
                // Each filter maps to a different set of groups
664
0
                bool accepted = false;
665
0
                for (const auto& sel_filter : filters) {
666
0
                    const auto& filter = sel_filter.filter;
667
0
                    if (!group.EligibleForSpending(filter)) continue;
668
669
                    // Don't include partial groups if there are full groups too and we don't want partial groups
670
0
                    if (group_it == groups.rbegin() && groups.size() > 1 && !filter.m_include_partial_groups) {
671
0
                        continue;
672
0
                    }
673
674
0
                    OutputType type = script.second;
675
                    // Either insert the group into the positive-only groups or the mixed ones.
676
0
                    filtered_groups[filter].Push(group, type, positive_only, /*insert_mixed=*/!positive_only);
677
0
                    accepted = true;
678
0
                }
679
0
                if (!accepted) ret_discarded_groups.emplace_back(group);
680
0
            }
681
0
        }
682
0
    };
683
684
0
    push_output_groups(spk_to_groups_map, /*positive_only=*/ false);
685
0
    push_output_groups(spk_to_positive_groups_map, /*positive_only=*/ true);
686
687
0
    return filtered_groups;
688
0
}
689
690
FilteredOutputGroups GroupOutputs(const CWallet& wallet,
691
                                  const CoinsResult& coins,
692
                                  const CoinSelectionParams& params,
693
                                  const std::vector<SelectionFilter>& filters)
694
0
{
695
0
    std::vector<OutputGroup> unused;
696
0
    return GroupOutputs(wallet, coins, params, filters, unused);
697
0
}
698
699
// Returns true if the result contains an error and the message is not empty
700
0
static bool HasErrorMsg(const util::Result<SelectionResult>& res) { return !util::ErrorString(res).empty(); }
701
702
util::Result<SelectionResult> AttemptSelection(interfaces::Chain& chain, const CAmount& nTargetValue, OutputGroupTypeMap& groups,
703
                               const CoinSelectionParams& coin_selection_params, bool allow_mixed_output_types)
704
0
{
705
    // Run coin selection on each OutputType and compute the Waste Metric
706
0
    std::vector<SelectionResult> results;
707
0
    for (auto& [type, group] : groups.groups_by_type) {
708
0
        auto result{ChooseSelectionResult(chain, nTargetValue, group, coin_selection_params)};
709
        // If any specific error message appears here, then something particularly wrong happened.
710
0
        if (HasErrorMsg(result)) return result; // So let's return the specific error.
711
        // Append the favorable result.
712
0
        if (result) results.push_back(*result);
713
0
    }
714
    // If we have at least one solution for funding the transaction without mixing, choose the minimum one according to waste metric
715
    // and return the result
716
0
    if (results.size() > 0) return *std::min_element(results.begin(), results.end());
717
718
    // If we can't fund the transaction from any individual OutputType, run coin selection one last time
719
    // over all available coins, which would allow mixing.
720
    // If TypesCount() <= 1, there is nothing to mix.
721
0
    if (allow_mixed_output_types && groups.TypesCount() > 1) {
722
0
        return ChooseSelectionResult(chain, nTargetValue, groups.all_groups, coin_selection_params);
723
0
    }
724
    // Either mixing is not allowed and we couldn't find a solution from any single OutputType, or mixing was allowed and we still couldn't
725
    // find a solution using all available coins
726
0
    return util::Error();
727
0
};
728
729
util::Result<SelectionResult> ChooseSelectionResult(interfaces::Chain& chain, const CAmount& nTargetValue, Groups& groups, const CoinSelectionParams& coin_selection_params)
730
0
{
731
    // Vector of results. We will choose the best one based on waste.
732
0
    std::vector<SelectionResult> results;
733
0
    std::vector<util::Result<SelectionResult>> errors;
734
0
    auto append_error = [&] (util::Result<SelectionResult>&& result) {
735
        // If any specific error message appears here, then something different from a simple "no selection found" happened.
736
        // Let's save it, so it can be retrieved to the user if no other selection algorithm succeeded.
737
0
        if (HasErrorMsg(result)) {
738
0
            errors.emplace_back(std::move(result));
739
0
        }
740
0
    };
741
742
    // Maximum allowed weight for selected coins.
743
0
    int max_transaction_weight = coin_selection_params.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT);
744
0
    int tx_weight_no_input = coin_selection_params.tx_noinputs_size * WITNESS_SCALE_FACTOR;
745
0
    int max_selection_weight = max_transaction_weight - tx_weight_no_input;
746
0
    if (max_selection_weight <= 0) {
747
0
        return util::Error{_("Maximum transaction weight is less than transaction weight without inputs")};
748
0
    }
749
750
    // SFFO frequently causes issues in the context of changeless input sets: skip BnB when SFFO is active
751
0
    if (!coin_selection_params.m_subtract_fee_outputs) {
752
0
        if (auto bnb_result{SelectCoinsBnB(groups.positive_group, nTargetValue, coin_selection_params.m_cost_of_change, max_selection_weight)}) {
753
0
            results.push_back(*bnb_result);
754
0
        } else append_error(std::move(bnb_result));
755
0
    }
756
757
    // Deduct change weight because remaining Coin Selection algorithms can create change output
758
0
    int change_outputs_weight = coin_selection_params.change_output_size * WITNESS_SCALE_FACTOR;
759
0
    max_selection_weight -= change_outputs_weight;
760
0
    if (max_selection_weight < 0 && results.empty()) {
761
0
        return util::Error{_("Maximum transaction weight is too low, can not accommodate change output")};
762
0
    }
763
764
    // The knapsack solver has some legacy behavior where it will spend dust outputs. We retain this behavior, so don't filter for positive only here.
765
0
    if (auto knapsack_result{KnapsackSolver(groups.mixed_group, nTargetValue, coin_selection_params.m_min_change_target, coin_selection_params.rng_fast, max_selection_weight)}) {
766
0
        results.push_back(*knapsack_result);
767
0
    } else append_error(std::move(knapsack_result));
768
769
0
    if (coin_selection_params.m_effective_feerate > CFeeRate{3 * coin_selection_params.m_long_term_feerate}) { // Minimize input set for feerates of at least 3×LTFRE (default: 30 ṩ/vB+)
770
0
        if (auto cg_result{CoinGrinder(groups.positive_group, nTargetValue, coin_selection_params.m_min_change_target, max_selection_weight)}) {
771
0
            cg_result->RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
772
0
            results.push_back(*cg_result);
773
0
        } else {
774
0
            append_error(std::move(cg_result));
775
0
        }
776
0
    }
777
778
0
    if (auto srd_result{SelectCoinsSRD(groups.positive_group, nTargetValue, coin_selection_params.m_change_fee, coin_selection_params.rng_fast, max_selection_weight)}) {
779
0
        results.push_back(*srd_result);
780
0
    } else append_error(std::move(srd_result));
781
782
0
    if (results.empty()) {
783
        // No solution found, retrieve the first explicit error (if any).
784
        // future: add 'severity level' to errors so the worst one can be retrieved instead of the first one.
785
0
        return errors.empty() ? util::Error() : std::move(errors.front());
786
0
    }
787
788
    // If the chosen input set has unconfirmed inputs, check for synergies from overlapping ancestry
789
0
    for (auto& result : results) {
790
0
        std::vector<COutPoint> outpoints;
791
0
        OutputSet coins = result.GetInputSet();
792
0
        CAmount summed_bump_fees = 0;
793
0
        for (auto& coin : coins) {
794
0
            if (coin->depth > 0) continue; // Bump fees only exist for unconfirmed inputs
795
0
            outpoints.push_back(coin->outpoint);
796
0
            summed_bump_fees += coin->ancestor_bump_fees;
797
0
        }
798
0
        std::optional<CAmount> combined_bump_fee = chain.calculateCombinedBumpFee(outpoints, coin_selection_params.m_effective_feerate);
799
0
        if (!combined_bump_fee.has_value()) {
800
0
            return util::Error{_("Failed to calculate bump fees, because unconfirmed UTXOs depend on an enormous cluster of unconfirmed transactions.")};
801
0
        }
802
0
        CAmount bump_fee_overestimate = summed_bump_fees - combined_bump_fee.value();
803
0
        if (bump_fee_overestimate) {
804
0
            result.SetBumpFeeDiscount(bump_fee_overestimate);
805
0
        }
806
0
        result.RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
807
0
    }
808
809
    // Choose the result with the least waste
810
    // If the waste is the same, choose the one which spends more inputs.
811
0
    return *std::min_element(results.begin(), results.end());
812
0
}
813
814
util::Result<SelectionResult> SelectCoins(const CWallet& wallet, CoinsResult& available_coins, const CoinsResult& pre_set_inputs,
815
                                          const CAmount& nTargetValue, const CCoinControl& coin_control,
816
                                          const CoinSelectionParams& coin_selection_params)
817
0
{
818
    // Deduct preset inputs amount from the search target
819
0
    CAmount selection_target = nTargetValue - pre_set_inputs.GetAppropriateTotal(coin_selection_params.m_subtract_fee_outputs).value_or(0);
820
821
    // Return if automatic coin selection is disabled, and we don't cover the selection target
822
0
    if (!coin_control.m_allow_other_inputs && selection_target > 0) {
823
0
        return util::Error{_("The preselected coins total amount does not cover the transaction target. "
824
0
                             "Please allow other inputs to be automatically selected or include more coins manually")};
825
0
    }
826
827
0
    OutputSet preset_coin_set;
828
0
    for (const auto& output: pre_set_inputs.All()) {
829
0
        preset_coin_set.insert(std::make_shared<COutput>(output));
830
0
    }
831
832
    // Return if we can cover the target only with the preset inputs
833
0
    if (selection_target <= 0) {
834
0
        SelectionResult result(nTargetValue, SelectionAlgorithm::MANUAL);
835
0
        result.AddInputs(preset_coin_set, coin_selection_params.m_subtract_fee_outputs);
836
0
        result.RecalculateWaste(coin_selection_params.min_viable_change, coin_selection_params.m_cost_of_change, coin_selection_params.m_change_fee);
837
0
        return result;
838
0
    }
839
840
    // Return early if we cannot cover the target with the wallet's UTXO.
841
    // We use the total effective value if we are not subtracting fee from outputs and 'available_coins' contains the data.
842
0
    CAmount available_coins_total_amount = available_coins.GetAppropriateTotal(coin_selection_params.m_subtract_fee_outputs).value_or(0);
843
0
    if (selection_target > available_coins_total_amount) {
844
0
        return util::Error(); // Insufficient funds
845
0
    }
846
847
    // Start wallet Coin Selection procedure
848
0
    auto op_selection_result = AutomaticCoinSelection(wallet, available_coins, selection_target, coin_selection_params);
849
0
    if (!op_selection_result) return op_selection_result;
850
851
    // If needed, add preset inputs to the automatic coin selection result
852
0
    if (!pre_set_inputs.coins.empty()) {
853
0
        auto preset_total = pre_set_inputs.GetAppropriateTotal(coin_selection_params.m_subtract_fee_outputs);
854
0
        assert(preset_total.has_value());
855
0
        SelectionResult preselected(preset_total.value(), SelectionAlgorithm::MANUAL);
856
0
        preselected.AddInputs(preset_coin_set, coin_selection_params.m_subtract_fee_outputs);
857
0
        op_selection_result->Merge(preselected);
858
0
        op_selection_result->RecalculateWaste(coin_selection_params.min_viable_change,
859
0
                                                coin_selection_params.m_cost_of_change,
860
0
                                                coin_selection_params.m_change_fee);
861
862
        // Verify we haven't exceeded the maximum allowed weight
863
0
        int max_inputs_weight = coin_selection_params.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT) - (coin_selection_params.tx_noinputs_size * WITNESS_SCALE_FACTOR);
864
0
        if (op_selection_result->GetWeight() > max_inputs_weight) {
865
0
            return util::Error{_("The combination of the pre-selected inputs and the wallet automatic inputs selection exceeds the transaction maximum weight. "
866
0
                                 "Please try sending a smaller amount or manually consolidating your wallet's UTXOs")};
867
0
        }
868
0
    }
869
0
    return op_selection_result;
870
0
}
871
872
util::Result<SelectionResult> AutomaticCoinSelection(const CWallet& wallet, CoinsResult& available_coins, const CAmount& value_to_select, const CoinSelectionParams& coin_selection_params)
873
0
{
874
    // Try to enforce a mixture of cluster limits and ancestor/descendant limits on transactions we create by limiting
875
    // the ancestors and the maximum cluster count of any UTXO we use. We use the ancestor/descendant limits, which are
876
    // lower than the cluster limits, to avoid exceeding any ancestor/descendant limits of legacy nodes. This filter is safe
877
    // because a transaction's ancestor or descendant count cannot be larger than its cluster count.
878
    // TODO: these limits can be relaxed in the future, and we can replace the ancestor filter with a cluster equivalent.
879
0
    unsigned int limit_ancestor_count = 0;
880
0
    unsigned int limit_descendant_count = 0;
881
0
    wallet.chain().getPackageLimits(limit_ancestor_count, limit_descendant_count);
882
0
    const size_t max_ancestors = (size_t)std::max<int64_t>(1, limit_ancestor_count);
883
0
    const size_t max_cluster_count = (size_t)std::max<int64_t>(1, limit_descendant_count);
884
0
    const bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
885
886
    // Cases where we have 101+ outputs all pointing to the same destination may result in
887
    // privacy leaks as they will potentially be deterministically sorted. We solve that by
888
    // explicitly shuffling the outputs before processing
889
0
    if (coin_selection_params.m_avoid_partial_spends && available_coins.Size() > OUTPUT_GROUP_MAX_ENTRIES) {
890
0
        available_coins.Shuffle(coin_selection_params.rng_fast);
891
0
    }
892
893
    // Coin Selection attempts to select inputs from a pool of eligible UTXOs to fund the
894
    // transaction at a target feerate. If an attempt fails, more attempts may be made using a more
895
    // permissive CoinEligibilityFilter.
896
0
    {
897
        // Place coins eligibility filters on a scope increasing order.
898
0
        std::vector<SelectionFilter> ordered_filters{
899
                // If possible, fund the transaction with confirmed UTXOs only. Prefer at least six
900
                // confirmations on outputs received from other wallets and only spend confirmed change.
901
0
                {CoinEligibilityFilter(1, 6, 0), /*allow_mixed_output_types=*/false},
902
0
                {CoinEligibilityFilter(1, 1, 0)},
903
0
        };
904
        // Fall back to using zero confirmation change (but with as few ancestors in the mempool as
905
        // possible) if we cannot fund the transaction otherwise.
906
0
        if (wallet.m_spend_zero_conf_change) {
907
0
            ordered_filters.push_back({CoinEligibilityFilter(0, 1, 2)});
908
0
            ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::min(size_t{4}, max_ancestors/3), std::min(size_t{4}, max_cluster_count/3))});
909
0
            ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors/2, max_cluster_count/2)});
910
            // If partial groups are allowed, relax the requirement of spending OutputGroups (groups
911
            // of UTXOs sent to the same address, which are obviously controlled by a single wallet)
912
            // in their entirety.
913
0
            ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors-1, max_cluster_count-1, /*include_partial=*/true)});
914
            // Try with unsafe inputs if they are allowed. This may spend unconfirmed outputs
915
            // received from other wallets.
916
0
            if (coin_selection_params.m_include_unsafe_inputs) {
917
0
                ordered_filters.push_back({CoinEligibilityFilter(/*conf_mine=*/0, /*conf_theirs=*/0, max_ancestors-1, max_cluster_count-1, /*include_partial=*/true)});
918
0
            }
919
            // Try with unlimited ancestors/clusters. The transaction will still need to meet
920
            // local mempool policy (i.e. cluster limits) to be accepted to mempool and broadcasted, and
921
            // limits of other nodes (e.g. ancestor/descendant limits) to propagate, but OutputGroups
922
            // use heuristics that may overestimate.
923
0
            if (!fRejectLongChains) {
924
0
                ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max(),
925
0
                                                                   std::numeric_limits<uint64_t>::max(),
926
0
                                                                   /*include_partial=*/true)});
927
0
            }
928
0
        }
929
930
        // Group outputs and map them by coin eligibility filter
931
0
        std::vector<OutputGroup> discarded_groups;
932
0
        FilteredOutputGroups filtered_groups = GroupOutputs(wallet, available_coins, coin_selection_params, ordered_filters, discarded_groups);
933
934
        // Check if we still have enough balance after applying filters (some coins might be discarded)
935
0
        CAmount total_discarded = 0;
936
0
        CAmount total_unconf_long_chain = 0;
937
0
        for (const auto& group : discarded_groups) {
938
0
            total_discarded += group.GetSelectionAmount();
939
0
            if (group.m_ancestors >= max_ancestors || group.m_max_cluster_count >= max_cluster_count) total_unconf_long_chain += group.GetSelectionAmount();
940
0
        }
941
942
0
        if (CAmount total_amount = available_coins.GetTotalAmount() - total_discarded < value_to_select) {
943
            // Special case, too-long-mempool cluster.
944
0
            if (total_amount + total_unconf_long_chain > value_to_select) {
945
0
                return util::Error{_("Unconfirmed UTXOs are available, but spending them creates a chain of transactions that will be rejected by the mempool")};
946
0
            }
947
0
            return util::Error{}; // General "Insufficient Funds"
948
0
        }
949
950
        // Walk-through the filters until the solution gets found.
951
        // If no solution is found, return the first detailed error (if any).
952
        // future: add "error level" so the worst one can be picked instead.
953
0
        std::vector<util::Result<SelectionResult>> res_detailed_errors;
954
0
        CoinSelectionParams updated_selection_params = coin_selection_params;
955
0
        for (const auto& select_filter : ordered_filters) {
956
0
            auto it = filtered_groups.find(select_filter.filter);
957
0
            if (it == filtered_groups.end()) continue;
958
0
            if (updated_selection_params.m_version == TRUC_VERSION && (select_filter.filter.conf_mine == 0 || select_filter.filter.conf_theirs == 0)) {
959
0
                if (updated_selection_params.m_max_tx_weight > (TRUC_CHILD_MAX_WEIGHT)) {
960
0
                    updated_selection_params.m_max_tx_weight = TRUC_CHILD_MAX_WEIGHT;
961
0
                }
962
0
            }
963
0
            if (auto res{AttemptSelection(wallet.chain(), value_to_select, it->second,
964
0
                                          updated_selection_params, select_filter.allow_mixed_output_types)}) {
965
0
                return res; // result found
966
0
            } else {
967
                // If any specific error message appears here, then something particularly wrong might have happened.
968
                // Save the error and continue the selection process. So if no solutions gets found, we can return
969
                // the detailed error to the upper layers.
970
0
                if (HasErrorMsg(res)) res_detailed_errors.emplace_back(std::move(res));
971
0
            }
972
0
        }
973
974
        // Return right away if we have a detailed error
975
0
        if (!res_detailed_errors.empty()) return std::move(res_detailed_errors.front());
976
977
978
        // General "Insufficient Funds"
979
0
        return util::Error{};
980
0
    }
981
0
}
982
983
static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, const uint256& block_hash)
984
0
{
985
0
    if (chain.isInitialBlockDownload()) {
986
0
        return false;
987
0
    }
988
0
    constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
989
0
    int64_t block_time;
990
0
    CHECK_NONFATAL(chain.findBlock(block_hash, FoundBlock().time(block_time)));
Line
Count
Source
110
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
991
0
    if (block_time < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
992
0
        return false;
993
0
    }
994
0
    return true;
995
0
}
996
997
void DiscourageFeeSniping(CMutableTransaction& tx, FastRandomContext& rng_fast,
998
                                 interfaces::Chain& chain, const uint256& block_hash, int block_height)
999
0
{
1000
    // All inputs must be added by now
1001
0
    assert(!tx.vin.empty());
1002
    // Discourage fee sniping.
1003
    //
1004
    // For a large miner the value of the transactions in the best block and
1005
    // the mempool can exceed the cost of deliberately attempting to mine two
1006
    // blocks to orphan the current best block. By setting nLockTime such that
1007
    // only the next block can include the transaction, we discourage this
1008
    // practice as the height restricted and limited blocksize gives miners
1009
    // considering fee sniping fewer options for pulling off this attack.
1010
    //
1011
    // A simple way to think about this is from the wallet's point of view we
1012
    // always want the blockchain to move forward. By setting nLockTime this
1013
    // way we're basically making the statement that we only want this
1014
    // transaction to appear in the next block; we don't want to potentially
1015
    // encourage reorgs by allowing transactions to appear at lower heights
1016
    // than the next block in forks of the best chain.
1017
    //
1018
    // Of course, the subsidy is high enough, and transaction volume low
1019
    // enough, that fee sniping isn't a problem yet, but by implementing a fix
1020
    // now we ensure code won't be written that makes assumptions about
1021
    // nLockTime that preclude a fix later.
1022
0
    if (IsCurrentForAntiFeeSniping(chain, block_hash)) {
1023
0
        tx.nLockTime = block_height;
1024
1025
        // Secondly occasionally randomly pick a nLockTime even further back, so
1026
        // that transactions that are delayed after signing for whatever reason,
1027
        // e.g. high-latency mix networks and some CoinJoin implementations, have
1028
        // better privacy.
1029
0
        if (rng_fast.randrange(10) == 0) {
1030
0
            tx.nLockTime = std::max(0, int(tx.nLockTime) - int(rng_fast.randrange(100)));
1031
0
        }
1032
0
    } else {
1033
        // If our chain is lagging behind, we can't discourage fee sniping nor help
1034
        // the privacy of high-latency transactions. To avoid leaking a potentially
1035
        // unique "nLockTime fingerprint", set nLockTime to a constant.
1036
0
        tx.nLockTime = 0;
1037
0
    }
1038
    // Sanity check all values
1039
0
    assert(tx.nLockTime < LOCKTIME_THRESHOLD); // Type must be block height
1040
0
    assert(tx.nLockTime <= uint64_t(block_height));
1041
0
    for (const auto& in : tx.vin) {
1042
        // Can not be FINAL for locktime to work
1043
0
        assert(in.nSequence != CTxIn::SEQUENCE_FINAL);
1044
        // May be MAX NONFINAL to disable both BIP68 and BIP125
1045
0
        if (in.nSequence == CTxIn::MAX_SEQUENCE_NONFINAL) continue;
1046
        // May be MAX BIP125 to disable BIP68 and enable BIP125
1047
0
        if (in.nSequence == MAX_BIP125_RBF_SEQUENCE) continue;
1048
        // The wallet does not support any other sequence-use right now.
1049
0
        assert(false);
1050
0
    }
1051
0
}
1052
1053
uint64_t GetSerializeSizeForRecipient(const CRecipient& recipient)
1054
0
{
1055
0
    return ::GetSerializeSize(CTxOut(recipient.nAmount, GetScriptForDestination(recipient.dest)));
1056
0
}
1057
1058
bool IsDust(const CRecipient& recipient, const CFeeRate& dustRelayFee)
1059
0
{
1060
0
    return ::IsDust(CTxOut(recipient.nAmount, GetScriptForDestination(recipient.dest)), dustRelayFee);
1061
0
}
1062
1063
static util::Result<CreatedTransactionResult> CreateTransactionInternal(
1064
        CWallet& wallet,
1065
        const std::vector<CRecipient>& vecSend,
1066
        std::optional<unsigned int> change_pos,
1067
        const CCoinControl& coin_control,
1068
        bool sign) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
1069
0
{
1070
0
    AssertLockHeld(wallet.cs_wallet);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1071
1072
0
    FastRandomContext rng_fast;
1073
0
    CMutableTransaction txNew; // The resulting transaction that we make
1074
1075
0
    txNew.version = coin_control.m_version;
1076
1077
0
    CoinSelectionParams coin_selection_params{rng_fast}; // Parameters for coin selection, init with dummy
1078
0
    coin_selection_params.m_avoid_partial_spends = coin_control.m_avoid_partial_spends;
1079
0
    coin_selection_params.m_include_unsafe_inputs = coin_control.m_include_unsafe_inputs;
1080
0
    coin_selection_params.m_max_tx_weight = coin_control.m_max_tx_weight.value_or(MAX_STANDARD_TX_WEIGHT);
1081
0
    coin_selection_params.m_version = coin_control.m_version;
1082
0
    int minimum_tx_weight = MIN_STANDARD_TX_NONWITNESS_SIZE * WITNESS_SCALE_FACTOR;
1083
0
    if (coin_selection_params.m_max_tx_weight.value() < minimum_tx_weight || coin_selection_params.m_max_tx_weight.value() > MAX_STANDARD_TX_WEIGHT) {
1084
0
        return util::Error{strprintf(_("Maximum transaction weight must be between %d and %d"), minimum_tx_weight, MAX_STANDARD_TX_WEIGHT)};
Line
Count
Source
1172
0
#define strprintf tfm::format
1085
0
    }
1086
    // Set the long term feerate estimate to the wallet's consolidate feerate
1087
0
    coin_selection_params.m_long_term_feerate = wallet.m_consolidate_feerate;
1088
    // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 witness overhead (dummy, flag, stack size)
1089
0
    coin_selection_params.tx_noinputs_size = 10 + GetSizeOfCompactSize(vecSend.size()); // bytes for output count
1090
1091
0
    CAmount recipients_sum = 0;
1092
0
    const OutputType change_type = wallet.TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : wallet.m_default_change_type, vecSend);
1093
0
    ReserveDestination reservedest(&wallet, change_type);
1094
0
    unsigned int outputs_to_subtract_fee_from = 0; // The number of outputs which we are subtracting the fee from
1095
0
    for (const auto& recipient : vecSend) {
1096
0
        if (IsDust(recipient, wallet.chain().relayDustFee())) {
1097
0
            return util::Error{_("Transaction amount too small")};
1098
0
        }
1099
1100
        // Include the fee cost for outputs.
1101
0
        coin_selection_params.tx_noinputs_size += GetSerializeSizeForRecipient(recipient);
1102
0
        recipients_sum += recipient.nAmount;
1103
1104
0
        if (recipient.fSubtractFeeFromAmount) {
1105
0
            outputs_to_subtract_fee_from++;
1106
0
            coin_selection_params.m_subtract_fee_outputs = true;
1107
0
        }
1108
0
    }
1109
1110
    // Create change script that will be used if we need change
1111
0
    CScript scriptChange;
1112
0
    bilingual_str error; // possible error str
1113
1114
    // coin control: send change to custom address
1115
0
    if (!std::get_if<CNoDestination>(&coin_control.destChange)) {
1116
0
        scriptChange = GetScriptForDestination(coin_control.destChange);
1117
0
    } else { // no coin control: send change to newly generated address
1118
        // Note: We use a new key here to keep it from being obvious which side is the change.
1119
        //  The drawback is that by not reusing a previous key, the change may be lost if a
1120
        //  backup is restored, if the backup doesn't have the new private key for the change.
1121
        //  If we reused the old key, it would be possible to add code to look for and
1122
        //  rediscover unknown transactions that were written with keys of ours to recover
1123
        //  post-backup change.
1124
1125
        // Reserve a new key pair from key pool. If it fails, provide a dummy
1126
        // destination in case we don't need change.
1127
0
        CTxDestination dest;
1128
0
        auto op_dest = reservedest.GetReservedDestination(true);
1129
0
        if (!op_dest) {
1130
0
            error = _("Transaction needs a change address, but we can't generate it.") + Untranslated(" ") + util::ErrorString(op_dest);
1131
0
        } else {
1132
0
            dest = *op_dest;
1133
0
            scriptChange = GetScriptForDestination(dest);
1134
0
        }
1135
        // A valid destination implies a change script (and
1136
        // vice-versa). An empty change script will abort later, if the
1137
        // change keypool ran out, but change is required.
1138
0
        CHECK_NONFATAL(IsValidDestination(dest) != scriptChange.empty());
Line
Count
Source
110
0
    inline_check_non_fatal(condition, std::source_location::current(), #condition)
1139
0
    }
1140
0
    CTxOut change_prototype_txout(0, scriptChange);
1141
0
    coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
1142
1143
    // Get size of spending the change output
1144
0
    int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, &wallet, /*coin_control=*/nullptr);
1145
    // If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
1146
    // as lower-bound to allow BnB to do its thing
1147
0
    if (change_spend_size == -1) {
1148
0
        coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
1149
0
    } else {
1150
0
        coin_selection_params.change_spend_size = change_spend_size;
1151
0
    }
1152
1153
    // Set discard feerate
1154
0
    coin_selection_params.m_discard_feerate = GetDiscardRate(wallet);
1155
1156
    // Get the fee rate to use effective values in coin selection
1157
0
    FeeCalculation feeCalc;
1158
0
    coin_selection_params.m_effective_feerate = GetMinimumFeeRate(wallet, coin_control, &feeCalc);
1159
    // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
1160
    // provided one
1161
0
    if (coin_control.m_feerate && coin_selection_params.m_effective_feerate > *coin_control.m_feerate) {
1162
0
        return util::Error{strprintf(_("Fee rate (%s) is lower than the minimum fee rate setting (%s)"), coin_control.m_feerate->ToString(FeeRateFormat::SAT_VB), coin_selection_params.m_effective_feerate.ToString(FeeRateFormat::SAT_VB))};
Line
Count
Source
1172
0
#define strprintf tfm::format
1163
0
    }
1164
0
    if (feeCalc.reason == FeeReason::FALLBACK && !wallet.m_allow_fallback_fee) {
1165
        // eventually allow a fallback fee
1166
0
        return util::Error{strprintf(_("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable %s."), "-fallbackfee")};
Line
Count
Source
1172
0
#define strprintf tfm::format
1167
0
    }
1168
1169
    // Calculate the cost of change
1170
    // Cost of change is the cost of creating the change output + cost of spending the change output in the future.
1171
    // For creating the change output now, we use the effective feerate.
1172
    // For spending the change output in the future, we use the discard feerate for now.
1173
    // So cost of change = (change output size * effective feerate) + (size of spending change output * discard feerate)
1174
0
    coin_selection_params.m_change_fee = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.change_output_size);
1175
0
    coin_selection_params.m_cost_of_change = coin_selection_params.m_discard_feerate.GetFee(coin_selection_params.change_spend_size) + coin_selection_params.m_change_fee;
1176
1177
0
    coin_selection_params.m_min_change_target = GenerateChangeTarget(std::floor(recipients_sum / vecSend.size()), coin_selection_params.m_change_fee, rng_fast);
1178
1179
    // The smallest change amount should be:
1180
    // 1. at least equal to dust threshold
1181
    // 2. at least 1 sat greater than fees to spend it at m_discard_feerate
1182
0
    const auto dust = GetDustThreshold(change_prototype_txout, coin_selection_params.m_discard_feerate);
1183
0
    const auto change_spend_fee = coin_selection_params.m_discard_feerate.GetFee(coin_selection_params.change_spend_size);
1184
0
    coin_selection_params.min_viable_change = std::max(change_spend_fee + 1, dust);
1185
1186
    // Include the fees for things that aren't inputs, excluding the change output
1187
0
    const CAmount not_input_fees = coin_selection_params.m_effective_feerate.GetFee(coin_selection_params.m_subtract_fee_outputs ? 0 : coin_selection_params.tx_noinputs_size);
1188
0
    CAmount selection_target = recipients_sum + not_input_fees;
1189
1190
    // This can only happen if feerate is 0, and requested destinations are value of 0 (e.g. OP_RETURN)
1191
    // and no pre-selected inputs. This will result in 0-input transaction, which is consensus-invalid anyways
1192
0
    if (selection_target == 0 && !coin_control.HasSelected()) {
1193
0
        return util::Error{_("Transaction requires one destination of non-zero value, a non-zero feerate, or a pre-selected input")};
1194
0
    }
1195
1196
    // Fetch manually selected coins
1197
0
    CoinsResult preset_inputs;
1198
0
    if (coin_control.HasSelected()) {
1199
0
        auto res_fetch_inputs = FetchSelectedInputs(wallet, coin_control, coin_selection_params);
1200
0
        if (!res_fetch_inputs) return util::Error{util::ErrorString(res_fetch_inputs)};
1201
0
        preset_inputs = *res_fetch_inputs;
1202
0
    }
1203
1204
    // Fetch wallet available coins if "other inputs" are
1205
    // allowed (coins automatically selected by the wallet)
1206
0
    CoinsResult available_coins;
1207
0
    if (coin_control.m_allow_other_inputs) {
1208
0
        available_coins = AvailableCoins(wallet, &coin_control, coin_selection_params.m_effective_feerate);
1209
0
    }
1210
1211
    // Choose coins to use
1212
0
    auto select_coins_res = SelectCoins(wallet, available_coins, preset_inputs, /*nTargetValue=*/selection_target, coin_control, coin_selection_params);
1213
0
    if (!select_coins_res) {
1214
        // 'SelectCoins' either returns a specific error message or, if empty, means a general "Insufficient funds".
1215
0
        const bilingual_str& err = util::ErrorString(select_coins_res);
1216
0
        if (!err.empty()) return util::Error{err};
1217
1218
        // Check if we have enough balance but cannot cover the fees
1219
0
        CAmount available_balance = preset_inputs.GetTotalAmount() + available_coins.GetTotalAmount();
1220
        // Note: if SelectCoins() fails when SFFO is enabled (recipients_sum = selection_target with SFFO),
1221
        // then recipients_sum > available_balance and we wouldn't enter into the if condition below.
1222
0
        if (available_balance >= recipients_sum) {
1223
            // If we have coins with balance, they should have effective values since we constructed them with valid feerate.
1224
0
            assert(!preset_inputs.Size() || preset_inputs.GetEffectiveTotalAmount().has_value());
1225
0
            assert(!available_coins.Size() || available_coins.GetEffectiveTotalAmount().has_value());
1226
0
            CAmount available_effective_balance = preset_inputs.GetEffectiveTotalAmount().value_or(0) + available_coins.GetEffectiveTotalAmount().value_or(0);
1227
0
            if (available_effective_balance < selection_target) {
1228
0
                Assume(!coin_selection_params.m_subtract_fee_outputs);
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
1229
0
                return util::Error{strprintf(_("The total exceeds your balance when the %s transaction fee is included."), FormatMoney(selection_target - recipients_sum))};
Line
Count
Source
1172
0
#define strprintf tfm::format
1230
0
            }
1231
0
        }
1232
1233
        // General failure description
1234
0
        return util::Error{_("Insufficient funds")};
1235
0
    }
1236
0
    const SelectionResult& result = *select_coins_res;
1237
0
    TRACEPOINT(coin_selection, selected_coins,
1238
0
           wallet.GetName().c_str(),
1239
0
           GetAlgorithmName(result.GetAlgo()).c_str(),
1240
0
           result.GetTarget(),
1241
0
           result.GetWaste(),
1242
0
           result.GetSelectedValue());
1243
1244
    // vouts to the payees
1245
0
    txNew.vout.reserve(vecSend.size() + 1); // + 1 because of possible later insert
1246
0
    for (const auto& recipient : vecSend)
1247
0
    {
1248
0
        txNew.vout.emplace_back(recipient.nAmount, GetScriptForDestination(recipient.dest));
1249
0
    }
1250
0
    const CAmount change_amount = result.GetChange(coin_selection_params.min_viable_change, coin_selection_params.m_change_fee);
1251
0
    if (change_amount > 0) {
1252
0
        CTxOut newTxOut(change_amount, scriptChange);
1253
0
        if (!change_pos) {
1254
            // Insert change txn at random position:
1255
0
            change_pos = rng_fast.randrange(txNew.vout.size() + 1);
1256
0
        } else if ((unsigned int)*change_pos > txNew.vout.size()) {
1257
0
            return util::Error{_("Transaction change output index out of range")};
1258
0
        }
1259
0
        txNew.vout.insert(txNew.vout.begin() + *change_pos, newTxOut);
1260
0
    } else {
1261
0
        change_pos = std::nullopt;
1262
0
    }
1263
1264
    // Shuffle selected coins and fill in final vin
1265
0
    std::vector<std::shared_ptr<COutput>> selected_coins = result.GetShuffledInputVector();
1266
1267
0
    if (coin_control.HasSelected() && coin_control.HasSelectedOrder()) {
1268
        // When there are preselected inputs, we need to move them to be the first UTXOs
1269
        // and have them be in the order selected. We can use stable_sort for this, where we
1270
        // compare with the positions stored in coin_control. The COutputs that have positions
1271
        // will be placed before those that don't, and those positions will be in order.
1272
0
        std::stable_sort(selected_coins.begin(), selected_coins.end(),
1273
0
            [&coin_control](const std::shared_ptr<COutput>& a, const std::shared_ptr<COutput>& b) {
1274
0
                auto a_pos = coin_control.GetSelectionPos(a->outpoint);
1275
0
                auto b_pos = coin_control.GetSelectionPos(b->outpoint);
1276
0
                if (a_pos.has_value() && b_pos.has_value()) {
1277
0
                    return a_pos.value() < b_pos.value();
1278
0
                } else if (a_pos.has_value() && !b_pos.has_value()) {
1279
0
                    return true;
1280
0
                } else {
1281
0
                    return false;
1282
0
                }
1283
0
            });
1284
0
    }
1285
1286
    // The sequence number is set to non-maxint so that DiscourageFeeSniping
1287
    // works.
1288
    //
1289
    // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
1290
    // we use the highest possible value in that range (maxint-2)
1291
    // to avoid conflicting with other possible uses of nSequence,
1292
    // and in the spirit of "smallest possible change from prior
1293
    // behavior."
1294
0
    bool use_anti_fee_sniping = true;
1295
0
    const uint32_t default_sequence{coin_control.m_signal_bip125_rbf.value_or(wallet.m_signal_rbf) ? MAX_BIP125_RBF_SEQUENCE : CTxIn::MAX_SEQUENCE_NONFINAL};
1296
0
    txNew.vin.reserve(selected_coins.size());
1297
0
    for (const auto& coin : selected_coins) {
1298
0
        std::optional<uint32_t> sequence = coin_control.GetSequence(coin->outpoint);
1299
0
        if (sequence) {
1300
            // If an input has a preset sequence, we can't do anti-fee-sniping
1301
0
            use_anti_fee_sniping = false;
1302
0
        }
1303
0
        txNew.vin.emplace_back(coin->outpoint, CScript{}, sequence.value_or(default_sequence));
1304
1305
0
        auto scripts = coin_control.GetScripts(coin->outpoint);
1306
0
        if (scripts.first) {
1307
0
            txNew.vin.back().scriptSig = *scripts.first;
1308
0
        }
1309
0
        if (scripts.second) {
1310
0
            txNew.vin.back().scriptWitness = *scripts.second;
1311
0
        }
1312
0
    }
1313
0
    if (coin_control.m_locktime) {
1314
0
        txNew.nLockTime = coin_control.m_locktime.value();
1315
        // If we have a locktime set, we can't use anti-fee-sniping
1316
0
        use_anti_fee_sniping = false;
1317
0
    }
1318
0
    if (use_anti_fee_sniping) {
1319
0
        DiscourageFeeSniping(txNew, rng_fast, wallet.chain(), wallet.GetLastBlockHash(), wallet.GetLastBlockHeight());
1320
0
    }
1321
1322
    // Calculate the transaction fee
1323
0
    TxSize tx_sizes = CalculateMaximumSignedTxSize(CTransaction(txNew), &wallet, &coin_control);
1324
0
    int nBytes = tx_sizes.vsize;
1325
0
    if (nBytes == -1) {
1326
0
        return util::Error{_("Missing solving data for estimating transaction size")};
1327
0
    }
1328
0
    CAmount fee_needed = coin_selection_params.m_effective_feerate.GetFee(nBytes) + result.GetTotalBumpFees();
1329
0
    const CAmount output_value = CalculateOutputValue(txNew);
1330
0
    Assume(recipients_sum + change_amount == output_value);
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
1331
0
    CAmount current_fee = result.GetSelectedValue() - output_value;
1332
1333
    // Sanity check that the fee cannot be negative as that means we have more output value than input value
1334
0
    if (current_fee < 0) {
1335
0
        return util::Error{Untranslated(STR_INTERNAL_BUG("Fee paid < 0"))};
Line
Count
Source
96
0
#define STR_INTERNAL_BUG(msg) StrFormatInternalBug((msg), std::source_location::current())
1336
0
    }
1337
1338
    // If there is a change output and we overpay the fees then increase the change to match the fee needed
1339
0
    if (change_pos && fee_needed < current_fee) {
1340
0
        auto& change = txNew.vout.at(*change_pos);
1341
0
        change.nValue += current_fee - fee_needed;
1342
0
        current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
1343
0
        if (fee_needed != current_fee) {
1344
0
            return util::Error{Untranslated(STR_INTERNAL_BUG("Change adjustment: Fee needed != fee paid"))};
Line
Count
Source
96
0
#define STR_INTERNAL_BUG(msg) StrFormatInternalBug((msg), std::source_location::current())
1345
0
        }
1346
0
    }
1347
1348
    // Reduce output values for subtractFeeFromAmount
1349
0
    if (coin_selection_params.m_subtract_fee_outputs) {
1350
0
        CAmount to_reduce = fee_needed - current_fee;
1351
0
        unsigned int i = 0;
1352
0
        bool fFirst = true;
1353
0
        for (const auto& recipient : vecSend)
1354
0
        {
1355
0
            if (change_pos && i == *change_pos) {
1356
0
                ++i;
1357
0
            }
1358
0
            CTxOut& txout = txNew.vout[i];
1359
1360
0
            if (recipient.fSubtractFeeFromAmount)
1361
0
            {
1362
0
                txout.nValue -= to_reduce / outputs_to_subtract_fee_from; // Subtract fee equally from each selected recipient
1363
1364
0
                if (fFirst) // first receiver pays the remainder not divisible by output count
1365
0
                {
1366
0
                    fFirst = false;
1367
0
                    txout.nValue -= to_reduce % outputs_to_subtract_fee_from;
1368
0
                }
1369
1370
                // Error if this output is reduced to be below dust
1371
0
                if (IsDust(txout, wallet.chain().relayDustFee())) {
1372
0
                    if (txout.nValue < 0) {
1373
0
                        return util::Error{_("The transaction amount is too small to pay the fee")};
1374
0
                    } else {
1375
0
                        return util::Error{_("The transaction amount is too small to send after the fee has been deducted")};
1376
0
                    }
1377
0
                }
1378
0
            }
1379
0
            ++i;
1380
0
        }
1381
0
        current_fee = result.GetSelectedValue() - CalculateOutputValue(txNew);
1382
0
        if (fee_needed != current_fee) {
1383
0
            return util::Error{Untranslated(STR_INTERNAL_BUG("SFFO: Fee needed != fee paid"))};
Line
Count
Source
96
0
#define STR_INTERNAL_BUG(msg) StrFormatInternalBug((msg), std::source_location::current())
1384
0
        }
1385
0
    }
1386
1387
    // fee_needed should now always be less than or equal to the current fees that we pay.
1388
    // If it is not, it is a bug.
1389
0
    if (fee_needed > current_fee) {
1390
0
        return util::Error{Untranslated(STR_INTERNAL_BUG("Fee needed > fee paid"))};
Line
Count
Source
96
0
#define STR_INTERNAL_BUG(msg) StrFormatInternalBug((msg), std::source_location::current())
1391
0
    }
1392
1393
    // Give up if change keypool ran out and change is required
1394
0
    if (scriptChange.empty() && change_pos) {
1395
0
        return util::Error{error};
1396
0
    }
1397
1398
0
    if (sign && !wallet.SignTransaction(txNew)) {
1399
0
        return util::Error{_("Signing transaction failed")};
1400
0
    }
1401
1402
    // Return the constructed transaction data.
1403
0
    CTransactionRef tx = MakeTransactionRef(std::move(txNew));
1404
1405
    // Limit size
1406
0
    if ((sign && GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT) ||
1407
0
        (!sign && tx_sizes.weight > MAX_STANDARD_TX_WEIGHT))
1408
0
    {
1409
0
        return util::Error{_("Transaction too large")};
1410
0
    }
1411
1412
0
    if (current_fee > wallet.m_default_max_tx_fee) {
1413
0
        return util::Error{TransactionErrorString(TransactionError::MAX_FEE_EXCEEDED)};
1414
0
    }
1415
1416
0
    if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
1417
        // Lastly, ensure this tx will pass the mempool's chain limits
1418
0
        auto result = wallet.chain().checkChainLimits(tx);
1419
0
        if (!result) {
1420
0
            return util::Error{util::ErrorString(result)};
1421
0
        }
1422
0
    }
1423
1424
    // Before we return success, we assume any change key will be used to prevent
1425
    // accidental reuse.
1426
0
    reservedest.KeepDestination();
1427
1428
0
    wallet.WalletLogPrintf("Coin Selection: Algorithm:%s, Waste Metric Score:%d\n", GetAlgorithmName(result.GetAlgo()), result.GetWaste());
1429
0
    wallet.WalletLogPrintf("Fee Calculation: Fee:%d Bytes:%u Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
1430
0
              current_fee, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
1431
0
              feeCalc.est.pass.start, feeCalc.est.pass.end,
1432
0
              (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool) > 0.0 ? 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool) : 0.0,
1433
0
              feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
1434
0
              feeCalc.est.fail.start, feeCalc.est.fail.end,
1435
0
              (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool) > 0.0 ? 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool) : 0.0,
1436
0
              feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
1437
0
    return CreatedTransactionResult(tx, current_fee, change_pos, feeCalc);
1438
0
}
1439
1440
util::Result<CreatedTransactionResult> CreateTransaction(
1441
        CWallet& wallet,
1442
        const std::vector<CRecipient>& vecSend,
1443
        std::optional<unsigned int> change_pos,
1444
        const CCoinControl& coin_control,
1445
        bool sign)
1446
0
{
1447
0
    if (vecSend.empty()) {
1448
0
        return util::Error{_("Transaction must have at least one recipient")};
1449
0
    }
1450
1451
0
    if (std::any_of(vecSend.cbegin(), vecSend.cend(), [](const auto& recipient){ return recipient.nAmount < 0; })) {
1452
0
        return util::Error{_("Transaction amounts must not be negative")};
1453
0
    }
1454
1455
0
    LOCK(wallet.cs_wallet);
Line
Count
Source
266
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1456
1457
0
    auto res = CreateTransactionInternal(wallet, vecSend, change_pos, coin_control, sign);
1458
0
    TRACEPOINT(coin_selection, normal_create_tx_internal,
1459
0
           wallet.GetName().c_str(),
1460
0
           bool(res),
1461
0
           res ? res->fee : 0,
1462
0
           res && res->change_pos.has_value() ? int32_t(*res->change_pos) : -1);
1463
0
    if (!res) return res;
1464
0
    const auto& txr_ungrouped = *res;
1465
    // try with avoidpartialspends unless it's enabled already
1466
0
    if (txr_ungrouped.fee > 0 /* 0 means non-functional fee rate estimation */ && wallet.m_max_aps_fee > -1 && !coin_control.m_avoid_partial_spends) {
1467
0
        TRACEPOINT(coin_selection, attempting_aps_create_tx, wallet.GetName().c_str());
1468
0
        CCoinControl tmp_cc = coin_control;
1469
0
        tmp_cc.m_avoid_partial_spends = true;
1470
1471
        // Reuse the change destination from the first creation attempt to avoid skipping BIP44 indexes
1472
0
        if (txr_ungrouped.change_pos) {
1473
0
            ExtractDestination(txr_ungrouped.tx->vout[*txr_ungrouped.change_pos].scriptPubKey, tmp_cc.destChange);
1474
0
        }
1475
1476
0
        auto txr_grouped = CreateTransactionInternal(wallet, vecSend, change_pos, tmp_cc, sign);
1477
        // if fee of this alternative one is within the range of the max fee, we use this one
1478
0
        const bool use_aps{txr_grouped.has_value() ? (txr_grouped->fee <= txr_ungrouped.fee + wallet.m_max_aps_fee) : false};
1479
0
        TRACEPOINT(coin_selection, aps_create_tx_internal,
1480
0
               wallet.GetName().c_str(),
1481
0
               use_aps,
1482
0
               txr_grouped.has_value(),
1483
0
               txr_grouped.has_value() ? txr_grouped->fee : 0,
1484
0
               txr_grouped.has_value() && txr_grouped->change_pos.has_value() ? int32_t(*txr_grouped->change_pos) : -1);
1485
0
        if (txr_grouped) {
1486
0
            wallet.WalletLogPrintf("Fee non-grouped = %lld, grouped = %lld, using %s\n",
1487
0
                txr_ungrouped.fee, txr_grouped->fee, use_aps ? "grouped" : "non-grouped");
1488
0
            if (use_aps) return txr_grouped;
1489
0
        }
1490
0
    }
1491
0
    return res;
1492
0
}
1493
1494
util::Result<CreatedTransactionResult> FundTransaction(CWallet& wallet, const CMutableTransaction& tx, const std::vector<CRecipient>& vecSend, std::optional<unsigned int> change_pos, bool lockUnspents, CCoinControl coinControl)
1495
0
{
1496
    // We want to make sure tx.vout is not used now that we are passing outputs as a vector of recipients.
1497
    // This sets us up to remove tx completely in a future PR in favor of passing the inputs directly.
1498
0
    assert(tx.vout.empty());
1499
1500
    // Set the user desired locktime
1501
0
    coinControl.m_locktime = tx.nLockTime;
1502
1503
    // Set the user desired version
1504
0
    coinControl.m_version = tx.version;
1505
1506
    // Acquire the locks to prevent races to the new locked unspents between the
1507
    // CreateTransaction call and LockCoin calls (when lockUnspents is true).
1508
0
    LOCK(wallet.cs_wallet);
Line
Count
Source
266
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1509
1510
    // Fetch specified UTXOs from the UTXO set to get the scriptPubKeys and values of the outputs being selected
1511
    // and to match with the given solving_data. Only used for non-wallet outputs.
1512
0
    std::map<COutPoint, Coin> coins;
1513
0
    for (const CTxIn& txin : tx.vin) {
1514
0
        coins[txin.prevout]; // Create empty map entry keyed by prevout.
1515
0
    }
1516
0
    wallet.chain().findCoins(coins);
1517
1518
0
    for (const CTxIn& txin : tx.vin) {
1519
0
        const auto& outPoint = txin.prevout;
1520
0
        PreselectedInput& preset_txin = coinControl.Select(outPoint);
1521
0
        if (!wallet.IsMine(outPoint)) {
1522
0
            if (coins[outPoint].out.IsNull()) {
1523
0
                return util::Error{_("Unable to find UTXO for external input")};
1524
0
            }
1525
1526
            // The input was not in the wallet, but is in the UTXO set, so select as external
1527
0
            preset_txin.SetTxOut(coins[outPoint].out);
1528
0
        }
1529
0
        preset_txin.SetSequence(txin.nSequence);
1530
0
        preset_txin.SetScriptSig(txin.scriptSig);
1531
0
        preset_txin.SetScriptWitness(txin.scriptWitness);
1532
0
    }
1533
1534
0
    auto res = CreateTransaction(wallet, vecSend, change_pos, coinControl, false);
1535
0
    if (!res) {
1536
0
        return res;
1537
0
    }
1538
1539
0
    if (lockUnspents) {
1540
0
        for (const CTxIn& txin : res->tx->vin) {
1541
0
            wallet.LockCoin(txin.prevout, /*persist=*/false);
1542
0
        }
1543
0
    }
1544
1545
0
    return res;
1546
0
}
1547
} // namespace wallet