Skip to content

Commit 8bda5e0

Browse files
committed
Merge bitcoin/bitcoin#22855: RBF move 3/3: move followups + improve RBF documentation
0ef08f8 add missing includes in policy/rbf (glozow) c6abeb7 make MAX_BIP125_RBF_SEQUENCE constexpr (glozow) 3cf46f6 [doc] improve RBF documentation (glozow) c78eb86 [policy/refactor] pass in relay fee instead of using global (glozow) Pull request description: Followups to #22675 and documentation-only changes intended to clarify the code/logic concerning mempool Replace-by-Fee. ACKs for top commit: jnewbery: utACK 0ef08f8 fanquake: ACK 0ef08f8 Tree-SHA512: 6797ae758beca0c9673cb00ce85da48e9a4ac5cb5100074ca93e004cdb31d24d91a1a7721b57fc2f619addfeb4950d8caf45fee0f5b7528defbbd121eb4d271f
2 parents b8cca9c + 0ef08f8 commit 8bda5e0

File tree

4 files changed

+50
-36
lines changed

4 files changed

+50
-36
lines changed

src/policy/rbf.cpp

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -48,26 +48,27 @@ RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx)
4848
}
4949

5050
std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx,
51-
CTxMemPool& pool,
52-
const CTxMemPool::setEntries& iters_conflicting,
53-
CTxMemPool::setEntries& all_conflicts)
51+
CTxMemPool& pool,
52+
const CTxMemPool::setEntries& iters_conflicting,
53+
CTxMemPool::setEntries& all_conflicts)
5454
{
5555
AssertLockHeld(pool.cs);
5656
const uint256 txid = tx.GetHash();
5757
uint64_t nConflictingCount = 0;
5858
for (const auto& mi : iters_conflicting) {
5959
nConflictingCount += mi->GetCountWithDescendants();
60-
// This potentially overestimates the number of actual descendants but we just want to be
61-
// conservative to avoid doing too much work.
60+
// BIP125 Rule #5: don't consider replacing more than MAX_BIP125_REPLACEMENT_CANDIDATES
61+
// entries from the mempool. This potentially overestimates the number of actual
62+
// descendants (i.e. if multiple conflicts share a descendant, it will be counted multiple
63+
// times), but we just want to be conservative to avoid doing too much work.
6264
if (nConflictingCount > MAX_BIP125_REPLACEMENT_CANDIDATES) {
6365
return strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
6466
txid.ToString(),
6567
nConflictingCount,
6668
MAX_BIP125_REPLACEMENT_CANDIDATES);
6769
}
6870
}
69-
// If not too many to replace, then calculate the set of
70-
// transactions that would have to be evicted
71+
// Calculate the set of all transactions that would have to be evicted.
7172
for (CTxMemPool::txiter it : iters_conflicting) {
7273
pool.CalculateDescendants(it, all_conflicts);
7374
}
@@ -81,19 +82,19 @@ std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx,
8182
AssertLockHeld(pool.cs);
8283
std::set<uint256> parents_of_conflicts;
8384
for (const auto& mi : iters_conflicting) {
84-
for (const CTxIn &txin : mi->GetTx().vin) {
85+
for (const CTxIn& txin : mi->GetTx().vin) {
8586
parents_of_conflicts.insert(txin.prevout.hash);
8687
}
8788
}
8889

8990
for (unsigned int j = 0; j < tx.vin.size(); j++) {
90-
// We don't want to accept replacements that require low feerate junk to be mined first.
91-
// Ideally we'd keep track of the ancestor feerates and make the decision based on that, but
92-
// for now requiring all new inputs to be confirmed works.
91+
// BIP125 Rule #2: We don't want to accept replacements that require low feerate junk to be
92+
// mined first. Ideally we'd keep track of the ancestor feerates and make the decision
93+
// based on that, but for now requiring all new inputs to be confirmed works.
9394
//
9495
// Note that if you relax this to make RBF a little more useful, this may break the
95-
// CalculateMempoolAncestors RBF relaxation, above. See the comment above the first
96-
// CalculateMempoolAncestors call for more info.
96+
// CalculateMempoolAncestors RBF relaxation which subtracts the conflict count/size from the
97+
// descendant limit.
9798
if (!parents_of_conflicts.count(tx.vin[j].prevout.hash)) {
9899
// Rather than check the UTXO set - potentially expensive - it's cheaper to just check
99100
// if the new input refers to a tx that's in the mempool.
@@ -111,7 +112,7 @@ std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries&
111112
const uint256& txid)
112113
{
113114
for (CTxMemPool::txiter ancestorIt : ancestors) {
114-
const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
115+
const uint256& hashAncestor = ancestorIt->GetTx().GetHash();
115116
if (direct_conflicts.count(hashAncestor)) {
116117
return strprintf("%s spends conflicting transaction %s",
117118
txid.ToString(),
@@ -150,24 +151,26 @@ std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& i
150151
std::optional<std::string> PaysForRBF(CAmount original_fees,
151152
CAmount replacement_fees,
152153
size_t replacement_vsize,
154+
CFeeRate relay_fee,
153155
const uint256& txid)
154156
{
155-
// The replacement must pay greater fees than the transactions it
156-
// replaces - if we did the bandwidth used by those conflicting
157-
// transactions would not be paid for.
157+
// BIP125 Rule #3: The replacement fees must be greater than or equal to fees of the
158+
// transactions it replaces, otherwise the bandwidth used by those conflicting transactions
159+
// would not be paid for.
158160
if (replacement_fees < original_fees) {
159161
return strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
160162
txid.ToString(), FormatMoney(replacement_fees), FormatMoney(original_fees));
161163
}
162164

163-
// Finally in addition to paying more fees than the conflicts the
164-
// new transaction must pay for its own bandwidth.
165+
// BIP125 Rule #4: The new transaction must pay for its own bandwidth. Otherwise, we have a DoS
166+
// vector where attackers can cause a transaction to be replaced (and relayed) repeatedly by
167+
// increasing the fee by tiny amounts.
165168
CAmount additional_fees = replacement_fees - original_fees;
166-
if (additional_fees < ::incrementalRelayFee.GetFee(replacement_vsize)) {
169+
if (additional_fees < relay_fee.GetFee(replacement_vsize)) {
167170
return strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
168171
txid.ToString(),
169172
FormatMoney(additional_fees),
170-
FormatMoney(::incrementalRelayFee.GetFee(replacement_vsize)));
173+
FormatMoney(relay_fee.GetFee(replacement_vsize)));
171174
}
172175
return std::nullopt;
173176
}

src/policy/rbf.h

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@
55
#ifndef BITCOIN_POLICY_RBF_H
66
#define BITCOIN_POLICY_RBF_H
77

8+
#include <primitives/transaction.h>
89
#include <txmempool.h>
10+
#include <uint256.h>
11+
12+
#include <optional>
13+
#include <string>
914

1015
/** Maximum number of transactions that can be replaced by BIP125 RBF (Rule #5). This includes all
1116
* mempool conflicts and their descendants. */
@@ -48,14 +53,14 @@ RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx);
4853
std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx, CTxMemPool& pool,
4954
const CTxMemPool::setEntries& iters_conflicting,
5055
CTxMemPool::setEntries& all_conflicts)
51-
EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
56+
EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
5257

5358
/** BIP125 Rule #2: "The replacement transaction may only include an unconfirmed input if that input
5459
* was included in one of the original transactions."
5560
* @returns error message if Rule #2 is broken, otherwise std::nullopt. */
5661
std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx, const CTxMemPool& pool,
5762
const CTxMemPool::setEntries& iters_conflicting)
58-
EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
63+
EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
5964

6065
/** Check the intersection between two sets of transactions (a set of mempool entries and a set of
6166
* txids) to make sure they are disjoint.
@@ -84,12 +89,14 @@ std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& i
8489
* @param[in] original_fees Total modified fees of original transaction(s).
8590
* @param[in] replacement_fees Total modified fees of replacement transaction(s).
8691
* @param[in] replacement_vsize Total virtual size of replacement transaction(s).
92+
* @param[in] relay_fee The node's minimum feerate for transaction relay.
8793
* @param[in] txid Transaction ID, included in the error message if violation occurs.
8894
* @returns error string if fees are insufficient, otherwise std::nullopt.
8995
*/
9096
std::optional<std::string> PaysForRBF(CAmount original_fees,
9197
CAmount replacement_fees,
9298
size_t replacement_vsize,
99+
CFeeRate relay_fee,
93100
const uint256& txid);
94101

95102
#endif // BITCOIN_POLICY_RBF_H

src/util/rbf.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,15 @@
99

1010
class CTransaction;
1111

12-
static const uint32_t MAX_BIP125_RBF_SEQUENCE = 0xfffffffd;
12+
static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE{0xfffffffd};
1313

1414
/** Check whether the sequence numbers on this transaction are signaling opt-in to replace-by-fee,
1515
* according to BIP 125. Allow opt-out of transaction replacement by setting nSequence >
1616
* MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
1717
*
1818
* SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by non-replaceable transactions. All
1919
* inputs rather than just one is for the sake of multi-party protocols, where we don't want a single
20-
* party to be able to disable replacement. */
21-
bool SignalsOptInRBF(const CTransaction &tx);
20+
* party to be able to disable replacement by opting out in their own input. */
21+
bool SignalsOptInRBF(const CTransaction& tx);
2222

2323
#endif // BITCOIN_UTIL_RBF_H

src/validation.cpp

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -772,39 +772,43 @@ bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
772772
// pathological case by making sure setConflicts and setAncestors don't
773773
// intersect.
774774
if (const auto err_string{EntriesAndTxidsDisjoint(setAncestors, setConflicts, hash)}) {
775+
// We classify this as a consensus error because a transaction depending on something it
776+
// conflicts with would be inconsistent.
775777
return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx", *err_string);
776778
}
777779

778780

779-
// If we don't hold the lock allConflicting might be incomplete; the
780-
// subsequent RemoveStaged() and addUnchecked() calls don't guarantee
781-
// mempool consistency for us.
782781
fReplacementTransaction = setConflicts.size();
783-
if (fReplacementTransaction)
784-
{
782+
if (fReplacementTransaction) {
785783
CFeeRate newFeeRate(nModifiedFees, nSize);
784+
// It's possible that the replacement pays more fees than its direct conflicts but not more
785+
// than all conflicts (i.e. the direct conflicts have high-fee descendants). However, if the
786+
// replacement doesn't pay more fees than its direct conflicts, then we can be sure it's not
787+
// more economically rational to mine. Before we go digging through the mempool for all
788+
// transactions that would need to be removed (direct conflicts and all descendants), check
789+
// that the replacement transaction pays more than its direct conflicts.
786790
if (const auto err_string{PaysMoreThanConflicts(setIterConflicting, newFeeRate, hash)}) {
787791
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
788792
}
789793

790-
// Calculate all conflicting entries and enforce Rule #5.
794+
// Calculate all conflicting entries and enforce BIP125 Rule #5.
791795
if (const auto err_string{GetEntriesForConflicts(tx, m_pool, setIterConflicting, allConflicting)}) {
792796
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY,
793797
"too many potential replacements", *err_string);
794798
}
795-
// Enforce Rule #2.
799+
// Enforce BIP125 Rule #2.
796800
if (const auto err_string{HasNoNewUnconfirmed(tx, m_pool, setIterConflicting)}) {
797801
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY,
798802
"replacement-adds-unconfirmed", *err_string);
799803
}
800804

801-
// Check if it's economically rational to mine this transaction rather
802-
// than the ones it replaces. Enforce Rules #3 and #4.
805+
// Check if it's economically rational to mine this transaction rather than the ones it
806+
// replaces and pays for its own relay fees. Enforce BIP125 Rules #3 and #4.
803807
for (CTxMemPool::txiter it : allConflicting) {
804808
nConflictingFees += it->GetModifiedFee();
805809
nConflictingSize += it->GetTxSize();
806810
}
807-
if (const auto err_string{PaysForRBF(nConflictingFees, nModifiedFees, nSize, hash)}) {
811+
if (const auto err_string{PaysForRBF(nConflictingFees, nModifiedFees, nSize, ::incrementalRelayFee, hash)}) {
808812
return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
809813
}
810814
}

0 commit comments

Comments
 (0)