Bitcoin Core 22.99.0
P2P Digital Currency
feebumper.cpp
Go to the documentation of this file.
1// Copyright (c) 2017-2020 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 <interfaces/chain.h>
6#include <policy/fees.h>
7#include <policy/policy.h>
8#include <util/moneystr.h>
9#include <util/rbf.h>
10#include <util/system.h>
11#include <util/translation.h>
12#include <wallet/coincontrol.h>
13#include <wallet/feebumper.h>
14#include <wallet/fees.h>
15#include <wallet/receive.h>
16#include <wallet/spend.h>
17#include <wallet/wallet.h>
18
21static feebumper::Result PreconditionChecks(const CWallet& wallet, const CWalletTx& wtx, std::vector<bilingual_str>& errors) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
22{
23 if (wallet.HasWalletSpend(wtx.GetHash())) {
24 errors.push_back(Untranslated("Transaction has descendants in the wallet"));
26 }
27
28 {
29 if (wallet.chain().hasDescendantsInMempool(wtx.GetHash())) {
30 errors.push_back(Untranslated("Transaction has descendants in the mempool"));
32 }
33 }
34
35 if (wallet.GetTxDepthInMainChain(wtx) != 0) {
36 errors.push_back(Untranslated("Transaction has been mined, or is conflicted with a mined transaction"));
38 }
39
40 if (!SignalsOptInRBF(*wtx.tx)) {
41 errors.push_back(Untranslated("Transaction is not BIP 125 replaceable"));
43 }
44
45 if (wtx.mapValue.count("replaced_by_txid")) {
46 errors.push_back(strprintf(Untranslated("Cannot bump transaction %s which was already bumped by transaction %s"), wtx.GetHash().ToString(), wtx.mapValue.at("replaced_by_txid")));
48 }
49
50 // check that original tx consists entirely of our inputs
51 // 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)
52 isminefilter filter = wallet.GetLegacyScriptPubKeyMan() && wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
53 if (!AllInputsMine(wallet, *wtx.tx, filter)) {
54 errors.push_back(Untranslated("Transaction contains inputs that don't belong to this wallet"));
56 }
57
58
60}
61
63static feebumper::Result CheckFeeRate(const CWallet& wallet, const CWalletTx& wtx, const CFeeRate& newFeerate, const int64_t maxTxSize, std::vector<bilingual_str>& errors)
64{
65 // check that fee rate is higher than mempool's minimum fee
66 // (no point in bumping fee if we know that the new tx won't be accepted to the mempool)
67 // This may occur if the user set fee_rate or paytxfee too low, if fallbackfee is too low, or, perhaps,
68 // in a rare situation where the mempool minimum fee increased significantly since the fee estimation just a
69 // moment earlier. In this case, we report an error to the user, who may adjust the fee.
70 CFeeRate minMempoolFeeRate = wallet.chain().mempoolMinFee();
71
72 if (newFeerate.GetFeePerK() < minMempoolFeeRate.GetFeePerK()) {
73 errors.push_back(strprintf(
74 Untranslated("New fee rate (%s) is lower than the minimum fee rate (%s) to get into the mempool -- "),
75 FormatMoney(newFeerate.GetFeePerK()),
76 FormatMoney(minMempoolFeeRate.GetFeePerK())));
78 }
79
80 CAmount new_total_fee = newFeerate.GetFee(maxTxSize);
81
82 CFeeRate incrementalRelayFee = std::max(wallet.chain().relayIncrementalFee(), CFeeRate(WALLET_INCREMENTAL_RELAY_FEE));
83
84 // Given old total fee and transaction size, calculate the old feeRate
85 isminefilter filter = wallet.GetLegacyScriptPubKeyMan() && wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
86 CAmount old_fee = CachedTxGetDebit(wallet, wtx, filter) - wtx.tx->GetValueOut();
87 const int64_t txSize = GetVirtualTransactionSize(*(wtx.tx));
88 CFeeRate nOldFeeRate(old_fee, txSize);
89 // Min total fee is old fee + relay fee
90 CAmount minTotalFee = nOldFeeRate.GetFee(maxTxSize) + incrementalRelayFee.GetFee(maxTxSize);
91
92 if (new_total_fee < minTotalFee) {
93 errors.push_back(strprintf(Untranslated("Insufficient total fee %s, must be at least %s (oldFee %s + incrementalFee %s)"),
94 FormatMoney(new_total_fee), FormatMoney(minTotalFee), FormatMoney(nOldFeeRate.GetFee(maxTxSize)), FormatMoney(incrementalRelayFee.GetFee(maxTxSize))));
96 }
97
98 CAmount requiredFee = GetRequiredFee(wallet, maxTxSize);
99 if (new_total_fee < requiredFee) {
100 errors.push_back(strprintf(Untranslated("Insufficient total fee (cannot be less than required fee %s)"),
101 FormatMoney(requiredFee)));
103 }
104
105 // Check that in all cases the new fee doesn't violate maxTxFee
106 const CAmount max_tx_fee = wallet.m_default_max_tx_fee;
107 if (new_total_fee > max_tx_fee) {
108 errors.push_back(strprintf(Untranslated("Specified or calculated fee %s is too high (cannot be higher than -maxtxfee %s)"),
109 FormatMoney(new_total_fee), FormatMoney(max_tx_fee)));
111 }
112
114}
115
116static CFeeRate EstimateFeeRate(const CWallet& wallet, const CWalletTx& wtx, const CAmount old_fee, const CCoinControl& coin_control)
117{
118 // Get the fee rate of the original transaction. This is calculated from
119 // the tx fee/vsize, so it may have been rounded down. Add 1 satoshi to the
120 // result.
121 int64_t txSize = GetVirtualTransactionSize(*(wtx.tx));
122 CFeeRate feerate(old_fee, txSize);
123 feerate += CFeeRate(1);
124
125 // The node has a configurable incremental relay fee. Increment the fee by
126 // the minimum of that and the wallet's conservative
127 // WALLET_INCREMENTAL_RELAY_FEE value to future proof against changes to
128 // network wide policy for incremental relay fee that our node may not be
129 // aware of. This ensures we're over the required relay fee rate
130 // (BIP 125 rule 4). The replacement tx will be at least as large as the
131 // original tx, so the total fee will be greater (BIP 125 rule 3)
132 CFeeRate node_incremental_relay_fee = wallet.chain().relayIncrementalFee();
133 CFeeRate wallet_incremental_relay_fee = CFeeRate(WALLET_INCREMENTAL_RELAY_FEE);
134 feerate += std::max(node_incremental_relay_fee, wallet_incremental_relay_fee);
135
136 // Fee rate must also be at least the wallet's GetMinimumFeeRate
137 CFeeRate min_feerate(GetMinimumFeeRate(wallet, coin_control, /* feeCalc */ nullptr));
138
139 // Set the required fee rate for the replacement transaction in coin control.
140 return std::max(feerate, min_feerate);
141}
142
143namespace feebumper {
144
146{
147 LOCK(wallet.cs_wallet);
148 const CWalletTx* wtx = wallet.GetWalletTx(txid);
149 if (wtx == nullptr) return false;
150
151 std::vector<bilingual_str> errors_dummy;
152 feebumper::Result res = PreconditionChecks(wallet, *wtx, errors_dummy);
153 return res == feebumper::Result::OK;
154}
155
156Result CreateRateBumpTransaction(CWallet& wallet, const uint256& txid, const CCoinControl& coin_control, std::vector<bilingual_str>& errors,
157 CAmount& old_fee, CAmount& new_fee, CMutableTransaction& mtx)
158{
159 // We are going to modify coin control later, copy to re-use
160 CCoinControl new_coin_control(coin_control);
161
162 LOCK(wallet.cs_wallet);
163 errors.clear();
164 auto it = wallet.mapWallet.find(txid);
165 if (it == wallet.mapWallet.end()) {
166 errors.push_back(Untranslated("Invalid or non-wallet transaction id"));
168 }
169 const CWalletTx& wtx = it->second;
170
171 Result result = PreconditionChecks(wallet, wtx, errors);
172 if (result != Result::OK) {
173 return result;
174 }
175
176 // Fill in recipients(and preserve a single change key if there is one)
177 std::vector<CRecipient> recipients;
178 for (const auto& output : wtx.tx->vout) {
179 if (!OutputIsChange(wallet, output)) {
180 CRecipient recipient = {output.scriptPubKey, output.nValue, false};
181 recipients.push_back(recipient);
182 } else {
183 CTxDestination change_dest;
184 ExtractDestination(output.scriptPubKey, change_dest);
185 new_coin_control.destChange = change_dest;
186 }
187 }
188
189 isminefilter filter = wallet.GetLegacyScriptPubKeyMan() && wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
190 old_fee = CachedTxGetDebit(wallet, wtx, filter) - wtx.tx->GetValueOut();
191
192 if (coin_control.m_feerate) {
193 // The user provided a feeRate argument.
194 // We calculate this here to avoid compiler warning on the cs_wallet lock
195 const int64_t maxTxSize{CalculateMaximumSignedTxSize(*wtx.tx, &wallet).vsize};
196 Result res = CheckFeeRate(wallet, wtx, *new_coin_control.m_feerate, maxTxSize, errors);
197 if (res != Result::OK) {
198 return res;
199 }
200 } else {
201 // The user did not provide a feeRate argument
202 new_coin_control.m_feerate = EstimateFeeRate(wallet, wtx, old_fee, new_coin_control);
203 }
204
205 // Fill in required inputs we are double-spending(all of them)
206 // N.B.: bip125 doesn't require all the inputs in the replaced transaction to be
207 // used in the replacement transaction, but it's very important for wallets to make
208 // sure that happens. If not, it would be possible to bump a transaction A twice to
209 // A2 and A3 where A2 and A3 don't conflict (or alternatively bump A to A2 and A2
210 // to A3 where A and A3 don't conflict). If both later get confirmed then the sender
211 // has accidentally double paid.
212 for (const auto& inputs : wtx.tx->vin) {
213 new_coin_control.Select(COutPoint(inputs.prevout));
214 }
215 new_coin_control.fAllowOtherInputs = true;
216
217 // We cannot source new unconfirmed inputs(bip125 rule 2)
218 new_coin_control.m_min_depth = 1;
219
220 CTransactionRef tx_new;
221 CAmount fee_ret;
222 int change_pos_in_out = -1; // No requested location for change
223 bilingual_str fail_reason;
224 FeeCalculation fee_calc_out;
225 if (!CreateTransaction(wallet, recipients, tx_new, fee_ret, change_pos_in_out, fail_reason, new_coin_control, fee_calc_out, false)) {
226 errors.push_back(Untranslated("Unable to create transaction.") + Untranslated(" ") + fail_reason);
228 }
229
230 // Write back new fee if successful
231 new_fee = fee_ret;
232
233 // Write back transaction
234 mtx = CMutableTransaction(*tx_new);
235 // Mark new tx not replaceable, if requested.
236 if (!coin_control.m_signal_bip125_rbf.value_or(wallet.m_signal_rbf)) {
237 for (auto& input : mtx.vin) {
238 if (input.nSequence < 0xfffffffe) input.nSequence = 0xfffffffe;
239 }
240 }
241
242 return Result::OK;
243}
244
246 LOCK(wallet.cs_wallet);
247 return wallet.SignTransaction(mtx);
248}
249
250Result CommitTransaction(CWallet& wallet, const uint256& txid, CMutableTransaction&& mtx, std::vector<bilingual_str>& errors, uint256& bumped_txid)
251{
252 LOCK(wallet.cs_wallet);
253 if (!errors.empty()) {
254 return Result::MISC_ERROR;
255 }
256 auto it = txid.IsNull() ? wallet.mapWallet.end() : wallet.mapWallet.find(txid);
257 if (it == wallet.mapWallet.end()) {
258 errors.push_back(Untranslated("Invalid or non-wallet transaction id"));
259 return Result::MISC_ERROR;
260 }
261 const CWalletTx& oldWtx = it->second;
262
263 // make sure the transaction still has no descendants and hasn't been mined in the meantime
264 Result result = PreconditionChecks(wallet, oldWtx, errors);
265 if (result != Result::OK) {
266 return result;
267 }
268
269 // commit/broadcast the tx
270 CTransactionRef tx = MakeTransactionRef(std::move(mtx));
271 mapValue_t mapValue = oldWtx.mapValue;
272 mapValue["replaces_txid"] = oldWtx.GetHash().ToString();
273
274 wallet.CommitTransaction(tx, std::move(mapValue), oldWtx.vOrderForm);
275
276 // mark the original tx as bumped
277 bumped_txid = tx->GetHash();
278 if (!wallet.MarkReplaced(oldWtx.GetHash(), bumped_txid)) {
279 // TODO: see if JSON-RPC has a standard way of returning a response
280 // along with an exception. It would be good to return information about
281 // wtxBumped to the caller even if marking the original transaction
282 // replaced does not succeed for some reason.
283 errors.push_back(Untranslated("Created new bumpfee transaction but could not mark the original transaction as replaced"));
284 }
285 return Result::OK;
286}
287
288} // namespace feebumper
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
Coin Control Features.
Definition: coincontrol.h:29
std::optional< bool > m_signal_bip125_rbf
Override the wallet's m_signal_rbf if set.
Definition: coincontrol.h:50
void Select(const COutPoint &output)
Definition: coincontrol.h:91
int m_min_depth
Minimum chain depth value for coin availability.
Definition: coincontrol.h:58
std::optional< CFeeRate > m_feerate
Override the wallet's m_pay_tx_fee if set.
Definition: coincontrol.h:46
CTxDestination destChange
Custom change destination, if not set an address is generated.
Definition: coincontrol.h:32
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:40
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:30
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:23
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:57
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:27
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:229
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:47
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: transaction.h:80
CTransactionRef tx
Definition: transaction.h:138
const uint256 & GetHash() const
Definition: transaction.h:267
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: transaction.h:81
std::string ToString() const
Definition: uint256.cpp:64
bool IsNull() const
Definition: uint256.h:31
void push_back(const T &value)
Definition: prevector.h:437
256-bit opaque blob.
Definition: uint256.h:124
static CFeeRate EstimateFeeRate(const CWallet &wallet, const CWalletTx &wtx, const CAmount old_fee, const CCoinControl &coin_control)
Definition: feebumper.cpp:116
static feebumper::Result CheckFeeRate(const CWallet &wallet, const CWalletTx &wtx, const CFeeRate &newFeerate, const int64_t maxTxSize, std::vector< bilingual_str > &errors)
Check if the user provided a valid feeRate.
Definition: feebumper.cpp:63
static feebumper::Result PreconditionChecks(const CWallet &wallet, const CWalletTx &wtx, std::vector< bilingual_str > &errors) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
Check whether transaction has descendant in wallet or mempool, or has been mined, or conflicts with a...
Definition: feebumper.cpp:21
uint8_t isminefilter
Definition: wallet.h:36
@ ISMINE_SPENDABLE
Definition: ismine.h:42
@ ISMINE_WATCH_ONLY
Definition: ismine.h:41
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:15
Result CommitTransaction(CWallet &wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:250
Result CreateRateBumpTransaction(CWallet &wallet, const uint256 &txid, const CCoinControl &coin_control, std::vector< bilingual_str > &errors, CAmount &old_fee, CAmount &new_fee, CMutableTransaction &mtx)
Create bumpfee transaction based on feerate estimates.
Definition: feebumper.cpp:156
bool TransactionCanBeBumped(const CWallet &wallet, const uint256 &txid)
Return whether transaction can be bumped.
Definition: feebumper.cpp:145
bool SignTransaction(CWallet &wallet, CMutableTransaction &mtx)
Sign the new transaction,.
Definition: feebumper.cpp:245
CFeeRate incrementalRelayFee
Definition: settings.cpp:12
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:285
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
bool AllInputsMine(const CWallet &wallet, const CTransaction &tx, const isminefilter &filter)
Returns whether all of the inputs match the filter.
Definition: receive.cpp:24
bool OutputIsChange(const CWallet &wallet, const CTxOut &txout)
Definition: receive.cpp:87
CAmount CachedTxGetDebit(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
filter decides which addresses will count towards the debit
Definition: receive.cpp:140
TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector< CTxOut > &txouts, const CCoinControl *coin_control)
Calculate the size of the transaction assuming all signatures are max size Use DummySignatureCreator,...
Definition: spend.cpp:53
bool CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, CAmount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, FeeCalculation &fee_calc_out, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:941
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:213
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
A mutable version of CTransaction.
Definition: transaction.h:345
std::vector< CTxIn > vin
Definition: transaction.h:346
CScript scriptPubKey
Definition: wallet.h:219
int64_t vsize
Definition: spend.h:73
Bilingual messages:
Definition: translation.h:16
#define LOCK(cs)
Definition: sync.h:226
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:46
bool SignalsOptInRBF(const CTransaction &tx)
Check whether the sequence numbers on this transaction are signaling opt-in to replace-by-fee,...
Definition: rbf.cpp:9
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee rate considering user set parameters and the required fee.
Definition: fees.cpp:28
CAmount GetRequiredFee(const CWallet &wallet, unsigned int nTxBytes)
Return the minimum required absolute fee for this size based on the required fee rate.
Definition: fees.cpp:12
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:20
static const CAmount WALLET_INCREMENTAL_RELAY_FEE
minimum recommended increment for BIP 125 replacement txs
Definition: wallet.h:87
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:50