8#include <blockfilter.h>
51#include <condition_variable>
67 auto node_context = util::AnyPtr<NodeContext>(context);
92 return *
node.chainman;
102 if (!
node.fee_estimator) {
105 return *
node.fee_estimator;
119 int nShift = (blockindex->
nBits >> 24) & 0xff;
121 (double)0x0000ffff / (
double)(blockindex->
nBits & 0x00ffffff);
140 if (next && next->
pprev == blockindex) {
144 return blockindex == tip ? 1 : -1;
152 const int height{param.
get_int()};
156 const int current_tip{active_chain.
Height()};
157 if (height > current_tip) {
161 return active_chain[height];
164 CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
183 result.
pushKV(
"confirmations", confirmations);
194 result.
pushKV(
"nTx", (uint64_t)blockindex->
nTx);
196 if (blockindex->
pprev)
224 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
227 const CTxUndo* txundo = (have_undo && i > 0) ? &blockUndo.
vtxundo.at(i - 1) :
nullptr;
242 "\nReturns the height of the most-work fully-validated chain.\n"
243 "The genesis block has height 0.\n",
263 "\nReturns the hash of the best (tip) block in the most-work fully-validated chain.\n",
285 latestblock.height = pindex->
nHeight;
293 "\nWaits for a specific new block and returns useful info about it.\n"
294 "\nReturns the current block on timeout or exit.\n",
311 if (!request.params[0].isNull())
312 timeout = request.params[0].
get_int();
335 "\nWaits for a specific new block and returns useful info about it.\n"
336 "\nReturns the current block on timeout or exit.\n",
348 HelpExampleCli(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\" 1000")
349 +
HelpExampleRpc(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
357 if (!request.params[1].isNull())
358 timeout = request.params[1].get_int();
381 "\nWaits for (at least) block height and returns the height and hash\n"
382 "of the current tip.\n"
383 "\nReturns the current block on timeout or exit.\n",
402 int height = request.params[0].
get_int();
404 if (!request.params[1].isNull())
405 timeout = request.params[1].get_int();
426 return RPCHelpMan{
"syncwithvalidationinterfacequeue",
427 "\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n",
445 "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
448 RPCResult::Type::NUM,
"",
"the proof-of-work difficulty as a multiple of the minimum difficulty."},
463 RPCResult{
RPCResult::Type::NUM,
"vsize",
"virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted."},
488 RPCResult{
RPCResult::Type::BOOL,
"unbroadcast",
"Whether this transaction is currently unbroadcast (initial broadcast not yet acknowledged by any peers)"},
500 info.pushKV(
"fees", fees);
502 info.pushKV(
"vsize", (
int)e.GetTxSize());
503 info.pushKV(
"weight", (
int)e.GetTxWeight());
507 info.pushKV(
"height", (
int)e.GetHeight());
508 info.pushKV(
"descendantcount", e.GetCountWithDescendants());
509 info.pushKV(
"descendantsize", e.GetSizeWithDescendants());
510 info.pushKV(
"descendantfees", e.GetModFeesWithDescendants());
511 info.pushKV(
"ancestorcount", e.GetCountWithAncestors());
512 info.pushKV(
"ancestorsize", e.GetSizeWithAncestors());
513 info.pushKV(
"ancestorfees", e.GetModFeesWithAncestors());
514 info.pushKV(
"wtxid", pool.vTxHashes[e.vTxHashesIdx].first.ToString());
516 std::set<std::string> setDepends;
524 for (
const std::string& dep : setDepends)
529 info.pushKV(
"depends", depends);
535 spent.
push_back(child.GetTx().GetHash().ToString());
538 info.pushKV(
"spentby", spent);
541 bool rbfStatus =
false;
549 info.pushKV(
"bip125-replaceable", rbfStatus);
550 info.pushKV(
"unbroadcast", pool.IsUnbroadcastTx(tx.
GetHash()));
556 if (include_mempool_sequence) {
572 uint64_t mempool_sequence;
573 std::vector<uint256> vtxid;
580 for (
const uint256& hash : vtxid)
583 if (!include_mempool_sequence) {
588 o.
pushKV(
"mempool_sequence", mempool_sequence);
597 "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
598 "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n",
601 {
"mempool_sequence",
RPCArg::Type::BOOL,
RPCArg::Default{
false},
"If verbose=false, returns a json object with transaction list and mempool sequence number attached."},
614 RPCResult{
"for verbose = false and mempool_sequence = true",
630 bool fVerbose =
false;
631 if (!request.params[0].isNull())
632 fVerbose = request.params[0].
get_bool();
634 bool include_mempool_sequence =
false;
635 if (!request.params[1].isNull()) {
636 include_mempool_sequence = request.params[1].get_bool();
647 "\nIf txid is in the mempool, returns all in-mempool ancestors.\n",
668 bool fVerbose =
false;
669 if (!request.params[1].isNull())
670 fVerbose = request.params[1].
get_bool();
678 if (it == mempool.mapTx.end()) {
683 uint64_t noLimit = std::numeric_limits<uint64_t>::max();
690 o.
push_back(ancestorIt->GetTx().GetHash().ToString());
711 "\nIf txid is in the mempool, returns all in-mempool descendants.\n",
732 bool fVerbose =
false;
733 if (!request.params[1].isNull())
734 fVerbose = request.params[1].
get_bool();
742 if (it == mempool.mapTx.end()) {
749 setDescendants.erase(it);
754 o.
push_back(descendantIt->GetTx().GetHash().ToString());
776 "\nReturns mempool data for given transaction\n",
794 if (it == mempool.mapTx.end()) {
809 "\nReturns hash of block in best-block-chain at height provided.\n",
825 int nHeight = request.params[0].get_int();
826 if (nHeight < 0 || nHeight > active_chain.
Height())
838 "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
839 "If verbose is true, returns an Object with information about blockheader <hash>.\n",
849 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
868 HelpExampleCli(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
869 +
HelpExampleRpc(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
875 bool fVerbose =
true;
876 if (!request.params[1].isNull())
877 fVerbose = request.params[1].get_bool();
884 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
896 std::string strHex =
HexStr(ssBlock);
939 "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
940 "If verbosity is 1, returns an Object with information about block <hash>.\n"
941 "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction.\n"
942 "If verbosity is 3, returns an Object with information about block <hash> and information about each transaction, including prevout information for inputs (only for unpruned blocks in the current best chain).\n",
954 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
969 {
RPCResult::Type::STR_HEX,
"chainwork",
"Expected number of hashes required to produce the chain up to this block (in hex)"},
982 {
RPCResult::Type::ELISION,
"",
"The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result"},
989 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
990 +
HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
997 if (!request.params[1].isNull()) {
998 if (request.params[1].isBool()) {
999 verbosity = request.params[1].get_bool() ? 1 : 0;
1001 verbosity = request.params[1].get_int();
1011 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1025 std::string strHex =
HexStr(ssBlock);
1030 if (verbosity == 1) {
1032 }
else if (verbosity == 2) {
1038 return blockToJSON(block, tip, pblockindex, tx_verbosity);
1048 " to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
1066 int heightParam = request.params[0].get_int();
1067 if (heightParam < 0)
1072 if (heightParam > 1000000000) {
1078 heightParam = pindex->
nHeight;
1081 unsigned int height = (
unsigned int) heightParam;
1082 unsigned int chainHeight = (
unsigned int) active_chain.
Height();
1085 else if (height > chainHeight)
1088 LogPrint(
BCLog::RPC,
"Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
1096 block = block->
pprev;
1098 return uint64_t(block->
nHeight);
1105 if (hash_type_input ==
"hash_serialized_2") {
1107 }
else if (hash_type_input ==
"muhash") {
1109 }
else if (hash_type_input ==
"none") {
1119 "\nReturns statistics about the unspent transaction output set.\n"
1120 "Note this call may take some time if you are not using coinstatsindex.\n",
1122 {
"hash_type",
RPCArg::Type::STR,
RPCArg::Default{
"hash_serialized_2"},
"Which UTXO set hash should be calculated. Options: 'hash_serialized_2' (the legacy algorithm), 'muhash', 'none'."},
1132 {
RPCResult::Type::NUM,
"bogosize",
"Database-independent, meaningless metric indicating the UTXO set size"},
1133 {
RPCResult::Type::STR_HEX,
"hash_serialized_2",
true,
"The serialized hash (only present if 'hash_serialized_2' hash_type is chosen)"},
1135 {
RPCResult::Type::NUM,
"transactions",
true,
"The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
1136 {
RPCResult::Type::NUM,
"disk_size",
true,
"The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
1138 {
RPCResult::Type::STR_AMOUNT,
"total_unspendable_amount",
true,
"The total amount of coins permanently excluded from the UTXO set (only available if coinstatsindex is used)"},
1139 {
RPCResult::Type::OBJ,
"block_info",
true,
"Info on amounts in the block at this block height (only available if coinstatsindex is used)",
1158 HelpExampleCli("gettxoutsetinfo", R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1162 HelpExampleRpc("gettxoutsetinfo", R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")
1171 stats.
index_requested = request.params[2].isNull() || request.params[2].get_bool();
1182 coins_view = &active_chainstate.
CoinsDB();
1187 if (!request.params[1].isNull()) {
1205 if (pindex->nHeight > summary.best_block_height) {
1211 if (
GetUTXOStats(coins_view, *blockman, stats,
node.rpc_interruption_point, pindex)) {
1212 ret.
pushKV(
"height", (int64_t)stats.nHeight);
1213 ret.
pushKV(
"bestblock", stats.hashBlock.GetHex());
1214 ret.
pushKV(
"txouts", (int64_t)stats.nTransactionOutputs);
1215 ret.
pushKV(
"bogosize", (int64_t)stats.nBogoSize);
1217 ret.
pushKV(
"hash_serialized_2", stats.hashSerialized.GetHex());
1220 ret.
pushKV(
"muhash", stats.hashSerialized.GetHex());
1223 if (!stats.index_used) {
1224 ret.
pushKV(
"transactions",
static_cast<int64_t
>(stats.nTransactions));
1225 ret.
pushKV(
"disk_size", stats.nDiskSize);
1231 if (pindex->nHeight > 0) {
1232 GetUTXOStats(coins_view, *blockman, prev_stats,
node.rpc_interruption_point, pindex->pprev);
1236 block_info.
pushKV(
"prevout_spent",
ValueFromAmount(stats.total_prevout_spent_amount - prev_stats.total_prevout_spent_amount));
1237 block_info.
pushKV(
"coinbase",
ValueFromAmount(stats.total_coinbase_amount - prev_stats.total_coinbase_amount));
1238 block_info.
pushKV(
"new_outputs_ex_coinbase",
ValueFromAmount(stats.total_new_outputs_ex_coinbase_amount - prev_stats.total_new_outputs_ex_coinbase_amount));
1239 block_info.
pushKV(
"unspendable",
ValueFromAmount(stats.total_unspendable_amount - prev_stats.total_unspendable_amount));
1242 unspendables.
pushKV(
"genesis_block",
ValueFromAmount(stats.total_unspendables_genesis_block - prev_stats.total_unspendables_genesis_block));
1243 unspendables.
pushKV(
"bip30",
ValueFromAmount(stats.total_unspendables_bip30 - prev_stats.total_unspendables_bip30));
1244 unspendables.
pushKV(
"scripts",
ValueFromAmount(stats.total_unspendables_scripts - prev_stats.total_unspendables_scripts));
1245 unspendables.
pushKV(
"unclaimed_rewards",
ValueFromAmount(stats.total_unspendables_unclaimed_rewards - prev_stats.total_unspendables_unclaimed_rewards));
1246 block_info.
pushKV(
"unspendables", unspendables);
1248 ret.
pushKV(
"block_info", block_info);
1261 "\nReturns details about an unspent transaction output.\n",
1265 {
"include_mempool",
RPCArg::Type::BOOL,
RPCArg::Default{
true},
"Whether to include the mempool. Note that an unspent output that is spent in the mempool won't appear."},
1277 {
RPCResult::Type::STR,
"address",
true,
"The Bitcoin address (only if a well-defined address exists)"},
1283 "\nGet unspent transactions\n"
1285 "\nView the details\n"
1287 "\nAs a JSON-RPC call\n"
1299 int n = request.params[1].get_int();
1301 bool fMempool =
true;
1302 if (!request.params[2].isNull())
1303 fMempool = request.params[2].get_bool();
1317 if (!coins_view->
GetCoin(out, coin)) {
1325 ret.
pushKV(
"confirmations", 0);
1332 ret.
pushKV(
"scriptPubKey", o);
1343 "\nVerifies blockchain database.\n",
1357 const int check_level(request.params[0].isNull() ?
DEFAULT_CHECKLEVEL : request.params[0].get_int());
1358 const int check_depth{request.params[1].isNull() ?
DEFAULT_CHECKBLOCKS : request.params[1].get_int()};
1365 active_chainstate,
Params(), active_chainstate.
CoinsTip(), check_level, check_depth);
1377 rv.
pushKV(
"type",
"buried");
1393 switch (thresholdState) {
1407 bip9.
pushKV(
"since", since_height);
1418 bip9.
pushKV(
"statistics", statsUV);
1423 rv.
pushKV(
"type",
"bip9");
1426 rv.
pushKV(
"height", since_height);
1436 "Returns an object containing various state info regarding blockchain processing.\n",
1442 {
RPCResult::Type::NUM,
"blocks",
"the height of the most-work fully-validated chain. The genesis block has height 0"},
1449 {
RPCResult::Type::BOOL,
"initialblockdownload",
"(debug information) estimate of whether this node is in Initial Block Download mode"},
1451 {
RPCResult::Type::NUM,
"size_on_disk",
"the estimated size of the block and undo files on disk"},
1453 {
RPCResult::Type::NUM,
"pruneheight",
true,
"lowest-height complete block stored (only present if pruning is enabled)"},
1454 {
RPCResult::Type::BOOL,
"automatic_pruning",
true,
"whether automatic pruning is enabled (only present if pruning is enabled)"},
1455 {
RPCResult::Type::NUM,
"prune_target_size",
true,
"the target size used by pruning (only present if automatic pruning is enabled)"},
1463 {
RPCResult::Type::STR,
"status",
"one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\""},
1464 {
RPCResult::Type::NUM,
"bit",
true,
"the bit (0-28) in the block version field used to signal this softfork (only for \"started\" and \"locked_in\" status)"},
1465 {
RPCResult::Type::NUM_TIME,
"start_time",
"the minimum median time past of a block at which the bit gains its meaning"},
1466 {
RPCResult::Type::NUM_TIME,
"timeout",
"the median time past of a block at which the deployment is considered failed if not yet locked in"},
1468 {
RPCResult::Type::NUM,
"min_activation_height",
"minimum height of blocks for which the rules may be enforced"},
1469 {
RPCResult::Type::OBJ,
"statistics",
true,
"numeric statistics about signalling for a softfork (only for \"started\" and \"locked_in\" status)",
1472 {
RPCResult::Type::NUM,
"threshold",
true,
"the number of blocks with the version bit set required to activate the feature (only for \"started\" status)"},
1473 {
RPCResult::Type::NUM,
"elapsed",
"the number of blocks elapsed since the beginning of the current period"},
1474 {
RPCResult::Type::NUM,
"count",
"the number of blocks with the version bit set in the current period"},
1475 {
RPCResult::Type::BOOL,
"possible",
true,
"returns false if there are not enough blocks left in this period to pass activation threshold (only for \"started\" status)"},
1478 {
RPCResult::Type::NUM,
"height",
true,
"height of the first block which the rules are or will be enforced (only for \"buried\" type, or \"bip9\" type with \"active\" status)"},
1479 {
RPCResult::Type::BOOL,
"active",
"true if the rules are enforced for the mempool and the next block"},
1496 const int height = tip->
nHeight;
1499 obj.
pushKV(
"blocks", height);
1514 block = block->
pprev;
1521 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1522 if (automatic_pruning) {
1536 obj.
pushKV(
"softforks", softforks);
1562 "Return information about all known tips in the block tree,"
1563 " including the main chain as well as orphaned branches.\n",
1571 {
RPCResult::Type::NUM,
"branchlen",
"zero for main chain, otherwise length of branch connecting the tip to the main chain"},
1573 "Possible values for status:\n"
1574 "1. \"invalid\" This branch contains at least one invalid block\n"
1575 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
1576 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
1577 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
1578 "5. \"active\" This is the tip of the active main chain, which is certainly valid"},
1597 std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1598 std::set<const CBlockIndex*> setOrphans;
1599 std::set<const CBlockIndex*> setPrevs;
1601 for (
const std::pair<const uint256, CBlockIndex*>& item : chainman.
BlockIndex()) {
1602 if (!active_chain.
Contains(item.second)) {
1603 setOrphans.insert(item.second);
1604 setPrevs.insert(item.second->pprev);
1608 for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) {
1609 if (setPrevs.erase(*it) == 0) {
1610 setTips.insert(*it);
1615 setTips.insert(active_chain.
Tip());
1621 obj.
pushKV(
"height", block->nHeight);
1622 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1624 const int branchLen = block->nHeight - active_chain.
FindFork(block)->
nHeight;
1625 obj.
pushKV(
"branchlen", branchLen);
1628 if (active_chain.
Contains(block)) {
1634 }
else if (!block->HaveTxsDownloaded()) {
1636 status =
"headers-only";
1639 status =
"valid-fork";
1642 status =
"valid-headers";
1647 obj.
pushKV(
"status", status);
1668 ret.
pushKV(
"maxmempool", (int64_t) maxmempool);
1678 "\nReturns details on the active state of the TX memory pool.\n",
1685 {
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"},
1691 {
RPCResult::Type::NUM,
"unbroadcastcount",
"Current number of transactions that haven't passed initial broadcast yet"}
1707 "\nTreats a block as if it were received before others with the same work.\n"
1708 "\nA later preciousblock call can override the effect of an earlier one.\n"
1709 "\nThe effects of preciousblock are not retained across restarts.\n",
1726 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1747 "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n",
1765 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1788 "\nRemoves invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n"
1789 "This can be used to undo the effects of invalidateblock.\n",
1805 CBlockIndex* pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1828 "\nCompute statistics about the total number and rate of transactions in the chain.\n",
1837 {
RPCResult::Type::NUM,
"txcount",
"The total number of transactions in the chain up to that point"},
1839 {
RPCResult::Type::NUM,
"window_final_block_height",
"The height of the final block in the window."},
1841 {
RPCResult::Type::NUM,
"window_tx_count",
true,
"The number of transactions in the window. Only returned if \"window_block_count\" is > 0"},
1842 {
RPCResult::Type::NUM,
"window_interval",
true,
"The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0"},
1843 {
RPCResult::Type::NUM,
"txrate",
true,
"The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0"},
1855 if (request.params[1].isNull()) {
1861 pindex = chainman.m_blockman.LookupBlockIndex(hash);
1872 if (request.params[0].isNull()) {
1873 blockcount = std::max(0, std::min(blockcount, pindex->
nHeight - 1));
1875 blockcount = request.params[0].get_int();
1877 if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->
nHeight)) {
1891 ret.
pushKV(
"window_block_count", blockcount);
1892 if (blockcount > 0) {
1893 ret.
pushKV(
"window_tx_count", nTxDiff);
1894 ret.
pushKV(
"window_interval", nTimeDiff);
1895 if (nTimeDiff > 0) {
1896 ret.
pushKV(
"txrate", ((
double)nTxDiff) / nTimeDiff);
1908 size_t size = scores.size();
1913 std::sort(scores.begin(), scores.end());
1914 if (size % 2 == 0) {
1915 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1917 return scores[size / 2];
1923 if (scores.empty()) {
1927 std::sort(scores.begin(), scores.end());
1931 total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
1934 int64_t next_percentile_index = 0;
1935 int64_t cumulative_weight = 0;
1936 for (
const auto& element : scores) {
1937 cumulative_weight += element.second;
1938 while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
1939 result[next_percentile_index] = element.first;
1940 ++next_percentile_index;
1946 result[i] = scores.back().first;
1951static inline bool SetHasKeys(
const std::set<T>& set) {
return false;}
1952template<
typename T,
typename Tk,
typename... Args>
1953static inline bool SetHasKeys(
const std::set<T>& set,
const Tk& key,
const Args&... args)
1955 return (set.count(key) != 0) ||
SetHasKeys(set, args...);
1964 "\nCompute per block statistics for a given window. All amounts are in satoshis.\n"
1965 "It won't work for some heights with pruning.\n",
1982 {
RPCResult::Type::ARR_FIXED,
"feerate_percentiles",
true,
"Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
2007 {
RPCResult::Type::NUM,
"total_out",
true,
"Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
2012 {
RPCResult::Type::NUM,
"utxo_increase",
true,
"The increase/decrease in the number of unspent outputs"},
2013 {
RPCResult::Type::NUM,
"utxo_size_inc",
true,
"The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
2016 HelpExampleCli(
"getblockstats", R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2017 HelpExampleCli("getblockstats", R
"(1000 '["minfeerate","avgfeerate"]')") +
2018 HelpExampleRpc("getblockstats", R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2019 HelpExampleRpc("getblockstats", R
"(1000, ["minfeerate","avgfeerate"])")
2028 std::set<std::string> stats;
2029 if (!request.params[1].isNull()) {
2031 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2032 const std::string stat = stats_univalue[i].
get_str();
2040 const bool do_all = stats.size() == 0;
2041 const bool do_mediantxsize = do_all || stats.count(
"mediantxsize") != 0;
2042 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
2043 const bool do_feerate_percentiles = do_all || stats.count(
"feerate_percentiles") != 0;
2044 const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
2045 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
"avgfeerate",
"minfee",
"maxfee",
"minfeerate",
"maxfeerate");
2046 const bool loop_outputs = do_all || loop_inputs || stats.count(
"total_out");
2047 const bool do_calculate_size = do_mediantxsize ||
2048 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
"maxtxsize",
"swtotal_size");
2049 const bool do_calculate_weight = do_all ||
SetHasKeys(stats,
"total_weight",
"avgfeerate",
"swtotal_weight",
"avgfeerate",
"feerate_percentiles",
"minfeerate",
"maxfeerate");
2050 const bool do_calculate_sw = do_all ||
SetHasKeys(stats,
"swtxs",
"swtotal_size",
"swtotal_weight");
2059 int64_t maxtxsize = 0;
2061 int64_t outputs = 0;
2062 int64_t swtotal_size = 0;
2063 int64_t swtotal_weight = 0;
2065 int64_t total_size = 0;
2066 int64_t total_weight = 0;
2067 int64_t utxo_size_inc = 0;
2068 std::vector<CAmount> fee_array;
2069 std::vector<std::pair<CAmount, int64_t>> feerate_array;
2070 std::vector<int64_t> txsize_array;
2072 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2073 const auto& tx = block.
vtx.at(i);
2074 outputs += tx->vout.size();
2078 for (
const CTxOut& out : tx->vout) {
2079 tx_total_out += out.
nValue;
2084 if (tx->IsCoinBase()) {
2088 inputs += tx->vin.size();
2089 total_out += tx_total_out;
2091 int64_t tx_size = 0;
2092 if (do_calculate_size) {
2094 tx_size = tx->GetTotalSize();
2095 if (do_mediantxsize) {
2096 txsize_array.push_back(tx_size);
2098 maxtxsize = std::max(maxtxsize, tx_size);
2099 mintxsize = std::min(mintxsize, tx_size);
2100 total_size += tx_size;
2104 if (do_calculate_weight) {
2106 total_weight += weight;
2109 if (do_calculate_sw && tx->HasWitness()) {
2111 swtotal_size += tx_size;
2112 swtotal_weight += weight;
2117 const auto& txundo = blockUndo.
vtxundo.at(i - 1);
2118 for (
const Coin& coin: txundo.vprevout) {
2121 tx_total_in += prevoutput.
nValue;
2125 CAmount txfee = tx_total_in - tx_total_out;
2128 fee_array.push_back(txfee);
2130 maxfee = std::max(maxfee, txfee);
2131 minfee = std::min(minfee, txfee);
2136 if (do_feerate_percentiles) {
2137 feerate_array.emplace_back(std::make_pair(feerate, weight));
2139 maxfeerate = std::max(maxfeerate, feerate);
2140 minfeerate = std::min(minfeerate, feerate);
2149 feerates_res.
push_back(feerate_percentiles[i]);
2153 ret_all.
pushKV(
"avgfee", (block.
vtx.size() > 1) ? totalfee / (block.
vtx.size() - 1) : 0);
2155 ret_all.
pushKV(
"avgtxsize", (block.
vtx.size() > 1) ? total_size / (block.
vtx.size() - 1) : 0);
2156 ret_all.
pushKV(
"blockhash", pindex->GetBlockHash().GetHex());
2157 ret_all.
pushKV(
"feerate_percentiles", feerates_res);
2158 ret_all.
pushKV(
"height", (int64_t)pindex->nHeight);
2159 ret_all.
pushKV(
"ins", inputs);
2160 ret_all.
pushKV(
"maxfee", maxfee);
2161 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2162 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2164 ret_all.
pushKV(
"mediantime", pindex->GetMedianTimePast());
2167 ret_all.
pushKV(
"minfeerate", (minfeerate ==
MAX_MONEY) ? 0 : minfeerate);
2169 ret_all.
pushKV(
"outs", outputs);
2171 ret_all.
pushKV(
"swtotal_size", swtotal_size);
2172 ret_all.
pushKV(
"swtotal_weight", swtotal_weight);
2173 ret_all.
pushKV(
"swtxs", swtxs);
2174 ret_all.
pushKV(
"time", pindex->GetBlockTime());
2175 ret_all.
pushKV(
"total_out", total_out);
2176 ret_all.
pushKV(
"total_size", total_size);
2177 ret_all.
pushKV(
"total_weight", total_weight);
2178 ret_all.
pushKV(
"totalfee", totalfee);
2179 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
2180 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2181 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2188 for (
const std::string& stat : stats) {
2189 const UniValue& value = ret_all[stat];
2203 "\nDumps the mempool to disk. It will fail until the previous dump is fully loaded.\n",
2229bool FindScriptPubKey(std::atomic<int>& scan_progress,
const std::atomic<bool>& should_abort, int64_t&
count,
CCoinsViewCursor* cursor,
const std::set<CScript>& needles, std::map<COutPoint, Coin>& out_results, std::function<
void()>& interruption_point)
2233 while (cursor->
Valid()) {
2236 if (!cursor->
GetKey(key) || !cursor->
GetValue(coin))
return false;
2237 if (++
count % 8192 == 0) {
2238 interruption_point();
2244 if (
count % 256 == 0) {
2247 scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
2250 out_results.emplace(key, coin);
2254 scan_progress = 100;
2291 "\nScans the unspent transaction output set for entries that match certain output descriptors.\n"
2292 "Examples of output descriptors are:\n"
2293 " addr(<address>) Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\n"
2294 " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
2295 " combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n"
2296 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
2297 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
2298 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2299 "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2300 "unhardened or hardened child keys.\n"
2301 "In the latter case, a range needs to be specified by below if different from 1000.\n"
2302 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
2305 "\"start\" for starting a scan\n"
2306 "\"abort\" for aborting the current scan (returns true when abort was successful)\n"
2307 "\"status\" for progress report (in %) of the current scan"},
2309 "Every scan object is either a string descriptor or an object:",
2318 "[scanobjects,...]"},
2350 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR});
2353 if (request.params[0].get_str() ==
"status") {
2361 }
else if (request.params[0].get_str() ==
"abort") {
2370 }
else if (request.params[0].get_str() ==
"start") {
2376 if (request.params.size() < 2) {
2380 std::set<CScript> needles;
2381 std::map<CScript, std::string> descriptors;
2388 for (
const auto& script : scripts) {
2390 needles.emplace(script);
2391 descriptors.emplace(std::move(script), std::move(inferred));
2397 std::vector<CTxOut> input_txos;
2398 std::map<COutPoint, Coin> coins;
2401 std::unique_ptr<CCoinsViewCursor> pcursor;
2415 result.
pushKV(
"success", res);
2420 for (
const auto& it : coins) {
2422 const Coin& coin = it.second;
2424 input_txos.push_back(txo);
2429 unspent.
pushKV(
"vout", (int32_t)outpoint.
n);
2437 result.
pushKV(
"unspents", unspents);
2450 "\nRetrieve a BIP 157 content filter for a particular block.\n",
2462 HelpExampleCli(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"") +
2463 HelpExampleRpc(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\", \"basic\"")
2468 std::string filtertype_name =
"basic";
2469 if (!request.params[1].isNull()) {
2470 filtertype_name = request.params[1].get_str();
2484 bool block_was_connected;
2488 block_index = chainman.m_blockman.LookupBlockIndex(block_hash);
2495 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2502 std::string errmsg =
"Filter not found.";
2504 if (!block_was_connected) {
2506 errmsg +=
" Block was not connected to active chain.";
2507 }
else if (!index_ready) {
2509 errmsg +=
" Block filters are still in the process of being indexed.";
2512 errmsg +=
" This error is unexpected and indicates index corruption.";
2535 "\nWrite the serialized UTXO set to disk.\n",
2541 "path to the output file. If relative, will be prefixed by datadir."},
2565 path.
u8string() +
" already exists. If you are sure this is what you want, "
2566 "move it out of the way first");
2573 fs::rename(temppath, path);
2583 std::unique_ptr<CCoinsViewCursor> pcursor;
2619 unsigned int iter{0};
2621 while (pcursor->Valid()) {
2622 if (iter % 5000 == 0)
node.rpc_interruption_point();
2624 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
2635 result.
pushKV(
"coins_written", stats.coins_count);
2683 for (
const auto& c : commands) {
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
bool MoneyRange(const CAmount &nValue)
int64_t CAmount
Amount in satoshis (Can be negative)
static RPCHelpMan getblock()
static int ComputeNextBlockAndDepth(const CBlockIndex *tip, const CBlockIndex *blockindex, const CBlockIndex *&next)
static RPCHelpMan getdifficulty()
static std::atomic< bool > g_scan_in_progress
static bool SetHasKeys(const std::set< T > &set)
static RPCHelpMan reconsiderblock()
static T CalculateTruncatedMedian(std::vector< T > &scores)
ChainstateManager & EnsureAnyChainman(const std::any &context)
static RPCHelpMan invalidateblock()
static RPCHelpMan getmempoolinfo()
static RPCHelpMan syncwithvalidationinterfacequeue()
static RPCHelpMan getchaintips()
CBlockPolicyEstimator & EnsureFeeEstimator(const NodeContext &node)
static RPCHelpMan gettxoutsetinfo()
static void entryToJSON(const CTxMemPool &pool, UniValue &info, const CTxMemPoolEntry &e) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
static RPCHelpMan getblockstats()
static RPCHelpMan preciousblock()
static constexpr size_t PER_UTXO_OVERHEAD
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index.
static RPCHelpMan getrawmempool()
NodeContext & EnsureAnyNodeContext(const std::any &context)
static RPCHelpMan scantxoutset()
static RPCHelpMan getmempoolentry()
CoinStatsHashType ParseHashType(const std::string &hash_type_input)
CTxMemPool & EnsureMemPool(const NodeContext &node)
static std::condition_variable cond_blockchange
static Mutex cs_blockchange
static std::atomic< int > g_scan_progress
RAII object to prevent concurrency issue when scanning the txout set.
ChainstateManager & EnsureChainman(const NodeContext &node)
UniValue MempoolInfoToJSON(const CTxMemPool &pool)
Mempool information to JSON.
UniValue blockToJSON(const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, TxVerbosity verbosity)
Block description to JSON.
CTxMemPool & EnsureAnyMemPool(const std::any &context)
static RPCHelpMan getblockfilter()
static RPCHelpMan getbestblockhash()
static CBlockUndo GetUndoChecked(const CBlockIndex *pblockindex)
static std::vector< RPCResult > MempoolEntryDescription()
CBlockIndex * ParseHashOrHeight(const UniValue ¶m, ChainstateManager &chainman)
RPCHelpMan getblockchaininfo()
static RPCHelpMan getchaintxstats()
static RPCHelpMan waitforblock()
CBlockPolicyEstimator & EnsureAnyFeeEstimator(const std::any &context)
static RPCHelpMan getblockhash()
void RegisterBlockchainRPCCommands(CRPCTable &t)
Register block chain RPC commands.
void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector< std::pair< CAmount, int64_t > > &scores, int64_t total_weight)
Used by getblockstats to get feerates at different percentiles by weight
static RPCHelpMan gettxout()
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
static RPCHelpMan verifychain()
static std::atomic< bool > g_should_abort_scan
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
Block header to JSON.
static CBlock GetBlockChecked(const CBlockIndex *pblockindex)
static RPCHelpMan waitforblockheight()
static RPCHelpMan pruneblockchain()
static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange)
static void SoftForkDescPushBack(const CBlockIndex *active_chain_tip, UniValue &softforks, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
static RPCHelpMan getblockheader()
UniValue CreateUTXOSnapshot(NodeContext &node, CChainState &chainstate, CAutoFile &afile)
Helper to create UTXO snapshots given a chainstate and a file handle.
static RPCHelpMan getmempooldescendants()
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
static RPCHelpMan getblockcount()
static RPCHelpMan waitfornewblock()
static RPCHelpMan getmempoolancestors()
static RPCHelpMan savemempool()
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
static constexpr int NUM_GETBLOCKSTATS_PERCENTILES
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
bool fPruneMode
True if we're running in -prune mode.
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
@ BLOCK_HAVE_DATA
full block available in blk*.dat
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
const CChainParams & Params()
Return the currently selected parameters.
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Complete block filter struct as defined in BIP 157.
const std::vector< unsigned char > & GetEncodedFilter() const
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out)
Get a single filter header by block.
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Non-refcounted RAII wrapper for FILE*.
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
CBlockIndex * pprev
pointer to the index of the predecessor of this block
CBlockHeader GetBlockHeader() const
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
uint256 GetBlockHash() const
int64_t GetMedianTimePast() const
unsigned int nTx
Number of transactions in this block.
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
int32_t nVersion
block header
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
int nHeight
height of the entry in the chain. The genesis block has height 0
uint32_t nStatus
Verification status of this block.
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
Undo information for a CBlock.
std::vector< CTxUndo > vtxundo
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
CBlockIndex * FindEarliestAtLeast(int64_t nTime, int height) const
Find the earliest block with timestamp equal or greater than the given time and height equal or great...
int Height() const
Return the maximal height in the chain.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
const Consensus::Params & GetConsensus() const
uint64_t PruneAfterHeight() const
CChainState stores and provides an API to update our local knowledge of the current best chain.
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(cs_main)
Find the best known block, and make it the tip of the block chain.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
CChain m_chain
The current chain of blockheaders we consult and build on.
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as invalid.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Cursor for iterating over CoinsView state.
virtual bool Valid() const =0
virtual bool GetKey(COutPoint &key) const =0
virtual bool GetValue(Coin &coin) const =0
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Abstract view on the open txout dataset.
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
CCoinsView that brings transactions from a mempool into view.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Double ended buffer combining vector and stream-like interfaces.
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
An outpoint - a combination of a transaction hash and an index n into its vout.
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
The basic transaction that is broadcasted on the network and contained in blocks.
const uint256 & GetHash() const
const std::vector< CTxIn > vin
An input of a transaction.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
const CTransaction & GetTx() const
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Children
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
size_t DynamicMemoryUsage() const
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
std::set< txiter, CompareIteratorByHash > setEntries
void queryHashes(std::vector< uint256 > &vtxid) const
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
unsigned long size() const
CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool isSpent(const COutPoint &outpoint) const
An output of a transaction.
Undo information for a CTransaction.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
bool VerifyDB(CChainState &chainstate, const CChainParams &chainparams, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
CChainState & ActiveChainstate() const
The most-work chain.
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
CChain & ActiveChain() const
CTxOut out
unspent transaction output
uint32_t nHeight
at which height this containing transaction was included in the active block chain
unsigned int fCoinBase
whether containing transaction was a coinbase
static GenTxid Txid(const uint256 &hash)
const std::string & get_str() const
void __pushKV(const std::string &key, const UniValue &val)
const std::vector< UniValue > & getValues() const
bool push_back(const UniValue &val)
const UniValue & get_array() const
bool pushKV(const std::string &key, const UniValue &val)
std::string ToString() const
static BIP9Stats Statistics(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the numerical statistics for a given deployment for the signalling period that includes the block...
ThresholdState State(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment for the block after pindexPrev.
int StateSinceHeight(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the block height at which the BIP9 deployment switched into the state for the block after pindexP...
std::string ToString() const
std::string GetHex() const
std::string GetHex() const
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
std::string u8string() const
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
static bool GetUTXOStats(CCoinsView *view, BlockManager &blockman, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point, const CBlockIndex *pindex)
Calculate statistics about the unspent transaction output set.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static int64_t GetBlockWeight(const CBlock &block)
static int64_t GetTransactionWeight(const CTransaction &tx)
static const unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
static const int WITNESS_SCALE_FACTOR
TxVerbosity
Verbose level for block's transaction.
@ SHOW_DETAILS_AND_PREVOUT
The same as previous option with information about prevouts if available.
@ SHOW_TXID
Only TXID for each block's transaction.
@ SHOW_DETAILS
Include TXID, inputs, outputs, and other common block's transaction information.
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool include_hex, bool include_address=true)
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS)
UniValue ValueFromAmount(const CAmount amount)
std::string DeploymentName(Consensus::BuriedDeployment dep)
VersionBitsCache g_versionbitscache
Global cache for versionbits deployment status.
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
bool DeploymentEnabled(const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is enabled (can ever be active)
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
const std::string CURRENCY_UNIT
#define T(expected, seed, data)
#define LogPrint(category,...)
BuriedDeployment
A buried deployment is one where the height of the activation has been hardcoded into the client impl...
static path u8path(const std::string &string)
static bool exists(const path &p)
FILE * fopen(const fs::path &p, const char *mode)
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
RBFTransactionState IsRBFOptIn(const CTransaction &tx, const CTxMemPool &pool)
Determine whether an unconfirmed transaction is signaling opt-in to RBF according to BIP 125 This inv...
RBFTransactionState
The rbf state of unconfirmed transactions.
@ UNKNOWN
Unconfirmed tx that does not signal rbf and is not in the mempool.
@ REPLACEABLE_BIP125
Either this tx or a mempool ancestor signals rbf.
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
static const int SERIALIZE_TRANSACTION_NO_WITNESS
A flag that is ORed into the protocol version to designate that a transaction should be (un)serialize...
std::shared_ptr< const CTransaction > CTransactionRef
UniValue JSONRPCError(int code, const std::string &message)
@ RPC_MISC_ERROR
General application defined errors.
@ RPC_CLIENT_MEMPOOL_DISABLED
Chain errors.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_DATABASE_ERROR
Database error.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
size_t GetSerializeSize(const T &t, int nVersion=0)
bool IsRPCRunning()
Query whether RPC is running.
int RPCSerializationFlags()
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
Display status of an in-progress BIP9 softfork.
int count
Number of blocks with the version bit set since the beginning of the current period.
int elapsed
Number of blocks elapsed since the beginning of the current period.
int threshold
Number of blocks with the version bit set required to activate the softfork.
bool possible
False if there are not enough blocks left in this period to pass activation threshold.
int period
Length of blocks of the BIP9 signalling period.
bool index_requested
Signals if the coinstatsindex should be used (when available).
Comparison function for sorting the getchaintips heads.
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
int min_activation_height
If lock in occurs, delay activation until at least this block height.
int bit
Bit position to select the particular bit in nVersion.
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
int64_t nStartTime
Start MedianTime for version bits miner confirmation.
Parameters that influence chain consensus.
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
int DeploymentHeight(BuriedDeployment dep) const
int64_t nPowTargetSpacing
NodeContext struct containing references to chain state and connection state.
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ ARR_FIXED
Special array that has a fixed number of entries.
@ 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.
#define WAIT_LOCK(cs, name)
#define AssertLockNotHeld(cs)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
const UniValue NullUniValue
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function, bool skip_file_commit)
Dump the mempool to disk.
static const unsigned int DEFAULT_CHECKLEVEL
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
static const signed int DEFAULT_CHECKBLOCKS
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static const int PROTOCOL_VERSION
network protocol versioning
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.