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 static int64_t CalculateMaximumSignedTxSize(const CTransaction
&tx
, const CWallet
*wallet
)
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
= wallet
->mapWallet
.find(input
.prevout
.hash
);
35 assert(mi
!= wallet
->mapWallet
.end() && input
.prevout
.n
< mi
->second
.tx
->vout
.size());
36 vCoins
.emplace_back(CInputCoin(&(mi
->second
), input
.prevout
.n
));
38 if (!wallet
->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 //! Check whether transaction has descendant in wallet or mempool, or has been
47 //! mined, or conflicts with a mined transaction. Return a feebumper::Result.
48 static feebumper::Result
PreconditionChecks(const CWallet
* wallet
, const CWalletTx
& wtx
, std::vector
<std::string
>& errors
)
50 if (wallet
->HasWalletSpend(wtx
.GetHash())) {
51 errors
.push_back("Transaction has descendants in the wallet");
52 return feebumper::Result::INVALID_PARAMETER
;
57 auto it_mp
= mempool
.mapTx
.find(wtx
.GetHash());
58 if (it_mp
!= mempool
.mapTx
.end() && it_mp
->GetCountWithDescendants() > 1) {
59 errors
.push_back("Transaction has descendants in the mempool");
60 return feebumper::Result::INVALID_PARAMETER
;
64 if (wtx
.GetDepthInMainChain() != 0) {
65 errors
.push_back("Transaction has been mined, or is conflicted with a mined transaction");
66 return feebumper::Result::WALLET_ERROR
;
68 return feebumper::Result::OK
;
73 bool TransactionCanBeBumped(CWallet
* wallet
, const uint256
& txid
)
75 LOCK2(cs_main
, wallet
->cs_wallet
);
76 const CWalletTx
* wtx
= wallet
->GetWalletTx(txid
);
77 return wtx
&& SignalsOptInRBF(*wtx
->tx
) && !wtx
->mapValue
.count("replaced_by_txid");
80 Result
CreateTransaction(const CWallet
* wallet
, const uint256
& txid
, const CCoinControl
& coin_control
, CAmount total_fee
, std::vector
<std::string
>& errors
,
81 CAmount
& old_fee
, CAmount
& new_fee
, CMutableTransaction
& mtx
)
83 LOCK2(cs_main
, wallet
->cs_wallet
);
85 auto it
= wallet
->mapWallet
.find(txid
);
86 if (it
== wallet
->mapWallet
.end()) {
87 errors
.push_back("Invalid or non-wallet transaction id");
88 return Result::INVALID_ADDRESS_OR_KEY
;
90 const CWalletTx
& wtx
= it
->second
;
92 Result result
= PreconditionChecks(wallet
, wtx
, errors
);
93 if (result
!= Result::OK
) {
97 if (!SignalsOptInRBF(*wtx
.tx
)) {
98 errors
.push_back("Transaction is not BIP 125 replaceable");
99 return Result::WALLET_ERROR
;
102 if (wtx
.mapValue
.count("replaced_by_txid")) {
103 errors
.push_back(strprintf("Cannot bump transaction %s which was already bumped by transaction %s", txid
.ToString(), wtx
.mapValue
.at("replaced_by_txid")));
104 return Result::WALLET_ERROR
;
107 // check that original tx consists entirely of our inputs
108 // 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)
109 if (!wallet
->IsAllFromMe(*wtx
.tx
, ISMINE_SPENDABLE
)) {
110 errors
.push_back("Transaction contains inputs that don't belong to this wallet");
111 return Result::WALLET_ERROR
;
114 // figure out which output was change
115 // if there was no change output or multiple change outputs, fail
117 for (size_t i
= 0; i
< wtx
.tx
->vout
.size(); ++i
) {
118 if (wallet
->IsChange(wtx
.tx
->vout
[i
])) {
120 errors
.push_back("Transaction has multiple change outputs");
121 return Result::WALLET_ERROR
;
127 errors
.push_back("Transaction does not have a change output");
128 return Result::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
, wallet
);
134 if (maxNewTxSize
< 0) {
135 errors
.push_back("Transaction contains inputs that cannot be signed");
136 return Result::INVALID_ADDRESS_OR_KEY
;
139 // calculate the old fee and fee-rate
140 old_fee
= wtx
.GetDebit(ISMINE_SPENDABLE
) - wtx
.tx
->GetValueOut();
141 CFeeRate
nOldFeeRate(old_fee
, txSize
);
142 CFeeRate nNewFeeRate
;
143 // The wallet uses a conservative WALLET_INCREMENTAL_RELAY_FEE value to
144 // future proof against changes to network wide policy for incremental relay
145 // fee that our node may not be aware of.
146 CFeeRate walletIncrementalRelayFee
= CFeeRate(WALLET_INCREMENTAL_RELAY_FEE
);
147 if (::incrementalRelayFee
> walletIncrementalRelayFee
) {
148 walletIncrementalRelayFee
= ::incrementalRelayFee
;
152 CAmount minTotalFee
= nOldFeeRate
.GetFee(maxNewTxSize
) + ::incrementalRelayFee
.GetFee(maxNewTxSize
);
153 if (total_fee
< minTotalFee
) {
154 errors
.push_back(strprintf("Insufficient totalFee, must be at least %s (oldFee %s + incrementalFee %s)",
155 FormatMoney(minTotalFee
), FormatMoney(nOldFeeRate
.GetFee(maxNewTxSize
)), FormatMoney(::incrementalRelayFee
.GetFee(maxNewTxSize
))));
156 return Result::INVALID_PARAMETER
;
158 CAmount requiredFee
= GetRequiredFee(maxNewTxSize
);
159 if (total_fee
< requiredFee
) {
160 errors
.push_back(strprintf("Insufficient totalFee (cannot be less than required fee %s)",
161 FormatMoney(requiredFee
)));
162 return Result::INVALID_PARAMETER
;
165 nNewFeeRate
= CFeeRate(total_fee
, maxNewTxSize
);
167 new_fee
= GetMinimumFee(maxNewTxSize
, coin_control
, mempool
, ::feeEstimator
, nullptr /* FeeCalculation */);
168 nNewFeeRate
= CFeeRate(new_fee
, maxNewTxSize
);
170 // New fee rate must be at least old rate + minimum incremental relay rate
171 // walletIncrementalRelayFee.GetFeePerK() should be exact, because it's initialized
172 // in that unit (fee per kb).
173 // However, nOldFeeRate is a calculated value from the tx fee/size, so
174 // add 1 satoshi to the result, because it may have been rounded down.
175 if (nNewFeeRate
.GetFeePerK() < nOldFeeRate
.GetFeePerK() + 1 + walletIncrementalRelayFee
.GetFeePerK()) {
176 nNewFeeRate
= CFeeRate(nOldFeeRate
.GetFeePerK() + 1 + walletIncrementalRelayFee
.GetFeePerK());
177 new_fee
= nNewFeeRate
.GetFee(maxNewTxSize
);
181 // Check that in all cases the new fee doesn't violate maxTxFee
182 if (new_fee
> maxTxFee
) {
183 errors
.push_back(strprintf("Specified or calculated fee %s is too high (cannot be higher than maxTxFee %s)",
184 FormatMoney(new_fee
), FormatMoney(maxTxFee
)));
185 return Result::WALLET_ERROR
;
188 // check that fee rate is higher than mempool's minimum fee
189 // (no point in bumping fee if we know that the new tx won't be accepted to the mempool)
190 // This may occur if the user set TotalFee or paytxfee too low, if fallbackfee is too low, or, perhaps,
191 // in a rare situation where the mempool minimum fee increased significantly since the fee estimation just a
192 // moment earlier. In this case, we report an error to the user, who may use total_fee to make an adjustment.
193 CFeeRate minMempoolFeeRate
= mempool
.GetMinFee(gArgs
.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000);
194 if (nNewFeeRate
.GetFeePerK() < minMempoolFeeRate
.GetFeePerK()) {
195 errors
.push_back(strprintf(
196 "New fee rate (%s) is lower than the minimum fee rate (%s) to get into the mempool -- "
197 "the totalFee value should be at least %s or the settxfee value should be at least %s to add transaction",
198 FormatMoney(nNewFeeRate
.GetFeePerK()),
199 FormatMoney(minMempoolFeeRate
.GetFeePerK()),
200 FormatMoney(minMempoolFeeRate
.GetFee(maxNewTxSize
)),
201 FormatMoney(minMempoolFeeRate
.GetFeePerK())));
202 return Result::WALLET_ERROR
;
205 // Now modify the output to increase the fee.
206 // If the output is not large enough to pay the fee, fail.
207 CAmount nDelta
= new_fee
- old_fee
;
210 CTxOut
* poutput
= &(mtx
.vout
[nOutput
]);
211 if (poutput
->nValue
< nDelta
) {
212 errors
.push_back("Change output is too small to bump the fee");
213 return Result::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 new_fee
+= 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;
234 bool SignTransaction(CWallet
* wallet
, CMutableTransaction
& mtx
) {
235 LOCK2(cs_main
, wallet
->cs_wallet
);
236 return wallet
->SignTransaction(mtx
);
239 Result
CommitTransaction(CWallet
* wallet
, const uint256
& txid
, CMutableTransaction
&& mtx
, std::vector
<std::string
>& errors
, uint256
& bumped_txid
)
241 LOCK2(cs_main
, wallet
->cs_wallet
);
242 if (!errors
.empty()) {
243 return Result::MISC_ERROR
;
245 auto it
= txid
.IsNull() ? wallet
->mapWallet
.end() : wallet
->mapWallet
.find(txid
);
246 if (it
== wallet
->mapWallet
.end()) {
247 errors
.push_back("Invalid or non-wallet transaction id");
248 return Result::MISC_ERROR
;
250 CWalletTx
& oldWtx
= it
->second
;
252 // make sure the transaction still has no descendants and hasn't been mined in the meantime
253 Result result
= PreconditionChecks(wallet
, oldWtx
, errors
);
254 if (result
!= Result::OK
) {
258 CWalletTx
wtxBumped(wallet
, MakeTransactionRef(std::move(mtx
)));
259 // commit/broadcast the tx
260 CReserveKey
reservekey(wallet
);
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 (!wallet
->CommitTransaction(wtxBumped
, reservekey
, g_connman
.get(), state
)) {
269 // NOTE: CommitTransaction never returns false, so this should never happen.
270 errors
.push_back(strprintf("The transaction was rejected: %s", state
.GetRejectReason()));
271 return Result::WALLET_ERROR
;
274 bumped_txid
= 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 errors
.push_back(strprintf("Error: The transaction was rejected: %s", FormatStateMessage(state
)));
281 // mark the original tx as bumped
282 if (!wallet
->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 errors
.push_back("Created new bumpfee transaction but could not mark the original transaction as replaced");
292 } // namespace feebumper