Skip to content

Commit 1af72e7

Browse files
committed
Merge bitcoin/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 #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: #4818 and #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
2 parents 8cc65f0 + 67b7fec commit 1af72e7

File tree

7 files changed

+154
-2
lines changed

7 files changed

+154
-2
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
@@ -480,6 +480,40 @@ static RPCHelpMan prioritisetransaction()
480480
};
481481
}
482482

483+
static RPCHelpMan getprioritisedtransactions()
484+
{
485+
return RPCHelpMan{"getprioritisedtransactions",
486+
"Returns a map of all user-created (see prioritisetransaction) fee deltas by txid, and whether the tx is present in mempool.",
487+
{},
488+
RPCResult{
489+
RPCResult::Type::OBJ_DYN, "prioritisation-map", "prioritisation keyed by txid",
490+
{
491+
{RPCResult::Type::OBJ, "txid", "", {
492+
{RPCResult::Type::NUM, "fee_delta", "transaction fee delta in satoshis"},
493+
{RPCResult::Type::BOOL, "in_mempool", "whether this transaction is currently in mempool"},
494+
}}
495+
},
496+
},
497+
RPCExamples{
498+
HelpExampleCli("getprioritisedtransactions", "")
499+
+ HelpExampleRpc("getprioritisedtransactions", "")
500+
},
501+
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
502+
{
503+
NodeContext& node = EnsureAnyNodeContext(request.context);
504+
CTxMemPool& mempool = EnsureMemPool(node);
505+
UniValue rpc_result{UniValue::VOBJ};
506+
for (const auto& delta_info : mempool.GetPrioritisedTransactions()) {
507+
UniValue result_inner{UniValue::VOBJ};
508+
result_inner.pushKV("fee_delta", delta_info.delta);
509+
result_inner.pushKV("in_mempool", delta_info.in_mempool);
510+
rpc_result.pushKV(delta_info.txid.GetHex(), result_inner);
511+
}
512+
return rpc_result;
513+
},
514+
};
515+
}
516+
483517

484518
// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
485519
static UniValue BIP22ValidationResult(const BlockValidationState& state)
@@ -1048,6 +1082,7 @@ void RegisterMiningRPCCommands(CRPCTable& t)
10481082
{"mining", &getnetworkhashps},
10491083
{"mining", &getmininginfo},
10501084
{"mining", &prioritisetransaction},
1085+
{"mining", &getprioritisedtransactions},
10511086
{"mining", &getblocktemplate},
10521087
{"mining", &submitblock},
10531088
{"mining", &submitheader},

src/test/fuzz/rpc.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ const std::vector<std::string> RPC_COMMANDS_SAFE_FOR_FUZZING{
136136
"getnetworkinfo",
137137
"getnodeaddresses",
138138
"getpeerinfo",
139+
"getprioritisedtransactions",
139140
"getrawmempool",
140141
"getrawtransaction",
141142
"getrpcinfo",

src/txmempool.cpp

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -876,8 +876,17 @@ void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeD
876876
}
877877
++nTransactionsUpdated;
878878
}
879+
if (delta == 0) {
880+
mapDeltas.erase(hash);
881+
LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
882+
} else {
883+
LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
884+
hash.ToString(),
885+
it == mapTx.end() ? "not " : "",
886+
FormatMoney(nFeeDelta),
887+
FormatMoney(delta));
888+
}
879889
}
880-
LogPrintf("PrioritiseTransaction: %s fee += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
881890
}
882891

883892
void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const
@@ -896,6 +905,22 @@ void CTxMemPool::ClearPrioritisation(const uint256& hash)
896905
mapDeltas.erase(hash);
897906
}
898907

908+
std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
909+
{
910+
AssertLockNotHeld(cs);
911+
LOCK(cs);
912+
std::vector<delta_info> result;
913+
result.reserve(mapDeltas.size());
914+
for (const auto& [txid, delta] : mapDeltas) {
915+
const auto iter{mapTx.find(txid)};
916+
const bool in_mempool{iter != mapTx.end()};
917+
std::optional<CAmount> modified_fee;
918+
if (in_mempool) modified_fee = iter->GetModifiedFee();
919+
result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
920+
}
921+
return result;
922+
}
923+
899924
const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
900925
{
901926
const auto it = mapNextTx.find(prevout);

src/txmempool.h

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

519+
struct delta_info {
520+
/** Whether this transaction is in the mempool. */
521+
const bool in_mempool;
522+
/** The fee delta added using PrioritiseTransaction(). */
523+
const CAmount delta;
524+
/** The modified fee (base fee + delta) of this entry. Only present if in_mempool=true. */
525+
std::optional<CAmount> modified_fee;
526+
/** The prioritised transaction's txid. */
527+
const uint256 txid;
528+
};
529+
/** Return a vector of all entries in mapDeltas with their corresponding delta_info. */
530+
std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
531+
519532
/** Get the transaction in the pool that spends the same prevout */
520533
const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
521534

test/functional/mempool_expiry.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@
1212

1313
from datetime import timedelta
1414

15-
from test_framework.messages import DEFAULT_MEMPOOL_EXPIRY_HOURS
15+
from test_framework.messages import (
16+
COIN,
17+
DEFAULT_MEMPOOL_EXPIRY_HOURS,
18+
)
1619
from test_framework.test_framework import BitcoinTestFramework
1720
from test_framework.util import (
1821
assert_equal,
@@ -37,6 +40,10 @@ def test_transaction_expiry(self, timeout):
3740
parent_utxo = self.wallet.get_utxo(txid=parent_txid)
3841
independent_utxo = self.wallet.get_utxo()
3942

43+
# Add prioritisation to this transaction to check that it persists after the expiry
44+
node.prioritisetransaction(parent_txid, 0, COIN)
45+
assert_equal(node.getprioritisedtransactions()[parent_txid], { "fee_delta" : COIN, "in_mempool" : True})
46+
4047
# Ensure the transactions we send to trigger the mempool check spend utxos that are independent of
4148
# the transactions being tested for expiration.
4249
trigger_utxo1 = self.wallet.get_utxo()
@@ -79,6 +86,9 @@ def test_transaction_expiry(self, timeout):
7986
assert_raises_rpc_error(-5, 'Transaction not in mempool',
8087
node.getmempoolentry, parent_txid)
8188

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

test/functional/mining_prioritisetransaction.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,33 @@ def set_test_params(self):
3030
]] * self.num_nodes
3131
self.supports_cli = False
3232

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+
3360
def test_diamond(self):
3461
self.log.info("Test diamond-shape package with priority")
3562
mock_time = int(time.time())
@@ -84,6 +111,13 @@ def test_diamond(self):
84111
raw_after = self.nodes[0].getrawmempool(verbose=True)
85112
assert_equal(raw_before[txid_a], raw_after[txid_a])
86113
assert_equal(raw_before, raw_after)
114+
prioritisation_map_in_mempool = self.nodes[0].getprioritisedtransactions()
115+
assert_equal(prioritisation_map_in_mempool[txid_b], {"fee_delta" : fee_delta_b*COIN, "in_mempool" : True})
116+
assert_equal(prioritisation_map_in_mempool[txid_c], {"fee_delta" : (fee_delta_c_1 + fee_delta_c_2)*COIN, "in_mempool" : True})
117+
# Clear prioritisation, otherwise the transactions' fee deltas are persisted to mempool.dat and loaded again when the node
118+
# is restarted at the end of this subtest. Deltas are removed when a transaction is mined, but only at that time. We do
119+
# not check whether mapDeltas transactions were mined when loading from mempool.dat.
120+
self.clear_prioritisation(node=self.nodes[0])
87121

88122
self.log.info("Test priority while txs are not in mempool")
89123
self.restart_node(0, extra_args=["-nopersistmempool"])
@@ -92,17 +126,26 @@ def test_diamond(self):
92126
self.nodes[0].prioritisetransaction(txid=txid_b, fee_delta=int(fee_delta_b * COIN))
93127
self.nodes[0].prioritisetransaction(txid=txid_c, fee_delta=int(fee_delta_c_1 * COIN))
94128
self.nodes[0].prioritisetransaction(txid=txid_c, fee_delta=int(fee_delta_c_2 * COIN))
129+
prioritisation_map_not_in_mempool = self.nodes[0].getprioritisedtransactions()
130+
assert_equal(prioritisation_map_not_in_mempool[txid_b], {"fee_delta" : fee_delta_b*COIN, "in_mempool" : False})
131+
assert_equal(prioritisation_map_not_in_mempool[txid_c], {"fee_delta" : (fee_delta_c_1 + fee_delta_c_2)*COIN, "in_mempool" : False})
95132
for t in [tx_o_a["hex"], tx_o_b["hex"], tx_o_c["hex"], tx_o_d["hex"]]:
96133
self.nodes[0].sendrawtransaction(t)
97134
raw_after = self.nodes[0].getrawmempool(verbose=True)
98135
assert_equal(raw_before[txid_a], raw_after[txid_a])
99136
assert_equal(raw_before, raw_after)
137+
prioritisation_map_in_mempool = self.nodes[0].getprioritisedtransactions()
138+
assert_equal(prioritisation_map_in_mempool[txid_b], {"fee_delta" : fee_delta_b*COIN, "in_mempool" : True})
139+
assert_equal(prioritisation_map_in_mempool[txid_c], {"fee_delta" : (fee_delta_c_1 + fee_delta_c_2)*COIN, "in_mempool" : True})
100140

101141
# Clear mempool
102142
self.generate(self.nodes[0], 1)
143+
# Prioritisation for transactions is automatically deleted after they are mined.
144+
assert_equal(self.nodes[0].getprioritisedtransactions(), {})
103145

104146
# Use default extra_args
105147
self.restart_node(0)
148+
assert_equal(self.nodes[0].getprioritisedtransactions(), {})
106149

107150
def run_test(self):
108151
self.wallet = MiniWallet(self.nodes[0])
@@ -115,6 +158,10 @@ def run_test(self):
115158
# Test `prioritisetransaction` invalid extra parameters
116159
assert_raises_rpc_error(-1, "prioritisetransaction", self.nodes[0].prioritisetransaction, '', 0, 0, 0)
117160

161+
# Test `getprioritisedtransactions` invalid parameters
162+
assert_raises_rpc_error(-1, "getprioritisedtransactions",
163+
self.nodes[0].getprioritisedtransactions, True)
164+
118165
# Test `prioritisetransaction` invalid `txid`
119166
assert_raises_rpc_error(-8, "txid must be of length 64 (not 3, for 'foo')", self.nodes[0].prioritisetransaction, txid='foo', fee_delta=0)
120167
assert_raises_rpc_error(-8, "txid must be hexadecimal string (not 'Zd1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000')", self.nodes[0].prioritisetransaction, txid='Zd1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000', fee_delta=0)
@@ -127,6 +174,7 @@ def run_test(self):
127174
# Test `prioritisetransaction` invalid `fee_delta`
128175
assert_raises_rpc_error(-3, "JSON value of type string is not of expected type number", self.nodes[0].prioritisetransaction, txid=txid, fee_delta='foo')
129176

177+
self.test_replacement()
130178
self.test_diamond()
131179

132180
self.txouts = gen_return_txouts()
@@ -165,9 +213,18 @@ def run_test(self):
165213
sizes[i] += mempool[j]['vsize']
166214
assert sizes[i] > MAX_BLOCK_WEIGHT // 4 # Fail => raise utxo_count
167215

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

172229
self.generate(self.nodes[0], 1)
173230

@@ -187,6 +244,7 @@ def run_test(self):
187244
# Add a prioritisation before a tx is in the mempool (de-prioritising a
188245
# high-fee transaction so that it's now low fee).
189246
self.nodes[0].prioritisetransaction(txid=high_fee_tx, fee_delta=-int(2*base_fee*COIN))
247+
assert_equal(self.nodes[0].getprioritisedtransactions()[high_fee_tx], { "fee_delta" : -2*base_fee*COIN, "in_mempool" : False})
190248

191249
# Add everything back to mempool
192250
self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash())
@@ -206,6 +264,7 @@ def run_test(self):
206264
mempool = self.nodes[0].getrawmempool()
207265
self.log.info("Assert that de-prioritised transaction is still in mempool")
208266
assert high_fee_tx in mempool
267+
assert_equal(self.nodes[0].getprioritisedtransactions()[high_fee_tx], { "fee_delta" : -2*base_fee*COIN, "in_mempool" : True})
209268
for x in txids[2]:
210269
if (x != high_fee_tx):
211270
assert x not in mempool
@@ -223,17 +282,23 @@ def run_test(self):
223282
# to be the minimum for a 1000-byte transaction and check that it is
224283
# accepted.
225284
self.nodes[0].prioritisetransaction(txid=tx_id, fee_delta=int(self.relayfee*COIN))
285+
assert_equal(self.nodes[0].getprioritisedtransactions()[tx_id], { "fee_delta" : self.relayfee*COIN, "in_mempool" : False})
226286

227287
self.log.info("Assert that prioritised free transaction is accepted to mempool")
228288
assert_equal(self.nodes[0].sendrawtransaction(tx_hex), tx_id)
229289
assert tx_id in self.nodes[0].getrawmempool()
290+
assert_equal(self.nodes[0].getprioritisedtransactions()[tx_id], { "fee_delta" : self.relayfee*COIN, "in_mempool" : True})
230291

231292
# Test that calling prioritisetransaction is sufficient to trigger
232293
# getblocktemplate to (eventually) return a new block.
233294
mock_time = int(time.time())
234295
self.nodes[0].setmocktime(mock_time)
235296
template = self.nodes[0].getblocktemplate({'rules': ['segwit']})
236297
self.nodes[0].prioritisetransaction(txid=tx_id, fee_delta=-int(self.relayfee*COIN))
298+
299+
# Calling prioritisetransaction with the inverse amount should delete its prioritisation entry
300+
assert tx_id not in self.nodes[0].getprioritisedtransactions()
301+
237302
self.nodes[0].setmocktime(mock_time+10)
238303
new_template = self.nodes[0].getblocktemplate({'rules': ['segwit']})
239304

0 commit comments

Comments
 (0)