1 // Copyright (c) 2017 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.
5 #include "consensus/validation.h"
6 #include "wallet/coincontrol.h"
7 #include "wallet/feebumper.h"
8 #include "wallet/fees.h"
9 #include "wallet/wallet.h"
10 #include "policy/fees.h"
11 #include "policy/policy.h"
12 #include "policy/rbf.h"
13 #include "validation.h" //for mempool access
14 #include "txmempool.h"
15 #include "utilmoneystr.h"
19 // Calculate the size of the transaction assuming all signatures are max size
20 // Use DummySignatureCreator, which inserts 72 byte signatures everywhere.
21 // TODO: re-use this in CWallet::CreateTransaction (right now
22 // CreateTransaction uses the constructed dummy-signed tx to do a priority
23 // calculation, but we should be able to refactor after priority is removed).
24 // NOTE: this requires that all inputs must be in mapWallet (eg the tx should
26 int64_t CalculateMaximumSignedTxSize(const CTransaction
&tx
, const CWallet
*pWallet
)
28 CMutableTransaction
txNew(tx
);
29 std::vector
<CInputCoin
> vCoins
;
30 // Look up the inputs. We should have already checked that this transaction
31 // IsAllFromMe(ISMINE_SPENDABLE), so every input should already be in our
32 // wallet, with a valid index into the vout array.
33 for (auto& input
: tx
.vin
) {
34 const auto mi
= pWallet
->mapWallet
.find(input
.prevout
.hash
);
35 assert(mi
!= pWallet
->mapWallet
.end() && input
.prevout
.n
< mi
->second
.tx
->vout
.size());
36 vCoins
.emplace_back(CInputCoin(&(mi
->second
), input
.prevout
.n
));
38 if (!pWallet
->DummySignTx(txNew
, vCoins
)) {
39 // This should never happen, because IsAllFromMe(ISMINE_SPENDABLE)
40 // implies that we can sign for every input.
43 return GetVirtualTransactionSize(txNew
);
46 bool CFeeBumper::preconditionChecks(const CWallet
*pWallet
, const CWalletTx
& wtx
) {
47 if (pWallet
->HasWalletSpend(wtx
.GetHash())) {
48 vErrors
.push_back("Transaction has descendants in the wallet");
49 currentResult
= BumpFeeResult::INVALID_PARAMETER
;
55 auto it_mp
= mempool
.mapTx
.find(wtx
.GetHash());
56 if (it_mp
!= mempool
.mapTx
.end() && it_mp
->GetCountWithDescendants() > 1) {
57 vErrors
.push_back("Transaction has descendants in the mempool");
58 currentResult
= BumpFeeResult::INVALID_PARAMETER
;
63 if (wtx
.GetDepthInMainChain() != 0) {
64 vErrors
.push_back("Transaction has been mined, or is conflicted with a mined transaction");
65 currentResult
= BumpFeeResult::WALLET_ERROR
;
71 CFeeBumper::CFeeBumper(const CWallet
*pWallet
, const uint256 txidIn
, const CCoinControl
& coin_control
, CAmount totalFee
)
73 txid(std::move(txidIn
)),
79 AssertLockHeld(pWallet
->cs_wallet
);
80 auto it
= pWallet
->mapWallet
.find(txid
);
81 if (it
== pWallet
->mapWallet
.end()) {
82 vErrors
.push_back("Invalid or non-wallet transaction id");
83 currentResult
= BumpFeeResult::INVALID_ADDRESS_OR_KEY
;
86 const CWalletTx
& wtx
= it
->second
;
88 if (!preconditionChecks(pWallet
, wtx
)) {
92 if (!SignalsOptInRBF(wtx
)) {
93 vErrors
.push_back("Transaction is not BIP 125 replaceable");
94 currentResult
= BumpFeeResult::WALLET_ERROR
;
98 if (wtx
.mapValue
.count("replaced_by_txid")) {
99 vErrors
.push_back(strprintf("Cannot bump transaction %s which was already bumped by transaction %s", txid
.ToString(), wtx
.mapValue
.at("replaced_by_txid")));
100 currentResult
= BumpFeeResult::WALLET_ERROR
;
104 // check that original tx consists entirely of our inputs
105 // 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)
106 if (!pWallet
->IsAllFromMe(wtx
, ISMINE_SPENDABLE
)) {
107 vErrors
.push_back("Transaction contains inputs that don't belong to this wallet");
108 currentResult
= BumpFeeResult::WALLET_ERROR
;
112 // figure out which output was change
113 // if there was no change output or multiple change outputs, fail
115 for (size_t i
= 0; i
< wtx
.tx
->vout
.size(); ++i
) {
116 if (pWallet
->IsChange(wtx
.tx
->vout
[i
])) {
118 vErrors
.push_back("Transaction has multiple change outputs");
119 currentResult
= BumpFeeResult::WALLET_ERROR
;
126 vErrors
.push_back("Transaction does not have a change output");
127 currentResult
= BumpFeeResult::WALLET_ERROR
;
131 // Calculate the expected size of the new transaction.
132 int64_t txSize
= GetVirtualTransactionSize(*(wtx
.tx
));
133 const int64_t maxNewTxSize
= CalculateMaximumSignedTxSize(*wtx
.tx
, pWallet
);
134 if (maxNewTxSize
< 0) {
135 vErrors
.push_back("Transaction contains inputs that cannot be signed");
136 currentResult
= BumpFeeResult::INVALID_ADDRESS_OR_KEY
;
140 // calculate the old fee and fee-rate
141 nOldFee
= wtx
.GetDebit(ISMINE_SPENDABLE
) - wtx
.tx
->GetValueOut();
142 CFeeRate
nOldFeeRate(nOldFee
, txSize
);
143 CFeeRate nNewFeeRate
;
144 // The wallet uses a conservative WALLET_INCREMENTAL_RELAY_FEE value to
145 // future proof against changes to network wide policy for incremental relay
146 // fee that our node may not be aware of.
147 CFeeRate walletIncrementalRelayFee
= CFeeRate(WALLET_INCREMENTAL_RELAY_FEE
);
148 if (::incrementalRelayFee
> walletIncrementalRelayFee
) {
149 walletIncrementalRelayFee
= ::incrementalRelayFee
;
153 CAmount minTotalFee
= nOldFeeRate
.GetFee(maxNewTxSize
) + ::incrementalRelayFee
.GetFee(maxNewTxSize
);
154 if (totalFee
< minTotalFee
) {
155 vErrors
.push_back(strprintf("Insufficient totalFee, must be at least %s (oldFee %s + incrementalFee %s)",
156 FormatMoney(minTotalFee
), FormatMoney(nOldFeeRate
.GetFee(maxNewTxSize
)), FormatMoney(::incrementalRelayFee
.GetFee(maxNewTxSize
))));
157 currentResult
= BumpFeeResult::INVALID_PARAMETER
;
160 CAmount requiredFee
= GetRequiredFee(maxNewTxSize
);
161 if (totalFee
< requiredFee
) {
162 vErrors
.push_back(strprintf("Insufficient totalFee (cannot be less than required fee %s)",
163 FormatMoney(requiredFee
)));
164 currentResult
= BumpFeeResult::INVALID_PARAMETER
;
168 nNewFeeRate
= CFeeRate(totalFee
, maxNewTxSize
);
170 nNewFee
= GetMinimumFee(maxNewTxSize
, coin_control
, mempool
, ::feeEstimator
, nullptr /* FeeCalculation */);
171 nNewFeeRate
= CFeeRate(nNewFee
, maxNewTxSize
);
173 // New fee rate must be at least old rate + minimum incremental relay rate
174 // walletIncrementalRelayFee.GetFeePerK() should be exact, because it's initialized
175 // in that unit (fee per kb).
176 // However, nOldFeeRate is a calculated value from the tx fee/size, so
177 // add 1 satoshi to the result, because it may have been rounded down.
178 if (nNewFeeRate
.GetFeePerK() < nOldFeeRate
.GetFeePerK() + 1 + walletIncrementalRelayFee
.GetFeePerK()) {
179 nNewFeeRate
= CFeeRate(nOldFeeRate
.GetFeePerK() + 1 + walletIncrementalRelayFee
.GetFeePerK());
180 nNewFee
= nNewFeeRate
.GetFee(maxNewTxSize
);
184 // Check that in all cases the new fee doesn't violate maxTxFee
185 if (nNewFee
> maxTxFee
) {
186 vErrors
.push_back(strprintf("Specified or calculated fee %s is too high (cannot be higher than maxTxFee %s)",
187 FormatMoney(nNewFee
), FormatMoney(maxTxFee
)));
188 currentResult
= BumpFeeResult::WALLET_ERROR
;
192 // check that fee rate is higher than mempool's minimum fee
193 // (no point in bumping fee if we know that the new tx won't be accepted to the mempool)
194 // This may occur if the user set TotalFee or paytxfee too low, if fallbackfee is too low, or, perhaps,
195 // in a rare situation where the mempool minimum fee increased significantly since the fee estimation just a
196 // moment earlier. In this case, we report an error to the user, who may use totalFee to make an adjustment.
197 CFeeRate minMempoolFeeRate
= mempool
.GetMinFee(gArgs
.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000);
198 if (nNewFeeRate
.GetFeePerK() < minMempoolFeeRate
.GetFeePerK()) {
199 vErrors
.push_back(strprintf("New fee rate (%s) is less than the minimum fee rate (%s) to get into the mempool. totalFee value should to be at least %s or settxfee value should be at least %s to add transaction.", FormatMoney(nNewFeeRate
.GetFeePerK()), FormatMoney(minMempoolFeeRate
.GetFeePerK()), FormatMoney(minMempoolFeeRate
.GetFee(maxNewTxSize
)), FormatMoney(minMempoolFeeRate
.GetFeePerK())));
200 currentResult
= BumpFeeResult::WALLET_ERROR
;
204 // Now modify the output to increase the fee.
205 // If the output is not large enough to pay the fee, fail.
206 CAmount nDelta
= nNewFee
- nOldFee
;
209 CTxOut
* poutput
= &(mtx
.vout
[nOutput
]);
210 if (poutput
->nValue
< nDelta
) {
211 vErrors
.push_back("Change output is too small to bump the fee");
212 currentResult
= BumpFeeResult::WALLET_ERROR
;
216 // If the output would become dust, discard it (converting the dust to fee)
217 poutput
->nValue
-= nDelta
;
218 if (poutput
->nValue
<= GetDustThreshold(*poutput
, ::dustRelayFee
)) {
219 LogPrint(BCLog::RPC
, "Bumping fee and discarding dust output\n");
220 nNewFee
+= poutput
->nValue
;
221 mtx
.vout
.erase(mtx
.vout
.begin() + nOutput
);
224 // Mark new tx not replaceable, if requested.
225 if (!coin_control
.signalRbf
) {
226 for (auto& input
: mtx
.vin
) {
227 if (input
.nSequence
< 0xfffffffe) input
.nSequence
= 0xfffffffe;
231 currentResult
= BumpFeeResult::OK
;
234 bool CFeeBumper::signTransaction(CWallet
*pWallet
)
236 return pWallet
->SignTransaction(mtx
);
239 bool CFeeBumper::commit(CWallet
*pWallet
)
241 AssertLockHeld(pWallet
->cs_wallet
);
242 if (!vErrors
.empty() || currentResult
!= BumpFeeResult::OK
) {
245 auto it
= txid
.IsNull() ? pWallet
->mapWallet
.end() : pWallet
->mapWallet
.find(txid
);
246 if (it
== pWallet
->mapWallet
.end()) {
247 vErrors
.push_back("Invalid or non-wallet transaction id");
248 currentResult
= BumpFeeResult::MISC_ERROR
;
251 CWalletTx
& oldWtx
= it
->second
;
253 // make sure the transaction still has no descendants and hasn't been mined in the meantime
254 if (!preconditionChecks(pWallet
, oldWtx
)) {
258 CWalletTx
wtxBumped(pWallet
, MakeTransactionRef(std::move(mtx
)));
259 // commit/broadcast the tx
260 CReserveKey
reservekey(pWallet
);
261 wtxBumped
.mapValue
= oldWtx
.mapValue
;
262 wtxBumped
.mapValue
["replaces_txid"] = oldWtx
.GetHash().ToString();
263 wtxBumped
.vOrderForm
= oldWtx
.vOrderForm
;
264 wtxBumped
.strFromAccount
= oldWtx
.strFromAccount
;
265 wtxBumped
.fTimeReceivedIsTxTime
= true;
266 wtxBumped
.fFromMe
= true;
267 CValidationState state
;
268 if (!pWallet
->CommitTransaction(wtxBumped
, reservekey
, g_connman
.get(), state
)) {
269 // NOTE: CommitTransaction never returns false, so this should never happen.
270 vErrors
.push_back(strprintf("Error: The transaction was rejected! Reason given: %s", state
.GetRejectReason()));
274 bumpedTxid
= wtxBumped
.GetHash();
275 if (state
.IsInvalid()) {
276 // This can happen if the mempool rejected the transaction. Report
277 // what happened in the "errors" response.
278 vErrors
.push_back(strprintf("Error: The transaction was rejected: %s", FormatStateMessage(state
)));
281 // mark the original tx as bumped
282 if (!pWallet
->MarkReplaced(oldWtx
.GetHash(), wtxBumped
.GetHash())) {
283 // TODO: see if JSON-RPC has a standard way of returning a response
284 // along with an exception. It would be good to return information about
285 // wtxBumped to the caller even if marking the original transaction
286 // replaced does not succeed for some reason.
287 vErrors
.push_back("Error: Created new bumpfee transaction but could not mark the original transaction as replaced.");