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