Skip to content

Commit c2dbbc3

Browse files
committed
Merge bitcoin/bitcoin#29242: Mempool util: Add RBF diagram checks for single chunks against clusters of size 2
7295986 Unit tests for CalculateFeerateDiagramsForRBF (Greg Sanders) b767e6b test: unit test for ImprovesFeerateDiagram (Greg Sanders) 7e89b65 Add fuzz test for FeeFrac (Greg Sanders) 4d6528a fuzz: fuzz diagram creation and comparison (Greg Sanders) e9c5aeb test: Add tests for CompareFeerateDiagram and CheckConflictTopology (Greg Sanders) 588a98d fuzz: Add fuzz target for ImprovesFeerateDiagram (Greg Sanders) 2079b80 Implement ImprovesFeerateDiagram (Greg Sanders) 66d966d Add FeeFrac unit tests (Greg Sanders) ce8e225 Add FeeFrac utils (Greg Sanders) Pull request description: This is a smaller piece of bitcoin/bitcoin#28984 broken off for easier review. Up to date explanation of diagram checks are here: https://delvingbitcoin.org/t/mempool-incentive-compatibility/553 This infrastructure has two near term applications prior to cluster mempool: 1) Limited Package RBF(bitcoin/bitcoin#28984): We want to allow package RBF only when we know it improves the mempool. This narrowly scoped functionality allows use with v3-like topologies, and will be expanded at some point post-cluster mempool when diagram checks can be done efficiently against bounded cluster sizes. 2) Replacement for single tx RBF(in a cluster size of up to two) against conflicts of up to cluster size two. `ImprovesFeerateDiagram` interface will have to change for this use-case, which is a future direction to solve certain pins and improve mempool incentive compatibility: https://delvingbitcoin.org/t/ephemeral-anchors-and-mev/383#diagram-checks-fix-this-3 And longer-term, this would be the proposed way we would compute incentive compatibility for all conflicts, post-cluster mempool. ACKs for top commit: sipa: utACK 7295986 glozow: code review ACK 7295986 murchandamus: utACK 7295986 ismaelsadeeq: Re-ACK bitcoin/bitcoin@7295986 willcl-ark: crACK 7295986 sdaftuar: ACK 7295986 Tree-SHA512: 79593e5a087801c06f06cc8b73aa3e7b96ab938d3b90f5d229c4e4bfca887a77b447605c49aa5eb7ddcead85706c534ac5eb6146ae2396af678f4beaaa5bea8e
2 parents b44f9e4 + 7295986 commit c2dbbc3

File tree

13 files changed

+1310
-41
lines changed

13 files changed

+1310
-41
lines changed

src/Makefile.am

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@ BITCOIN_CORE_H = \
302302
util/error.h \
303303
util/exception.h \
304304
util/fastrange.h \
305+
util/feefrac.h \
305306
util/fees.h \
306307
util/fs.h \
307308
util/fs_helpers.h \
@@ -741,6 +742,7 @@ libbitcoin_util_a_SOURCES = \
741742
util/check.cpp \
742743
util/error.cpp \
743744
util/exception.cpp \
745+
util/feefrac.cpp \
744746
util/fees.cpp \
745747
util/fs.cpp \
746748
util/fs_helpers.cpp \
@@ -983,6 +985,7 @@ libbitcoinkernel_la_SOURCES = \
983985
util/batchpriority.cpp \
984986
util/chaintype.cpp \
985987
util/check.cpp \
988+
util/feefrac.cpp \
986989
util/fs.cpp \
987990
util/fs_helpers.cpp \
988991
util/hasher.cpp \

src/Makefile.test.include

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ BITCOIN_TESTS =\
9393
test/denialofservice_tests.cpp \
9494
test/descriptor_tests.cpp \
9595
test/disconnected_transactions.cpp \
96+
test/feefrac_tests.cpp \
9697
test/flatfile_tests.cpp \
9798
test/fs_tests.cpp \
9899
test/getarg_tests.cpp \
@@ -313,7 +314,9 @@ test_fuzz_fuzz_SOURCES = \
313314
test/fuzz/descriptor_parse.cpp \
314315
test/fuzz/deserialize.cpp \
315316
test/fuzz/eval_script.cpp \
317+
test/fuzz/feefrac.cpp \
316318
test/fuzz/fee_rate.cpp \
319+
test/fuzz/feeratediagram.cpp \
317320
test/fuzz/fees.cpp \
318321
test/fuzz/flatfile.cpp \
319322
test/fuzz/float.cpp \

src/policy/rbf.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
#include <limits>
2020
#include <vector>
2121

22+
#include <compare>
23+
2224
RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool)
2325
{
2426
AssertLockHeld(pool.cs);
@@ -181,3 +183,24 @@ std::optional<std::string> PaysForRBF(CAmount original_fees,
181183
}
182184
return std::nullopt;
183185
}
186+
187+
std::optional<std::pair<DiagramCheckError, std::string>> ImprovesFeerateDiagram(CTxMemPool& pool,
188+
const CTxMemPool::setEntries& direct_conflicts,
189+
const CTxMemPool::setEntries& all_conflicts,
190+
CAmount replacement_fees,
191+
int64_t replacement_vsize)
192+
{
193+
// Require that the replacement strictly improve the mempool's feerate diagram.
194+
std::vector<FeeFrac> old_diagram, new_diagram;
195+
196+
const auto diagram_results{pool.CalculateFeerateDiagramsForRBF(replacement_fees, replacement_vsize, direct_conflicts, all_conflicts)};
197+
198+
if (!diagram_results.has_value()) {
199+
return std::make_pair(DiagramCheckError::UNCALCULABLE, util::ErrorString(diagram_results).original);
200+
}
201+
202+
if (!std::is_gt(CompareFeerateDiagram(diagram_results.value().second, diagram_results.value().first))) {
203+
return std::make_pair(DiagramCheckError::FAILURE, "insufficient feerate: does not improve feerate diagram");
204+
}
205+
return std::nullopt;
206+
}

src/policy/rbf.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
#include <primitives/transaction.h>
1010
#include <threadsafety.h>
1111
#include <txmempool.h>
12+
#include <util/feefrac.h>
1213

14+
#include <compare>
1315
#include <cstddef>
1416
#include <cstdint>
1517
#include <optional>
@@ -33,6 +35,13 @@ enum class RBFTransactionState {
3335
FINAL,
3436
};
3537

38+
enum class DiagramCheckError {
39+
/** Unable to calculate due to topology or other reason */
40+
UNCALCULABLE,
41+
/** New diagram wasn't strictly superior */
42+
FAILURE,
43+
};
44+
3645
/**
3746
* Determine whether an unconfirmed transaction is signaling opt-in to RBF
3847
* according to BIP 125
@@ -106,4 +115,21 @@ std::optional<std::string> PaysForRBF(CAmount original_fees,
106115
CFeeRate relay_fee,
107116
const uint256& txid);
108117

118+
/**
119+
* The replacement transaction must improve the feerate diagram of the mempool.
120+
* @param[in] pool The mempool.
121+
* @param[in] direct_conflicts Set of in-mempool txids corresponding to the direct conflicts i.e.
122+
* input double-spends with the proposed transaction
123+
* @param[in] all_conflicts Set of mempool entries corresponding to all transactions to be evicted
124+
* @param[in] replacement_fees Fees of proposed replacement package
125+
* @param[in] replacement_vsize Size of proposed replacement package
126+
* @returns error type and string if mempool diagram doesn't improve, otherwise std::nullopt.
127+
*/
128+
std::optional<std::pair<DiagramCheckError, std::string>> ImprovesFeerateDiagram(CTxMemPool& pool,
129+
const CTxMemPool::setEntries& direct_conflicts,
130+
const CTxMemPool::setEntries& all_conflicts,
131+
CAmount replacement_fees,
132+
int64_t replacement_vsize)
133+
EXCLUSIVE_LOCKS_REQUIRED(pool.cs);
134+
109135
#endif // BITCOIN_POLICY_RBF_H

src/test/feefrac_tests.cpp

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
// Copyright (c) 2024-present 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 <util/feefrac.h>
6+
#include <random.h>
7+
8+
#include <boost/test/unit_test.hpp>
9+
10+
BOOST_AUTO_TEST_SUITE(feefrac_tests)
11+
12+
BOOST_AUTO_TEST_CASE(feefrac_operators)
13+
{
14+
FeeFrac p1{1000, 100}, p2{500, 300};
15+
FeeFrac sum{1500, 400};
16+
FeeFrac diff{500, -200};
17+
FeeFrac empty{0, 0};
18+
FeeFrac zero_fee{0, 1}; // zero-fee allowed
19+
20+
BOOST_CHECK(empty == FeeFrac{}); // same as no-args
21+
22+
BOOST_CHECK(p1 == p1);
23+
BOOST_CHECK(p1 + p2 == sum);
24+
BOOST_CHECK(p1 - p2 == diff);
25+
26+
FeeFrac p3{2000, 200};
27+
BOOST_CHECK(p1 != p3); // feefracs only equal if both fee and size are same
28+
BOOST_CHECK(p2 != p3);
29+
30+
FeeFrac p4{3000, 300};
31+
BOOST_CHECK(p1 == p4-p3);
32+
BOOST_CHECK(p1 + p3 == p4);
33+
34+
// Fee-rate comparison
35+
BOOST_CHECK(p1 > p2);
36+
BOOST_CHECK(p1 >= p2);
37+
BOOST_CHECK(p1 >= p4-p3);
38+
BOOST_CHECK(!(p1 >> p3)); // not strictly better
39+
BOOST_CHECK(p1 >> p2); // strictly greater feerate
40+
41+
BOOST_CHECK(p2 < p1);
42+
BOOST_CHECK(p2 <= p1);
43+
BOOST_CHECK(p1 <= p4-p3);
44+
BOOST_CHECK(!(p3 << p1)); // not strictly worse
45+
BOOST_CHECK(p2 << p1); // strictly lower feerate
46+
47+
// "empty" comparisons
48+
BOOST_CHECK(!(p1 >> empty)); // << will always result in false
49+
BOOST_CHECK(!(p1 << empty));
50+
BOOST_CHECK(!(empty >> empty));
51+
BOOST_CHECK(!(empty << empty));
52+
53+
// empty is always bigger than everything else
54+
BOOST_CHECK(empty > p1);
55+
BOOST_CHECK(empty > p2);
56+
BOOST_CHECK(empty > p3);
57+
BOOST_CHECK(empty >= p1);
58+
BOOST_CHECK(empty >= p2);
59+
BOOST_CHECK(empty >= p3);
60+
61+
// check "max" values for comparison
62+
FeeFrac oversized_1{4611686000000, 4000000};
63+
FeeFrac oversized_2{184467440000000, 100000};
64+
65+
BOOST_CHECK(oversized_1 < oversized_2);
66+
BOOST_CHECK(oversized_1 <= oversized_2);
67+
BOOST_CHECK(oversized_1 << oversized_2);
68+
BOOST_CHECK(oversized_1 != oversized_2);
69+
70+
// Tests paths that use double arithmetic
71+
FeeFrac busted{(static_cast<int64_t>(INT32_MAX)) + 1, INT32_MAX};
72+
BOOST_CHECK(!(busted < busted));
73+
74+
FeeFrac max_fee{2100000000000000, INT32_MAX};
75+
BOOST_CHECK(!(max_fee < max_fee));
76+
BOOST_CHECK(!(max_fee > max_fee));
77+
BOOST_CHECK(max_fee <= max_fee);
78+
BOOST_CHECK(max_fee >= max_fee);
79+
80+
FeeFrac max_fee2{1, 1};
81+
BOOST_CHECK(max_fee >= max_fee2);
82+
83+
}
84+
85+
BOOST_AUTO_TEST_CASE(build_diagram_test)
86+
{
87+
FeeFrac p1{1000, 100};
88+
FeeFrac empty{0, 0};
89+
FeeFrac zero_fee{0, 1};
90+
FeeFrac oversized_1{4611686000000, 4000000};
91+
FeeFrac oversized_2{184467440000000, 100000};
92+
93+
// Diagram-building will reorder chunks
94+
std::vector<FeeFrac> chunks;
95+
chunks.push_back(p1);
96+
chunks.push_back(zero_fee);
97+
chunks.push_back(empty);
98+
chunks.push_back(oversized_1);
99+
chunks.push_back(oversized_2);
100+
101+
// Caller in charge of sorting chunks in case chunk size limit
102+
// differs from cluster size limit
103+
std::sort(chunks.begin(), chunks.end(), [](const FeeFrac& a, const FeeFrac& b) { return a > b; });
104+
105+
// Chunks are now sorted in reverse order (largest first)
106+
BOOST_CHECK(chunks[0] == empty); // empty is considered "highest" fee
107+
BOOST_CHECK(chunks[1] == oversized_2);
108+
BOOST_CHECK(chunks[2] == oversized_1);
109+
BOOST_CHECK(chunks[3] == p1);
110+
BOOST_CHECK(chunks[4] == zero_fee);
111+
112+
std::vector<FeeFrac> generated_diagram{BuildDiagramFromChunks(chunks)};
113+
BOOST_CHECK(generated_diagram.size() == 1 + chunks.size());
114+
115+
// Prepended with an empty, then the chunks summed in order as above
116+
BOOST_CHECK(generated_diagram[0] == empty);
117+
BOOST_CHECK(generated_diagram[1] == empty);
118+
BOOST_CHECK(generated_diagram[2] == oversized_2);
119+
BOOST_CHECK(generated_diagram[3] == oversized_2 + oversized_1);
120+
BOOST_CHECK(generated_diagram[4] == oversized_2 + oversized_1 + p1);
121+
BOOST_CHECK(generated_diagram[5] == oversized_2 + oversized_1 + p1 + zero_fee);
122+
}
123+
124+
BOOST_AUTO_TEST_SUITE_END()

src/test/fuzz/feefrac.cpp

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// Copyright (c) 2024 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 <util/feefrac.h>
6+
#include <test/fuzz/FuzzedDataProvider.h>
7+
#include <test/fuzz/fuzz.h>
8+
#include <test/fuzz/util.h>
9+
10+
#include <compare>
11+
#include <cstdint>
12+
#include <iostream>
13+
14+
namespace {
15+
16+
/** Compute a * b, represented in 4x32 bits, highest limb first. */
17+
std::array<uint32_t, 4> Mul128(uint64_t a, uint64_t b)
18+
{
19+
std::array<uint32_t, 4> ret{0, 0, 0, 0};
20+
21+
/** Perform ret += v << (32 * pos), at 128-bit precision. */
22+
auto add_fn = [&](uint64_t v, int pos) {
23+
uint64_t accum{0};
24+
for (int i = 0; i + pos < 4; ++i) {
25+
// Add current value at limb pos in ret.
26+
accum += ret[3 - pos - i];
27+
// Add low or high half of v.
28+
if (i == 0) accum += v & 0xffffffff;
29+
if (i == 1) accum += v >> 32;
30+
// Store lower half of result in limb pos in ret.
31+
ret[3 - pos - i] = accum & 0xffffffff;
32+
// Leave carry in accum.
33+
accum >>= 32;
34+
}
35+
// Make sure no overflow.
36+
assert(accum == 0);
37+
};
38+
39+
// Multiply the 4 individual limbs (schoolbook multiply, with base 2^32).
40+
add_fn((a & 0xffffffff) * (b & 0xffffffff), 0);
41+
add_fn((a >> 32) * (b & 0xffffffff), 1);
42+
add_fn((a & 0xffffffff) * (b >> 32), 1);
43+
add_fn((a >> 32) * (b >> 32), 2);
44+
return ret;
45+
}
46+
47+
/* comparison helper for std::array */
48+
std::strong_ordering compare_arrays(const std::array<uint32_t, 4>& a, const std::array<uint32_t, 4>& b) {
49+
for (size_t i = 0; i < a.size(); ++i) {
50+
if (a[i] != b[i]) return a[i] <=> b[i];
51+
}
52+
return std::strong_ordering::equal;
53+
}
54+
55+
std::strong_ordering MulCompare(int64_t a1, int64_t a2, int64_t b1, int64_t b2)
56+
{
57+
// Compute and compare signs.
58+
int sign_a = (a1 == 0 ? 0 : a1 < 0 ? -1 : 1) * (a2 == 0 ? 0 : a2 < 0 ? -1 : 1);
59+
int sign_b = (b1 == 0 ? 0 : b1 < 0 ? -1 : 1) * (b2 == 0 ? 0 : b2 < 0 ? -1 : 1);
60+
if (sign_a != sign_b) return sign_a <=> sign_b;
61+
62+
// Compute absolute values.
63+
uint64_t abs_a1 = static_cast<uint64_t>(a1), abs_a2 = static_cast<uint64_t>(a2);
64+
uint64_t abs_b1 = static_cast<uint64_t>(b1), abs_b2 = static_cast<uint64_t>(b2);
65+
// Use (~x + 1) instead of the equivalent (-x) to silence the linter; mod 2^64 behavior is
66+
// intentional here.
67+
if (a1 < 0) abs_a1 = ~abs_a1 + 1;
68+
if (a2 < 0) abs_a2 = ~abs_a2 + 1;
69+
if (b1 < 0) abs_b1 = ~abs_b1 + 1;
70+
if (b2 < 0) abs_b2 = ~abs_b2 + 1;
71+
72+
// Compute products of absolute values.
73+
auto mul_abs_a = Mul128(abs_a1, abs_a2);
74+
auto mul_abs_b = Mul128(abs_b1, abs_b2);
75+
if (sign_a < 0) {
76+
return compare_arrays(mul_abs_b, mul_abs_a);
77+
} else {
78+
return compare_arrays(mul_abs_a, mul_abs_b);
79+
}
80+
}
81+
82+
} // namespace
83+
84+
FUZZ_TARGET(feefrac)
85+
{
86+
FuzzedDataProvider provider(buffer.data(), buffer.size());
87+
88+
int64_t f1 = provider.ConsumeIntegral<int64_t>();
89+
int32_t s1 = provider.ConsumeIntegral<int32_t>();
90+
if (s1 == 0) f1 = 0;
91+
FeeFrac fr1(f1, s1);
92+
assert(fr1.IsEmpty() == (s1 == 0));
93+
94+
int64_t f2 = provider.ConsumeIntegral<int64_t>();
95+
int32_t s2 = provider.ConsumeIntegral<int32_t>();
96+
if (s2 == 0) f2 = 0;
97+
FeeFrac fr2(f2, s2);
98+
assert(fr2.IsEmpty() == (s2 == 0));
99+
100+
// Feerate comparisons
101+
auto cmp_feerate = MulCompare(f1, s2, f2, s1);
102+
assert(FeeRateCompare(fr1, fr2) == cmp_feerate);
103+
assert((fr1 << fr2) == std::is_lt(cmp_feerate));
104+
assert((fr1 >> fr2) == std::is_gt(cmp_feerate));
105+
106+
// Compare with manual invocation of FeeFrac::Mul.
107+
auto cmp_mul = FeeFrac::Mul(f1, s2) <=> FeeFrac::Mul(f2, s1);
108+
assert(cmp_mul == cmp_feerate);
109+
110+
// Same, but using FeeFrac::MulFallback.
111+
auto cmp_fallback = FeeFrac::MulFallback(f1, s2) <=> FeeFrac::MulFallback(f2, s1);
112+
assert(cmp_fallback == cmp_feerate);
113+
114+
// Total order comparisons
115+
auto cmp_total = std::is_eq(cmp_feerate) ? (s2 <=> s1) : cmp_feerate;
116+
assert((fr1 <=> fr2) == cmp_total);
117+
assert((fr1 < fr2) == std::is_lt(cmp_total));
118+
assert((fr1 > fr2) == std::is_gt(cmp_total));
119+
assert((fr1 <= fr2) == std::is_lteq(cmp_total));
120+
assert((fr1 >= fr2) == std::is_gteq(cmp_total));
121+
assert((fr1 == fr2) == std::is_eq(cmp_total));
122+
assert((fr1 != fr2) == std::is_neq(cmp_total));
123+
}

0 commit comments

Comments
 (0)