Coverage Report

Created: 2026-09-14 20:36

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