Skip to content

Commit c7baa63

Browse files
achow101Claude Code
authored andcommitted
Merge bitcoin#27501: mempool / rpc: add getprioritisedtransactions, delete a mapDeltas entry when delta==0
67b7fec [mempool] clear mapDeltas entry if prioritisetransaction sets delta to 0 (glozow) c1061ac [functional test] prioritisation is not removed during replacement and expiry (glozow) 0e5874f [functional test] getprioritisedtransactions RPC (glozow) 99f8046 [rpc] add getprioritisedtransactions (glozow) 9e9ca36 [mempool] add GetPrioritisedTransactions (glozow) Pull request description: Add an RPC to get prioritised transactions (also tells you whether the tx is in mempool or not), helping users clean up `mapDeltas` manually. When `CTxMemPool::PrioritiseTransaction` sets a delta to 0, remove the entry from `mapDeltas`. Motivation / Background - `mapDeltas` entries are never removed from mapDeltas except when the tx is mined in a block or conflicted. - Mostly it is a feature to allow `prioritisetransaction` for a tx that isn't in the mempool {yet, anymore}. A user can may resbumit a tx and it retains its priority, or mark a tx as "definitely accept" before it is seen. - Since bitcoin#8448, `mapDeltas` is persisted to mempool.dat and loaded on restart. This is also good, otherwise we lose prioritisation on restart. - Note the removal due to block/conflict is only done when `removeForBlock` is called, i.e. when the block is received. If you load a mempool.dat containing `mapDeltas` with transactions that were mined already (e.g. the file was saved prior to the last few blocks), you don't delete them. - Related: dashpay#4818 and dashpay#6464. - There is no way to query the node for not-in-mempool `mapDeltas`. If you add a priority and forget what the value was, the only way to get that information is to inspect mempool.dat. - Calling `prioritisetransaction` with an inverse value does not remove it from `mapDeltas`, it just sets the value to 0. It disappears on a restart (`LoadMempool` checks if delta is 0), but that might not happen for a while. Added together, if a user calls `prioritisetransaction` very regularly and not all those transactions get mined/conflicted, `mapDeltas` might keep lots of entries of delta=0 around. A user should clean up the not-in-mempool prioritisations, but that's currently difficult without keeping track of what those txids/amounts are. ACKs for top commit: achow101: ACK 67b7fec theStack: Code-review ACK 67b7fec instagibbs: code review ACK 67b7fec ajtowns: ACK 67b7fec code review only, some nits Tree-SHA512: 9df48b622ef27f33db1a2748f682bb3f16abe8172fcb7ac3c1a3e1654121ffb9b31aeaad5570c4162261f7e2ff5b5912ddc61a1b8beac0e9f346a86f5952260a
1 parent 3b3169d commit c7baa63

File tree

7 files changed

+160
-5
lines changed

7 files changed

+160
-5
lines changed

doc/release-notes-27501.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
- A new `getprioritisedtransactions` RPC has been added. It returns a map of all fee deltas created by the
2+
user with prioritisetransaction, indexed by txid. The map also indicates whether each transaction is
3+
present in the mempool.

src/rpc/mining.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,40 @@ static RPCHelpMan prioritisetransaction()
511511
};
512512
}
513513

514+
static RPCHelpMan getprioritisedtransactions()
515+
{
516+
return RPCHelpMan{"getprioritisedtransactions",
517+
"Returns a map of all user-created (see prioritisetransaction) fee deltas by txid, and whether the tx is present in mempool.",
518+
{},
519+
RPCResult{
520+
RPCResult::Type::OBJ_DYN, "prioritisation-map", "prioritisation keyed by txid",
521+
{
522+
{RPCResult::Type::OBJ, "txid", "", {
523+
{RPCResult::Type::NUM, "fee_delta", "transaction fee delta in satoshis"},
524+
{RPCResult::Type::BOOL, "in_mempool", "whether this transaction is currently in mempool"},
525+
}}
526+
},
527+
},
528+
RPCExamples{
529+
HelpExampleCli("getprioritisedtransactions", "")
530+
+ HelpExampleRpc("getprioritisedtransactions", "")
531+
},
532+
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
533+
{
534+
NodeContext& node = EnsureAnyNodeContext(request.context);
535+
CTxMemPool& mempool = EnsureMemPool(node);
536+
UniValue rpc_result{UniValue::VOBJ};
537+
for (const auto& delta_info : mempool.GetPrioritisedTransactions()) {
538+
UniValue result_inner{UniValue::VOBJ};
539+
result_inner.pushKV("fee_delta", delta_info.delta);
540+
result_inner.pushKV("in_mempool", delta_info.in_mempool);
541+
rpc_result.pushKV(delta_info.txid.GetHex(), result_inner);
542+
}
543+
return rpc_result;
544+
},
545+
};
546+
}
547+
514548

515549
// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
516550
static UniValue BIP22ValidationResult(const BlockValidationState& state)
@@ -1101,6 +1135,7 @@ static const CRPCCommand commands[] =
11011135
{ "mining", &getnetworkhashps, },
11021136
{ "mining", &getmininginfo, },
11031137
{ "mining", &prioritisetransaction, },
1138+
{ "mining", &getprioritisedtransactions, },
11041139
{ "mining", &getblocktemplate, },
11051140
{ "mining", &submitblock, },
11061141
{ "mining", &submitheader, },

src/test/fuzz/rpc.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ const std::vector<std::string> RPC_COMMANDS_SAFE_FOR_FUZZING{
133133
"getnetworkinfo",
134134
"getnodeaddresses",
135135
"getpeerinfo",
136+
"getprioritisedtransactions",
136137
"getrawmempool",
137138
"getrawtransaction",
138139
"getrpcinfo",

src/txmempool.cpp

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1457,8 +1457,17 @@ void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeD
14571457
}
14581458
++nTransactionsUpdated;
14591459
}
1460+
if (delta == 0) {
1461+
mapDeltas.erase(hash);
1462+
LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
1463+
} else {
1464+
LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
1465+
hash.ToString(),
1466+
it == mapTx.end() ? "not " : "",
1467+
FormatMoney(nFeeDelta),
1468+
FormatMoney(delta));
1469+
}
14601470
}
1461-
LogPrint(BCLog::MEMPOOL, "PrioritiseTransaction: %s fee += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
14621471
}
14631472

14641473
void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const
@@ -1477,6 +1486,22 @@ void CTxMemPool::ClearPrioritisation(const uint256& hash)
14771486
mapDeltas.erase(hash);
14781487
}
14791488

1489+
std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
1490+
{
1491+
AssertLockNotHeld(cs);
1492+
LOCK(cs);
1493+
std::vector<delta_info> result;
1494+
result.reserve(mapDeltas.size());
1495+
for (const auto& [txid, delta] : mapDeltas) {
1496+
const auto iter{mapTx.find(txid)};
1497+
const bool in_mempool{iter != mapTx.end()};
1498+
std::optional<CAmount> modified_fee;
1499+
if (in_mempool) modified_fee = iter->GetModifiedFee();
1500+
result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
1501+
}
1502+
return result;
1503+
}
1504+
14801505
const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
14811506
{
14821507
const auto it = mapNextTx.find(prevout);

src/txmempool.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,19 @@ class CTxMemPool
656656
void ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
657657
void ClearPrioritisation(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs);
658658

659+
struct delta_info {
660+
/** Whether this transaction is in the mempool. */
661+
const bool in_mempool;
662+
/** The fee delta added using PrioritiseTransaction(). */
663+
const CAmount delta;
664+
/** The modified fee (base fee + delta) of this entry. Only present if in_mempool=true. */
665+
std::optional<CAmount> modified_fee;
666+
/** The prioritised transaction's txid. */
667+
const uint256 txid;
668+
};
669+
/** Return a vector of all entries in mapDeltas with their corresponding delta_info. */
670+
std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
671+
659672
/** Get the transaction in the pool that spends the same prevout */
660673
const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
661674

test/functional/mempool_expiry.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@
1212

1313
from datetime import timedelta
1414

15+
from test_framework.messages import (
16+
COIN,
17+
DEFAULT_MEMPOOL_EXPIRY_HOURS,
18+
)
1519
from test_framework.test_framework import BitcoinTestFramework
1620
from test_framework.util import (
1721
assert_equal,
@@ -43,6 +47,10 @@ def test_transaction_expiry(self, timeout):
4347
parent_utxo = self.wallet.get_utxo(txid=parent_txid)
4448
independent_utxo = self.wallet.get_utxo()
4549

50+
# Add prioritisation to this transaction to check that it persists after the expiry
51+
node.prioritisetransaction(parent_txid, 0, COIN)
52+
assert_equal(node.getprioritisedtransactions()[parent_txid], { "fee_delta" : COIN, "in_mempool" : True})
53+
4654
# Ensure the transactions we send to trigger the mempool check spend utxos that are independent of
4755
# the transactions being tested for expiration.
4856
trigger_utxo1 = self.wallet.get_utxo()
@@ -85,6 +93,9 @@ def test_transaction_expiry(self, timeout):
8593
assert_raises_rpc_error(-5, 'Transaction not in mempool',
8694
node.getmempoolentry, parent_txid)
8795

96+
# Prioritisation does not disappear when transaction expires
97+
assert_equal(node.getprioritisedtransactions()[parent_txid], { "fee_delta" : COIN, "in_mempool" : False})
98+
8899
# The child transaction should be removed from the mempool as well.
89100
self.log.info('Test child tx is evicted as well.')
90101
assert_raises_rpc_error(-5, 'Transaction not in mempool',

test/functional/mining_prioritisetransaction.py

Lines changed: 71 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
55
"""Test the prioritisetransaction mining RPC."""
66

7+
import time
78
from decimal import Decimal
89

910
from test_framework.messages import (
@@ -29,6 +30,33 @@ def set_test_params(self):
2930
]] * self.num_nodes
3031
self.supports_cli = False
3132

33+
def clear_prioritisation(self, node):
34+
for txid, info in node.getprioritisedtransactions().items():
35+
delta = info["fee_delta"]
36+
node.prioritisetransaction(txid, 0, -delta)
37+
assert_equal(node.getprioritisedtransactions(), {})
38+
39+
def test_replacement(self):
40+
self.log.info("Test tx prioritisation stays after a tx is replaced")
41+
conflicting_input = self.wallet.get_utxo()
42+
tx_replacee = self.wallet.create_self_transfer(utxo_to_spend=conflicting_input, fee_rate=Decimal("0.0001"))
43+
tx_replacement = self.wallet.create_self_transfer(utxo_to_spend=conflicting_input, fee_rate=Decimal("0.005"))
44+
# Add 1 satoshi fee delta to replacee
45+
self.nodes[0].prioritisetransaction(tx_replacee["txid"], 0, 100)
46+
assert_equal(self.nodes[0].getprioritisedtransactions(), { tx_replacee["txid"] : { "fee_delta" : 100, "in_mempool" : False}})
47+
self.nodes[0].sendrawtransaction(tx_replacee["hex"])
48+
assert_equal(self.nodes[0].getprioritisedtransactions(), { tx_replacee["txid"] : { "fee_delta" : 100, "in_mempool" : True}})
49+
self.nodes[0].sendrawtransaction(tx_replacement["hex"])
50+
assert tx_replacee["txid"] not in self.nodes[0].getrawmempool()
51+
assert_equal(self.nodes[0].getprioritisedtransactions(), { tx_replacee["txid"] : { "fee_delta" : 100, "in_mempool" : False}})
52+
53+
# PrioritiseTransaction is additive
54+
self.nodes[0].prioritisetransaction(tx_replacee["txid"], 0, COIN)
55+
self.nodes[0].sendrawtransaction(tx_replacee["hex"])
56+
assert_equal(self.nodes[0].getprioritisedtransactions(), { tx_replacee["txid"] : { "fee_delta" : COIN + 100, "in_mempool" : True}})
57+
self.generate(self.nodes[0], 1)
58+
assert_equal(self.nodes[0].getprioritisedtransactions(), {})
59+
3260
def test_diamond(self):
3361
self.log.info("Test diamond-shape package with priority")
3462
self.nodes[0].setmocktime(self.mocktime)
@@ -82,6 +110,13 @@ def test_diamond(self):
82110
raw_after = self.nodes[0].getrawmempool(verbose=True)
83111
assert_equal(raw_before[txid_a], raw_after[txid_a])
84112
assert_equal(raw_before, raw_after)
113+
prioritisation_map_in_mempool = self.nodes[0].getprioritisedtransactions()
114+
assert_equal(prioritisation_map_in_mempool[txid_b], {"fee_delta" : fee_delta_b*COIN, "in_mempool" : True})
115+
assert_equal(prioritisation_map_in_mempool[txid_c], {"fee_delta" : (fee_delta_c_1 + fee_delta_c_2)*COIN, "in_mempool" : True})
116+
# Clear prioritisation, otherwise the transactions' fee deltas are persisted to mempool.dat and loaded again when the node
117+
# is restarted at the end of this subtest. Deltas are removed when a transaction is mined, but only at that time. We do
118+
# not check whether mapDeltas transactions were mined when loading from mempool.dat.
119+
self.clear_prioritisation(node=self.nodes[0])
85120

86121
self.log.info("Test priority while txs are not in mempool")
87122
self.restart_node(0, extra_args=["-nopersistmempool"])
@@ -90,19 +125,29 @@ def test_diamond(self):
90125
self.nodes[0].prioritisetransaction(txid=txid_b, fee_delta=int(fee_delta_b * COIN))
91126
self.nodes[0].prioritisetransaction(txid=txid_c, fee_delta=int(fee_delta_c_1 * COIN))
92127
self.nodes[0].prioritisetransaction(txid=txid_c, fee_delta=int(fee_delta_c_2 * COIN))
128+
prioritisation_map_not_in_mempool = self.nodes[0].getprioritisedtransactions()
129+
assert_equal(prioritisation_map_not_in_mempool[txid_b], {"fee_delta" : fee_delta_b*COIN, "in_mempool" : False})
130+
assert_equal(prioritisation_map_not_in_mempool[txid_c], {"fee_delta" : (fee_delta_c_1 + fee_delta_c_2)*COIN, "in_mempool" : False})
93131
for t in [tx_o_a["hex"], tx_o_b["hex"], tx_o_c["hex"], tx_o_d["hex"]]:
94132
self.nodes[0].sendrawtransaction(t)
95133
raw_after = self.nodes[0].getrawmempool(verbose=True)
96134
assert_equal(raw_before[txid_a], raw_after[txid_a])
97135
assert_equal(raw_before, raw_after)
136+
prioritisation_map_in_mempool = self.nodes[0].getprioritisedtransactions()
137+
assert_equal(prioritisation_map_in_mempool[txid_b], {"fee_delta" : fee_delta_b*COIN, "in_mempool" : True})
138+
assert_equal(prioritisation_map_in_mempool[txid_c], {"fee_delta" : (fee_delta_c_1 + fee_delta_c_2)*COIN, "in_mempool" : True})
98139

99140
# Clear mempool
100141
self.generate(self.nodes[0], 1)
142+
# Prioritisation for transactions is automatically deleted after they are mined.
143+
assert_equal(self.nodes[0].getprioritisedtransactions(), {})
101144

102145
# Use default extra_args
103146
self.restart_node(0)
147+
assert_equal(self.nodes[0].getprioritisedtransactions(), {})
104148

105149
def run_test(self):
150+
self.mocktime = int(time.time())
106151
self.wallet = MiniWallet(self.nodes[0])
107152
self.wallet.rescan_utxos()
108153

@@ -113,6 +158,10 @@ def run_test(self):
113158
# Test `prioritisetransaction` invalid extra parameters
114159
assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction, '', 0, 0)
115160

161+
# Test `getprioritisedtransactions` invalid parameters
162+
assert_raises_rpc_error(-1, "getprioritisedtransactions",
163+
self.nodes[0].getprioritisedtransactions, True)
164+
116165
# Test `prioritisetransaction` invalid `txid`
117166
assert_raises_rpc_error(-8, "txid must be of length 64 (not 3, for 'foo')", self.nodes[0].prioritisetransaction, txid='foo', fee_delta=0)
118167
assert_raises_rpc_error(-8, "txid must be hexadecimal string (not 'Zd1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000')", self.nodes[0].prioritisetransaction, txid='Zd1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000', fee_delta=0)
@@ -122,6 +171,7 @@ def run_test(self):
122171
# Test `prioritisetransaction` invalid `fee_delta`
123172
assert_raises_rpc_error(-1, "JSON value is not an integer as expected", self.nodes[0].prioritisetransaction, txid=txid, fee_delta='foo')
124173

174+
self.test_replacement()
125175
self.test_diamond()
126176

127177
self.txouts = gen_return_txouts()
@@ -160,9 +210,18 @@ def run_test(self):
160210
sizes[i] += mempool[j]['vsize']
161211
assert sizes[i] > MAX_BLOCK_SIZE # Fail => raise utxo_count
162212

213+
assert_equal(self.nodes[0].getprioritisedtransactions(), {})
163214
# add a fee delta to something in the cheapest bucket and make sure it gets mined
164215
# also check that a different entry in the cheapest bucket is NOT mined
165-
self.nodes[0].prioritisetransaction(txids[0][0], int(3*base_fee*COIN))
216+
self.nodes[0].prioritisetransaction(txid=txids[0][0], fee_delta=int(3*base_fee*COIN))
217+
assert_equal(self.nodes[0].getprioritisedtransactions(), {txids[0][0] : { "fee_delta" : 3*base_fee*COIN, "in_mempool" : True}})
218+
219+
# Priority disappears when prioritisetransaction is called with an inverse value...
220+
self.nodes[0].prioritisetransaction(txid=txids[0][0], fee_delta=int(-3*base_fee*COIN))
221+
assert txids[0][0] not in self.nodes[0].getprioritisedtransactions()
222+
# ... and reappears when prioritisetransaction is called again.
223+
self.nodes[0].prioritisetransaction(txid=txids[0][0], fee_delta=int(3*base_fee*COIN))
224+
assert txids[0][0] in self.nodes[0].getprioritisedtransactions()
166225

167226
self.generate(self.nodes[0], 1)
168227

@@ -181,7 +240,8 @@ def run_test(self):
181240

182241
# Add a prioritisation before a tx is in the mempool (de-prioritising a
183242
# high-fee transaction so that it's now low fee).
184-
self.nodes[0].prioritisetransaction(high_fee_tx, -int(2*base_fee*COIN))
243+
self.nodes[0].prioritisetransaction(txid=high_fee_tx, fee_delta=-int(2*base_fee*COIN))
244+
assert_equal(self.nodes[0].getprioritisedtransactions()[high_fee_tx], { "fee_delta" : -2*base_fee*COIN, "in_mempool" : False})
185245

186246
# Add everything back to mempool
187247
self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())
@@ -201,6 +261,7 @@ def run_test(self):
201261
mempool = self.nodes[0].getrawmempool()
202262
self.log.info("Assert that de-prioritised transaction is still in mempool")
203263
assert high_fee_tx in mempool
264+
assert_equal(self.nodes[0].getprioritisedtransactions()[high_fee_tx], { "fee_delta" : -2*base_fee*COIN, "in_mempool" : True})
204265
for x in txids[2]:
205266
if (x != high_fee_tx):
206267
assert x not in mempool
@@ -217,17 +278,23 @@ def run_test(self):
217278
# This is a less than 1000-byte transaction, so just set the fee
218279
# to be the minimum for a 1000-byte transaction and check that it is
219280
# accepted.
220-
self.nodes[0].prioritisetransaction(tx_id, int(self.relayfee*COIN))
281+
self.nodes[0].prioritisetransaction(txid=tx_id, fee_delta=int(self.relayfee*COIN))
282+
assert_equal(self.nodes[0].getprioritisedtransactions()[tx_id], { "fee_delta" : self.relayfee*COIN, "in_mempool" : False})
221283

222284
self.log.info("Assert that prioritised free transaction is accepted to mempool")
223285
assert_equal(self.nodes[0].sendrawtransaction(tx_hex), tx_id)
224286
assert tx_id in self.nodes[0].getrawmempool()
287+
assert_equal(self.nodes[0].getprioritisedtransactions()[tx_id], { "fee_delta" : self.relayfee*COIN, "in_mempool" : True})
225288

226289
# Test that calling prioritisetransaction is sufficient to trigger
227290
# getblocktemplate to (eventually) return a new block.
228291
self.nodes[0].setmocktime(self.mocktime)
229292
template = self.nodes[0].getblocktemplate()
230-
self.nodes[0].prioritisetransaction(tx_id, -int(self.relayfee*COIN))
293+
self.nodes[0].prioritisetransaction(txid=tx_id, fee_delta=-int(self.relayfee*COIN))
294+
295+
# Calling prioritisetransaction with the inverse amount should delete its prioritisation entry
296+
assert tx_id not in self.nodes[0].getprioritisedtransactions()
297+
231298
self.nodes[0].setmocktime(self.mocktime+10)
232299
new_template = self.nodes[0].getblocktemplate()
233300

0 commit comments

Comments
 (0)