Coverage Report

Created: 2026-06-16 16:41

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