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