9#include <chainparams.h>
22#include <validation.h>
35 "Submits raw transaction (serialized, hex-encoded) to local node and "
37 "\nAlso see createrawtransaction and "
38 "signrawtransactionwithkey calls.\n",
41 "The hex string of the raw transaction"},
45 "Reject transactions whose fee rate is higher than the specified "
46 "value, expressed in " +
48 "/kB\nSet to 0 to accept any fee rate.\n"},
52 "\nCreate a transaction\n" +
54 "createrawtransaction",
55 "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" "
56 "\"{\\\"myaddress\\\":10000}\"") +
57 "Sign the transaction, and get back the hex\n" +
59 "\nSend the transaction (signed hex)\n" +
61 "\nAs a JSON-RPC call\n" +
67 if (!
DecodeHexTx(mtx, request.params[0].get_str())) {
75 request.params[1].isNull()
80 Amount max_raw_tx_fee = max_raw_tx_fee_rate.
GetFee(virtual_size);
82 std::string err_string;
86 node, tx, err_string, max_raw_tx_fee,
true,
95 return tx->GetHash().GetHex();
104 "\nReturns result of mempool acceptance tests indicating if raw "
105 "transaction(s) (serialized, hex-encoded) would be accepted by "
107 "\nIf multiple transactions are passed in, parents must come before "
108 "children and package policies apply: the transactions cannot conflict "
109 "with any mempool transactions or each other.\n"
110 "\nIf one transaction fails, other transactions may not be fully "
111 "validated (the 'allowed' key will be blank).\n"
112 "\nThe maximum number of transactions allowed is " +
115 "\nThis checks if transactions violate the consensus or policy "
117 "\nSee sendrawtransaction call.\n",
123 "An array of hex strings of raw transactions.",
132 "Reject transactions whose fee rate is higher than the specified "
133 "value, expressed in " +
139 "The result of the mempool acceptance test for each raw "
140 "transaction in the input array.\n"
141 "Returns results for each transaction in the same order they were "
143 "Transactions that cannot be fully validated due to failures in "
144 "other transactions will not contain an 'allowed' result.\n",
151 "The transaction hash in hex"},
153 "Package validation error, if any (only possible if "
154 "rawtxs had more than 1 transaction)."},
156 "Whether this tx would be accepted to the mempool and "
157 "pass client-specified maxfeerate. "
158 "If not present, the tx was not fully validated due to a "
159 "failure in another tx in the list."},
163 "Transaction fees (only present if 'allowed' is true)",
166 "transaction fee in " + ticker},
168 "the effective feerate in " + ticker +
169 " per KvB. May differ from the base feerate if, "
170 "for example, there are modified fees from "
171 "prioritisetransaction or a package feerate was "
174 "effective-includes",
175 "transactions whose fees and vsizes are included in "
176 "effective-feerate.",
179 "transaction txid in hex"},
183 "Rejection string (only present when 'allowed' is "
188 "\nCreate a transaction\n" +
190 "createrawtransaction",
191 "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" "
192 "\"{\\\"myaddress\\\":10000}\"") +
193 "Sign the transaction, and get back the hex\n" +
195 "\nTest acceptance of the transaction (signed hex)\n" +
197 "\nAs a JSON-RPC call\n" +
202 if (raw_transactions.
size() < 1 ||
205 "Array must contain between 1 and " +
210 const CFeeRate max_raw_tx_fee_rate =
211 request.params[1].isNull()
215 std::vector<CTransactionRef> txns;
216 txns.reserve(raw_transactions.
size());
217 for (
const auto &rawtx : raw_transactions.
getValues()) {
221 "TX decode failed: " + rawtx.get_str());
232 if (txns.size() > 1) {
248 bool exit_early{
false};
249 for (
const auto &tx : txns) {
251 result_inner.
pushKV(
"txid", tx->GetId().GetHex());
258 auto it = package_result.
m_tx_results.find(tx->GetId());
259 if (exit_early || it == package_result.
m_tx_results.end()) {
264 const auto &tx_result = it->second;
269 if (tx_result.m_result_type ==
271 const Amount fee = tx_result.m_base_fees.value();
273 const int64_t virtual_size = tx_result.m_vsize.value();
274 const Amount max_raw_tx_fee =
275 max_raw_tx_fee_rate.
GetFee(virtual_size);
277 fee > max_raw_tx_fee) {
278 result_inner.
pushKV(
"allowed",
false);
279 result_inner.
pushKV(
"reject-reason",
286 result_inner.
pushKV(
"allowed",
true);
287 result_inner.
pushKV(
"size", virtual_size);
292 tx_result.m_effective_feerate.value().GetFeePerK());
294 for (
const auto &txid :
295 tx_result.m_txids_fee_calculations.value()) {
296 effective_includes_res.
push_back(txid.ToString());
298 fees.
pushKV(
"effective-includes",
299 effective_includes_res);
300 result_inner.
pushKV(
"fees", fees);
303 result_inner.
pushKV(
"allowed",
false);
307 result_inner.
pushKV(
"reject-reason",
"missing-inputs");
309 result_inner.
pushKV(
"reject-reason",
325 "local time transaction entered pool in seconds since 1 Jan "
328 "block height when transaction entered pool"},
334 "transaction fee in " + ticker},
336 "transaction fee with fee deltas used for "
337 "mining priority in " +
343 "unconfirmed transactions used as inputs for this transaction",
345 "parent transaction id"}}},
349 "unconfirmed transactions spending outputs from this transaction",
351 "child transaction id"}}},
353 "Whether this transaction is currently unbroadcast (initial "
354 "broadcast not yet acknowledged by any peers)"},
364 fees.
pushKV(
"base", e->GetFee());
365 fees.
pushKV(
"modified", e->GetModifiedFee());
366 info.pushKV(
"fees", fees);
368 info.pushKV(
"size", (
int)e->GetTxSize());
370 info.pushKV(
"height", (
int)e->GetHeight());
371 const CTransaction &tx = e->GetTx();
372 std::set<std::string> setDepends;
373 for (
const CTxIn &txin : tx.vin) {
374 if (pool.exists(txin.prevout.GetTxId())) {
375 setDepends.insert(txin.prevout.GetTxId().ToString());
380 for (
const std::string &dep : setDepends) {
384 info.pushKV(
"depends", depends);
387 for (
const auto &child : e->GetMemPoolChildrenConst()) {
388 spent.
push_back(child.get()->GetTx().GetId().ToString());
391 info.pushKV(
"spentby", spent);
392 info.pushKV(
"unbroadcast", pool.IsUnbroadcastTx(tx.GetId()));
396 bool include_mempool_sequence) {
398 if (include_mempool_sequence) {
401 "Verbose results cannot contain mempool sequence values.");
406 const TxId &txid = e->GetTx().GetId();
416 uint64_t mempool_sequence;
417 std::vector<TxId> vtxids;
424 for (
const TxId &txid : vtxids) {
428 if (!include_mempool_sequence) {
433 o.
pushKV(
"mempool_sequence", mempool_sequence);
442 "Returns all transaction ids in memory pool as a json array of "
443 "string transaction ids.\n"
444 "\nHint: use getmempoolentry to fetch a specific transaction from the "
448 "True for a json object, false for array of transaction ids"},
450 "If verbose=false, returns a json object with transaction list "
451 "and mempool sequence number attached."},
470 "for verbose = false and mempool_sequence = true",
482 "The mempool sequence value."},
489 bool fVerbose =
false;
490 if (!request.params[0].isNull()) {
491 fVerbose = request.params[0].
get_bool();
494 bool include_mempool_sequence =
false;
495 if (!request.params[1].isNull()) {
496 include_mempool_sequence = request.params[1].get_bool();
500 include_mempool_sequence);
507 "getmempoolancestors",
508 "If txid is in the mempool, returns all in-mempool ancestors.\n",
511 "The transaction id (must be in mempool)"},
513 "True for a json object, false for array of transaction ids"},
517 "for verbose = false",
522 "The transaction id of an in-mempool ancestor transaction"}}},
536 bool fVerbose =
false;
537 if (!request.params[1].isNull()) {
538 fVerbose = request.params[1].
get_bool();
547 if (it == mempool.mapTx.end()) {
549 "Transaction not in mempool");
558 o.
push_back((*ancestorIt)->GetTx().GetId().ToString());
565 const TxId &_txid = e->GetTx().GetId();
578 "getmempooldescendants",
579 "If txid is in the mempool, returns all in-mempool descendants.\n",
582 "The transaction id (must be in mempool)"},
584 "True for a json object, false for array of transaction ids"},
592 "The transaction id of an in-mempool descendant "
607 bool fVerbose =
false;
608 if (!request.params[1].isNull()) {
609 fVerbose = request.params[1].
get_bool();
618 if (it == mempool.mapTx.end()) {
620 "Transaction not in mempool");
626 setDescendants.erase(it);
631 o.
push_back((*descendantIt)->GetTx().GetId().ToString());
639 const TxId &_txid = e->GetTx().GetId();
653 "Returns mempool data for given transaction\n",
656 "The transaction id (must be in mempool)"},
669 if (it == mempool.mapTx.end()) {
671 "Transaction not in mempool");
703 "Returns details on the active state of the TX memory pool.\n",
711 "True if the mempool is fully loaded"},
715 "Total memory usage for the mempool"},
717 "Maximum memory usage for the mempool"},
719 "Total fees for the mempool in " + ticker +
720 ", ignoring modified fees through prioritizetransaction"},
722 "Minimum fee rate in " + ticker +
723 "/kB for tx to be accepted. Is the maximum of "
724 "minrelaytxfee and minimum mempool fee"},
726 "Current minimum relay fee for transactions"},
728 "Current number of transactions that haven't passed initial "
743 "Dumps the mempool to disk. It will fail until the previous dump is "
751 "the directory and file where the mempool was saved"},
762 "The mempool was not loaded yet");
769 "Unable to dump mempool to disk");
784 "Submit a package of raw transactions (serialized, hex-encoded) to "
786 "The package must consist of a child with its parents, and none of the "
787 "parents may depend on one another.\n"
788 "The package will be validated according to consensus and mempool "
789 "policy rules. If any transaction passes, it will be accepted to "
791 "This RPC is experimental and the interface may be unstable. Refer to "
792 "doc/policy/packages.md for documentation on package policies.\n"
793 "Warning: successful submission does not mean the transactions will "
794 "propagate throughout the network.\n",
800 "An array of raw transactions.",
813 "The transaction package result message. \"success\" "
814 "indicates all transactions were accepted into or are already "
818 "transaction results keyed by txid",
824 "Virtual transaction size."},
831 "transaction fee in " + ticker},
833 "the effective feerate in " + ticker +
834 " per KvB. May differ from the base feerate "
835 "if, for example, there are modified fees "
836 "from prioritisetransaction or a package "
837 "feerate was used."},
839 "effective-includes",
840 "transactions whose fees and vsizes are included "
841 "in effective-feerate.",
844 "transaction txid in hex"},
848 "The transaction error string, if it was rejected by "
858 if (raw_transactions.
size() < 1 ||
861 "Array must contain between 1 and " +
866 std::vector<CTransactionRef> txns;
867 txns.reserve(raw_transactions.
size());
868 for (
const auto &rawtx : raw_transactions.
getValues()) {
873 "TX decode failed: " + rawtx.get_str() +
874 " Make sure the tx has at least one input.");
881 "package topology disallowed. not child-with-parents or "
882 "parents depend on each other.");
892 std::string package_msg =
"success";
895 switch (package_result.m_state.GetResult()) {
901 for (
const auto &tx : txns) {
911 package_result.m_state.GetRejectReason());
917 package_msg = package_result.m_state.GetRejectReason();
920 package_result.m_tx_results.empty());
924 size_t num_broadcast{0};
925 for (
const auto &tx : txns) {
928 if (!mempool.
exists(tx->GetId())) {
934 std::string err_string;
941 strprintf(
"transaction broadcast failed: %s (%d "
942 "transactions were broadcast successfully)",
943 err_string, num_broadcast));
949 rpc_result.pushKV(
"package_msg", package_msg);
951 for (
const auto &tx : txns) {
953 auto it = package_result.m_tx_results.find(tx->GetId());
954 if (it == package_result.m_tx_results.end()) {
956 result_inner.pushKV(
"error",
"unevaluated");
959 const auto &tx_result = it->second;
960 switch (it->second.m_result_type) {
962 result_inner.pushKV(
"error",
963 it->second.m_state.ToString());
968 "vsize", int64_t{it->second.m_vsize.value()});
970 fees.
pushKV(
"base", it->second.m_base_fees.value());
971 if (tx_result.m_result_type ==
978 fees.
pushKV(
"effective-feerate",
979 tx_result.m_effective_feerate.value()
982 for (
const auto &txid :
983 tx_result.m_txids_fee_calculations.value()) {
987 fees.
pushKV(
"effective-includes",
988 effective_includes_res);
990 result_inner.pushKV(
"fees", fees);
993 tx_result_map.pushKV(tx->GetId().GetHex(), result_inner);
995 rpc_result.pushKV(
"tx-results", tx_result_map);
1016 for (
const auto &c : commands) {
#define CHECK_NONFATAL(condition)
Identity function.
Fee rate in satoshis per kilobyte: Amount / kB.
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Amount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
A mutable version of CTransaction.
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
std::set< txiter, CompareIteratorById > setEntries
bool GetLoadTried() const
CFeeRate GetMinFee() const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Amount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
const int64_t m_max_size_bytes
void getAllTxIds(std::vector< TxId > &vtxid) const
size_t DynamicMemoryUsage() const
bool exists(const TxId &txid) const
std::set< TxId > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
const CFeeRate m_min_relay_feerate
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
bool CalculateMemPoolAncestors(const CTxMemPoolEntryRef &entry, setEntries &setAncestors, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
unsigned long size() const
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & ActiveChainstate() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
void push_back(UniValue val)
const std::vector< UniValue > & getValues() const
void pushKVEnd(std::string key, UniValue val)
const UniValue & get_array() const
void pushKV(std::string key, UniValue val)
std::string GetRejectReason() const
std::string ToString() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
std::string u8string() const
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
static RPCHelpMan getmempoolinfo()
static RPCHelpMan sendrawtransaction()
void RegisterMempoolRPCCommands(CRPCTable &t)
Register mempool RPC commands.
static RPCHelpMan getrawmempool()
static RPCHelpMan getmempoolentry()
UniValue MempoolInfoToJSON(const CTxMemPool &pool)
Mempool information to JSON.
static std::vector< RPCResult > MempoolEntryDescription()
static RPCHelpMan submitpackage()
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
static void entryToJSON(const CTxMemPool &pool, UniValue &info, const CTxMemPoolEntryRef &e) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
static RPCHelpMan testmempoolaccept()
static RPCHelpMan getmempooldescendants()
static RPCHelpMan getmempoolancestors()
static RPCHelpMan savemempool()
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, FopenFn mockable_fopen_function, bool skip_file_commit)
TransactionError BroadcastTransaction(const NodeContext &node, const CTransactionRef tx, std::string &err_string, const Amount max_tx_fee, bool relay, bool wait_callback)
Submit a transaction to the mempool and (optionally) relay it to all P2P peers.
fs::path MempoolPath(const ArgsManager &argsman)
bool ShouldPersistMempool(const ArgsManager &argsman)
static const CFeeRate DEFAULT_MAX_RAW_TX_FEE_RATE
Maximum fee rate for sendrawtransaction and testmempoolaccept RPC calls.
bool IsChildWithParentsTree(const Package &package)
Context-free check that a package IsChildWithParents() and none of the parents depend on each other (...
static constexpr uint32_t MAX_PACKAGE_COUNT
Default maximum number of transactions in a package.
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
@ PCKG_RESULT_UNSET
Initial value. The package has not yet been rejected.
@ PCKG_MEMPOOL_ERROR
Mempool logic error.
@ PCKG_TX
At least one tx is invalid.
int64_t GetVirtualTransactionSize(int64_t nSize, int64_t nSigChecks, unsigned int bytes_per_sigCheck)
Compute the virtual transaction size (size, or more if sigChecks are too dense).
static CTransactionRef MakeTransactionRef()
std::shared_ptr< const CTransaction > CTransactionRef
UniValue JSONRPCError(int code, const std::string &message)
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Amount AmountFromValue(const UniValue &value)
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
NodeContext & EnsureAnyNodeContext(const std::any &context)
CTxMemPool & EnsureMemPool(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
CTxMemPool & EnsureAnyMemPool(const std::any &context)
ArgsManager & EnsureAnyArgsman(const std::any &context)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
static constexpr Amount zero() noexcept
static const Currency & get()
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
Validation result for package mempool acceptance.
PackageValidationState m_state
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
@ STR_HEX
Special type that is a STR with only hex chars.
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
@ OMITTED
The arg is optional for one of two reasons:
@ NUM_TIME
Special numeric to denote unix epoch time.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
A TxId is the identifier of a transaction.
NodeContext struct containing references to chain state and connection state.
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
constexpr int64_t count_seconds(std::chrono::seconds t)
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...