Bitcoin Core 29.99.0
P2P Digital Currency
rbf.cpp
Go to the documentation of this file.
1// Copyright (c) 2016-2022 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 <policy/rbf.h>
6
7#include <consensus/amount.h>
9#include <policy/feerate.h>
11#include <sync.h>
12#include <tinyformat.h>
13#include <txmempool.h>
14#include <uint256.h>
15#include <util/check.h>
16#include <util/moneystr.h>
17#include <util/rbf.h>
18
19#include <limits>
20#include <vector>
21
22#include <compare>
23
25{
26 AssertLockHeld(pool.cs);
27
28 // First check the transaction itself.
29 if (SignalsOptInRBF(tx)) {
31 }
32
33 // If this transaction is not in our mempool, then we can't be sure
34 // we will know about all its inputs.
35 if (!pool.exists(tx.GetHash())) {
37 }
38
39 // If all the inputs have nSequence >= maxint-1, it still might be
40 // signaled for RBF if any unconfirmed parents have signaled.
41 const auto& entry{*Assert(pool.GetEntry(tx.GetHash()))};
42 auto ancestors{pool.AssumeCalculateMemPoolAncestors(__func__, entry, CTxMemPool::Limits::NoLimits(),
43 /*fSearchForParents=*/false)};
44
45 for (CTxMemPool::txiter it : ancestors) {
46 if (SignalsOptInRBF(it->GetTx())) {
48 }
49 }
51}
52
54{
55 // If we don't have a local mempool we can only check the transaction itself.
57}
58
59std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx,
60 CTxMemPool& pool,
61 const CTxMemPool::setEntries& iters_conflicting,
62 CTxMemPool::setEntries& all_conflicts)
63{
64 AssertLockHeld(pool.cs);
65 uint64_t nConflictingCount = 0;
66 for (const auto& mi : iters_conflicting) {
67 nConflictingCount += mi->GetCountWithDescendants();
68 // Rule #5: don't consider replacing more than MAX_REPLACEMENT_CANDIDATES
69 // entries from the mempool. This potentially overestimates the number of actual
70 // descendants (i.e. if multiple conflicts share a descendant, it will be counted multiple
71 // times), but we just want to be conservative to avoid doing too much work.
72 if (nConflictingCount > MAX_REPLACEMENT_CANDIDATES) {
73 return strprintf("rejecting replacement %s; too many potential replacements (%d > %d)",
74 tx.GetHash().ToString(),
75 nConflictingCount,
77 }
78 }
79 // Calculate the set of all transactions that would have to be evicted.
80 for (CTxMemPool::txiter it : iters_conflicting) {
81 pool.CalculateDescendants(it, all_conflicts);
82 }
83 return std::nullopt;
84}
85
86std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx,
87 const CTxMemPool& pool,
88 const CTxMemPool::setEntries& iters_conflicting)
89{
90 AssertLockHeld(pool.cs);
91 std::set<Txid> parents_of_conflicts;
92 for (const auto& mi : iters_conflicting) {
93 for (const CTxIn& txin : mi->GetTx().vin) {
94 parents_of_conflicts.insert(txin.prevout.hash);
95 }
96 }
97
98 for (unsigned int j = 0; j < tx.vin.size(); j++) {
99 // Rule #2: We don't want to accept replacements that require low feerate junk to be
100 // mined first. Ideally we'd keep track of the ancestor feerates and make the decision
101 // based on that, but for now requiring all new inputs to be confirmed works.
102 //
103 // Note that if you relax this to make RBF a little more useful, this may break the
104 // CalculateMempoolAncestors RBF relaxation which subtracts the conflict count/size from the
105 // descendant limit.
106 if (!parents_of_conflicts.count(tx.vin[j].prevout.hash)) {
107 // Rather than check the UTXO set - potentially expensive - it's cheaper to just check
108 // if the new input refers to a tx that's in the mempool.
109 if (pool.exists(tx.vin[j].prevout.hash)) {
110 return strprintf("replacement %s adds unconfirmed input, idx %d",
111 tx.GetHash().ToString(), j);
112 }
113 }
114 }
115 return std::nullopt;
116}
117
118std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors,
119 const std::set<Txid>& direct_conflicts,
120 const Txid& txid)
121{
122 for (CTxMemPool::txiter ancestorIt : ancestors) {
123 const Txid& hashAncestor = ancestorIt->GetTx().GetHash();
124 if (direct_conflicts.count(hashAncestor)) {
125 return strprintf("%s spends conflicting transaction %s",
126 txid.ToString(),
127 hashAncestor.ToString());
128 }
129 }
130 return std::nullopt;
131}
132
133std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting,
134 CFeeRate replacement_feerate,
135 const Txid& txid)
136{
137 for (const auto& mi : iters_conflicting) {
138 // Don't allow the replacement to reduce the feerate of the mempool.
139 //
140 // We usually don't want to accept replacements with lower feerates than what they replaced
141 // as that would lower the feerate of the next block. Requiring that the feerate always be
142 // increased is also an easy-to-reason about way to prevent DoS attacks via replacements.
143 //
144 // We only consider the feerates of transactions being directly replaced, not their indirect
145 // descendants. While that does mean high feerate children are ignored when deciding whether
146 // or not to replace, we do require the replacement to pay more overall fees too, mitigating
147 // most cases.
148 CFeeRate original_feerate(mi->GetModifiedFee(), mi->GetTxSize());
149 if (replacement_feerate <= original_feerate) {
150 return strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
151 txid.ToString(),
152 replacement_feerate.ToString(),
153 original_feerate.ToString());
154 }
155 }
156 return std::nullopt;
157}
158
159std::optional<std::string> PaysForRBF(CAmount original_fees,
160 CAmount replacement_fees,
161 size_t replacement_vsize,
162 CFeeRate relay_fee,
163 const Txid& txid)
164{
165 // Rule #3: The replacement fees must be greater than or equal to fees of the
166 // transactions it replaces, otherwise the bandwidth used by those conflicting transactions
167 // would not be paid for.
168 if (replacement_fees < original_fees) {
169 return strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
170 txid.ToString(), FormatMoney(replacement_fees), FormatMoney(original_fees));
171 }
172
173 // Rule #4: The new transaction must pay for its own bandwidth. Otherwise, we have a DoS
174 // vector where attackers can cause a transaction to be replaced (and relayed) repeatedly by
175 // increasing the fee by tiny amounts.
176 CAmount additional_fees = replacement_fees - original_fees;
177 if (additional_fees < relay_fee.GetFee(replacement_vsize)) {
178 return strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
179 txid.ToString(),
180 FormatMoney(additional_fees),
181 FormatMoney(relay_fee.GetFee(replacement_vsize)));
182 }
183 return std::nullopt;
184}
185
186std::optional<std::pair<DiagramCheckError, std::string>> ImprovesFeerateDiagram(CTxMemPool::ChangeSet& changeset)
187{
188 // Require that the replacement strictly improves the mempool's feerate diagram.
189 const auto chunk_results{changeset.CalculateChunksForRBF()};
190
191 if (!chunk_results.has_value()) {
192 return std::make_pair(DiagramCheckError::UNCALCULABLE, util::ErrorString(chunk_results).original);
193 }
194
195 if (!std::is_gt(CompareChunks(chunk_results.value().second, chunk_results.value().first))) {
196 return std::make_pair(DiagramCheckError::FAILURE, "insufficient feerate: does not improve feerate diagram");
197 }
198 return std::nullopt;
199}
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define Assert(val)
Identity function.
Definition: check.h:106
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:35
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:29
CAmount GetFee(int32_t virtual_bytes) const
Return the fee in satoshis for the given vsize in vbytes.
Definition: feerate.cpp:20
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
const std::vector< CTxIn > vin
Definition: transaction.h:306
An input of a transaction.
Definition: transaction.h:67
util::Result< std::pair< std::vector< FeeFrac >, std::vector< FeeFrac > > > CalculateChunksForRBF()
Calculate the sorted chunks for the old and new mempool relating to the clusters that would be affect...
Definition: txmempool.cpp:1297
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:281
setEntries AssumeCalculateMemPoolAncestors(std::string_view calling_fn_name, const CTxMemPoolEntry &entry, const Limits &limits, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Same as CalculateMemPoolAncestors, but always returns a (non-optional) setEntries.
Definition: txmempool.cpp:275
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:367
bool exists(const Txid &txid) const
Definition: txmempool.h:630
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:373
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:370
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:572
const CTxMemPoolEntry * GetEntry(const Txid &txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:872
std::string ToString() const
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:19
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
std::optional< std::string > HasNoNewUnconfirmed(const CTransaction &tx, const CTxMemPool &pool, const CTxMemPool::setEntries &iters_conflicting)
The replacement transaction may only include an unconfirmed input if that input was included in one o...
Definition: rbf.cpp:86
std::optional< std::pair< DiagramCheckError, std::string > > ImprovesFeerateDiagram(CTxMemPool::ChangeSet &changeset)
The replacement transaction must improve the feerate diagram of the mempool.
Definition: rbf.cpp:186
RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction &tx)
Definition: rbf.cpp:53
std::optional< std::string > PaysForRBF(CAmount original_fees, CAmount replacement_fees, size_t replacement_vsize, CFeeRate relay_fee, const Txid &txid)
The replacement transaction must pay more fees than the original transactions.
Definition: rbf.cpp:159
std::optional< std::string > PaysMoreThanConflicts(const CTxMemPool::setEntries &iters_conflicting, CFeeRate replacement_feerate, const Txid &txid)
Check that the feerate of the replacement transaction(s) is higher than the feerate of each of the tr...
Definition: rbf.cpp:133
std::optional< std::string > EntriesAndTxidsDisjoint(const CTxMemPool::setEntries &ancestors, const std::set< Txid > &direct_conflicts, const Txid &txid)
Check the intersection between two sets of transactions (a set of mempool entries and a set of txids)...
Definition: rbf.cpp:118
RBFTransactionState IsRBFOptIn(const CTransaction &tx, const CTxMemPool &pool)
Determine whether an unconfirmed transaction is signaling opt-in to RBF according to BIP 125 This inv...
Definition: rbf.cpp:24
std::optional< std::string > GetEntriesForConflicts(const CTransaction &tx, CTxMemPool &pool, const CTxMemPool::setEntries &iters_conflicting, CTxMemPool::setEntries &all_conflicts)
Get all descendants of iters_conflicting.
Definition: rbf.cpp:59
RBFTransactionState
The rbf state of unconfirmed transactions.
Definition: rbf.h:29
@ UNKNOWN
Unconfirmed tx that does not signal rbf and is not in the mempool.
@ FINAL
Neither this tx nor a mempool ancestor signals rbf.
@ REPLACEABLE_BIP125
Either this tx or a mempool ancestor signals rbf.
static constexpr uint32_t MAX_REPLACEMENT_CANDIDATES
Maximum number of transactions that can be replaced by RBF (Rule #5).
Definition: rbf.h:26
@ FAILURE
New diagram wasn't strictly superior
@ UNCALCULABLE
Unable to calculate due to topology or other reason.
static constexpr MemPoolLimits NoLimits()
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
std::partial_ordering CompareChunks(std::span< const FeeFrac > chunks0, std::span< const FeeFrac > chunks1)
Compare the feerate diagrams implied by the provided sorted chunks data.
Definition: feefrac.cpp:10
bool SignalsOptInRBF(const CTransaction &tx)
Check whether the sequence numbers on this transaction are signaling opt-in to replace-by-fee,...
Definition: rbf.cpp:9
AssertLockHeld(pool.cs)