LCOV - code coverage report
Current view: top level - src/wallet - feebumper.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 141 166 84.9 %
Date: 2022-04-21 14:51:19 Functions: 7 7 100.0 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 50 60 83.3 %

           Branch data     Line data    Source code
#       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 {
#      20                 :            : //! Check whether transaction has descendant in wallet or mempool, or has been
#      21                 :            : //! mined, or conflicts with a mined transaction. Return a feebumper::Result.
#      22                 :            : static feebumper::Result PreconditionChecks(const CWallet& wallet, const CWalletTx& wtx, std::vector<bilingual_str>& errors) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
#      23                 :        327 : {
#      24         [ +  + ]:        327 :     if (wallet.HasWalletSpend(wtx.GetHash())) {
#      25                 :          2 :         errors.push_back(Untranslated("Transaction has descendants in the wallet"));
#      26                 :          2 :         return feebumper::Result::INVALID_PARAMETER;
#      27                 :          2 :     }
#      28                 :            : 
#      29                 :        325 :     {
#      30         [ +  + ]:        325 :         if (wallet.chain().hasDescendantsInMempool(wtx.GetHash())) {
#      31                 :          2 :             errors.push_back(Untranslated("Transaction has descendants in the mempool"));
#      32                 :          2 :             return feebumper::Result::INVALID_PARAMETER;
#      33                 :          2 :         }
#      34                 :        325 :     }
#      35                 :            : 
#      36         [ -  + ]:        323 :     if (wallet.GetTxDepthInMainChain(wtx) != 0) {
#      37                 :          0 :         errors.push_back(Untranslated("Transaction has been mined, or is conflicted with a mined transaction"));
#      38                 :          0 :         return feebumper::Result::WALLET_ERROR;
#      39                 :          0 :     }
#      40                 :            : 
#      41         [ +  + ]:        323 :     if (!SignalsOptInRBF(*wtx.tx)) {
#      42                 :          6 :         errors.push_back(Untranslated("Transaction is not BIP 125 replaceable"));
#      43                 :          6 :         return feebumper::Result::WALLET_ERROR;
#      44                 :          6 :     }
#      45                 :            : 
#      46         [ +  + ]:        317 :     if (wtx.mapValue.count("replaced_by_txid")) {
#      47                 :          4 :         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                 :          4 :         return feebumper::Result::WALLET_ERROR;
#      49                 :          4 :     }
#      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 [ +  + ][ +  + ]:        313 :     isminefilter filter = wallet.GetLegacyScriptPubKeyMan() && wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
#      54         [ +  + ]:        313 :     if (!AllInputsMine(wallet, *wtx.tx, filter)) {
#      55                 :          2 :         errors.push_back(Untranslated("Transaction contains inputs that don't belong to this wallet"));
#      56                 :          2 :         return feebumper::Result::WALLET_ERROR;
#      57                 :          2 :     }
#      58                 :            : 
#      59                 :            : 
#      60                 :        311 :     return feebumper::Result::OK;
#      61                 :        313 : }
#      62                 :            : 
#      63                 :            : //! Check if the user provided a valid feeRate
#      64                 :            : static feebumper::Result CheckFeeRate(const CWallet& wallet, const CWalletTx& wtx, const CFeeRate& newFeerate, const int64_t maxTxSize, std::vector<bilingual_str>& errors)
#      65                 :         32 : {
#      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                 :         32 :     CFeeRate minMempoolFeeRate = wallet.chain().mempoolMinFee();
#      72                 :            : 
#      73         [ -  + ]:         32 :     if (newFeerate.GetFeePerK() < minMempoolFeeRate.GetFeePerK()) {
#      74                 :          0 :         errors.push_back(strprintf(
#      75                 :          0 :             Untranslated("New fee rate (%s) is lower than the minimum fee rate (%s) to get into the mempool -- "),
#      76                 :          0 :             FormatMoney(newFeerate.GetFeePerK()),
#      77                 :          0 :             FormatMoney(minMempoolFeeRate.GetFeePerK())));
#      78                 :          0 :         return feebumper::Result::WALLET_ERROR;
#      79                 :          0 :     }
#      80                 :            : 
#      81                 :         32 :     CAmount new_total_fee = newFeerate.GetFee(maxTxSize);
#      82                 :            : 
#      83                 :         32 :     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 [ +  + ][ +  + ]:         32 :     isminefilter filter = wallet.GetLegacyScriptPubKeyMan() && wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
#      87                 :         32 :     CAmount old_fee = CachedTxGetDebit(wallet, wtx, filter) - wtx.tx->GetValueOut();
#      88                 :         32 :     const int64_t txSize = GetVirtualTransactionSize(*(wtx.tx));
#      89                 :         32 :     CFeeRate nOldFeeRate(old_fee, txSize);
#      90                 :            :     // Min total fee is old fee + relay fee
#      91                 :         32 :     CAmount minTotalFee = nOldFeeRate.GetFee(maxTxSize) + incrementalRelayFee.GetFee(maxTxSize);
#      92                 :            : 
#      93         [ +  + ]:         32 :     if (new_total_fee < minTotalFee) {
#      94                 :         14 :         errors.push_back(strprintf(Untranslated("Insufficient total fee %s, must be at least %s (oldFee %s + incrementalFee %s)"),
#      95                 :         14 :             FormatMoney(new_total_fee), FormatMoney(minTotalFee), FormatMoney(nOldFeeRate.GetFee(maxTxSize)), FormatMoney(incrementalRelayFee.GetFee(maxTxSize))));
#      96                 :         14 :         return feebumper::Result::INVALID_PARAMETER;
#      97                 :         14 :     }
#      98                 :            : 
#      99                 :         18 :     CAmount requiredFee = GetRequiredFee(wallet, maxTxSize);
#     100         [ -  + ]:         18 :     if (new_total_fee < requiredFee) {
#     101                 :          0 :         errors.push_back(strprintf(Untranslated("Insufficient total fee (cannot be less than required fee %s)"),
#     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                 :         18 :     const CAmount max_tx_fee = wallet.m_default_max_tx_fee;
#     108         [ +  + ]:         18 :     if (new_total_fee > max_tx_fee) {
#     109                 :          2 :         errors.push_back(strprintf(Untranslated("Specified or calculated fee %s is too high (cannot be higher than -maxtxfee %s)"),
#     110                 :          2 :             FormatMoney(new_total_fee), FormatMoney(max_tx_fee)));
#     111                 :          2 :         return feebumper::Result::WALLET_ERROR;
#     112                 :          2 :     }
#     113                 :            : 
#     114                 :         16 :     return feebumper::Result::OK;
#     115                 :         18 : }
#     116                 :            : 
#     117                 :            : static CFeeRate EstimateFeeRate(const CWallet& wallet, const CWalletTx& wtx, const CAmount old_fee, const CCoinControl& coin_control)
#     118                 :        136 : {
#     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                 :        136 :     int64_t txSize = GetVirtualTransactionSize(*(wtx.tx));
#     123                 :        136 :     CFeeRate feerate(old_fee, txSize);
#     124                 :        136 :     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                 :        136 :     CFeeRate node_incremental_relay_fee = wallet.chain().relayIncrementalFee();
#     134                 :        136 :     CFeeRate wallet_incremental_relay_fee = CFeeRate(WALLET_INCREMENTAL_RELAY_FEE);
#     135                 :        136 :     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                 :        136 :     CFeeRate min_feerate(GetMinimumFeeRate(wallet, coin_control, /*feeCalc=*/nullptr));
#     139                 :            : 
#     140                 :            :     // Set the required fee rate for the replacement transaction in coin control.
#     141                 :        136 :     return std::max(feerate, min_feerate);
#     142                 :        136 : }
#     143                 :            : 
#     144                 :            : namespace feebumper {
#     145                 :            : 
#     146                 :            : bool TransactionCanBeBumped(const CWallet& wallet, const uint256& txid)
#     147                 :          4 : {
#     148                 :          4 :     LOCK(wallet.cs_wallet);
#     149                 :          4 :     const CWalletTx* wtx = wallet.GetWalletTx(txid);
#     150         [ -  + ]:          4 :     if (wtx == nullptr) return false;
#     151                 :            : 
#     152                 :          4 :     std::vector<bilingual_str> errors_dummy;
#     153                 :          4 :     feebumper::Result res = PreconditionChecks(wallet, *wtx, errors_dummy);
#     154                 :          4 :     return res == feebumper::Result::OK;
#     155                 :          4 : }
#     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                 :        182 : {
#     160                 :            :     // We are going to modify coin control later, copy to re-use
#     161                 :        182 :     CCoinControl new_coin_control(coin_control);
#     162                 :            : 
#     163                 :        182 :     LOCK(wallet.cs_wallet);
#     164                 :        182 :     errors.clear();
#     165                 :        182 :     auto it = wallet.mapWallet.find(txid);
#     166         [ -  + ]:        182 :     if (it == wallet.mapWallet.end()) {
#     167                 :          0 :         errors.push_back(Untranslated("Invalid or non-wallet transaction id"));
#     168                 :          0 :         return Result::INVALID_ADDRESS_OR_KEY;
#     169                 :          0 :     }
#     170                 :        182 :     const CWalletTx& wtx = it->second;
#     171                 :            : 
#     172                 :        182 :     Result result = PreconditionChecks(wallet, wtx, errors);
#     173         [ +  + ]:        182 :     if (result != Result::OK) {
#     174                 :         14 :         return result;
#     175                 :         14 :     }
#     176                 :            : 
#     177                 :            :     // Fill in recipients(and preserve a single change key if there is one)
#     178                 :        168 :     std::vector<CRecipient> recipients;
#     179         [ +  + ]:        332 :     for (const auto& output : wtx.tx->vout) {
#     180         [ +  + ]:        332 :         if (!OutputIsChange(wallet, output)) {
#     181                 :        168 :             CRecipient recipient = {output.scriptPubKey, output.nValue, false};
#     182                 :        168 :             recipients.push_back(recipient);
#     183                 :        168 :         } else {
#     184                 :        164 :             CTxDestination change_dest;
#     185                 :        164 :             ExtractDestination(output.scriptPubKey, change_dest);
#     186                 :        164 :             new_coin_control.destChange = change_dest;
#     187                 :        164 :         }
#     188                 :        332 :     }
#     189                 :            : 
#     190 [ +  + ][ +  + ]:        168 :     isminefilter filter = wallet.GetLegacyScriptPubKeyMan() && wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) ? ISMINE_WATCH_ONLY : ISMINE_SPENDABLE;
#     191                 :        168 :     old_fee = CachedTxGetDebit(wallet, wtx, filter) - wtx.tx->GetValueOut();
#     192                 :            : 
#     193         [ +  + ]:        168 :     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                 :         32 :         const int64_t maxTxSize{CalculateMaximumSignedTxSize(*wtx.tx, &wallet).vsize};
#     197                 :         32 :         Result res = CheckFeeRate(wallet, wtx, *new_coin_control.m_feerate, maxTxSize, errors);
#     198         [ +  + ]:         32 :         if (res != Result::OK) {
#     199                 :         16 :             return res;
#     200                 :         16 :         }
#     201                 :        136 :     } else {
#     202                 :            :         // The user did not provide a feeRate argument
#     203                 :        136 :         new_coin_control.m_feerate = EstimateFeeRate(wallet, wtx, old_fee, new_coin_control);
#     204                 :        136 :     }
#     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         [ +  + ]:        440 :     for (const auto& inputs : wtx.tx->vin) {
#     214                 :        440 :         new_coin_control.Select(COutPoint(inputs.prevout));
#     215                 :        440 :     }
#     216                 :        152 :     new_coin_control.fAllowOtherInputs = true;
#     217                 :            : 
#     218                 :            :     // We cannot source new unconfirmed inputs(bip125 rule 2)
#     219                 :        152 :     new_coin_control.m_min_depth = 1;
#     220                 :            : 
#     221                 :        152 :     CTransactionRef tx_new;
#     222                 :        152 :     CAmount fee_ret;
#     223                 :        152 :     int change_pos_in_out = -1; // No requested location for change
#     224                 :        152 :     bilingual_str fail_reason;
#     225                 :        152 :     FeeCalculation fee_calc_out;
#     226         [ +  + ]:        152 :     if (!CreateTransaction(wallet, recipients, tx_new, fee_ret, change_pos_in_out, fail_reason, new_coin_control, fee_calc_out, false)) {
#     227                 :          4 :         errors.push_back(Untranslated("Unable to create transaction.") + Untranslated(" ") + fail_reason);
#     228                 :          4 :         return Result::WALLET_ERROR;
#     229                 :          4 :     }
#     230                 :            : 
#     231                 :            :     // Write back new fee if successful
#     232                 :        148 :     new_fee = fee_ret;
#     233                 :            : 
#     234                 :            :     // Write back transaction
#     235                 :        148 :     mtx = CMutableTransaction(*tx_new);
#     236                 :            : 
#     237                 :        148 :     return Result::OK;
#     238                 :        152 : }
#     239                 :            : 
#     240                 :        141 : bool SignTransaction(CWallet& wallet, CMutableTransaction& mtx) {
#     241                 :        141 :     LOCK(wallet.cs_wallet);
#     242                 :        141 :     return wallet.SignTransaction(mtx);
#     243                 :        141 : }
#     244                 :            : 
#     245                 :            : Result CommitTransaction(CWallet& wallet, const uint256& txid, CMutableTransaction&& mtx, std::vector<bilingual_str>& errors, uint256& bumped_txid)
#     246                 :        141 : {
#     247                 :        141 :     LOCK(wallet.cs_wallet);
#     248         [ -  + ]:        141 :     if (!errors.empty()) {
#     249                 :          0 :         return Result::MISC_ERROR;
#     250                 :          0 :     }
#     251         [ -  + ]:        141 :     auto it = txid.IsNull() ? wallet.mapWallet.end() : wallet.mapWallet.find(txid);
#     252         [ -  + ]:        141 :     if (it == wallet.mapWallet.end()) {
#     253                 :          0 :         errors.push_back(Untranslated("Invalid or non-wallet transaction id"));
#     254                 :          0 :         return Result::MISC_ERROR;
#     255                 :          0 :     }
#     256                 :        141 :     const CWalletTx& oldWtx = it->second;
#     257                 :            : 
#     258                 :            :     // make sure the transaction still has no descendants and hasn't been mined in the meantime
#     259                 :        141 :     Result result = PreconditionChecks(wallet, oldWtx, errors);
#     260         [ -  + ]:        141 :     if (result != Result::OK) {
#     261                 :          0 :         return result;
#     262                 :          0 :     }
#     263                 :            : 
#     264                 :            :     // commit/broadcast the tx
#     265                 :        141 :     CTransactionRef tx = MakeTransactionRef(std::move(mtx));
#     266                 :        141 :     mapValue_t mapValue = oldWtx.mapValue;
#     267                 :        141 :     mapValue["replaces_txid"] = oldWtx.GetHash().ToString();
#     268                 :            : 
#     269                 :        141 :     wallet.CommitTransaction(tx, std::move(mapValue), oldWtx.vOrderForm);
#     270                 :            : 
#     271                 :            :     // mark the original tx as bumped
#     272                 :        141 :     bumped_txid = tx->GetHash();
#     273         [ -  + ]:        141 :     if (!wallet.MarkReplaced(oldWtx.GetHash(), bumped_txid)) {
#     274                 :          0 :         errors.push_back(Untranslated("Created new bumpfee transaction but could not mark the original transaction as replaced"));
#     275                 :          0 :     }
#     276                 :        141 :     return Result::OK;
#     277                 :        141 : }
#     278                 :            : 
#     279                 :            : } // namespace feebumper
#     280                 :            : } // namespace wallet

Generated by: LCOV version 0-eol-96201-ge66f56f4af6a