Skip to content

Commit cc585d5

Browse files
committed
Refactor BumpFee, move relevant code into CFeeBumper
1 parent 65e2e00 commit cc585d5

File tree

7 files changed

+346
-272
lines changed

7 files changed

+346
-272
lines changed

src/Makefile.am

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ BITCOIN_CORE_H = \
155155
wallet/coincontrol.h \
156156
wallet/crypter.h \
157157
wallet/db.h \
158+
wallet/feebumper.h \
158159
wallet/rpcwallet.h \
159160
wallet/wallet.h \
160161
wallet/walletdb.h \
@@ -229,6 +230,7 @@ libbitcoin_wallet_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
229230
libbitcoin_wallet_a_SOURCES = \
230231
wallet/crypter.cpp \
231232
wallet/db.cpp \
233+
wallet/feebumper.cpp \
232234
wallet/rpcdump.cpp \
233235
wallet/rpcwallet.cpp \
234236
wallet/wallet.cpp \

src/primitives/transaction.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,7 +451,9 @@ struct CMutableTransaction
451451
};
452452

453453
typedef std::shared_ptr<const CTransaction> CTransactionRef;
454+
typedef std::shared_ptr<CMutableTransaction> CMutableTransactionRef;
454455
static inline CTransactionRef MakeTransactionRef() { return std::make_shared<const CTransaction>(); }
456+
static inline CMutableTransactionRef MakeMutableTransactionRef(const CTransactionRef& txRef) { return std::make_shared<CMutableTransaction>(*txRef); }
455457
template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); }
456458

457459
/** Compute the weight of a transaction, as defined by BIP 141 */

src/wallet/feebumper.cpp

Lines changed: 276 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
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.
4+
5+
#include "consensus/validation.h"
6+
#include "wallet/feebumper.h"
7+
#include "wallet/wallet.h"
8+
#include "policy/policy.h"
9+
#include "policy/rbf.h"
10+
#include "validation.h" //for mempool access
11+
#include "txmempool.h"
12+
#include "utilmoneystr.h"
13+
#include "util.h"
14+
#include "net.h"
15+
16+
// Calculate the size of the transaction assuming all signatures are max size
17+
// Use DummySignatureCreator, which inserts 72 byte signatures everywhere.
18+
// TODO: re-use this in CWallet::CreateTransaction (right now
19+
// CreateTransaction uses the constructed dummy-signed tx to do a priority
20+
// calculation, but we should be able to refactor after priority is removed).
21+
// NOTE: this requires that all inputs must be in mapWallet (eg the tx should
22+
// be IsAllFromMe).
23+
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx)
24+
{
25+
CMutableTransaction txNew(tx);
26+
std::vector<std::pair<CWalletTx *, unsigned int>> vCoins;
27+
// Look up the inputs. We should have already checked that this transaction
28+
// IsAllFromMe(ISMINE_SPENDABLE), so every input should already be in our
29+
// wallet, with a valid index into the vout array.
30+
for (auto& input : tx.vin) {
31+
const auto mi = pwalletMain->mapWallet.find(input.prevout.hash);
32+
assert(mi != pwalletMain->mapWallet.end() && input.prevout.n < mi->second.tx->vout.size());
33+
vCoins.emplace_back(std::make_pair(&(mi->second), input.prevout.n));
34+
}
35+
if (!pwalletMain->DummySignTx(txNew, vCoins)) {
36+
// This should never happen, because IsAllFromMe(ISMINE_SPENDABLE)
37+
// implies that we can sign for every input.
38+
return -1;
39+
}
40+
return GetVirtualTransactionSize(txNew);
41+
}
42+
43+
CFeeBumper::CFeeBumper(const CWallet *pWallet, const uint256 txidIn, int newConfirmTarget, bool specifiedConfirmTarget, CAmount totalFee, bool newTxReplaceable)
44+
:
45+
txid(txidIn),
46+
mtx(0),
47+
nOldFee(0),
48+
nNewFee(0)
49+
{
50+
vErrors.clear();
51+
bumpedTxid.SetNull();
52+
AssertLockHeld(pWallet->cs_wallet);
53+
if (!pWallet->mapWallet.count(txid)) {
54+
vErrors.push_back("Invalid or non-wallet transaction id");
55+
currentResult = CFeeBumper::BumpFeeResult::INVALID_ADDRESS_OR_KEY;
56+
return;
57+
}
58+
auto it = pWallet->mapWallet.find(txid);
59+
const CWalletTx& wtx = it->second;
60+
61+
if (pWallet->HasWalletSpend(txid)) {
62+
vErrors.push_back("Transaction has descendants in the wallet");
63+
currentResult = CFeeBumper::BumpFeeResult::MISC_ERROR;
64+
return;
65+
}
66+
67+
{
68+
LOCK(mempool.cs);
69+
auto it = mempool.mapTx.find(txid);
70+
if (it != mempool.mapTx.end() && it->GetCountWithDescendants() > 1) {
71+
vErrors.push_back("Transaction has descendants in the mempool");
72+
currentResult = CFeeBumper::BumpFeeResult::MISC_ERROR;
73+
return;
74+
}
75+
}
76+
77+
if (wtx.GetDepthInMainChain() != 0) {
78+
vErrors.push_back("Transaction has been mined, or is conflicted with a mined transaction");
79+
currentResult = CFeeBumper::BumpFeeResult::INVALID_ADDRESS_OR_KEY;
80+
return;
81+
}
82+
83+
if (!SignalsOptInRBF(wtx)) {
84+
vErrors.push_back("Transaction is not BIP 125 replaceable");
85+
currentResult = CFeeBumper::BumpFeeResult::INVALID_ADDRESS_OR_KEY;
86+
return;
87+
}
88+
89+
if (wtx.mapValue.count("replaced_by_txid")) {
90+
vErrors.push_back(strprintf("Cannot bump transaction %s which was already bumped by transaction %s", txid.ToString(), wtx.mapValue.at("replaced_by_txid")));
91+
currentResult = CFeeBumper::BumpFeeResult::INVALID_REQUEST;
92+
return;
93+
}
94+
95+
// check that original tx consists entirely of our inputs
96+
// 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)
97+
if (!pWallet->IsAllFromMe(wtx, ISMINE_SPENDABLE)) {
98+
vErrors.push_back("Transaction contains inputs that don't belong to this wallet");
99+
currentResult = CFeeBumper::BumpFeeResult::INVALID_ADDRESS_OR_KEY;
100+
return;
101+
}
102+
103+
// figure out which output was change
104+
// if there was no change output or multiple change outputs, fail
105+
int nOutput = -1;
106+
for (size_t i = 0; i < wtx.tx->vout.size(); ++i) {
107+
if (pWallet->IsChange(wtx.tx->vout[i])) {
108+
if (nOutput != -1) {
109+
vErrors.push_back("Transaction has multiple change outputs");
110+
currentResult = CFeeBumper::BumpFeeResult::MISC_ERROR;
111+
return;
112+
}
113+
nOutput = i;
114+
}
115+
}
116+
if (nOutput == -1) {
117+
vErrors.push_back("Transaction does not have a change output");
118+
currentResult = CFeeBumper::BumpFeeResult::MISC_ERROR;
119+
return;
120+
}
121+
122+
// Calculate the expected size of the new transaction.
123+
int64_t txSize = GetVirtualTransactionSize(*(wtx.tx));
124+
const int64_t maxNewTxSize = CalculateMaximumSignedTxSize(*wtx.tx);
125+
if (maxNewTxSize < 0) {
126+
vErrors.push_back("Transaction contains inputs that cannot be signed");
127+
currentResult = CFeeBumper::BumpFeeResult::INVALID_ADDRESS_OR_KEY;
128+
return;
129+
}
130+
131+
// calculate the old fee and fee-rate
132+
nOldFee = wtx.GetDebit(ISMINE_SPENDABLE) - wtx.tx->GetValueOut();
133+
CFeeRate nOldFeeRate(nOldFee, txSize);
134+
CFeeRate nNewFeeRate;
135+
// The wallet uses a conservative WALLET_INCREMENTAL_RELAY_FEE value to
136+
// future proof against changes to network wide policy for incremental relay
137+
// fee that our node may not be aware of.
138+
CFeeRate walletIncrementalRelayFee = CFeeRate(WALLET_INCREMENTAL_RELAY_FEE);
139+
if (::incrementalRelayFee > walletIncrementalRelayFee) {
140+
walletIncrementalRelayFee = ::incrementalRelayFee;
141+
}
142+
143+
if (totalFee > 0) {
144+
CAmount minTotalFee = nOldFeeRate.GetFee(maxNewTxSize) + ::incrementalRelayFee.GetFee(maxNewTxSize);
145+
if (totalFee < minTotalFee) {
146+
vErrors.push_back(strprintf("Insufficient totalFee, must be at least %s (oldFee %s + incrementalFee %s)",
147+
FormatMoney(minTotalFee), FormatMoney(nOldFeeRate.GetFee(maxNewTxSize)), FormatMoney(::incrementalRelayFee.GetFee(maxNewTxSize))));
148+
currentResult = CFeeBumper::BumpFeeResult::INVALID_PARAMETER;
149+
return;
150+
}
151+
CAmount requiredFee = pWallet->GetRequiredFee(maxNewTxSize);
152+
if (totalFee < requiredFee) {
153+
vErrors.push_back(strprintf("Insufficient totalFee (cannot be less than required fee %s)",
154+
FormatMoney(requiredFee)));
155+
currentResult = CFeeBumper::BumpFeeResult::INVALID_PARAMETER;
156+
return;
157+
}
158+
nNewFee = totalFee;
159+
nNewFeeRate = CFeeRate(totalFee, maxNewTxSize);
160+
} else {
161+
// if user specified a confirm target then don't consider any global payTxFee
162+
if (specifiedConfirmTarget) {
163+
nNewFee = pWallet->GetMinimumFee(maxNewTxSize, newConfirmTarget, mempool, CAmount(0));
164+
}
165+
// otherwise use the regular wallet logic to select payTxFee or default confirm target
166+
else {
167+
nNewFee = pWallet->GetMinimumFee(maxNewTxSize, newConfirmTarget, mempool);
168+
}
169+
170+
nNewFeeRate = CFeeRate(nNewFee, maxNewTxSize);
171+
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);
180+
}
181+
}
182+
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 = CFeeBumper::BumpFeeResult::MISC_ERROR;
188+
return;
189+
}
190+
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 = CFeeBumper::BumpFeeResult::MISC_ERROR;
200+
return;
201+
}
202+
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 = MakeMutableTransactionRef(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 = CFeeBumper::BumpFeeResult::MISC_ERROR;
212+
return;
213+
}
214+
215+
// If the output would become dust, discard it (converting the dust to fee)
216+
poutput->nValue -= nDelta;
217+
if (poutput->nValue <= poutput->GetDustThreshold(::dustRelayFee)) {
218+
LogPrint("rpc", "Bumping fee and discarding dust output\n");
219+
nNewFee += poutput->nValue;
220+
mtx->vout.erase(mtx->vout.begin() + nOutput);
221+
}
222+
223+
// Mark new tx not replaceable, if requested.
224+
if (!newTxReplaceable) {
225+
for (auto& input : mtx->vin) {
226+
if (input.nSequence < 0xfffffffe) input.nSequence = 0xfffffffe;
227+
}
228+
}
229+
230+
currentResult = BumpFeeResult::OK;
231+
}
232+
233+
bool CFeeBumper::commit(CWallet *pWallet)
234+
{
235+
AssertLockHeld(pWallet->cs_wallet);
236+
vErrors.clear();
237+
if (txid.IsNull() || !pWallet->mapWallet.count(txid)) {
238+
vErrors.push_back("Invalid or non-wallet transaction id");
239+
currentResult = CFeeBumper::BumpFeeResult::MISC_ERROR;
240+
}
241+
CWalletTx& oldWtx = pWallet->mapWallet[txid];
242+
243+
CWalletTx wtxBumped(pWallet, MakeTransactionRef(std::move(*mtx)));
244+
// commit/broadcast the tx
245+
CReserveKey reservekey(pWallet);
246+
wtxBumped.mapValue = oldWtx.mapValue;
247+
wtxBumped.mapValue["replaces_txid"] = oldWtx.GetHash().ToString();
248+
wtxBumped.vOrderForm = oldWtx.vOrderForm;
249+
wtxBumped.strFromAccount = oldWtx.strFromAccount;
250+
wtxBumped.fTimeReceivedIsTxTime = true;
251+
wtxBumped.fFromMe = true;
252+
CValidationState state;
253+
if (!pWallet->CommitTransaction(wtxBumped, reservekey, g_connman.get(), state)) {
254+
// NOTE: CommitTransaction never returns false, so this should never happen.
255+
vErrors.push_back(strprintf("Error: The transaction was rejected! Reason given: %s", state.GetRejectReason()));
256+
return false;
257+
}
258+
259+
bumpedTxid = wtxBumped.GetHash();
260+
if (state.IsInvalid()) {
261+
// This can happen if the mempool rejected the transaction. Report
262+
// what happened in the "errors" response.
263+
vErrors.push_back(strprintf("Error: The transaction was rejected: %s", FormatStateMessage(state)));
264+
}
265+
266+
// mark the original tx as bumped
267+
if (!pWallet->MarkReplaced(oldWtx.GetHash(), wtxBumped.GetHash())) {
268+
// TODO: see if JSON-RPC has a standard way of returning a response
269+
// along with an exception. It would be good to return information about
270+
// wtxBumped to the caller even if marking the original transaction
271+
// replaced does not succeed for some reason.
272+
vErrors.push_back("Error: Created new bumpfee transaction but could not mark the original transaction as replaced.");
273+
}
274+
return true;
275+
}
276+

src/wallet/feebumper.h

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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.
4+
5+
#ifndef BITCOIN_WALLET_FEEBUMPER_H
6+
#define BITCOIN_WALLET_FEEBUMPER_H
7+
8+
#include <primitives/transaction.h>
9+
10+
class CWallet;
11+
class uint256;
12+
13+
class CFeeBumper
14+
{
15+
public:
16+
enum class BumpFeeResult
17+
{
18+
OK,
19+
INVALID_ADDRESS_OR_KEY,
20+
INVALID_REQUEST,
21+
INVALID_PARAMETER,
22+
MISC_ERROR,
23+
};
24+
25+
CFeeBumper(const CWallet *pWalletIn, const uint256 txidIn, int newConfirmTarget, bool specifiedConfirmTarget, CAmount totalFee, bool newTxReplaceable);
26+
CFeeBumper::BumpFeeResult getResult() const { return currentResult; }
27+
const std::vector<std::string>& getErrors() const { return vErrors; }
28+
CAmount getOldFee() const { return nOldFee; }
29+
CAmount getNewFee() const { return nNewFee; }
30+
CMutableTransactionRef getBumpedTxRef() const { return mtx; }
31+
uint256 getBumpedTxId() const { return bumpedTxid; }
32+
33+
bool commit(CWallet *pWalletNonConst);
34+
35+
private:
36+
const uint256 txid;
37+
uint256 bumpedTxid;
38+
CMutableTransactionRef mtx;
39+
std::vector<std::string> vErrors;
40+
BumpFeeResult currentResult;
41+
CAmount nOldFee;
42+
CAmount nNewFee;
43+
};
44+
45+
#endif // BITCOIN_WALLET_FEEBUMPER_H

0 commit comments

Comments
 (0)