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