Bitcoin Core Fuzz Coverage Report for wallet_tx_can_be_bumped

Coverage Report

Created: 2025-11-19 11:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/Users/brunogarcia/projects/bitcoin-core-dev/src/wallet/feebumper.cpp
Line
Count
Source
1
// Copyright (c) 2017-2022 The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <common/system.h>
6
#include <consensus/validation.h>
7
#include <interfaces/chain.h>
8
#include <policy/fees/block_policy_estimator.h>
9
#include <policy/policy.h>
10
#include <util/moneystr.h>
11
#include <util/rbf.h>
12
#include <util/translation.h>
13
#include <wallet/coincontrol.h>
14
#include <wallet/feebumper.h>
15
#include <wallet/fees.h>
16
#include <wallet/receive.h>
17
#include <wallet/spend.h>
18
#include <wallet/wallet.h>
19
20
namespace wallet {
21
//! Check whether transaction has descendant in wallet or mempool, or has been
22
//! mined, or conflicts with a mined transaction. Return a feebumper::Result.
23
static feebumper::Result PreconditionChecks(const CWallet& wallet, const CWalletTx& wtx, bool require_mine, std::vector<bilingual_str>& errors) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
24
3.76k
{
25
3.76k
    if (wallet.HasWalletSpend(wtx.tx)) {
26
145
        errors.emplace_back(Untranslated("Transaction has descendants in the wallet"));
27
145
        return feebumper::Result::INVALID_PARAMETER;
28
145
    }
29
3.62k
    {
30
3.62k
        if (wallet.chain().hasDescendantsInMempool(wtx.GetHash())) {
31
718
            errors.emplace_back(Untranslated("Transaction has descendants in the mempool"));
32
718
            return feebumper::Result::INVALID_PARAMETER;
33
718
        }
34
3.62k
    }
35
36
2.90k
    if (wallet.GetTxDepthInMainChain(wtx) != 0) {
37
105
        errors.emplace_back(Untranslated("Transaction has been mined, or is conflicted with a mined transaction"));
38
105
        return feebumper::Result::WALLET_ERROR;
39
105
    }
40
41
2.80k
    if (wtx.mapValue.count("replaced_by_txid")) {
42
183
        errors.push_back(Untranslated(strprintf("Cannot bump transaction %s which was already bumped by transaction %s", wtx.GetHash().ToString(), wtx.mapValue.at("replaced_by_txid"))));
Line
Count
Source
1172
183
#define strprintf tfm::format
43
183
        return feebumper::Result::WALLET_ERROR;
44
183
    }
45
46
2.61k
    if (require_mine) {
47
        // check that original tx consists entirely of our inputs
48
        // if not, we can't bump the fee, because the wallet has no way of knowing the value of the other inputs (thus the fee)
49
2.61k
        if (!AllInputsMine(wallet, *wtx.tx)) {
50
1.27k
            errors.emplace_back(Untranslated("Transaction contains inputs that don't belong to this wallet"));
51
1.27k
            return feebumper::Result::WALLET_ERROR;
52
1.27k
        }
53
2.61k
    }
54
55
1.34k
    return feebumper::Result::OK;
56
2.61k
}
57
58
//! Check if the user provided a valid feeRate
59
static feebumper::Result CheckFeeRate(const CWallet& wallet, const CMutableTransaction& mtx, const CFeeRate& newFeerate, const int64_t maxTxSize, CAmount old_fee, std::vector<bilingual_str>& errors)
60
0
{
61
    // check that fee rate is higher than mempool's minimum fee
62
    // (no point in bumping fee if we know that the new tx won't be accepted to the mempool)
63
    // This may occur if the user set fee_rate or paytxfee too low, if fallbackfee is too low, or, perhaps,
64
    // in a rare situation where the mempool minimum fee increased significantly since the fee estimation just a
65
    // moment earlier. In this case, we report an error to the user, who may adjust the fee.
66
0
    CFeeRate minMempoolFeeRate = wallet.chain().mempoolMinFee();
67
68
0
    if (newFeerate.GetFeePerK() < minMempoolFeeRate.GetFeePerK()) {
69
0
        errors.push_back(Untranslated(
70
0
            strprintf("New fee rate (%s) is lower than the minimum fee rate (%s) to get into the mempool -- ",
Line
Count
Source
1172
0
#define strprintf tfm::format
71
0
            FormatMoney(newFeerate.GetFeePerK()),
72
0
            FormatMoney(minMempoolFeeRate.GetFeePerK()))));
73
0
        return feebumper::Result::WALLET_ERROR;
74
0
    }
75
76
0
    std::vector<COutPoint> reused_inputs;
77
0
    reused_inputs.reserve(mtx.vin.size());
78
0
    for (const CTxIn& txin : mtx.vin) {
79
0
        reused_inputs.push_back(txin.prevout);
80
0
    }
81
82
0
    std::optional<CAmount> combined_bump_fee = wallet.chain().calculateCombinedBumpFee(reused_inputs, newFeerate);
83
0
    if (!combined_bump_fee.has_value()) {
84
0
        errors.push_back(Untranslated(strprintf("Failed to calculate bump fees, because unconfirmed UTXOs depend on an enormous cluster of unconfirmed transactions.")));
Line
Count
Source
1172
0
#define strprintf tfm::format
85
0
    }
86
0
    CAmount new_total_fee = newFeerate.GetFee(maxTxSize) + combined_bump_fee.value();
87
88
0
    CFeeRate incrementalRelayFee = wallet.chain().relayIncrementalFee();
89
90
    // Min total fee is old fee + relay fee
91
0
    CAmount minTotalFee = old_fee + incrementalRelayFee.GetFee(maxTxSize);
92
93
0
    if (new_total_fee < minTotalFee) {
94
0
        errors.push_back(Untranslated(strprintf("Insufficient total fee %s, must be at least %s (oldFee %s + incrementalFee %s)",
Line
Count
Source
1172
0
#define strprintf tfm::format
95
0
            FormatMoney(new_total_fee), FormatMoney(minTotalFee), FormatMoney(old_fee), FormatMoney(incrementalRelayFee.GetFee(maxTxSize)))));
96
0
        return feebumper::Result::INVALID_PARAMETER;
97
0
    }
98
99
0
    CAmount requiredFee = GetRequiredFee(wallet, maxTxSize);
100
0
    if (new_total_fee < requiredFee) {
101
0
        errors.push_back(Untranslated(strprintf("Insufficient total fee (cannot be less than required fee %s)",
Line
Count
Source
1172
0
#define strprintf tfm::format
102
0
            FormatMoney(requiredFee))));
103
0
        return feebumper::Result::INVALID_PARAMETER;
104
0
    }
105
106
    // Check that in all cases the new fee doesn't violate maxTxFee
107
0
    const CAmount max_tx_fee = wallet.m_default_max_tx_fee;
108
0
    if (new_total_fee > max_tx_fee) {
109
0
        errors.push_back(Untranslated(strprintf("Specified or calculated fee %s is too high (cannot be higher than -maxtxfee %s)",
Line
Count
Source
1172
0
#define strprintf tfm::format
110
0
            FormatMoney(new_total_fee), FormatMoney(max_tx_fee))));
111
0
        return feebumper::Result::WALLET_ERROR;
112
0
    }
113
114
0
    return feebumper::Result::OK;
115
0
}
116
117
static CFeeRate EstimateFeeRate(const CWallet& wallet, const CWalletTx& wtx, const CAmount old_fee, const CCoinControl& coin_control)
118
0
{
119
    // Get the fee rate of the original transaction. This is calculated from
120
    // the tx fee/vsize, so it may have been rounded down. Add 1 satoshi to the
121
    // result.
122
0
    int64_t txSize = GetVirtualTransactionSize(*(wtx.tx));
123
0
    CFeeRate feerate(old_fee, txSize);
124
0
    feerate += CFeeRate(1);
125
126
    // The node has a configurable incremental relay fee. Increment the fee by
127
    // the minimum of that and the wallet's conservative
128
    // WALLET_INCREMENTAL_RELAY_FEE value to future proof against changes to
129
    // network wide policy for incremental relay fee that our node may not be
130
    // aware of. This ensures we're over the required relay fee rate
131
    // (Rule 4).  The replacement tx will be at least as large as the
132
    // original tx, so the total fee will be greater (Rule 3)
133
0
    CFeeRate node_incremental_relay_fee = wallet.chain().relayIncrementalFee();
134
0
    CFeeRate wallet_incremental_relay_fee = CFeeRate(WALLET_INCREMENTAL_RELAY_FEE);
135
0
    feerate += std::max(node_incremental_relay_fee, wallet_incremental_relay_fee);
136
137
    // Fee rate must also be at least the wallet's GetMinimumFeeRate
138
0
    CFeeRate min_feerate(GetMinimumFeeRate(wallet, coin_control, /*feeCalc=*/nullptr));
139
140
    // Set the required fee rate for the replacement transaction in coin control.
141
0
    return std::max(feerate, min_feerate);
142
0
}
143
144
namespace feebumper {
145
146
bool TransactionCanBeBumped(const CWallet& wallet, const Txid& txid)
147
3.76k
{
148
3.76k
    LOCK(wallet.cs_wallet);
Line
Count
Source
259
3.76k
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
3.76k
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
3.76k
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
3.76k
#define PASTE(x, y) x ## y
149
3.76k
    const CWalletTx* wtx = wallet.GetWalletTx(txid);
150
3.76k
    if (wtx == nullptr) 
return false0
;
151
152
3.76k
    std::vector<bilingual_str> errors_dummy;
153
3.76k
    feebumper::Result res = PreconditionChecks(wallet, *wtx, /* require_mine=*/ true, errors_dummy);
154
3.76k
    return res == feebumper::Result::OK;
155
3.76k
}
156
157
Result CreateRateBumpTransaction(CWallet& wallet, const Txid& txid, const CCoinControl& coin_control, std::vector<bilingual_str>& errors,
158
                                 CAmount& old_fee, CAmount& new_fee, CMutableTransaction& mtx, bool require_mine, const std::vector<CTxOut>& outputs, std::optional<uint32_t> original_change_index)
159
0
{
160
    // For now, cannot specify both new outputs to use and an output index to send change
161
0
    if (!outputs.empty() && original_change_index.has_value()) {
162
0
        errors.emplace_back(Untranslated("The options 'outputs' and 'original_change_index' are incompatible. You can only either specify a new set of outputs, or designate a change output to be recycled."));
163
0
        return Result::INVALID_PARAMETER;
164
0
    }
165
166
    // We are going to modify coin control later, copy to reuse
167
0
    CCoinControl new_coin_control(coin_control);
168
169
0
    LOCK(wallet.cs_wallet);
Line
Count
Source
259
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
170
0
    errors.clear();
171
0
    auto it = wallet.mapWallet.find(txid);
172
0
    if (it == wallet.mapWallet.end()) {
173
0
        errors.emplace_back(Untranslated("Invalid or non-wallet transaction id"));
174
0
        return Result::INVALID_ADDRESS_OR_KEY;
175
0
    }
176
0
    const CWalletTx& wtx = it->second;
177
178
    // Make sure that original_change_index is valid
179
0
    if (original_change_index.has_value() && original_change_index.value() >= wtx.tx->vout.size()) {
180
0
        errors.emplace_back(Untranslated("Change position is out of range"));
181
0
        return Result::INVALID_PARAMETER;
182
0
    }
183
184
    // Retrieve all of the UTXOs and add them to coin control
185
    // While we're here, calculate the input amount
186
0
    std::map<COutPoint, Coin> coins;
187
0
    CAmount input_value = 0;
188
0
    std::vector<CTxOut> spent_outputs;
189
0
    for (const CTxIn& txin : wtx.tx->vin) {
190
0
        coins[txin.prevout]; // Create empty map entry keyed by prevout.
191
0
    }
192
0
    wallet.chain().findCoins(coins);
193
0
    for (const CTxIn& txin : wtx.tx->vin) {
194
0
        const Coin& coin = coins.at(txin.prevout);
195
0
        if (coin.out.IsNull()) {
196
0
            errors.emplace_back(Untranslated(strprintf("%s:%u is already spent", txin.prevout.hash.GetHex(), txin.prevout.n)));
Line
Count
Source
1172
0
#define strprintf tfm::format
197
0
            return Result::MISC_ERROR;
198
0
        }
199
0
        PreselectedInput& preset_txin = new_coin_control.Select(txin.prevout);
200
0
        if (!wallet.IsMine(txin.prevout)) {
201
0
            preset_txin.SetTxOut(coin.out);
202
0
        }
203
0
        input_value += coin.out.nValue;
204
0
        spent_outputs.push_back(coin.out);
205
0
    }
206
207
    // Figure out if we need to compute the input weight, and do so if necessary
208
0
    PrecomputedTransactionData txdata;
209
0
    txdata.Init(*wtx.tx, std::move(spent_outputs), /* force=*/ true);
210
0
    for (unsigned int i = 0; i < wtx.tx->vin.size(); ++i) {
211
0
        const CTxIn& txin = wtx.tx->vin.at(i);
212
0
        const Coin& coin = coins.at(txin.prevout);
213
214
0
        if (new_coin_control.IsExternalSelected(txin.prevout)) {
215
            // For external inputs, we estimate the size using the size of this input
216
0
            int64_t input_weight = GetTransactionInputWeight(txin);
217
            // Because signatures can have different sizes, we need to figure out all of the
218
            // signature sizes and replace them with the max sized signature.
219
            // In order to do this, we verify the script with a special SignatureChecker which
220
            // will observe the signatures verified and record their sizes.
221
0
            SignatureWeights weights;
222
0
            TransactionSignatureChecker tx_checker(wtx.tx.get(), i, coin.out.nValue, txdata, MissingDataBehavior::FAIL);
223
0
            SignatureWeightChecker size_checker(weights, tx_checker);
224
0
            VerifyScript(txin.scriptSig, coin.out.scriptPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, size_checker);
225
            // Add the difference between max and current to input_weight so that it represents the largest the input could be
226
0
            input_weight += weights.GetWeightDiffToMax();
227
0
            new_coin_control.SetInputWeight(txin.prevout, input_weight);
228
0
        }
229
0
    }
230
231
0
    Result result = PreconditionChecks(wallet, wtx, require_mine, errors);
232
0
    if (result != Result::OK) {
233
0
        return result;
234
0
    }
235
236
    // Calculate the old output amount.
237
0
    CAmount output_value = 0;
238
0
    for (const auto& old_output : wtx.tx->vout) {
239
0
        output_value += old_output.nValue;
240
0
    }
241
242
0
    old_fee = input_value - output_value;
243
244
    // Fill in recipients (and preserve a single change key if there
245
    // is one). If outputs vector is non-empty, replace original
246
    // outputs with its contents, otherwise use original outputs.
247
0
    std::vector<CRecipient> recipients;
248
0
    CAmount new_outputs_value = 0;
249
0
    const auto& txouts = outputs.empty() ? wtx.tx->vout : outputs;
250
0
    for (size_t i = 0; i < txouts.size(); ++i) {
251
0
        const CTxOut& output = txouts.at(i);
252
0
        CTxDestination dest;
253
0
        ExtractDestination(output.scriptPubKey, dest);
254
0
        if (original_change_index.has_value() ?  original_change_index.value() == i : OutputIsChange(wallet, output)) {
255
0
            new_coin_control.destChange = dest;
256
0
        } else {
257
0
            CRecipient recipient = {dest, output.nValue, false};
258
0
            recipients.push_back(recipient);
259
0
        }
260
0
        new_outputs_value += output.nValue;
261
0
    }
262
263
    // If no recipients, means that we are sending coins to a change address
264
0
    if (recipients.empty()) {
265
        // Just as a sanity check, ensure that the change address exist
266
0
        if (std::get_if<CNoDestination>(&new_coin_control.destChange)) {
267
0
            errors.emplace_back(Untranslated("Unable to create transaction. Transaction must have at least one recipient"));
268
0
            return Result::INVALID_PARAMETER;
269
0
        }
270
271
        // Add change as recipient with SFFO flag enabled, so fees are deduced from it.
272
        // If the output differs from the original tx output (because the user customized it) a new change output will be created.
273
0
        recipients.emplace_back(CRecipient{new_coin_control.destChange, new_outputs_value, /*fSubtractFeeFromAmount=*/true});
274
0
        new_coin_control.destChange = CNoDestination();
275
0
    }
276
277
0
    if (coin_control.m_feerate) {
278
        // The user provided a feeRate argument.
279
        // We calculate this here to avoid compiler warning on the cs_wallet lock
280
        // We need to make a temporary transaction with no input witnesses as the dummy signer expects them to be empty for external inputs
281
0
        CMutableTransaction temp_mtx{*wtx.tx};
282
0
        for (auto& txin : temp_mtx.vin) {
283
0
            txin.scriptSig.clear();
284
0
            txin.scriptWitness.SetNull();
285
0
        }
286
0
        temp_mtx.vout = txouts;
287
0
        const int64_t maxTxSize{CalculateMaximumSignedTxSize(CTransaction(temp_mtx), &wallet, &new_coin_control).vsize};
288
0
        Result res = CheckFeeRate(wallet, temp_mtx, *new_coin_control.m_feerate, maxTxSize, old_fee, errors);
289
0
        if (res != Result::OK) {
290
0
            return res;
291
0
        }
292
0
    } else {
293
        // The user did not provide a feeRate argument
294
0
        new_coin_control.m_feerate = EstimateFeeRate(wallet, wtx, old_fee, new_coin_control);
295
0
    }
296
297
    // Fill in required inputs we are double-spending(all of them)
298
    // N.B.: bip125 doesn't require all the inputs in the replaced transaction to be
299
    // used in the replacement transaction, but it's very important for wallets to make
300
    // sure that happens. If not, it would be possible to bump a transaction A twice to
301
    // A2 and A3 where A2 and A3 don't conflict (or alternatively bump A to A2 and A2
302
    // to A3 where A and A3 don't conflict). If both later get confirmed then the sender
303
    // has accidentally double paid.
304
0
    for (const auto& inputs : wtx.tx->vin) {
305
0
        new_coin_control.Select(COutPoint(inputs.prevout));
306
0
    }
307
0
    new_coin_control.m_allow_other_inputs = true;
308
309
    // We cannot source new unconfirmed inputs(bip125 rule 2)
310
0
    new_coin_control.m_min_depth = 1;
311
312
0
    auto res = CreateTransaction(wallet, recipients, /*change_pos=*/std::nullopt, new_coin_control, false);
313
0
    if (!res) {
314
0
        errors.emplace_back(Untranslated("Unable to create transaction.") + Untranslated(" ") + util::ErrorString(res));
315
0
        return Result::WALLET_ERROR;
316
0
    }
317
318
0
    const auto& txr = *res;
319
    // Write back new fee if successful
320
0
    new_fee = txr.fee;
321
322
    // Write back transaction
323
0
    mtx = CMutableTransaction(*txr.tx);
324
325
0
    return Result::OK;
326
0
}
327
328
0
bool SignTransaction(CWallet& wallet, CMutableTransaction& mtx) {
329
0
    LOCK(wallet.cs_wallet);
Line
Count
Source
259
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
330
331
0
    if (wallet.IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
332
        // Make a blank psbt
333
0
        PartiallySignedTransaction psbtx(mtx);
334
335
        // First fill transaction with our data without signing,
336
        // so external signers are not asked to sign more than once.
337
0
        bool complete;
338
0
        wallet.FillPSBT(psbtx, complete, std::nullopt, /*sign=*/false, /*bip32derivs=*/true);
339
0
        auto err{wallet.FillPSBT(psbtx, complete, std::nullopt, /*sign=*/true, /*bip32derivs=*/false)};
340
0
        if (err) return false;
341
0
        complete = FinalizeAndExtractPSBT(psbtx, mtx);
342
0
        return complete;
343
0
    } else {
344
0
        return wallet.SignTransaction(mtx);
345
0
    }
346
0
}
347
348
Result CommitTransaction(CWallet& wallet, const Txid& txid, CMutableTransaction&& mtx, std::vector<bilingual_str>& errors, Txid& bumped_txid)
349
0
{
350
0
    LOCK(wallet.cs_wallet);
Line
Count
Source
259
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
351
0
    if (!errors.empty()) {
352
0
        return Result::MISC_ERROR;
353
0
    }
354
0
    auto it = txid.IsNull() ? wallet.mapWallet.end() : wallet.mapWallet.find(txid);
355
0
    if (it == wallet.mapWallet.end()) {
356
0
        errors.emplace_back(Untranslated("Invalid or non-wallet transaction id"));
357
0
        return Result::MISC_ERROR;
358
0
    }
359
0
    const CWalletTx& oldWtx = it->second;
360
361
    // make sure the transaction still has no descendants and hasn't been mined in the meantime
362
0
    Result result = PreconditionChecks(wallet, oldWtx, /* require_mine=*/ false, errors);
363
0
    if (result != Result::OK) {
364
0
        return result;
365
0
    }
366
367
    // commit/broadcast the tx
368
0
    CTransactionRef tx = MakeTransactionRef(std::move(mtx));
369
0
    mapValue_t mapValue = oldWtx.mapValue;
370
0
    mapValue["replaces_txid"] = oldWtx.GetHash().ToString();
371
372
0
    wallet.CommitTransaction(tx, std::move(mapValue), oldWtx.vOrderForm);
373
374
    // mark the original tx as bumped
375
0
    bumped_txid = tx->GetHash();
376
0
    if (!wallet.MarkReplaced(oldWtx.GetHash(), bumped_txid)) {
377
0
        errors.emplace_back(Untranslated("Created new bumpfee transaction but could not mark the original transaction as replaced"));
378
0
    }
379
0
    return Result::OK;
380
0
}
381
382
} // namespace feebumper
383
} // namespace wallet