Coverage Report

Created: 2026-10-19 15:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/rpc/mempool.cpp
Line
Count
Source
1
// Copyright (c) 2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <rpc/mempool.h>
7
#include <rpc/register.h> // IWYU pragma: associated
8
9
#include <common/args.h>
10
#include <consensus/amount.h>
11
#include <consensus/validation.h>
12
#include <core_io.h>
13
#include <index/txospenderindex.h>
14
#include <net.h>
15
#include <net_processing.h>
16
#include <netaddress.h>
17
#include <netbase.h>
18
#include <node/mempool_persist.h>
19
#include <node/mempool_persist_args.h>
20
#include <node/transaction.h>
21
#include <node/txorphanage.h>
22
#include <node/types.h>
23
#include <policy/feerate.h>
24
#include <policy/packages.h>
25
#include <policy/policy.h>
26
#include <policy/rbf.h>
27
#include <primitives/transaction.h>
28
#include <rpc/protocol.h>
29
#include <rpc/request.h>
30
#include <rpc/server.h>
31
#include <rpc/server_util.h>
32
#include <rpc/util.h>
33
#include <script/script.h>
34
#include <sync.h>
35
#include <tinyformat.h>
36
#include <txgraph.h>
37
#include <txmempool.h>
38
#include <uint256.h>
39
#include <univalue.h>
40
#include <util/check.h>
41
#include <util/expected.h>
42
#include <util/feefrac.h>
43
#include <util/fs.h>
44
#include <util/moneystr.h>
45
#include <util/string.h>
46
#include <util/time.h>
47
#include <util/vector.h>
48
#include <validation.h>
49
50
#include <algorithm>
51
#include <cstddef>
52
#include <cstdint>
53
#include <functional>
54
#include <list>
55
#include <map>
56
#include <memory>
57
#include <optional>
58
#include <ranges>
59
#include <set>
60
#include <string>
61
#include <string_view>
62
#include <tuple>
63
#include <utility>
64
#include <vector>
65
66
namespace node {
67
struct NodeContext;
68
} // namespace node
69
70
using node::DumpMempool;
71
72
using node::DEFAULT_MAX_BURN_AMOUNT;
73
using node::DEFAULT_MAX_RAW_TX_FEE_RATE;
74
using node::MempoolPath;
75
using node::NodeContext;
76
using node::TransactionError;
77
using util::ToString;
78
79
static RPCMethod sendrawtransaction()
80
39.9k
{
81
39.9k
    return RPCMethod{
82
39.9k
        "sendrawtransaction",
83
39.9k
        "Submit a raw transaction (serialized, hex-encoded) to the network.\n"
84
85
39.9k
        "\nIf -privatebroadcast is disabled, then the transaction will be put into the\n"
86
39.9k
        "local mempool of the node and will be sent unconditionally to all currently\n"
87
39.9k
        "connected peers, so using sendrawtransaction for manual rebroadcast will degrade\n"
88
39.9k
        "privacy by leaking the transaction's origin, as nodes will normally not\n"
89
39.9k
        "rebroadcast non-wallet transactions already in their mempool.\n"
90
91
39.9k
        "\nIf -privatebroadcast is enabled, then the transaction will be sent via\n"
92
39.9k
        "dedicated, short-lived connections to Tor or I2P peers, or to IPv4/IPv6 peers\n"
93
39.9k
        "via the Tor network. This provides best-effort concealment of the transaction's origin.\n"
94
39.9k
        "Private broadcast is experimental and may change in future releases.\n"
95
39.9k
        "Submission does not itself add the transaction to the local mempool; normal\n"
96
39.9k
        "mempool acceptance and relay apply when it is received back from the network.\n"
97
39.9k
        "The private broadcast queue is bounded: when it is full, this RPC fails and\n"
98
39.9k
        "the transaction is not scheduled until an existing one completes or is\n"
99
39.9k
        "aborted. Use getprivatebroadcastinfo to inspect the queue and abortprivatebroadcast to abort.\n"
100
101
39.9k
        "\nA specific exception, RPC_TRANSACTION_ALREADY_IN_UTXO_SET, may throw if the transaction cannot be added to the mempool.\n"
102
103
39.9k
        "\nRelated RPCs: createrawtransaction, signrawtransactionwithkey\n",
104
39.9k
        {
105
39.9k
            {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of the raw transaction"},
106
39.9k
            {"maxfeerate", RPCArg::Type::AMOUNT, RPCArg::Default{FormatMoney(DEFAULT_MAX_RAW_TX_FEE_RATE.GetFeePerK())},
107
39.9k
             "Reject transactions whose fee rate is higher than the specified value, expressed in " + CURRENCY_UNIT +
108
39.9k
                 "/kvB.\nFee rates larger than 1BTC/kvB are rejected.\nSet to 0 to accept any fee rate."},
109
39.9k
            {"maxburnamount", RPCArg::Type::AMOUNT, RPCArg::Default{FormatMoney(DEFAULT_MAX_BURN_AMOUNT)},
110
39.9k
             "Reject transactions with provably unspendable outputs (e.g. 'datacarrier' outputs that use the OP_RETURN opcode) greater than the specified value, expressed in " + CURRENCY_UNIT + ".\n"
111
39.9k
             "If burning funds through unspendable outputs is desired, increase this value.\n"
112
39.9k
             "This check is based on heuristics and does not guarantee spendability of outputs.\n"},
113
39.9k
        },
114
39.9k
        RPCResult{
115
39.9k
            RPCResult::Type::STR_HEX, "", "The transaction hash in hex"
116
39.9k
        },
117
39.9k
        RPCExamples{
118
39.9k
            "\nCreate a transaction\n"
119
39.9k
            + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
120
39.9k
            "Sign the transaction, and get back the hex\n"
121
39.9k
            + HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
122
39.9k
            "\nSend the transaction (signed hex)\n"
123
39.9k
            + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
124
39.9k
            "\nAs a JSON-RPC call\n"
125
39.9k
            + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
126
39.9k
                },
127
39.9k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
128
39.9k
        {
129
37.3k
            const CAmount max_burn_amount = request.params[2].isNull() ? 0 : AmountFromValue(request.params[2]);
130
131
37.3k
            CMutableTransaction mtx;
132
37.3k
            if (!DecodeHexTx(mtx, request.params[0].get_str())) {
133
162
                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
134
162
            }
135
136
73.1k
            for (const auto& out : mtx.vout) {
137
73.1k
                if((out.scriptPubKey.IsUnspendable() || !out.scriptPubKey.HasValidOps()) && out.nValue > max_burn_amount) {
138
4
                    throw JSONRPCTransactionError(TransactionError::MAX_BURN_EXCEEDED);
139
4
                }
140
73.1k
            }
141
142
37.1k
            CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
143
144
37.1k
            const CFeeRate max_raw_tx_fee_rate{ParseFeeRate(self.Arg<UniValue>("maxfeerate"))};
145
146
147
37.1k
            std::string err_string;
148
37.1k
            AssertLockNotHeld(cs_main);
149
37.1k
            NodeContext& node = EnsureAnyNodeContext(request.context);
150
37.1k
            const bool private_broadcast_enabled{gArgs.GetBoolArg("-privatebroadcast", DEFAULT_PRIVATE_BROADCAST)};
151
37.1k
            if (private_broadcast_enabled &&
152
37.1k
                !g_reachable_nets.Contains(NET_ONION) &&
153
37.1k
                !g_reachable_nets.Contains(NET_I2P)) {
154
1
                throw JSONRPCError(RPC_MISC_ERROR,
155
1
                                   "-privatebroadcast is enabled, but none of the Tor or I2P networks is "
156
1
                                   "reachable. Maybe the location of the Tor proxy couldn't be retrieved "
157
1
                                   "from the Tor daemon at startup. Check whether the Tor daemon is running "
158
1
                                   "and that -torcontrol, -torpassword and -i2psam are configured properly.");
159
1
            }
160
37.1k
            const auto method = private_broadcast_enabled ? node::TxBroadcast::NO_MEMPOOL_PRIVATE_BROADCAST
161
37.1k
                                                          : node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL;
162
37.1k
            const TransactionError err = BroadcastTransaction(node,
163
37.1k
                                                              tx,
164
37.1k
                                                              err_string,
165
37.1k
                                                              /*max_tx_fee=*/0,
166
37.1k
                                                              max_raw_tx_fee_rate,
167
37.1k
                                                              method,
168
37.1k
                                                              /*wait_callback=*/true);
169
37.1k
            if (TransactionError::OK != err) {
170
4.45k
                throw JSONRPCTransactionError(err, err_string);
171
4.45k
            }
172
173
32.7k
            return tx->GetHash().GetHex();
174
37.1k
        },
175
39.9k
    };
176
39.9k
}
177
178
static RPCMethod getprivatebroadcastinfo()
179
2.56k
{
180
2.56k
    return RPCMethod{
181
2.56k
        "getprivatebroadcastinfo",
182
2.56k
        "Returns information about transactions tracked for private broadcast.\n"
183
2.56k
        "Transactions that have reached the send-attempt limit remain in the result with attempts_remaining=0.\n"
184
2.56k
        "This method is only available when running with -privatebroadcast enabled.\n",
185
2.56k
        {},
186
2.56k
        RPCResult{
187
2.56k
            RPCResult::Type::OBJ, "", "",
188
2.56k
            {
189
2.56k
                {RPCResult::Type::ARR, "transactions", "",
190
2.56k
                    {
191
2.56k
                        {RPCResult::Type::OBJ, "", "",
192
2.56k
                            {
193
2.56k
                                {RPCResult::Type::STR_HEX, "txid", "The transaction hash in hex"},
194
2.56k
                                {RPCResult::Type::STR_HEX, "wtxid", "The transaction witness hash in hex"},
195
2.56k
                                {RPCResult::Type::STR_HEX, "hex", "The serialized, hex-encoded transaction data"},
196
2.56k
                                {RPCResult::Type::NUM_TIME, "time_added", "The time this transaction was added to the private broadcast queue (seconds since epoch)"},
197
2.56k
                                {RPCResult::Type::NUM, "attempts_remaining", "The number of additional private broadcast send attempts allowed for this transaction"},
198
2.56k
                                {RPCResult::Type::ARR, "peers", "Per-peer send and acknowledgment information for this transaction",
199
2.56k
                                    {
200
2.56k
                                        {RPCResult::Type::OBJ, "", "",
201
2.56k
                                            {
202
2.56k
                                                {RPCResult::Type::STR, "address", "The address of the peer to which the transaction was sent"},
203
2.56k
                                                {RPCResult::Type::NUM_TIME, "sent", "The time this transaction was picked for sending to this peer via private broadcast (seconds since epoch)"},
204
2.56k
                                                {RPCResult::Type::NUM_TIME, "received", /*optional=*/true, "The time this peer acknowledged reception of the transaction (seconds since epoch)"},
205
2.56k
                                            }},
206
2.56k
                                    }},
207
2.56k
                            }},
208
2.56k
                    }},
209
2.56k
            }},
210
2.56k
        RPCExamples{
211
2.56k
            HelpExampleCli("getprivatebroadcastinfo", "")
212
2.56k
            + HelpExampleRpc("getprivatebroadcastinfo", "")
213
2.56k
        },
214
2.56k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
215
2.56k
        {
216
13
            const NodeContext& node{EnsureAnyNodeContext(request.context)};
217
13
            const PeerManager& peerman{EnsurePeerman(node)};
218
13
            if (!peerman.GetInfo().private_broadcast) {
219
1
                throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Private broadcast is not enabled. Ensure you're running Bitcoin Core with -privatebroadcast=1.");
220
1
            }
221
222
12
            const auto txs{peerman.GetPrivateBroadcastInfo()};
223
224
12
            UniValue transactions(UniValue::VARR);
225
50.0k
            for (const auto& tx_info : txs) {
226
50.0k
                UniValue o(UniValue::VOBJ);
227
50.0k
                o.pushKV("txid", tx_info.tx->GetHash().ToString());
228
50.0k
                o.pushKV("wtxid", tx_info.tx->GetWitnessHash().ToString());
229
50.0k
                o.pushKV("hex", EncodeHexTx(*tx_info.tx));
230
50.0k
                o.pushKV("time_added", TicksSinceEpoch<std::chrono::seconds>(tx_info.time_added));
231
50.0k
                o.pushKV("attempts_remaining", tx_info.attempts_remaining);
232
50.0k
                UniValue peers(UniValue::VARR);
233
50.0k
                for (const auto& peer : tx_info.peers) {
234
24
                    UniValue p(UniValue::VOBJ);
235
24
                    p.pushKV("address", peer.address.ToStringAddrPort());
236
24
                    p.pushKV("sent", TicksSinceEpoch<std::chrono::seconds>(peer.sent));
237
24
                    if (peer.received.has_value()) {
238
24
                        p.pushKV("received", TicksSinceEpoch<std::chrono::seconds>(*peer.received));
239
24
                    }
240
24
                    peers.push_back(std::move(p));
241
24
                }
242
50.0k
                o.pushKV("peers", std::move(peers));
243
50.0k
                transactions.push_back(std::move(o));
244
50.0k
            }
245
246
12
            UniValue ret(UniValue::VOBJ);
247
12
            ret.pushKV("transactions", std::move(transactions));
248
12
            return ret;
249
13
        },
250
2.56k
    };
251
2.56k
}
252
253
static RPCMethod abortprivatebroadcast()
254
2.55k
{
255
2.55k
    return RPCMethod{
256
2.55k
        "abortprivatebroadcast",
257
2.55k
        "Abort private broadcast attempts for a transaction currently being privately broadcast.\n"
258
2.55k
        "The transaction will be removed from the private broadcast queue.\n"
259
2.55k
        "This method is only available when running with -privatebroadcast enabled.\n",
260
2.55k
        {
261
2.55k
            {"id", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A transaction identifier to abort. It will be matched against both txid and wtxid for all transactions in the private broadcast queue.\n"
262
2.55k
                                                                "If the provided id matches a txid that corresponds to multiple transactions with different wtxids, multiple transactions will be removed and returned."},
263
2.55k
        },
264
2.55k
        RPCResult{
265
2.55k
            RPCResult::Type::OBJ, "", "",
266
2.55k
            {
267
2.55k
                {RPCResult::Type::ARR, "removed_transactions", "Transactions removed from the private broadcast queue",
268
2.55k
                    {
269
2.55k
                        {RPCResult::Type::OBJ, "", "",
270
2.55k
                            {
271
2.55k
                                {RPCResult::Type::STR_HEX, "txid", "The transaction hash in hex"},
272
2.55k
                                {RPCResult::Type::STR_HEX, "wtxid", "The transaction witness hash in hex"},
273
2.55k
                                {RPCResult::Type::STR_HEX, "hex", "The serialized, hex-encoded transaction data"},
274
2.55k
                            }},
275
2.55k
                    }},
276
2.55k
            }
277
2.55k
        },
278
2.55k
        RPCExamples{
279
2.55k
            HelpExampleCli("abortprivatebroadcast", "\"id\"")
280
2.55k
            + HelpExampleRpc("abortprivatebroadcast", "\"id\"")
281
2.55k
        },
282
2.55k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
283
2.55k
        {
284
285
4
            const NodeContext& node{EnsureAnyNodeContext(request.context)};
286
4
            PeerManager& peerman{EnsurePeerman(node)};
287
4
            if (!peerman.GetInfo().private_broadcast) {
288
1
                throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Private broadcast is not enabled. Ensure you're running Bitcoin Core with -privatebroadcast=1.");
289
1
            }
290
291
3
            const uint256 id{ParseHashV(self.Arg<UniValue>("id"), "id")};
292
293
3
            const auto removed_txs{peerman.AbortPrivateBroadcast(id)};
294
3
            if (removed_txs.empty()) {
295
1
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in private broadcast queue. Check getprivatebroadcastinfo.");
296
1
            }
297
298
2
            UniValue removed_transactions(UniValue::VARR);
299
2
            for (const auto& tx : removed_txs) {
300
2
                UniValue o(UniValue::VOBJ);
301
2
                o.pushKV("txid", tx->GetHash().ToString());
302
2
                o.pushKV("wtxid", tx->GetWitnessHash().ToString());
303
2
                o.pushKV("hex", EncodeHexTx(*tx));
304
2
                removed_transactions.push_back(std::move(o));
305
2
            }
306
2
            UniValue ret(UniValue::VOBJ);
307
2
            ret.pushKV("removed_transactions", std::move(removed_transactions));
308
2
            return ret;
309
3
        },
310
2.55k
    };
311
2.55k
}
312
313
static RPCMethod testmempoolaccept()
314
4.00k
{
315
4.00k
    return RPCMethod{
316
4.00k
        "testmempoolaccept",
317
4.00k
        "Returns result of mempool acceptance tests indicating if raw transaction(s) (serialized, hex-encoded) would be accepted by mempool.\n"
318
4.00k
        "\nIf multiple transactions are passed in, parents must come before children and package policies apply: the transactions cannot conflict with any mempool transactions or each other.\n"
319
4.00k
        "\nIf one transaction fails, other transactions may not be fully validated (the 'allowed' key will be blank).\n"
320
4.00k
        "\nThe maximum number of transactions allowed is " + ToString(MAX_PACKAGE_COUNT) + ".\n"
321
4.00k
        "\nThis checks if transactions violate the consensus or policy rules.\n"
322
4.00k
        "\nSee sendrawtransaction call.\n",
323
4.00k
        {
324
4.00k
            {"rawtxs", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings of raw transactions.",
325
4.00k
                {
326
4.00k
                    {"rawtx", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, ""},
327
4.00k
                },
328
4.00k
            },
329
4.00k
            {"maxfeerate", RPCArg::Type::AMOUNT, RPCArg::Default{FormatMoney(DEFAULT_MAX_RAW_TX_FEE_RATE.GetFeePerK())},
330
4.00k
             "Reject transactions whose fee rate is higher than the specified value, expressed in " + CURRENCY_UNIT +
331
4.00k
                 "/kvB.\nFee rates larger than 1BTC/kvB are rejected.\nSet to 0 to accept any fee rate."},
332
4.00k
        },
333
4.00k
        RPCResult{
334
4.00k
            RPCResult::Type::ARR, "", "The result of the mempool acceptance test for each raw transaction in the input array.\n"
335
4.00k
                                      "Returns results for each transaction in the same order they were passed in.\n"
336
4.00k
                                      "Transactions that cannot be fully validated due to failures in other transactions will not contain an 'allowed' result.\n",
337
4.00k
            {
338
4.00k
                {RPCResult::Type::OBJ, "", "",
339
4.00k
                {
340
4.00k
                    {RPCResult::Type::STR_HEX, "txid", "The transaction hash in hex"},
341
4.00k
                    {RPCResult::Type::STR_HEX, "wtxid", "The transaction witness hash in hex"},
342
4.00k
                    {RPCResult::Type::STR, "package-error", /*optional=*/true, "Package validation error, if any (only possible if rawtxs had more than 1 transaction)."},
343
4.00k
                    {RPCResult::Type::BOOL, "allowed", /*optional=*/true, "Whether this tx would be accepted to the mempool and pass client-specified maxfeerate. "
344
4.00k
                                                       "If not present, the tx was not fully validated due to a failure in another tx in the list."},
345
4.00k
                    {RPCResult::Type::NUM, "vsize_adjusted", /*optional=*/true, "Maximum of sigop-adjusted size (-bytespersigop) and virtual transaction size as defined in BIP 141 (only present when 'allowed' is true)."},
346
4.00k
                    {RPCResult::Type::NUM, "vsize", /*optional=*/true, "(DEPRECATED) Was previously erroneously described as the BIP 141 vsize, but is actually sigops-adjusted vsize.\n"
347
4.00k
                                                                "Use vsize_bip141 to actually get that behavior or switch to the explicit vsize_adjusted for retained behavior."},
348
4.00k
                    {RPCResult::Type::NUM, "vsize_bip141", /*optional=*/true, "Virtual transaction size as defined in BIP 141.\n"
349
4.00k
                                                                       "This is different from actual serialized size for witness transactions as witness data is discounted (only present when 'allowed' is true)."},
350
4.00k
                    {RPCResult::Type::OBJ, "fees", /*optional=*/true, "Transaction fees (only present if 'allowed' is true)",
351
4.00k
                    {
352
4.00k
                        {RPCResult::Type::STR_AMOUNT, "base", "transaction fee in " + CURRENCY_UNIT},
353
4.00k
                        {RPCResult::Type::STR_AMOUNT, "effective-feerate", /*optional=*/false, "the effective feerate in " + CURRENCY_UNIT + " per KvB. May differ from the base feerate if, for example, there are modified fees from prioritisetransaction or a package feerate was used."},
354
4.00k
                        {RPCResult::Type::ARR, "effective-includes", /*optional=*/false, "transactions whose fees and vsizes are included in effective-feerate.",
355
4.00k
                            {RPCResult{RPCResult::Type::STR_HEX, "", "transaction wtxid in hex"},
356
4.00k
                        }},
357
4.00k
                    }},
358
4.00k
                    {RPCResult::Type::STR, "reject-reason", /*optional=*/true, "Rejection reason (only present when 'allowed' is false)"},
359
4.00k
                    {RPCResult::Type::STR, "reject-details", /*optional=*/true, "Rejection details (only present when 'allowed' is false and rejection details exist)"},
360
4.00k
                }},
361
4.00k
            }
362
4.00k
        },
363
4.00k
        RPCExamples{
364
4.00k
            "\nCreate a transaction\n"
365
4.00k
            + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
366
4.00k
            "Sign the transaction, and get back the hex\n"
367
4.00k
            + HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
368
4.00k
            "\nTest acceptance of the transaction (signed hex)\n"
369
4.00k
            + HelpExampleCli("testmempoolaccept", R"('["signedhex"]')") +
370
4.00k
            "\nAs a JSON-RPC call\n"
371
4.00k
            + HelpExampleRpc("testmempoolaccept", "[\"signedhex\"]")
372
4.00k
                },
373
4.00k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
374
4.00k
        {
375
1.45k
            const UniValue raw_transactions = request.params[0].get_array();
376
1.45k
            if (raw_transactions.size() < 1 || raw_transactions.size() > MAX_PACKAGE_COUNT) {
377
2
                throw JSONRPCError(RPC_INVALID_PARAMETER,
378
2
                                   "Array must contain between 1 and " + ToString(MAX_PACKAGE_COUNT) + " transactions.");
379
2
            }
380
381
1.45k
            const CFeeRate max_raw_tx_fee_rate{ParseFeeRate(self.Arg<UniValue>("maxfeerate"))};
382
383
1.45k
            std::vector<CTransactionRef> txns;
384
1.45k
            txns.reserve(raw_transactions.size());
385
2.03k
            for (const auto& rawtx : raw_transactions.getValues()) {
386
2.03k
                CMutableTransaction mtx;
387
2.03k
                if (!DecodeHexTx(mtx, rawtx.get_str())) {
388
1
                    throw JSONRPCError(RPC_DESERIALIZATION_ERROR,
389
1
                                       "TX decode failed: " + rawtx.get_str() + " Make sure the tx has at least one input.");
390
1
                }
391
2.03k
                txns.emplace_back(MakeTransactionRef(std::move(mtx)));
392
2.03k
            }
393
394
1.45k
            NodeContext& node = EnsureAnyNodeContext(request.context);
395
1.45k
            CTxMemPool& mempool = EnsureMemPool(node);
396
1.45k
            ChainstateManager& chainman = EnsureChainman(node);
397
1.45k
            Chainstate& chainstate = chainman.ActiveChainstate();
398
1.45k
            const PackageMempoolAcceptResult package_result = [&] {
399
1.45k
                LOCK(::cs_main);
400
1.45k
                if (txns.size() > 1) return ProcessNewPackage(chainstate, mempool, txns, /*test_accept=*/true, /*client_maxfeerate=*/{});
401
1.37k
                return PackageMempoolAcceptResult(txns[0]->GetWitnessHash(),
402
1.37k
                                                  chainman.ProcessTransaction(txns[0], /*test_accept=*/true));
403
1.45k
            }();
404
405
1.45k
            UniValue rpc_result(UniValue::VARR);
406
            // We will check transaction fees while we iterate through txns in order. If any transaction fee
407
            // exceeds maxfeerate, we will leave the rest of the validation results blank, because it
408
            // doesn't make sense to return a validation result for a transaction if its ancestor(s) would
409
            // not be submitted.
410
1.45k
            bool exit_early{false};
411
2.03k
            for (const auto& tx : txns) {
412
2.03k
                UniValue result_inner(UniValue::VOBJ);
413
2.03k
                result_inner.pushKV("txid", tx->GetHash().GetHex());
414
2.03k
                result_inner.pushKV("wtxid", tx->GetWitnessHash().GetHex());
415
2.03k
                if (package_result.m_state.GetResult() == PackageValidationResult::PCKG_POLICY) {
416
99
                    result_inner.pushKV("package-error", package_result.m_state.ToString());
417
99
                }
418
2.03k
                auto it = package_result.m_tx_results.find(tx->GetWitnessHash());
419
2.03k
                if (exit_early || it == package_result.m_tx_results.end()) {
420
                    // Validation unfinished. Just return the txid and wtxid.
421
139
                    rpc_result.push_back(std::move(result_inner));
422
139
                    continue;
423
139
                }
424
1.89k
                const auto& tx_result = it->second;
425
                // Package testmempoolaccept doesn't allow transactions to already be in the mempool.
426
1.89k
                CHECK_NONFATAL(tx_result.m_result_type != MempoolAcceptResult::ResultType::MEMPOOL_ENTRY);
427
1.89k
                if (tx_result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
428
1.64k
                    const CAmount fee = tx_result.m_base_fees.value();
429
                    // Check that fee does not exceed maximum fee
430
1.64k
                    const int64_t virtual_size = tx_result.m_vsize.value();
431
1.64k
                    const CAmount max_raw_tx_fee = max_raw_tx_fee_rate.GetFee(virtual_size);
432
1.64k
                    if (max_raw_tx_fee && fee > max_raw_tx_fee) {
433
4
                        result_inner.pushKV("allowed", false);
434
4
                        result_inner.pushKV("reject-reason", "max-fee-exceeded");
435
4
                        exit_early = true;
436
1.64k
                    } else {
437
                        // Only return the fee and vsize if the transaction would pass ATMP.
438
                        // These can be used to calculate the feerate.
439
1.64k
                        result_inner.pushKV("allowed", true);
440
1.64k
                        result_inner.pushKV("vsize_adjusted", virtual_size);
441
1.64k
                        result_inner.pushKV("vsize", virtual_size);
442
1.64k
                        result_inner.pushKV("vsize_bip141", GetVirtualTransactionSize(*tx));
443
1.64k
                        UniValue fees(UniValue::VOBJ);
444
1.64k
                        fees.pushKV("base", ValueFromAmount(fee));
445
1.64k
                        fees.pushKV("effective-feerate", ValueFromAmount(tx_result.m_effective_feerate.value().GetFeePerK()));
446
1.64k
                        UniValue effective_includes_res(UniValue::VARR);
447
1.64k
                        for (const auto& wtxid : tx_result.m_wtxids_fee_calculations.value()) {
448
1.64k
                            effective_includes_res.push_back(wtxid.ToString());
449
1.64k
                        }
450
1.64k
                        fees.pushKV("effective-includes", std::move(effective_includes_res));
451
1.64k
                        result_inner.pushKV("fees", std::move(fees));
452
1.64k
                    }
453
1.64k
                } else {
454
249
                    result_inner.pushKV("allowed", false);
455
249
                    const TxValidationState state = tx_result.m_state;
456
249
                    if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) {
457
116
                        result_inner.pushKV("reject-reason", "missing-inputs");
458
133
                    } else {
459
133
                        result_inner.pushKV("reject-reason", state.GetRejectReason());
460
133
                        result_inner.pushKV("reject-details", state.ToString());
461
133
                    }
462
249
                }
463
1.89k
                rpc_result.push_back(std::move(result_inner));
464
1.89k
            }
465
1.45k
            return rpc_result;
466
1.45k
        },
467
4.00k
    };
468
4.00k
}
469
470
static std::vector<RPCResult> ClusterDescription()
471
3.69k
{
472
3.69k
    return {
473
3.69k
        RPCResult{RPCResult::Type::NUM, "clusterweight", "total sigops-adjusted weight (as defined in BIP 141 and modified by '-bytespersigop')"},
474
3.69k
        RPCResult{RPCResult::Type::NUM, "txcount", "number of transactions"},
475
3.69k
        RPCResult{RPCResult::Type::ARR, "chunks", "chunks in this cluster (in mining order)",
476
3.69k
            {RPCResult{RPCResult::Type::OBJ, "chunk", "",
477
3.69k
                {
478
3.69k
                    RPCResult{RPCResult::Type::STR_AMOUNT, "chunkfee", "fees of the transactions in this chunk"},
479
3.69k
                    RPCResult{RPCResult::Type::NUM, "chunkweight", "sigops-adjusted weight of all transactions in this chunk"},
480
3.69k
                    RPCResult{RPCResult::Type::ARR, "txs", "transactions in this chunk in mining order",
481
3.69k
                        {RPCResult{RPCResult::Type::STR_HEX, "txid", "transaction id"}}},
482
3.69k
                }
483
3.69k
            }}
484
3.69k
        }
485
3.69k
    };
486
3.69k
}
487
488
static std::vector<RPCResult> MempoolEntryDescription()
489
32.7k
{
490
32.7k
    std::vector<RPCResult> list = {
491
32.7k
        {RPCResult::Type::NUM, "vsize", "(DEPRECATED) Was previously erroneously described as the BIP 141 vsize, but is actually sigops-adjusted vsize.\n"
492
32.7k
        "Use vsize_bip141 to actually get that behavior or switch to the explicit vsize_adjusted for retained behavior."},
493
32.7k
        {RPCResult::Type::NUM, "vsize_bip141", "Virtual transaction size as defined in BIP 141.\n"
494
32.7k
        "This is different from actual serialized size for witness transactions as witness data is discounted."},
495
32.7k
        {RPCResult::Type::NUM, "vsize_adjusted", "Maximum of sigop-adjusted size (-bytespersigop) and virtual transaction size as defined in BIP 141."},
496
32.7k
        RPCResult{RPCResult::Type::NUM, "weight", "transaction weight as defined in BIP 141."},
497
32.7k
        RPCResult{RPCResult::Type::NUM_TIME, "time", "local time transaction entered pool in seconds since 1 Jan 1970 GMT"},
498
32.7k
        RPCResult{RPCResult::Type::NUM, "height", "block height when transaction entered pool"},
499
32.7k
        RPCResult{RPCResult::Type::NUM, "descendantcount", "number of in-mempool descendant transactions (including this one)"},
500
32.7k
        RPCResult{RPCResult::Type::NUM, "descendantsize", "virtual transaction size of in-mempool descendants (including this one)"},
501
32.7k
        RPCResult{RPCResult::Type::NUM, "ancestorcount", "number of in-mempool ancestor transactions (including this one)"},
502
32.7k
        RPCResult{RPCResult::Type::NUM, "ancestorsize", "virtual transaction size of in-mempool ancestors (including this one)"},
503
32.7k
        RPCResult{RPCResult::Type::NUM, "chunkweight", "sigops-adjusted weight (as defined in BIP 141 and modified by '-bytespersigop') of this transaction's chunk"},
504
32.7k
        RPCResult{RPCResult::Type::STR_HEX, "wtxid", "hash of serialized transaction, including witness data"},
505
32.7k
        RPCResult{RPCResult::Type::OBJ, "fees", "",
506
32.7k
            {
507
32.7k
                RPCResult{RPCResult::Type::STR_AMOUNT, "base", "transaction fee, denominated in " + CURRENCY_UNIT},
508
32.7k
                RPCResult{RPCResult::Type::STR_AMOUNT, "modified", "transaction fee with fee deltas used for mining priority, denominated in " + CURRENCY_UNIT},
509
32.7k
                RPCResult{RPCResult::Type::STR_AMOUNT, "ancestor", "transaction fees of in-mempool ancestors (including this one) with fee deltas used for mining priority, denominated in " + CURRENCY_UNIT},
510
32.7k
                RPCResult{RPCResult::Type::STR_AMOUNT, "descendant", "transaction fees of in-mempool descendants (including this one) with fee deltas used for mining priority, denominated in " + CURRENCY_UNIT},
511
32.7k
                RPCResult{RPCResult::Type::STR_AMOUNT, "chunk", "transaction fees of chunk, denominated in " + CURRENCY_UNIT},
512
32.7k
            }},
513
32.7k
        RPCResult{RPCResult::Type::ARR, "depends", "unconfirmed transactions used as inputs for this transaction",
514
32.7k
            {RPCResult{RPCResult::Type::STR_HEX, "transactionid", "parent transaction id"}}},
515
32.7k
        RPCResult{RPCResult::Type::ARR, "spentby", "unconfirmed transactions spending outputs from this transaction",
516
32.7k
            {RPCResult{RPCResult::Type::STR_HEX, "transactionid", "child transaction id"}}},
517
32.7k
        RPCResult{RPCResult::Type::BOOL, "unbroadcast", "Whether this transaction is currently unbroadcast (initial broadcast not yet acknowledged by any peers)"},
518
32.7k
    };
519
32.7k
    if (IsDeprecatedRPCEnabled("bip125")) {
520
68
        list.emplace_back(RPCResult::Type::BOOL, "bip125-replaceable", "Whether this transaction signals BIP125 replaceability or has an unconfirmed ancestor signaling BIP125 replaceability. (DEPRECATED)\n");
521
68
    }
522
32.7k
    return list;
523
32.7k
}
524
525
void AppendChunkInfo(UniValue& all_chunks, FeePerWeight chunk_feerate, std::vector<const CTxMemPoolEntry *> chunk_txs)
526
25.8k
{
527
25.8k
    UniValue chunk(UniValue::VOBJ);
528
25.8k
    chunk.pushKV("chunkfee", ValueFromAmount(chunk_feerate.fee));
529
25.8k
    chunk.pushKV("chunkweight", chunk_feerate.size);
530
25.8k
    UniValue chunk_txids(UniValue::VARR);
531
25.9k
    for (const auto& chunk_tx : chunk_txs) {
532
25.9k
        chunk_txids.push_back(chunk_tx->GetTx().GetHash().ToString());
533
25.9k
    }
534
25.8k
    chunk.pushKV("txs", std::move(chunk_txids));
535
25.8k
    all_chunks.push_back(std::move(chunk));
536
25.8k
}
537
538
static void clusterToJSON(const CTxMemPool& pool, UniValue& info, std::vector<const CTxMemPoolEntry *> cluster) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
539
1.14k
{
540
1.14k
    AssertLockHeld(pool.cs);
541
1.14k
    int total_weight{0};
542
25.9k
    for (const auto& tx : cluster) {
543
25.9k
        total_weight += tx->GetAdjustedWeight();
544
25.9k
    }
545
1.14k
    info.pushKV("clusterweight", total_weight);
546
1.14k
    info.pushKV("txcount", cluster.size());
547
548
    // Output the cluster by chunk. This isn't handed to us by the mempool, but
549
    // we can calculate it by looking at the chunk feerates of each transaction
550
    // in the cluster.
551
1.14k
    FeePerWeight current_chunk_feerate = pool.GetMainChunkFeerate(*cluster[0]);
552
1.14k
    std::vector<const CTxMemPoolEntry *> current_chunk;
553
1.14k
    current_chunk.reserve(cluster.size());
554
555
1.14k
    UniValue all_chunks(UniValue::VARR);
556
25.9k
    for (const auto& tx : cluster) {
557
25.9k
        if (current_chunk_feerate.size == 0) {
558
            // We've iterated all the transactions in the previous chunk; so
559
            // append it to the output.
560
24.7k
            AppendChunkInfo(all_chunks, pool.GetMainChunkFeerate(*current_chunk[0]), current_chunk);
561
24.7k
            current_chunk.clear();
562
24.7k
            current_chunk_feerate = pool.GetMainChunkFeerate(*tx);
563
24.7k
        }
564
25.9k
        current_chunk.push_back(tx);
565
25.9k
        current_chunk_feerate.size -= tx->GetAdjustedWeight();
566
25.9k
    }
567
1.14k
    AppendChunkInfo(all_chunks, pool.GetMainChunkFeerate(*current_chunk[0]), current_chunk);
568
1.14k
    current_chunk.clear();
569
1.14k
    info.pushKV("chunks", std::move(all_chunks));
570
1.14k
}
571
572
static void entryToJSON(const CTxMemPool& pool, UniValue& info, const CTxMemPoolEntry& e) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
573
8.60k
{
574
8.60k
    AssertLockHeld(pool.cs);
575
576
8.60k
    auto [ancestor_count, ancestor_size, ancestor_fees] = pool.CalculateAncestorData(e);
577
8.60k
    auto [descendant_count, descendant_size, descendant_fees] = pool.CalculateDescendantData(e);
578
579
8.60k
    info.pushKV("vsize_adjusted", e.GetTxSize());
580
8.60k
    info.pushKV("vsize", e.GetTxSize());
581
8.60k
    info.pushKV("vsize_bip141", GetVirtualTransactionSize(e.GetTx()));
582
8.60k
    info.pushKV("weight", e.GetTxWeight());
583
8.60k
    info.pushKV("time", count_seconds(e.GetTime()));
584
8.60k
    info.pushKV("height", e.GetHeight());
585
8.60k
    info.pushKV("descendantcount", descendant_count);
586
8.60k
    info.pushKV("descendantsize", descendant_size);
587
8.60k
    info.pushKV("ancestorcount", ancestor_count);
588
8.60k
    info.pushKV("ancestorsize", ancestor_size);
589
8.60k
    info.pushKV("wtxid", e.GetTx().GetWitnessHash().ToString());
590
8.60k
    auto feerate = pool.GetMainChunkFeerate(e);
591
8.60k
    info.pushKV("chunkweight", feerate.size);
592
593
8.60k
    UniValue fees(UniValue::VOBJ);
594
8.60k
    fees.pushKV("base", ValueFromAmount(e.GetFee()));
595
8.60k
    fees.pushKV("modified", ValueFromAmount(e.GetModifiedFee()));
596
8.60k
    fees.pushKV("ancestor", ValueFromAmount(ancestor_fees));
597
8.60k
    fees.pushKV("descendant", ValueFromAmount(descendant_fees));
598
8.60k
    fees.pushKV("chunk", ValueFromAmount(feerate.fee));
599
8.60k
    info.pushKV("fees", std::move(fees));
600
601
8.60k
    const CTransaction& tx = e.GetTx();
602
8.60k
    std::set<std::string> setDepends;
603
8.60k
    for (const CTxIn& txin : tx.vin)
604
11.9k
    {
605
11.9k
        if (pool.exists(txin.prevout.hash))
606
7.30k
            setDepends.insert(txin.prevout.hash.ToString());
607
11.9k
    }
608
609
8.60k
    UniValue depends(UniValue::VARR);
610
8.60k
    for (const std::string& dep : setDepends)
611
7.30k
    {
612
7.30k
        depends.push_back(dep);
613
7.30k
    }
614
615
8.60k
    info.pushKV("depends", std::move(depends));
616
617
8.60k
    UniValue spent(UniValue::VARR);
618
8.60k
    for (const CTxMemPoolEntry& child : pool.GetChildren(e)) {
619
7.32k
        spent.push_back(child.GetTx().GetHash().ToString());
620
7.32k
    }
621
622
8.60k
    info.pushKV("spentby", std::move(spent));
623
8.60k
    info.pushKV("unbroadcast", pool.IsUnbroadcastTx(tx.GetHash()));
624
625
    // Add opt-in RBF status
626
8.60k
    if (IsDeprecatedRPCEnabled("bip125")) {
627
1
        bool rbfStatus = false;
628
1
        RBFTransactionState rbfState = IsRBFOptIn(tx, pool);
629
1
        if (rbfState == RBFTransactionState::UNKNOWN) {
630
0
            throw JSONRPCError(RPC_MISC_ERROR, "Transaction is not in mempool");
631
1
        } else if (rbfState == RBFTransactionState::REPLACEABLE_BIP125) {
632
0
            rbfStatus = true;
633
0
        }
634
1
        info.pushKV("bip125-replaceable", rbfStatus);
635
1
    }
636
8.60k
}
637
638
UniValue MempoolToJSON(const CTxMemPool& pool, bool verbose, bool include_mempool_sequence)
639
11.6k
{
640
11.6k
    if (verbose) {
641
1.08k
        if (include_mempool_sequence) {
642
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Verbose results cannot contain mempool sequence values.");
643
0
        }
644
1.08k
        LOCK(pool.cs);
645
1.08k
        UniValue o(UniValue::VOBJ);
646
3.64k
        for (const CTxMemPoolEntry& e : pool.entryAll()) {
647
3.64k
            UniValue info(UniValue::VOBJ);
648
3.64k
            entryToJSON(pool, info, e);
649
            // Mempool has unique entries so there is no advantage in using
650
            // UniValue::pushKV, which checks if the key already exists in O(N).
651
            // UniValue::pushKVEnd is used instead which currently is O(1).
652
3.64k
            o.pushKVEnd(e.GetTx().GetHash().ToString(), std::move(info));
653
3.64k
        }
654
1.08k
        return o;
655
10.5k
    } else {
656
10.5k
        UniValue a(UniValue::VARR);
657
10.5k
        uint64_t mempool_sequence;
658
10.5k
        {
659
10.5k
            LOCK(pool.cs);
660
340k
            for (const CTxMemPoolEntry& e : pool.entryAll()) {
661
340k
                a.push_back(e.GetTx().GetHash().ToString());
662
340k
            }
663
10.5k
            mempool_sequence = pool.GetSequence();
664
10.5k
        }
665
10.5k
        if (!include_mempool_sequence) {
666
10.5k
            return a;
667
10.5k
        } else {
668
6
            UniValue o(UniValue::VOBJ);
669
6
            o.pushKV("txids", std::move(a));
670
6
            o.pushKV("mempool_sequence", mempool_sequence);
671
6
            return o;
672
6
        }
673
10.5k
    }
674
11.6k
}
675
676
static RPCMethod getmempoolfeeratediagram()
677
2.54k
{
678
2.54k
    return RPCMethod{"getmempoolfeeratediagram",
679
2.54k
        "Returns the feerate diagram for the whole mempool.",
680
2.54k
        {},
681
2.54k
        {
682
2.54k
            RPCResult{"mempool chunks",
683
2.54k
                RPCResult::Type::ARR, "", "",
684
2.54k
                {
685
2.54k
                    {
686
2.54k
                        RPCResult::Type::OBJ, "", "",
687
2.54k
                        {
688
2.54k
                            {RPCResult::Type::NUM, "weight", "cumulative sigops-adjusted weight"},
689
2.54k
                            {RPCResult::Type::STR_AMOUNT, "fee", "cumulative fee"}
690
2.54k
                        }
691
2.54k
                    }
692
2.54k
                }
693
2.54k
            }
694
2.54k
        },
695
2.54k
        RPCExamples{
696
2.54k
            HelpExampleCli("getmempoolfeeratediagram", "")
697
2.54k
            + HelpExampleRpc("getmempoolfeeratediagram", "")
698
2.54k
        },
699
2.54k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
700
2.54k
        {
701
5
            const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
702
5
            LOCK(mempool.cs);
703
704
5
            UniValue result(UniValue::VARR);
705
706
5
            auto diagram = mempool.GetFeerateDiagram();
707
708
131
            for (auto f : diagram) {
709
131
                UniValue o(UniValue::VOBJ);
710
131
                o.pushKV("weight", f.size);
711
131
                o.pushKV("fee", ValueFromAmount(f.fee));
712
131
                result.push_back(o);
713
131
            }
714
5
            return result;
715
5
        }
716
2.54k
    };
717
2.54k
}
718
719
static RPCMethod getrawmempool()
720
14.1k
{
721
14.1k
    return RPCMethod{
722
14.1k
        "getrawmempool",
723
14.1k
        "Returns all transaction ids in memory pool as a json array of string transaction ids.\n"
724
14.1k
        "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n",
725
14.1k
        {
726
14.1k
            {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "True for a json object, false for array of transaction ids"},
727
14.1k
            {"mempool_sequence", RPCArg::Type::BOOL, RPCArg::Default{false}, "If verbose=false, returns a json object with transaction list and mempool sequence number attached."},
728
14.1k
        },
729
14.1k
        {
730
14.1k
            RPCResult{"for verbose = false",
731
14.1k
                RPCResult::Type::ARR, "", "",
732
14.1k
                {
733
14.1k
                    {RPCResult::Type::STR_HEX, "", "The transaction id"},
734
14.1k
                }},
735
14.1k
            RPCResult{"for verbose = true",
736
14.1k
                RPCResult::Type::OBJ_DYN, "", "",
737
14.1k
                {
738
14.1k
                    {RPCResult::Type::OBJ, "transactionid", "", MempoolEntryDescription()},
739
14.1k
                }},
740
14.1k
            RPCResult{"for verbose = false and mempool_sequence = true",
741
14.1k
                RPCResult::Type::OBJ, "", "",
742
14.1k
                {
743
14.1k
                    {RPCResult::Type::ARR, "txids", "",
744
14.1k
                    {
745
14.1k
                        {RPCResult::Type::STR_HEX, "", "The transaction id"},
746
14.1k
                    }},
747
14.1k
                    {RPCResult::Type::NUM, "mempool_sequence", "The mempool sequence value."},
748
14.1k
                }},
749
14.1k
        },
750
14.1k
        RPCExamples{
751
14.1k
            HelpExampleCli("getrawmempool", "true")
752
14.1k
            + HelpExampleRpc("getrawmempool", "true")
753
14.1k
        },
754
14.1k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
755
14.1k
{
756
11.6k
    bool fVerbose = false;
757
11.6k
    if (!request.params[0].isNull())
758
1.13k
        fVerbose = request.params[0].get_bool();
759
760
11.6k
    bool include_mempool_sequence = false;
761
11.6k
    if (!request.params[1].isNull()) {
762
5
        include_mempool_sequence = request.params[1].get_bool();
763
5
    }
764
765
11.6k
    return MempoolToJSON(EnsureAnyMemPool(request.context), fVerbose, include_mempool_sequence);
766
11.6k
},
767
14.1k
    };
768
14.1k
}
769
770
static RPCMethod getmempoolancestors()
771
3.16k
{
772
3.16k
    return RPCMethod{
773
3.16k
        "getmempoolancestors",
774
3.16k
        "If txid is in the mempool, returns all in-mempool ancestors.\n",
775
3.16k
        {
776
3.16k
            {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id (must be in mempool)"},
777
3.16k
            {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "True for a json object, false for array of transaction ids"},
778
3.16k
        },
779
3.16k
        {
780
3.16k
            RPCResult{"for verbose = false",
781
3.16k
                RPCResult::Type::ARR, "", "",
782
3.16k
                {{RPCResult::Type::STR_HEX, "", "The transaction id of an in-mempool ancestor transaction"}}},
783
3.16k
            RPCResult{"for verbose = true",
784
3.16k
                RPCResult::Type::OBJ_DYN, "", "",
785
3.16k
                {
786
3.16k
                    {RPCResult::Type::OBJ, "transactionid", "", MempoolEntryDescription()},
787
3.16k
                }},
788
3.16k
        },
789
3.16k
        RPCExamples{
790
3.16k
            HelpExampleCli("getmempoolancestors", "\"mytxid\"")
791
3.16k
            + HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
792
3.16k
        },
793
3.16k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
794
3.16k
{
795
613
    bool fVerbose = false;
796
613
    if (!request.params[1].isNull())
797
65
        fVerbose = request.params[1].get_bool();
798
799
613
    auto txid{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
800
801
613
    const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
802
613
    LOCK(mempool.cs);
803
804
613
    const auto entry{mempool.GetEntry(txid)};
805
613
    if (entry == nullptr) {
806
0
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
807
0
    }
808
809
613
    auto ancestors{mempool.CalculateMemPoolAncestors(*entry)};
810
811
613
    if (!fVerbose) {
812
548
        UniValue o(UniValue::VARR);
813
11.4k
        for (CTxMemPool::txiter ancestorIt : ancestors) {
814
11.4k
            o.push_back(ancestorIt->GetTx().GetHash().ToString());
815
11.4k
        }
816
548
        return o;
817
548
    } else {
818
65
        UniValue o(UniValue::VOBJ);
819
2.07k
        for (CTxMemPool::txiter ancestorIt : ancestors) {
820
2.07k
            const CTxMemPoolEntry &e = *ancestorIt;
821
2.07k
            UniValue info(UniValue::VOBJ);
822
2.07k
            entryToJSON(mempool, info, e);
823
2.07k
            o.pushKVEnd(e.GetTx().GetHash().ToString(), std::move(info));
824
2.07k
        }
825
65
        return o;
826
65
    }
827
613
},
828
3.16k
    };
829
3.16k
}
830
831
static RPCMethod getmempooldescendants()
832
12.0k
{
833
12.0k
    return RPCMethod{
834
12.0k
        "getmempooldescendants",
835
12.0k
        "If txid is in the mempool, returns all in-mempool descendants.\n",
836
12.0k
        {
837
12.0k
            {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id (must be in mempool)"},
838
12.0k
            {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "True for a json object, false for array of transaction ids"},
839
12.0k
        },
840
12.0k
        {
841
12.0k
            RPCResult{"for verbose = false",
842
12.0k
                RPCResult::Type::ARR, "", "",
843
12.0k
                {{RPCResult::Type::STR_HEX, "", "The transaction id of an in-mempool descendant transaction"}}},
844
12.0k
            RPCResult{"for verbose = true",
845
12.0k
                RPCResult::Type::OBJ_DYN, "", "",
846
12.0k
                {
847
12.0k
                    {RPCResult::Type::OBJ, "transactionid", "", MempoolEntryDescription()},
848
12.0k
                }},
849
12.0k
        },
850
12.0k
        RPCExamples{
851
12.0k
            HelpExampleCli("getmempooldescendants", "\"mytxid\"")
852
12.0k
            + HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
853
12.0k
        },
854
12.0k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
855
12.0k
{
856
9.51k
    bool fVerbose = false;
857
9.51k
    if (!request.params[1].isNull())
858
65
        fVerbose = request.params[1].get_bool();
859
860
9.51k
    auto txid{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
861
862
9.51k
    const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
863
9.51k
    LOCK(mempool.cs);
864
865
9.51k
    const auto it{mempool.GetIter(txid)};
866
9.51k
    if (!it) {
867
0
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
868
0
    }
869
870
9.51k
    CTxMemPool::setEntries setDescendants;
871
9.51k
    mempool.CalculateDescendants(*it, setDescendants);
872
    // CTxMemPool::CalculateDescendants will include the given tx
873
9.51k
    setDescendants.erase(*it);
874
875
9.51k
    if (!fVerbose) {
876
9.45k
        UniValue o(UniValue::VARR);
877
166k
        for (CTxMemPool::txiter descendantIt : setDescendants) {
878
166k
            o.push_back(descendantIt->GetTx().GetHash().ToString());
879
166k
        }
880
881
9.45k
        return o;
882
9.45k
    } else {
883
65
        UniValue o(UniValue::VOBJ);
884
2.07k
        for (CTxMemPool::txiter descendantIt : setDescendants) {
885
2.07k
            const CTxMemPoolEntry &e = *descendantIt;
886
2.07k
            UniValue info(UniValue::VOBJ);
887
2.07k
            entryToJSON(mempool, info, e);
888
2.07k
            o.pushKVEnd(e.GetTx().GetHash().ToString(), std::move(info));
889
2.07k
        }
890
65
        return o;
891
65
    }
892
9.51k
},
893
12.0k
    };
894
12.0k
}
895
896
static RPCMethod getmempoolcluster()
897
3.69k
{
898
3.69k
    return RPCMethod{"getmempoolcluster",
899
3.69k
        "Returns mempool data for given cluster\n",
900
3.69k
        {
901
3.69k
            {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The txid of a transaction in the cluster"},
902
3.69k
        },
903
3.69k
        RPCResult{
904
3.69k
            RPCResult::Type::OBJ, "", "", ClusterDescription()},
905
3.69k
        RPCExamples{
906
3.69k
            HelpExampleCli("getmempoolcluster", "txid")
907
3.69k
            + HelpExampleRpc("getmempoolcluster", R"("txid")")
908
3.69k
        },
909
3.69k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
910
3.69k
{
911
1.14k
    uint256 hash = ParseHashV(request.params[0], "txid");
912
913
1.14k
    const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
914
1.14k
    LOCK(mempool.cs);
915
916
1.14k
    auto txid = Txid::FromUint256(hash);
917
1.14k
    const auto entry{mempool.GetEntry(txid)};
918
1.14k
    if (entry == nullptr) {
919
1
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
920
1
    }
921
922
1.14k
    auto cluster = mempool.GetCluster(txid);
923
924
1.14k
    UniValue info(UniValue::VOBJ);
925
1.14k
    clusterToJSON(mempool, info, cluster);
926
1.14k
    return info;
927
1.14k
},
928
3.69k
    };
929
3.69k
}
930
931
static RPCMethod getmempoolentry()
932
3.38k
{
933
3.38k
    return RPCMethod{
934
3.38k
        "getmempoolentry",
935
3.38k
        "Returns mempool data for given transaction\n",
936
3.38k
        {
937
3.38k
            {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id (must be in mempool)"},
938
3.38k
        },
939
3.38k
        RPCResult{
940
3.38k
            RPCResult::Type::OBJ, "", "", MempoolEntryDescription()},
941
3.38k
        RPCExamples{
942
3.38k
            HelpExampleCli("getmempoolentry", "\"mytxid\"")
943
3.38k
            + HelpExampleRpc("getmempoolentry", "\"mytxid\"")
944
3.38k
        },
945
3.38k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
946
3.38k
{
947
832
    auto txid{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
948
949
832
    const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
950
832
    LOCK(mempool.cs);
951
952
832
    const auto entry{mempool.GetEntry(txid)};
953
832
    if (entry == nullptr) {
954
24
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
955
24
    }
956
957
808
    UniValue info(UniValue::VOBJ);
958
808
    entryToJSON(mempool, info, *entry);
959
808
    return info;
960
832
},
961
3.38k
    };
962
3.38k
}
963
964
static RPCMethod gettxspendingprevout()
965
2.64k
{
966
2.64k
    return RPCMethod{"gettxspendingprevout",
967
2.64k
        "Scans the mempool (and the txospenderindex, if available) to find transactions spending any of the given outputs",
968
2.64k
        {
969
2.64k
            {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The transaction outputs that we want to check, and within each, the txid (string) vout (numeric).",
970
2.64k
                {
971
2.64k
                    {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
972
2.64k
                        {
973
2.64k
                            {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
974
2.64k
                            {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
975
2.64k
                        },
976
2.64k
                    },
977
2.64k
                },
978
2.64k
            },
979
2.64k
            {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
980
2.64k
                {
981
2.64k
                    {"mempool_only", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true if txospenderindex unavailable, otherwise false"}, "If false and mempool lacks a relevant spend, use txospenderindex (throws an exception if not available)."},
982
2.64k
                    {"return_spending_tx", RPCArg::Type::BOOL, RPCArg::DefaultHint{"false"}, "If true, return the full spending tx."},
983
2.64k
                },
984
2.64k
            },
985
2.64k
        },
986
2.64k
        RPCResult{
987
2.64k
            RPCResult::Type::ARR, "", "",
988
2.64k
            {
989
2.64k
                {RPCResult::Type::OBJ, "", "",
990
2.64k
                {
991
2.64k
                    {RPCResult::Type::STR_HEX, "txid", "the transaction id of the checked output"},
992
2.64k
                    {RPCResult::Type::NUM, "vout", "the vout value of the checked output"},
993
2.64k
                    {RPCResult::Type::STR_HEX, "spendingtxid", /*optional=*/true, "the transaction id of the mempool transaction spending this output (omitted if unspent)"},
994
2.64k
                    {RPCResult::Type::STR_HEX, "spendingtx", /*optional=*/true, "the transaction spending this output (only if return_spending_tx is set, omitted if unspent)"},
995
2.64k
                    {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "the hash of the spending block (omitted if unspent or the spending tx is not confirmed)"},
996
2.64k
                }},
997
2.64k
            }
998
2.64k
        },
999
2.64k
        RPCExamples{
1000
2.64k
            HelpExampleCli("gettxspendingprevout", "\"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":3}]\"")
1001
2.64k
            + HelpExampleRpc("gettxspendingprevout", "\"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":3}]\"")
1002
2.64k
            + HelpExampleCliNamed("gettxspendingprevout", {{"outputs", "[{\"txid\":\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\",\"vout\":3}]"}, {"return_spending_tx", true}})
1003
2.64k
        },
1004
2.64k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1005
2.64k
        {
1006
92
            const UniValue& output_params = request.params[0].get_array();
1007
92
            if (output_params.empty()) {
1008
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, outputs are missing");
1009
1
            }
1010
91
            const UniValue options{request.params[1].isNull() ? UniValue::VOBJ : request.params[1]};
1011
91
            RPCTypeCheckObj(options,
1012
91
                            {
1013
91
                                {"mempool_only", UniValueType(UniValue::VBOOL)},
1014
91
                                {"return_spending_tx", UniValueType(UniValue::VBOOL)},
1015
91
                            }, /*fAllowNull=*/true, /*fStrict=*/true);
1016
1017
91
            const bool mempool_only{options.exists("mempool_only") ? options["mempool_only"].get_bool() : !g_txospenderindex};
1018
91
            const bool return_spending_tx{options.exists("return_spending_tx") ? options["return_spending_tx"].get_bool() : false};
1019
1020
            // Worklist of outpoints to resolve
1021
91
            struct Entry {
1022
91
                COutPoint outpoint;
1023
91
                size_t request_index;
1024
91
            };
1025
91
            std::vector<Entry> prevouts_to_process;
1026
91
            prevouts_to_process.reserve(output_params.size());
1027
101
            for (const size_t idx : std::views::iota(size_t{0}, output_params.size())) {
1028
101
                const UniValue& o = output_params[idx].get_obj();
1029
1030
101
                RPCTypeCheckObj(o,
1031
101
                                {
1032
101
                                    {"txid", UniValueType(UniValue::VSTR)},
1033
101
                                    {"vout", UniValueType(UniValue::VNUM)},
1034
101
                                }, /*fAllowNull=*/false, /*fStrict=*/true);
1035
1036
101
                const Txid txid = Txid::FromUint256(ParseHashO(o, "txid"));
1037
101
                const int nOutput{o.find_value("vout").getInt<int>()};
1038
101
                if (nOutput < 0) {
1039
1
                    throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
1040
1
                }
1041
100
                prevouts_to_process.emplace_back(COutPoint{txid, static_cast<uint32_t>(nOutput)}, idx);
1042
100
            }
1043
1044
96
            auto make_output = [&output_params, return_spending_tx](const Entry& prevout, const CTransaction* spending_tx = nullptr) {
1045
96
                UniValue o{output_params[prevout.request_index]};
1046
96
                if (spending_tx) {
1047
86
                    o.pushKV("spendingtxid", spending_tx->GetHash().ToString());
1048
86
                    if (return_spending_tx) {
1049
11
                        o.pushKV("spendingtx", EncodeHexTx(*spending_tx));
1050
11
                    }
1051
86
                }
1052
96
                return o;
1053
96
            };
1054
1055
90
            std::vector<UniValue> results(output_params.size());
1056
1057
            // Search the mempool first
1058
90
            std::vector<Entry> unresolved;
1059
90
            unresolved.reserve(prevouts_to_process.size());
1060
90
            {
1061
90
                const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
1062
90
                LOCK(mempool.cs);
1063
1064
                // Make the result if the spending tx appears in the mempool or this is a mempool_only request
1065
96
                for (const auto& prevout : prevouts_to_process) {
1066
96
                    const auto* spending_tx{mempool.GetConflictTx(prevout.outpoint)};
1067
1068
                    // If the outpoint is not spent in the mempool and this is not a mempool-only
1069
                    // request, we cannot answer it yet.
1070
96
                    if (!spending_tx && !mempool_only) {
1071
16
                        unresolved.push_back(prevout);
1072
80
                    } else {
1073
80
                        results[prevout.request_index] = make_output(prevout, spending_tx);
1074
80
                    }
1075
96
                }
1076
90
            }
1077
1078
            // mempool_only requests resolve every outpoint above, so only other requests reach the index.
1079
90
            if (!unresolved.empty() && (!g_txospenderindex || !g_txospenderindex->BlockUntilSyncedToCurrentChain())) {
1080
0
                throw JSONRPCError(RPC_MISC_ERROR, "Mempool lacks a relevant spend, and txospenderindex is unavailable.");
1081
0
            }
1082
1083
90
            for (const auto& prevout : unresolved) {
1084
16
                const auto spender{g_txospenderindex->FindSpender(prevout.outpoint)};
1085
16
                if (!spender) {
1086
0
                    throw JSONRPCError(RPC_MISC_ERROR, spender.error());
1087
0
                }
1088
1089
16
                if (const auto& spender_opt{spender.value()}) {
1090
11
                    UniValue o{make_output(prevout, spender_opt->tx.get())};
1091
11
                    o.pushKV("blockhash", spender_opt->block_hash.GetHex());
1092
11
                    results[prevout.request_index] = std::move(o);
1093
11
                } else {
1094
                    // Only return the input outpoint itself, which indicates it is unspent.
1095
5
                    results[prevout.request_index] = make_output(prevout);
1096
5
                }
1097
16
            }
1098
1099
90
            UniValue result{UniValue::VARR};
1100
90
            result.reserve(results.size());
1101
96
            for (auto& output : results) result.push_back(std::move(output));
1102
90
            return result;
1103
90
        },
1104
2.64k
    };
1105
2.64k
}
1106
1107
UniValue MempoolInfoToJSON(const CTxMemPool& pool)
1108
1.52k
{
1109
    // Make sure this call is atomic in the pool.
1110
1.52k
    LOCK(pool.cs);
1111
1.52k
    UniValue ret(UniValue::VOBJ);
1112
1.52k
    ret.pushKV("loaded", pool.GetLoadTried());
1113
1.52k
    ret.pushKV("size", pool.size());
1114
1.52k
    ret.pushKV("bytes", pool.GetTotalTxSize());
1115
1.52k
    ret.pushKV("usage", pool.DynamicMemoryUsage());
1116
1.52k
    ret.pushKV("total_fee", ValueFromAmount(pool.GetTotalFee()));
1117
1.52k
    ret.pushKV("maxmempool", pool.m_opts.max_size_bytes);
1118
1.52k
    ret.pushKV("mempoolminfee", ValueFromAmount(std::max(pool.GetMinFee(), pool.m_opts.min_relay_feerate).GetFeePerK()));
1119
1.52k
    ret.pushKV("minrelaytxfee", ValueFromAmount(pool.m_opts.min_relay_feerate.GetFeePerK()));
1120
1.52k
    ret.pushKV("incrementalrelayfee", ValueFromAmount(pool.m_opts.incremental_relay_feerate.GetFeePerK()));
1121
1.52k
    ret.pushKV("unbroadcastcount", pool.GetUnbroadcastTxCount());
1122
1.52k
    ret.pushKV("permitbaremultisig", pool.m_opts.permit_bare_multisig);
1123
1.52k
    ret.pushKV("maxdatacarriersize", pool.m_opts.max_datacarrier_bytes.value_or(0));
1124
1.52k
    ret.pushKV("limitclustercount", pool.m_opts.limits.cluster_count);
1125
1.52k
    ret.pushKV("limitclustersize", pool.m_opts.limits.cluster_size_vbytes);
1126
1.52k
    ret.pushKV("optimal", pool.m_txgraph->DoWork(0)); // 0 work is a quick check for known optimality
1127
1.52k
    if (IsDeprecatedRPCEnabled("fullrbf")) {
1128
3
        ret.pushKV("fullrbf", true);
1129
3
    }
1130
1.52k
    return ret;
1131
1.52k
}
1132
1133
static RPCMethod getmempoolinfo()
1134
4.06k
{
1135
4.06k
    return RPCMethod{"getmempoolinfo",
1136
4.06k
        "Returns details on the active state of the TX memory pool.",
1137
4.06k
        {},
1138
4.06k
        RPCResult{
1139
4.06k
            RPCResult::Type::OBJ, "", "",
1140
4.06k
            [](){
1141
4.06k
                std::vector<RPCResult> list = {
1142
4.06k
                    {RPCResult::Type::BOOL, "loaded", "True if the initial load attempt of the persisted mempool finished"},
1143
4.06k
                    {RPCResult::Type::NUM, "size", "Current tx count"},
1144
4.06k
                    {RPCResult::Type::NUM, "bytes", "Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted"},
1145
4.06k
                    {RPCResult::Type::NUM, "usage", "Total memory usage for the mempool"},
1146
4.06k
                    {RPCResult::Type::STR_AMOUNT, "total_fee", "Total fees for the mempool in " + CURRENCY_UNIT + ", ignoring modified fees through prioritisetransaction"},
1147
4.06k
                    {RPCResult::Type::NUM, "maxmempool", "Maximum memory usage for the mempool"},
1148
4.06k
                    {RPCResult::Type::STR_AMOUNT, "mempoolminfee", "Minimum fee rate in " + CURRENCY_UNIT + "/kvB for tx to be accepted. Is the maximum of minrelaytxfee and minimum mempool fee"},
1149
4.06k
                    {RPCResult::Type::STR_AMOUNT, "minrelaytxfee", "Current minimum relay fee for transactions"},
1150
4.06k
                    {RPCResult::Type::STR_AMOUNT, "incrementalrelayfee", "minimum fee rate increment for mempool limiting or replacement in " + CURRENCY_UNIT + "/kvB"},
1151
4.06k
                    {RPCResult::Type::NUM, "unbroadcastcount", "Current number of transactions that haven't passed initial broadcast yet"},
1152
4.06k
                    {RPCResult::Type::BOOL, "permitbaremultisig", "True if the mempool accepts transactions with bare multisig outputs"},
1153
4.06k
                    {RPCResult::Type::NUM, "maxdatacarriersize", "Maximum number of bytes that can be used by OP_RETURN outputs in the mempool"},
1154
4.06k
                    {RPCResult::Type::NUM, "limitclustercount", "Maximum number of transactions that can be in a cluster (configured by -limitclustercount)"},
1155
4.06k
                    {RPCResult::Type::NUM, "limitclustersize", "Maximum size of a cluster in virtual bytes (configured by -limitclustersize)"},
1156
4.06k
                    {RPCResult::Type::BOOL, "optimal", "If the mempool is in a known-optimal transaction ordering"},
1157
4.06k
                };
1158
4.06k
                if (IsDeprecatedRPCEnabled("fullrbf")) {
1159
5
                    list.emplace_back(RPCResult::Type::BOOL, "fullrbf", "True if the mempool accepts RBF without replaceability signaling inspection (DEPRECATED)");
1160
5
                }
1161
4.06k
                return list;
1162
4.06k
            }()
1163
4.06k
            },
1164
4.06k
        RPCExamples{
1165
4.06k
            HelpExampleCli("getmempoolinfo", "")
1166
4.06k
            + HelpExampleRpc("getmempoolinfo", "")
1167
4.06k
        },
1168
4.06k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1169
4.06k
{
1170
1.51k
    return MempoolInfoToJSON(EnsureAnyMemPool(request.context));
1171
1.51k
},
1172
4.06k
    };
1173
4.06k
}
1174
1175
static RPCMethod importmempool()
1176
2.55k
{
1177
2.55k
    return RPCMethod{
1178
2.55k
        "importmempool",
1179
2.55k
        "Import a mempool.dat file and attempt to add its contents to the mempool.\n"
1180
2.55k
        "Warning: Importing untrusted files is dangerous, especially if metadata from the file is taken over.",
1181
2.55k
        {
1182
2.55k
            {"filepath", RPCArg::Type::STR, RPCArg::Optional::NO, "The mempool file"},
1183
2.55k
            {"options",
1184
2.55k
             RPCArg::Type::OBJ_NAMED_PARAMS,
1185
2.55k
             RPCArg::Optional::OMITTED,
1186
2.55k
             "",
1187
2.55k
             {
1188
2.55k
                 {"use_current_time", RPCArg::Type::BOOL, RPCArg::Default{true},
1189
2.55k
                  "Whether to use the current system time or use the entry time metadata from the mempool file.\n"
1190
2.55k
                  "Warning: Importing untrusted metadata may lead to unexpected issues and undesirable behavior."},
1191
2.55k
                 {"apply_fee_delta_priority", RPCArg::Type::BOOL, RPCArg::Default{false},
1192
2.55k
                  "Whether to apply the fee delta metadata from the mempool file.\n"
1193
2.55k
                  "It will be added to any existing fee deltas.\n"
1194
2.55k
                  "The fee delta can be set by the prioritisetransaction RPC.\n"
1195
2.55k
                  "Warning: Importing untrusted metadata may lead to unexpected issues and undesirable behavior.\n"
1196
2.55k
                  "Only set this bool if you understand what it does."},
1197
2.55k
                 {"apply_unbroadcast_set", RPCArg::Type::BOOL, RPCArg::Default{false},
1198
2.55k
                  "Whether to apply the unbroadcast set metadata from the mempool file.\n"
1199
2.55k
                  "Warning: Importing untrusted metadata may lead to unexpected issues and undesirable behavior."},
1200
2.55k
             },
1201
2.55k
             RPCArgOptions{.oneline_description = "options"}},
1202
2.55k
        },
1203
2.55k
        RPCResult{RPCResult::Type::OBJ, "", "", std::vector<RPCResult>{}},
1204
2.55k
        RPCExamples{HelpExampleCli("importmempool", "/path/to/mempool.dat") + HelpExampleRpc("importmempool", R"("/path/to/mempool.dat")")},
1205
2.55k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue {
1206
4
            const NodeContext& node{EnsureAnyNodeContext(request.context)};
1207
1208
4
            CTxMemPool& mempool{EnsureMemPool(node)};
1209
4
            ChainstateManager& chainman = EnsureChainman(node);
1210
4
            Chainstate& chainstate = chainman.ActiveChainstate();
1211
1212
4
            if (chainman.IsInitialBlockDownload()) {
1213
0
                throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Can only import the mempool after the block download and sync is done.");
1214
0
            }
1215
1216
4
            const fs::path load_path{fs::u8path(self.Arg<std::string_view>("filepath"))};
1217
4
            const UniValue& use_current_time{request.params[1]["use_current_time"]};
1218
4
            const UniValue& apply_fee_delta{request.params[1]["apply_fee_delta_priority"]};
1219
4
            const UniValue& apply_unbroadcast{request.params[1]["apply_unbroadcast_set"]};
1220
4
            node::ImportMempoolOptions opts{
1221
4
                .use_current_time = use_current_time.isNull() ? true : use_current_time.get_bool(),
1222
4
                .apply_fee_delta_priority = apply_fee_delta.isNull() ? false : apply_fee_delta.get_bool(),
1223
4
                .apply_unbroadcast_set = apply_unbroadcast.isNull() ? false : apply_unbroadcast.get_bool(),
1224
4
            };
1225
1226
4
            if (!node::LoadMempool(mempool, load_path, chainstate, std::move(opts))) {
1227
1
                throw JSONRPCError(RPC_MISC_ERROR, "Unable to import mempool file, see debug log for details.");
1228
1
            }
1229
1230
3
            UniValue ret{UniValue::VOBJ};
1231
3
            return ret;
1232
4
        },
1233
2.55k
    };
1234
2.55k
}
1235
1236
static RPCMethod savemempool()
1237
2.55k
{
1238
2.55k
    return RPCMethod{
1239
2.55k
        "savemempool",
1240
2.55k
        "Dumps the mempool to disk. It will fail until the previous dump is fully loaded.\n",
1241
2.55k
        {},
1242
2.55k
        RPCResult{
1243
2.55k
            RPCResult::Type::OBJ, "", "",
1244
2.55k
            {
1245
2.55k
                {RPCResult::Type::STR, "filename", "the directory and file where the mempool was saved"},
1246
2.55k
            }},
1247
2.55k
        RPCExamples{
1248
2.55k
            HelpExampleCli("savemempool", "")
1249
2.55k
            + HelpExampleRpc("savemempool", "")
1250
2.55k
        },
1251
2.55k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1252
2.55k
{
1253
5
    const ArgsManager& args{EnsureAnyArgsman(request.context)};
1254
5
    const CTxMemPool& mempool = EnsureAnyMemPool(request.context);
1255
1256
5
    if (!mempool.GetLoadTried()) {
1257
0
        throw JSONRPCError(RPC_MISC_ERROR, "The mempool was not loaded yet");
1258
0
    }
1259
1260
5
    const fs::path& dump_path = MempoolPath(args);
1261
1262
5
    if (!DumpMempool(mempool, dump_path)) {
1263
1
        throw JSONRPCError(RPC_MISC_ERROR, "Unable to dump mempool to disk");
1264
1
    }
1265
1266
4
    UniValue ret(UniValue::VOBJ);
1267
4
    ret.pushKV("filename", dump_path.utf8string());
1268
1269
4
    return ret;
1270
5
},
1271
2.55k
    };
1272
2.55k
}
1273
1274
static std::vector<RPCResult> OrphanDescription()
1275
5.53k
{
1276
5.53k
    return {
1277
5.53k
        RPCResult{RPCResult::Type::STR_HEX, "txid", "The transaction hash in hex"},
1278
5.53k
        RPCResult{RPCResult::Type::STR_HEX, "wtxid", "The transaction witness hash in hex"},
1279
5.53k
        RPCResult{RPCResult::Type::NUM, "bytes", "The serialized transaction size in bytes"},
1280
5.53k
        RPCResult{RPCResult::Type::NUM, "vsize", "(DEPRECATED) use vsize_bip141 instead. The virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted."},
1281
5.53k
        RPCResult{RPCResult::Type::NUM, "vsize_bip141", "The virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted."},
1282
5.53k
        RPCResult{RPCResult::Type::NUM, "weight", "The transaction weight as defined in BIP 141."},
1283
5.53k
        RPCResult{RPCResult::Type::ARR, "from", "",
1284
5.53k
        {
1285
5.53k
            RPCResult{RPCResult::Type::NUM, "peer_id", "Peer ID"},
1286
5.53k
        }},
1287
5.53k
    };
1288
5.53k
}
1289
1290
static UniValue OrphanToJSON(const node::TxOrphanage::OrphanInfo& orphan)
1291
94
{
1292
94
    UniValue o(UniValue::VOBJ);
1293
94
    o.pushKV("txid", orphan.tx->GetHash().ToString());
1294
94
    o.pushKV("wtxid", orphan.tx->GetWitnessHash().ToString());
1295
94
    o.pushKV("bytes", orphan.tx->ComputeTotalSize());
1296
94
    o.pushKV("vsize", GetVirtualTransactionSize(*orphan.tx));
1297
94
    o.pushKV("vsize_bip141", GetVirtualTransactionSize(*orphan.tx));
1298
94
    o.pushKV("weight", GetTransactionWeight(*orphan.tx));
1299
94
    UniValue from(UniValue::VARR);
1300
3.05k
    for (const auto fromPeer: orphan.announcers) {
1301
3.05k
        from.push_back(fromPeer);
1302
3.05k
    }
1303
94
    o.pushKV("from", from);
1304
94
    return o;
1305
94
}
1306
1307
static RPCMethod getorphantxs()
1308
2.76k
{
1309
2.76k
    return RPCMethod{
1310
2.76k
        "getorphantxs",
1311
2.76k
        "Shows transactions in the tx orphanage.\n"
1312
2.76k
        "\nEXPERIMENTAL warning: this call may be changed in future releases.\n",
1313
2.76k
        {
1314
2.76k
            {"verbosity", RPCArg::Type::NUM, RPCArg::Default{0}, "0 for an array of txids (may contain duplicates), 1 for an array of objects with tx details, and 2 for details from (1) and tx hex",
1315
2.76k
             RPCArgOptions{.skip_type_check = true}},
1316
2.76k
        },
1317
2.76k
        {
1318
2.76k
            RPCResult{"for verbose = 0",
1319
2.76k
                RPCResult::Type::ARR, "", "",
1320
2.76k
                {
1321
2.76k
                    {RPCResult::Type::STR_HEX, "txid", "The transaction hash in hex"},
1322
2.76k
                }},
1323
2.76k
            RPCResult{"for verbose = 1",
1324
2.76k
                RPCResult::Type::ARR, "", "",
1325
2.76k
                {
1326
2.76k
                    {RPCResult::Type::OBJ, "", "", OrphanDescription()},
1327
2.76k
                }},
1328
2.76k
            RPCResult{"for verbose = 2",
1329
2.76k
                RPCResult::Type::ARR, "", "",
1330
2.76k
                {
1331
2.76k
                    {RPCResult::Type::OBJ, "", "",
1332
2.76k
                        Cat<std::vector<RPCResult>>(
1333
2.76k
                            OrphanDescription(),
1334
2.76k
                            {{RPCResult::Type::STR_HEX, "hex", "The serialized, hex-encoded transaction data"}}
1335
2.76k
                        )
1336
2.76k
                    },
1337
2.76k
                }},
1338
2.76k
        },
1339
2.76k
        RPCExamples{
1340
2.76k
            HelpExampleCli("getorphantxs", "2")
1341
2.76k
            + HelpExampleRpc("getorphantxs", "2")
1342
2.76k
        },
1343
2.76k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1344
2.76k
        {
1345
231
            const NodeContext& node = EnsureAnyNodeContext(request.context);
1346
231
            PeerManager& peerman = EnsurePeerman(node);
1347
231
            std::vector<node::TxOrphanage::OrphanInfo> orphanage = peerman.GetOrphanTransactions();
1348
1349
231
            int verbosity{ParseVerbosity(request.params[0], /*default_verbosity=*/0, /*allow_bool=*/false)};
1350
1351
231
            UniValue ret(UniValue::VARR);
1352
1353
231
            if (verbosity == 0) {
1354
12.9k
                for (auto const& orphan : orphanage) {
1355
12.9k
                    ret.push_back(orphan.tx->GetHash().ToString());
1356
12.9k
                }
1357
191
            } else if (verbosity == 1) {
1358
33
                for (auto const& orphan : orphanage) {
1359
33
                    ret.push_back(OrphanToJSON(orphan));
1360
33
                }
1361
25
            } else if (verbosity == 2) {
1362
61
                for (auto const& orphan : orphanage) {
1363
61
                    UniValue o{OrphanToJSON(orphan)};
1364
61
                    o.pushKV("hex", EncodeHexTx(*orphan.tx));
1365
61
                    ret.push_back(o);
1366
61
                }
1367
11
            } else {
1368
4
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid verbosity value " + ToString(verbosity));
1369
4
            }
1370
1371
227
            return ret;
1372
231
        },
1373
2.76k
    };
1374
2.76k
}
1375
1376
static RPCMethod submitpackage()
1377
2.66k
{
1378
2.66k
    return RPCMethod{"submitpackage",
1379
2.66k
        "Submit a package of raw transactions (serialized, hex-encoded) to local node.\n"
1380
2.66k
        "The package will be validated according to consensus and mempool policy rules. If any transaction passes, it will be accepted to mempool.\n"
1381
2.66k
        "This RPC is experimental and the interface may be unstable. Refer to doc/policy/packages.md for documentation on package policies.\n"
1382
2.66k
        "Warning: successful submission does not mean the transactions will propagate throughout the network.\n"
1383
2.66k
        ,
1384
2.66k
        {
1385
2.66k
            {"package", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of raw transactions.\n"
1386
2.66k
                "The package must consist of a transaction with (some, all, or none of) its unconfirmed parents. A single transaction is permitted.\n"
1387
2.66k
                "None of the parents may depend on each other. Parents that are already in mempool do not need to be present in the package.\n"
1388
2.66k
                "The package must be topologically sorted, with the child being the last element in the array if there are multiple elements.",
1389
2.66k
                {
1390
2.66k
                    {"rawtx", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, ""},
1391
2.66k
                },
1392
2.66k
            },
1393
2.66k
            {"maxfeerate", RPCArg::Type::AMOUNT, RPCArg::Default{FormatMoney(DEFAULT_MAX_RAW_TX_FEE_RATE.GetFeePerK())},
1394
2.66k
             "Reject transactions whose fee rate is higher than the specified value, expressed in " + CURRENCY_UNIT +
1395
2.66k
                 "/kvB.\nFee rates larger than 1BTC/kvB are rejected.\nSet to 0 to accept any fee rate."},
1396
2.66k
            {"maxburnamount", RPCArg::Type::AMOUNT, RPCArg::Default{FormatMoney(DEFAULT_MAX_BURN_AMOUNT)},
1397
2.66k
             "Reject transactions with provably unspendable outputs (e.g. 'datacarrier' outputs that use the OP_RETURN opcode) greater than the specified value, expressed in " + CURRENCY_UNIT + ".\n"
1398
2.66k
             "If burning funds through unspendable outputs is desired, increase this value.\n"
1399
2.66k
             "This check is based on heuristics and does not guarantee spendability of outputs.\n"
1400
2.66k
            },
1401
2.66k
        },
1402
2.66k
        RPCResult{
1403
2.66k
            RPCResult::Type::OBJ, "", "",
1404
2.66k
            {
1405
2.66k
                {RPCResult::Type::STR, "package_msg", "The transaction package result message. \"success\" indicates all transactions were accepted into or are already in the mempool."},
1406
2.66k
                {RPCResult::Type::OBJ_DYN, "tx-results", "The transaction results keyed by wtxid. An entry is returned for every submitted wtxid.",
1407
2.66k
                {
1408
2.66k
                    {RPCResult::Type::OBJ, "wtxid", "transaction wtxid", {
1409
2.66k
                        {RPCResult::Type::STR_HEX, "txid", "The transaction hash in hex"},
1410
2.66k
                        {RPCResult::Type::STR_HEX, "other-wtxid", /*optional=*/true, "The wtxid of a different transaction with the same txid but different witness found in the mempool. This means the submitted transaction was ignored."},
1411
2.66k
                        {RPCResult::Type::NUM, "vsize_adjusted", /*optional=*/true, "Maximum of sigop-adjusted size (-bytespersigop) and virtual transaction size as defined in BIP 141."},
1412
2.66k
                        {RPCResult::Type::NUM, "vsize", /*optional=*/true, "(DEPRECATED) Was previously erroneously described as the BIP 141 vsize, but is actually sigops-adjusted vsize.\n"
1413
2.66k
                                                                    "Use vsize_bip141 to actually get that behavior or switch to the explicit vsize_adjusted for retained behavior."},
1414
2.66k
                        {RPCResult::Type::NUM, "vsize_bip141", /*optional=*/true, "Virtual transaction size as defined in BIP 141."},
1415
2.66k
                        {RPCResult::Type::OBJ, "fees", /*optional=*/true, "Transaction fees", {
1416
2.66k
                            {RPCResult::Type::STR_AMOUNT, "base", "transaction fee in " + CURRENCY_UNIT},
1417
2.66k
                            {RPCResult::Type::STR_AMOUNT, "effective-feerate", /*optional=*/true, "if the transaction was not already in the mempool, the effective feerate in " + CURRENCY_UNIT + " per KvB. For example, the package feerate and/or feerate with modified fees from prioritisetransaction."},
1418
2.66k
                            {RPCResult::Type::ARR, "effective-includes", /*optional=*/true, "if effective-feerate is provided, the wtxids of the transactions whose fees and vsizes are included in effective-feerate.",
1419
2.66k
                                {{RPCResult::Type::STR_HEX, "", "transaction wtxid in hex"},
1420
2.66k
                            }},
1421
2.66k
                        }},
1422
2.66k
                        {RPCResult::Type::STR, "error", /*optional=*/true, "Error string if rejected from mempool, or \"package-not-validated\" when the package aborts before any per-tx processing."},
1423
2.66k
                    }}
1424
2.66k
                }},
1425
2.66k
                {RPCResult::Type::ARR, "replaced-transactions", /*optional=*/true, "List of txids of replaced transactions",
1426
2.66k
                {
1427
2.66k
                    {RPCResult::Type::STR_HEX, "", "The transaction id"},
1428
2.66k
                }},
1429
2.66k
            },
1430
2.66k
        },
1431
2.66k
        RPCExamples{
1432
2.66k
            HelpExampleRpc("submitpackage", R"(["raw-parent-tx-1", "raw-parent-tx-2", "raw-child-tx"])") +
1433
2.66k
            HelpExampleCli("submitpackage", R"('["raw-tx-without-unconfirmed-parents"]')")
1434
2.66k
        },
1435
2.66k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1436
2.66k
        {
1437
119
            const UniValue raw_transactions = request.params[0].get_array();
1438
119
            if (raw_transactions.empty() || raw_transactions.size() > MAX_PACKAGE_COUNT) {
1439
2
                throw JSONRPCError(RPC_INVALID_PARAMETER,
1440
2
                                   "Array must contain between 1 and " + ToString(MAX_PACKAGE_COUNT) + " transactions.");
1441
2
            }
1442
1443
            // Fee check needs to be run with chainstate and package context
1444
117
            const CFeeRate max_raw_tx_fee_rate{ParseFeeRate(self.Arg<UniValue>("maxfeerate"))};
1445
117
            std::optional<CFeeRate> client_maxfeerate{max_raw_tx_fee_rate};
1446
            // 0-value is special; it's mapped to no sanity check
1447
117
            if (max_raw_tx_fee_rate == CFeeRate(0)) {
1448
29
                client_maxfeerate = std::nullopt;
1449
29
            }
1450
1451
            // Burn sanity check is run with no context
1452
117
            const CAmount max_burn_amount = request.params[2].isNull() ? 0 : AmountFromValue(request.params[2]);
1453
1454
117
            std::vector<CTransactionRef> txns;
1455
117
            txns.reserve(raw_transactions.size());
1456
382
            for (const auto& rawtx : raw_transactions.getValues()) {
1457
382
                CMutableTransaction mtx;
1458
382
                if (!DecodeHexTx(mtx, rawtx.get_str())) {
1459
1
                    throw JSONRPCError(RPC_DESERIALIZATION_ERROR,
1460
1
                                       "TX decode failed: " + rawtx.get_str() + " Make sure the tx has at least one input.");
1461
1
                }
1462
1463
515
                for (const auto& out : mtx.vout) {
1464
515
                    if((out.scriptPubKey.IsUnspendable() || !out.scriptPubKey.HasValidOps()) && out.nValue > max_burn_amount) {
1465
1
                        throw JSONRPCTransactionError(TransactionError::MAX_BURN_EXCEEDED);
1466
1
                    }
1467
515
                }
1468
1469
380
                txns.emplace_back(MakeTransactionRef(std::move(mtx)));
1470
380
            }
1471
115
            CHECK_NONFATAL(!txns.empty());
1472
115
            if (txns.size() > 1 && !IsChildWithParentsTree(txns)) {
1473
2
                throw JSONRPCTransactionError(TransactionError::INVALID_PACKAGE, "package topology disallowed. not child-with-parents or parents depend on each other.");
1474
2
            }
1475
1476
113
            NodeContext& node = EnsureAnyNodeContext(request.context);
1477
113
            CTxMemPool& mempool = EnsureMemPool(node);
1478
113
            Chainstate& chainstate = EnsureChainman(node).ActiveChainstate();
1479
113
            const auto package_result = WITH_LOCK(::cs_main, return ProcessNewPackage(chainstate, mempool, txns, /*test_accept=*/ false, client_maxfeerate));
1480
1481
113
            std::string package_msg = "success";
1482
1483
            // First catch package-wide errors, continue if we can
1484
113
            switch(package_result.m_state.GetResult()) {
1485
67
                case PackageValidationResult::PCKG_RESULT_UNSET:
1486
67
                {
1487
                    // Belt-and-suspenders check; everything should be successful here
1488
67
                    CHECK_NONFATAL(package_result.m_tx_results.size() == txns.size());
1489
228
                    for (const auto& tx : txns) {
1490
228
                        CHECK_NONFATAL(mempool.exists(tx->GetHash()));
1491
228
                    }
1492
67
                    break;
1493
0
                }
1494
0
                case PackageValidationResult::PCKG_MEMPOOL_ERROR:
1495
0
                {
1496
                    // This only happens with internal bug; user should stop and report
1497
0
                    throw JSONRPCTransactionError(TransactionError::MEMPOOL_ERROR,
1498
0
                        package_result.m_state.GetRejectReason());
1499
0
                }
1500
13
                case PackageValidationResult::PCKG_POLICY:
1501
46
                case PackageValidationResult::PCKG_TX:
1502
46
                {
1503
                    // Package-wide error we want to return, but we also want to return individual responses
1504
46
                    package_msg = package_result.m_state.ToString();
1505
46
                    CHECK_NONFATAL(package_result.m_tx_results.size() == txns.size() ||
1506
46
                            package_result.m_tx_results.empty());
1507
46
                    break;
1508
13
                }
1509
113
            }
1510
1511
113
            size_t num_broadcast{0};
1512
372
            for (const auto& tx : txns) {
1513
                // We don't want to re-submit the txn for validation in BroadcastTransaction
1514
372
                if (!mempool.exists(tx->GetHash())) {
1515
82
                    continue;
1516
82
                }
1517
1518
                // We do not expect an error here; we are only broadcasting things already/still in mempool
1519
290
                std::string err_string;
1520
290
                const auto err = BroadcastTransaction(node, tx, err_string, /*max_tx_fee=*/0, /*max_tx_fee_rate=*/CFeeRate(0), /*broadcast_method=*/node::TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL, /*wait_callback=*/true);
1521
290
                if (err != TransactionError::OK) {
1522
0
                    throw JSONRPCTransactionError(err,
1523
0
                        strprintf("transaction broadcast failed: %s (%d transactions were broadcast successfully)",
1524
0
                            err_string, num_broadcast));
1525
0
                }
1526
290
                num_broadcast++;
1527
290
            }
1528
1529
113
            UniValue rpc_result{UniValue::VOBJ};
1530
113
            rpc_result.pushKV("package_msg", package_msg);
1531
113
            UniValue tx_result_map{UniValue::VOBJ};
1532
113
            std::set<Txid> replaced_txids;
1533
372
            for (const auto& tx : txns) {
1534
372
                UniValue result_inner{UniValue::VOBJ};
1535
372
                result_inner.pushKV("txid", tx->GetHash().GetHex());
1536
372
                const auto wtxid_hex = tx->GetWitnessHash().GetHex();
1537
372
                auto it = package_result.m_tx_results.find(tx->GetWitnessHash());
1538
372
                if (it == package_result.m_tx_results.end()) {
1539
                    // No per-tx result for this wtxid
1540
                    // Current invariant: per-tx results are all-or-none (every member or empty on package abort).
1541
                    // If any exist yet this one is missing, it's an unexpected partial map.
1542
6
                    CHECK_NONFATAL(package_result.m_tx_results.empty());
1543
6
                    result_inner.pushKV("error", "package-not-validated");
1544
6
                    tx_result_map.pushKV(wtxid_hex, std::move(result_inner));
1545
6
                    continue;
1546
6
                }
1547
366
                const auto& tx_result = it->second;
1548
366
                switch(it->second.m_result_type) {
1549
1
                case MempoolAcceptResult::ResultType::DIFFERENT_WITNESS:
1550
1
                    result_inner.pushKV("other-wtxid", it->second.m_other_wtxid.value().GetHex());
1551
1
                    break;
1552
77
                case MempoolAcceptResult::ResultType::INVALID:
1553
77
                    result_inner.pushKV("error", it->second.m_state.ToString());
1554
77
                    break;
1555
199
                case MempoolAcceptResult::ResultType::VALID:
1556
288
                case MempoolAcceptResult::ResultType::MEMPOOL_ENTRY:
1557
288
                    result_inner.pushKV("vsize_adjusted", it->second.m_vsize.value());
1558
288
                    result_inner.pushKV("vsize", it->second.m_vsize.value());
1559
288
                    result_inner.pushKV("vsize_bip141", GetVirtualTransactionSize(*tx));
1560
288
                    UniValue fees(UniValue::VOBJ);
1561
288
                    fees.pushKV("base", ValueFromAmount(it->second.m_base_fees.value()));
1562
288
                    if (tx_result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
1563
                        // Effective feerate is not provided for MEMPOOL_ENTRY transactions even
1564
                        // though modified fees is known, because it is unknown whether package
1565
                        // feerate was used when it was originally submitted.
1566
199
                        fees.pushKV("effective-feerate", ValueFromAmount(tx_result.m_effective_feerate.value().GetFeePerK()));
1567
199
                        UniValue effective_includes_res(UniValue::VARR);
1568
267
                        for (const auto& wtxid : tx_result.m_wtxids_fee_calculations.value()) {
1569
267
                            effective_includes_res.push_back(wtxid.ToString());
1570
267
                        }
1571
199
                        fees.pushKV("effective-includes", std::move(effective_includes_res));
1572
199
                    }
1573
288
                    result_inner.pushKV("fees", std::move(fees));
1574
393
                    for (const auto& ptx : it->second.m_replaced_transactions) {
1575
393
                        replaced_txids.insert(ptx->GetHash());
1576
393
                    }
1577
288
                    break;
1578
366
                }
1579
366
                tx_result_map.pushKV(wtxid_hex, std::move(result_inner));
1580
366
            }
1581
113
            rpc_result.pushKV("tx-results", std::move(tx_result_map));
1582
113
            UniValue replaced_list(UniValue::VARR);
1583
393
            for (const auto& txid : replaced_txids) replaced_list.push_back(txid.ToString());
1584
113
            rpc_result.pushKV("replaced-transactions", std::move(replaced_list));
1585
113
            return rpc_result;
1586
113
        },
1587
2.66k
    };
1588
2.66k
}
1589
1590
void RegisterMempoolRPCCommands(CRPCTable& t)
1591
1.41k
{
1592
1.41k
    static const CRPCCommand commands[]{
1593
1.41k
        {"rawtransactions", &sendrawtransaction},
1594
1.41k
        {"rawtransactions", &getprivatebroadcastinfo},
1595
1.41k
        {"rawtransactions", &abortprivatebroadcast},
1596
1.41k
        {"rawtransactions", &testmempoolaccept},
1597
1.41k
        {"blockchain", &getmempoolancestors},
1598
1.41k
        {"blockchain", &getmempooldescendants},
1599
1.41k
        {"blockchain", &getmempoolentry},
1600
1.41k
        {"blockchain", &getmempoolcluster},
1601
1.41k
        {"blockchain", &gettxspendingprevout},
1602
1.41k
        {"blockchain", &getmempoolinfo},
1603
1.41k
        {"hidden", &getmempoolfeeratediagram},
1604
1.41k
        {"blockchain", &getrawmempool},
1605
1.41k
        {"blockchain", &importmempool},
1606
1.41k
        {"blockchain", &savemempool},
1607
1.41k
        {"hidden", &getorphantxs},
1608
1.41k
        {"rawtransactions", &submitpackage},
1609
1.41k
    };
1610
22.5k
    for (const auto& c : commands) {
1611
22.5k
        t.appendCommand(c.name, &c);
1612
22.5k
    }
1613
1.41k
}