50 #include <condition_variable> 66 auto node_context = util::AnyPtr<NodeContext>(context);
91 return *
node.chainman;
101 if (!
node.fee_estimator) {
104 return *
node.fee_estimator;
118 int nShift = (blockindex->
nBits >> 24) & 0xff;
120 (double)0x0000ffff / (
double)(blockindex->
nBits & 0x00ffffff);
139 if (next && next->
pprev == blockindex) {
143 return blockindex == tip ? 1 : -1;
151 const int height{param.
get_int()};
155 const int current_tip{active_chain.
Height()};
156 if (height > current_tip) {
160 return active_chain[height];
163 CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
182 result.
pushKV(
"confirmations", confirmations);
193 result.
pushKV(
"nTx", (uint64_t)blockindex->
nTx);
195 if (blockindex->
pprev)
213 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
216 const CTxUndo* txundo = (have_undo && i) ? &blockUndo.
vtxundo.at(i - 1) :
nullptr;
234 "\nReturns the height of the most-work fully-validated chain.\n" 235 "The genesis block has height 0.\n",
255 "\nReturns the hash of the best (tip) block in the most-work fully-validated chain.\n",
277 latestblock.height = pindex->
nHeight;
285 "\nWaits for a specific new block and returns useful info about it.\n" 286 "\nReturns the current block on timeout or exit.\n",
303 if (!request.params[0].isNull())
304 timeout = request.params[0].
get_int();
327 "\nWaits for a specific new block and returns useful info about it.\n" 328 "\nReturns the current block on timeout or exit.\n",
340 HelpExampleCli(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\" 1000")
341 +
HelpExampleRpc(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
349 if (!request.params[1].isNull())
350 timeout = request.params[1].get_int();
373 "\nWaits for (at least) block height and returns the height and hash\n" 374 "of the current tip.\n" 375 "\nReturns the current block on timeout or exit.\n",
394 int height = request.params[0].
get_int();
396 if (!request.params[1].isNull())
397 timeout = request.params[1].get_int();
418 return RPCHelpMan{
"syncwithvalidationinterfacequeue",
419 "\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n",
437 "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
440 RPCResult::Type::NUM,
"",
"the proof-of-work difficulty as a multiple of the minimum difficulty."},
455 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."},
480 RPCResult{
RPCResult::Type::BOOL,
"unbroadcast",
"Whether this transaction is currently unbroadcast (initial broadcast not yet acknowledged by any peers)"},
492 info.pushKV(
"fees", fees);
494 info.pushKV(
"vsize", (
int)e.GetTxSize());
495 info.pushKV(
"weight", (
int)e.GetTxWeight());
499 info.pushKV(
"height", (
int)e.GetHeight());
500 info.pushKV(
"descendantcount", e.GetCountWithDescendants());
501 info.pushKV(
"descendantsize", e.GetSizeWithDescendants());
502 info.pushKV(
"descendantfees", e.GetModFeesWithDescendants());
503 info.pushKV(
"ancestorcount", e.GetCountWithAncestors());
504 info.pushKV(
"ancestorsize", e.GetSizeWithAncestors());
505 info.pushKV(
"ancestorfees", e.GetModFeesWithAncestors());
506 info.pushKV(
"wtxid", pool.vTxHashes[e.vTxHashesIdx].first.ToString());
508 std::set<std::string> setDepends;
516 for (
const std::string& dep : setDepends)
521 info.pushKV(
"depends", depends);
527 spent.
push_back(child.GetTx().GetHash().ToString());
530 info.pushKV(
"spentby", spent);
533 bool rbfStatus =
false;
541 info.pushKV(
"bip125-replaceable", rbfStatus);
542 info.pushKV(
"unbroadcast", pool.IsUnbroadcastTx(tx.
GetHash()));
548 if (include_mempool_sequence) {
564 uint64_t mempool_sequence;
565 std::vector<uint256> vtxid;
572 for (
const uint256& hash : vtxid)
575 if (!include_mempool_sequence) {
580 o.
pushKV(
"mempool_sequence", mempool_sequence);
589 "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" 590 "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n",
593 {
"mempool_sequence",
RPCArg::Type::BOOL,
RPCArg::Default{
false},
"If verbose=false, returns a json object with transaction list and mempool sequence number attached."},
606 RPCResult{
"for verbose = false and mempool_sequence = true",
622 bool fVerbose =
false;
623 if (!request.params[0].isNull())
624 fVerbose = request.params[0].
get_bool();
626 bool include_mempool_sequence =
false;
627 if (!request.params[1].isNull()) {
628 include_mempool_sequence = request.params[1].get_bool();
639 "\nIf txid is in the mempool, returns all in-mempool ancestors.\n",
660 bool fVerbose =
false;
661 if (!request.params[1].isNull())
662 fVerbose = request.params[1].
get_bool();
670 if (it == mempool.mapTx.end()) {
675 uint64_t noLimit = std::numeric_limits<uint64_t>::max();
682 o.
push_back(ancestorIt->GetTx().GetHash().ToString());
703 "\nIf txid is in the mempool, returns all in-mempool descendants.\n",
724 bool fVerbose =
false;
725 if (!request.params[1].isNull())
726 fVerbose = request.params[1].
get_bool();
734 if (it == mempool.mapTx.end()) {
741 setDescendants.erase(it);
746 o.
push_back(descendantIt->GetTx().GetHash().ToString());
768 "\nReturns mempool data for given transaction\n",
786 if (it == mempool.mapTx.end()) {
801 "\nReturns hash of block in best-block-chain at height provided.\n",
817 int nHeight = request.params[0].get_int();
818 if (nHeight < 0 || nHeight > active_chain.
Height())
830 "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" 831 "If verbose is true, returns an Object with information about blockheader <hash>.\n",
841 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
860 HelpExampleCli(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
861 +
HelpExampleRpc(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
867 bool fVerbose =
true;
868 if (!request.params[1].isNull())
869 fVerbose = request.params[1].get_bool();
876 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
888 std::string strHex =
HexStr(ssBlock);
931 "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n" 932 "If verbosity is 1, returns an Object with information about block <hash>.\n" 933 "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n",
945 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
960 {
RPCResult::Type::STR_HEX,
"chainwork",
"Expected number of hashes required to produce the chain up to this block (in hex)"},
973 {
RPCResult::Type::ELISION,
"",
"The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result"},
980 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
981 +
HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
988 if (!request.params[1].isNull()) {
989 if (request.params[1].isBool()) {
990 verbosity = request.params[1].get_bool() ? 1 : 0;
992 verbosity = request.params[1].get_int();
1002 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1016 std::string strHex =
HexStr(ssBlock);
1020 return blockToJSON(block, tip, pblockindex, verbosity >= 2);
1030 " to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
1048 int heightParam = request.params[0].get_int();
1049 if (heightParam < 0)
1054 if (heightParam > 1000000000) {
1060 heightParam = pindex->
nHeight;
1063 unsigned int height = (
unsigned int) heightParam;
1064 unsigned int chainHeight = (
unsigned int) active_chain.
Height();
1065 if (chainHeight <
Params().PruneAfterHeight())
1067 else if (height > chainHeight)
1070 LogPrint(
BCLog::RPC,
"Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
1078 block = block->
pprev;
1080 return uint64_t(block->
nHeight);
1087 if (hash_type_input ==
"hash_serialized_2") {
1089 }
else if (hash_type_input ==
"muhash") {
1091 }
else if (hash_type_input ==
"none") {
1101 "\nReturns statistics about the unspent transaction output set.\n" 1102 "Note this call may take some time if you are not using coinstatsindex.\n",
1104 {
"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'."},
1114 {
RPCResult::Type::NUM,
"bogosize",
"Database-independent, meaningless metric indicating the UTXO set size"},
1115 {
RPCResult::Type::STR_HEX,
"hash_serialized_2",
true,
"The serialized hash (only present if 'hash_serialized_2' hash_type is chosen)"},
1117 {
RPCResult::Type::NUM,
"transactions",
"The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
1118 {
RPCResult::Type::NUM,
"disk_size",
"The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
1120 {
RPCResult::Type::STR_AMOUNT,
"total_unspendable_amount",
"The total amount of coins permanently excluded from the UTXO set (only available if coinstatsindex is used)"},
1121 {
RPCResult::Type::OBJ,
"block_info",
"Info on amounts in the block at this block height (only available if coinstatsindex is used)",
1140 HelpExampleCli("gettxoutsetinfo", R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") + 1144 HelpExampleRpc("gettxoutsetinfo", R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")") 1153 stats.
index_requested = request.params[2].isNull() || request.params[2].get_bool();
1164 coins_view = &active_chainstate.
CoinsDB();
1169 if (!request.params[1].isNull()) {
1181 if (
GetUTXOStats(coins_view, *blockman, stats,
node.rpc_interruption_point, pindex)) {
1182 ret.
pushKV(
"height", (int64_t)stats.nHeight);
1183 ret.
pushKV(
"bestblock", stats.hashBlock.GetHex());
1184 ret.
pushKV(
"txouts", (int64_t)stats.nTransactionOutputs);
1185 ret.
pushKV(
"bogosize", (int64_t)stats.nBogoSize);
1187 ret.
pushKV(
"hash_serialized_2", stats.hashSerialized.GetHex());
1190 ret.
pushKV(
"muhash", stats.hashSerialized.GetHex());
1193 if (!stats.index_used) {
1194 ret.
pushKV(
"transactions", static_cast<int64_t>(stats.nTransactions));
1195 ret.
pushKV(
"disk_size", stats.nDiskSize);
1201 if (pindex->nHeight > 0) {
1202 GetUTXOStats(coins_view, *blockman, prev_stats,
node.rpc_interruption_point, pindex->pprev);
1206 block_info.
pushKV(
"prevout_spent",
ValueFromAmount(stats.block_prevout_spent_amount - prev_stats.block_prevout_spent_amount));
1207 block_info.
pushKV(
"coinbase",
ValueFromAmount(stats.block_coinbase_amount - prev_stats.block_coinbase_amount));
1208 block_info.
pushKV(
"new_outputs_ex_coinbase",
ValueFromAmount(stats.block_new_outputs_ex_coinbase_amount - prev_stats.block_new_outputs_ex_coinbase_amount));
1209 block_info.
pushKV(
"unspendable",
ValueFromAmount(stats.block_unspendable_amount - prev_stats.block_unspendable_amount));
1212 unspendables.
pushKV(
"genesis_block",
ValueFromAmount(stats.unspendables_genesis_block - prev_stats.unspendables_genesis_block));
1213 unspendables.
pushKV(
"bip30",
ValueFromAmount(stats.unspendables_bip30 - prev_stats.unspendables_bip30));
1214 unspendables.
pushKV(
"scripts",
ValueFromAmount(stats.unspendables_scripts - prev_stats.unspendables_scripts));
1215 unspendables.
pushKV(
"unclaimed_rewards",
ValueFromAmount(stats.unspendables_unclaimed_rewards - prev_stats.unspendables_unclaimed_rewards));
1216 block_info.
pushKV(
"unspendables", unspendables);
1218 ret.
pushKV(
"block_info", block_info);
1224 if (!summary.synced) {
1238 "\nReturns details about an unspent transaction output.\n",
1242 {
"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."},
1253 {
RPCResult::Type::NUM,
"reqSigs",
true,
"(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Number of required signatures"},
1255 {
RPCResult::Type::STR,
"address",
true,
"bitcoin address (only if a well-defined address exists)"},
1256 {
RPCResult::Type::ARR,
"addresses",
true,
"(DEPRECATED, returned only if config option -deprecatedrpc=addresses is passed) Array of bitcoin addresses",
1263 "\nGet unspent transactions\n" 1265 "\nView the details\n" 1267 "\nAs a JSON-RPC call\n" 1279 int n = request.params[1].get_int();
1281 bool fMempool =
true;
1282 if (!request.params[2].isNull())
1283 fMempool = request.params[2].get_bool();
1297 if (!coins_view->
GetCoin(out, coin)) {
1305 ret.
pushKV(
"confirmations", 0);
1312 ret.
pushKV(
"scriptPubKey", o);
1323 "\nVerifies blockchain database.\n",
1337 const int check_level(request.params[0].isNull() ?
DEFAULT_CHECKLEVEL : request.params[0].get_int());
1345 active_chainstate,
Params(), active_chainstate.
CoinsTip(), check_level, check_depth);
1357 rv.
pushKV(
"type",
"buried");
1373 switch (thresholdState) {
1387 bip9.
pushKV(
"since", since_height);
1397 bip9.
pushKV(
"statistics", statsUV);
1402 rv.
pushKV(
"type",
"bip9");
1405 rv.
pushKV(
"height", since_height);
1415 "Returns an object containing various state info regarding blockchain processing.\n",
1421 {
RPCResult::Type::NUM,
"blocks",
"the height of the most-work fully-validated chain. The genesis block has height 0"},
1427 {
RPCResult::Type::BOOL,
"initialblockdownload",
"(debug information) estimate of whether this node is in Initial Block Download mode"},
1429 {
RPCResult::Type::NUM,
"size_on_disk",
"the estimated size of the block and undo files on disk"},
1431 {
RPCResult::Type::NUM,
"pruneheight",
"lowest-height complete block stored (only present if pruning is enabled)"},
1432 {
RPCResult::Type::BOOL,
"automatic_pruning",
"whether automatic pruning is enabled (only present if pruning is enabled)"},
1433 {
RPCResult::Type::NUM,
"prune_target_size",
"the target size used by pruning (only present if automatic pruning is enabled)"},
1441 {
RPCResult::Type::STR,
"status",
"one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\""},
1442 {
RPCResult::Type::NUM,
"bit",
"the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)"},
1443 {
RPCResult::Type::NUM_TIME,
"start_time",
"the minimum median time past of a block at which the bit gains its meaning"},
1444 {
RPCResult::Type::NUM_TIME,
"timeout",
"the median time past of a block at which the deployment is considered failed if not yet locked in"},
1446 {
RPCResult::Type::NUM,
"min_activation_height",
"minimum height of blocks for which the rules may be enforced"},
1447 {
RPCResult::Type::OBJ,
"statistics",
"numeric statistics about BIP9 signalling for a softfork (only for \"started\" status)",
1450 {
RPCResult::Type::NUM,
"threshold",
"the number of blocks with the version bit set required to activate the feature"},
1451 {
RPCResult::Type::NUM,
"elapsed",
"the number of blocks elapsed since the beginning of the current period"},
1452 {
RPCResult::Type::NUM,
"count",
"the number of blocks with the version bit set in the current period"},
1453 {
RPCResult::Type::BOOL,
"possible",
"returns false if there are not enough blocks left in this period to pass activation threshold"},
1456 {
RPCResult::Type::NUM,
"height",
"height of the first block which the rules are or will be enforced (only for \"buried\" type, or \"bip9\" type with \"active\" status)"},
1457 {
RPCResult::Type::BOOL,
"active",
"true if the rules are enforced for the mempool and the next block"},
1474 const int height = tip->
nHeight;
1477 obj.
pushKV(
"blocks", height);
1491 block = block->
pprev;
1497 bool automatic_pruning = (
gArgs.
GetArg(
"-prune", 0) != 1);
1498 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1499 if (automatic_pruning) {
1513 obj.
pushKV(
"softforks", softforks);
1539 "Return information about all known tips in the block tree," 1540 " including the main chain as well as orphaned branches.\n",
1548 {
RPCResult::Type::NUM,
"branchlen",
"zero for main chain, otherwise length of branch connecting the tip to the main chain"},
1550 "Possible values for status:\n" 1551 "1. \"invalid\" This branch contains at least one invalid block\n" 1552 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" 1553 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" 1554 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" 1555 "5. \"active\" This is the tip of the active main chain, which is certainly valid"},
1574 std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1575 std::set<const CBlockIndex*> setOrphans;
1576 std::set<const CBlockIndex*> setPrevs;
1578 for (
const std::pair<const uint256, CBlockIndex*>& item : chainman.
BlockIndex()) {
1579 if (!active_chain.
Contains(item.second)) {
1580 setOrphans.insert(item.second);
1581 setPrevs.insert(item.second->pprev);
1585 for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) {
1586 if (setPrevs.erase(*it) == 0) {
1587 setTips.insert(*it);
1592 setTips.insert(active_chain.
Tip());
1598 obj.
pushKV(
"height", block->nHeight);
1599 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1601 const int branchLen = block->nHeight - active_chain.
FindFork(block)->
nHeight;
1602 obj.
pushKV(
"branchlen", branchLen);
1605 if (active_chain.
Contains(block)) {
1611 }
else if (!block->HaveTxsDownloaded()) {
1613 status =
"headers-only";
1616 status =
"valid-fork";
1619 status =
"valid-headers";
1624 obj.
pushKV(
"status", status);
1645 ret.
pushKV(
"maxmempool", (int64_t) maxmempool);
1655 "\nReturns details on the active state of the TX memory pool.\n",
1662 {
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"},
1668 {
RPCResult::Type::NUM,
"unbroadcastcount",
"Current number of transactions that haven't passed initial broadcast yet"}
1684 "\nTreats a block as if it were received before others with the same work.\n" 1685 "\nA later preciousblock call can override the effect of an earlier one.\n" 1686 "\nThe effects of preciousblock are not retained across restarts.\n",
1703 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1724 "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n",
1742 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1765 "\nRemoves invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n" 1766 "This can be used to undo the effects of invalidateblock.\n",
1782 CBlockIndex* pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1805 "\nCompute statistics about the total number and rate of transactions in the chain.\n",
1814 {
RPCResult::Type::NUM,
"txcount",
"The total number of transactions in the chain up to that point"},
1816 {
RPCResult::Type::NUM,
"window_final_block_height",
"The height of the final block in the window."},
1818 {
RPCResult::Type::NUM,
"window_tx_count",
true,
"The number of transactions in the window. Only returned if \"window_block_count\" is > 0"},
1819 {
RPCResult::Type::NUM,
"window_interval",
true,
"The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0"},
1820 {
RPCResult::Type::NUM,
"txrate",
true,
"The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0"},
1832 if (request.params[1].isNull()) {
1838 pindex = chainman.m_blockman.LookupBlockIndex(hash);
1849 if (request.params[0].isNull()) {
1850 blockcount = std::max(0, std::min(blockcount, pindex->
nHeight - 1));
1852 blockcount = request.params[0].get_int();
1854 if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->
nHeight)) {
1868 ret.
pushKV(
"window_block_count", blockcount);
1869 if (blockcount > 0) {
1870 ret.
pushKV(
"window_tx_count", nTxDiff);
1871 ret.
pushKV(
"window_interval", nTimeDiff);
1872 if (nTimeDiff > 0) {
1873 ret.
pushKV(
"txrate", ((
double)nTxDiff) / nTimeDiff);
1882 template<
typename T>
1885 size_t size = scores.size();
1890 std::sort(scores.begin(), scores.end());
1891 if (size % 2 == 0) {
1892 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1894 return scores[size / 2];
1900 if (scores.empty()) {
1904 std::sort(scores.begin(), scores.end());
1908 total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
1911 int64_t next_percentile_index = 0;
1912 int64_t cumulative_weight = 0;
1913 for (
const auto& element : scores) {
1914 cumulative_weight += element.second;
1915 while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
1916 result[next_percentile_index] = element.first;
1917 ++next_percentile_index;
1923 result[i] = scores.back().first;
1937 template<
typename T>
1938 static inline bool SetHasKeys(
const std::set<T>&
set) {
return false;}
1939 template<
typename T,
typename Tk,
typename... Args>
1940 static inline bool SetHasKeys(
const std::set<T>&
set,
const Tk& key,
const Args&... args)
1951 "\nCompute per block statistics for a given window. All amounts are in satoshis.\n" 1952 "It won't work for some heights with pruning.\n",
1969 {
RPCResult::Type::ARR_FIXED,
"feerate_percentiles",
"Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
1994 {
RPCResult::Type::NUM,
"total_out",
"Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
1999 {
RPCResult::Type::NUM,
"utxo_increase",
"The increase/decrease in the number of unspent outputs"},
2000 {
RPCResult::Type::NUM,
"utxo_size_inc",
"The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
2003 HelpExampleCli(
"getblockstats", R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") + 2004 HelpExampleCli("getblockstats", R
"(1000 '["minfeerate","avgfeerate"]')") + 2005 HelpExampleRpc("getblockstats", R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") + 2006 HelpExampleRpc("getblockstats", R
"(1000, ["minfeerate","avgfeerate"])") 2015 std::set<std::string> stats;
2016 if (!request.params[1].isNull()) {
2018 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2019 const std::string stat = stats_univalue[i].
get_str();
2027 const bool do_all = stats.size() == 0;
2028 const bool do_mediantxsize = do_all || stats.count(
"mediantxsize") != 0;
2029 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
2030 const bool do_feerate_percentiles = do_all || stats.count(
"feerate_percentiles") != 0;
2031 const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
2032 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
"avgfeerate",
"minfee",
"maxfee",
"minfeerate",
"maxfeerate");
2033 const bool loop_outputs = do_all || loop_inputs || stats.count(
"total_out");
2034 const bool do_calculate_size = do_mediantxsize ||
2035 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
"maxtxsize",
"swtotal_size");
2036 const bool do_calculate_weight = do_all ||
SetHasKeys(stats,
"total_weight",
"avgfeerate",
"swtotal_weight",
"avgfeerate",
"feerate_percentiles",
"minfeerate",
"maxfeerate");
2037 const bool do_calculate_sw = do_all ||
SetHasKeys(stats,
"swtxs",
"swtotal_size",
"swtotal_weight");
2046 int64_t maxtxsize = 0;
2048 int64_t outputs = 0;
2049 int64_t swtotal_size = 0;
2050 int64_t swtotal_weight = 0;
2052 int64_t total_size = 0;
2053 int64_t total_weight = 0;
2054 int64_t utxo_size_inc = 0;
2055 std::vector<CAmount> fee_array;
2056 std::vector<std::pair<CAmount, int64_t>> feerate_array;
2057 std::vector<int64_t> txsize_array;
2059 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2060 const auto& tx = block.
vtx.at(i);
2061 outputs += tx->vout.size();
2065 for (
const CTxOut& out : tx->vout) {
2066 tx_total_out += out.
nValue;
2071 if (tx->IsCoinBase()) {
2075 inputs += tx->vin.size();
2076 total_out += tx_total_out;
2078 int64_t tx_size = 0;
2079 if (do_calculate_size) {
2081 tx_size = tx->GetTotalSize();
2082 if (do_mediantxsize) {
2083 txsize_array.push_back(tx_size);
2085 maxtxsize = std::max(maxtxsize, tx_size);
2086 mintxsize = std::min(mintxsize, tx_size);
2087 total_size += tx_size;
2091 if (do_calculate_weight) {
2093 total_weight += weight;
2096 if (do_calculate_sw && tx->HasWitness()) {
2098 swtotal_size += tx_size;
2099 swtotal_weight += weight;
2104 const auto& txundo = blockUndo.
vtxundo.at(i - 1);
2105 for (
const Coin& coin: txundo.vprevout) {
2108 tx_total_in += prevoutput.
nValue;
2112 CAmount txfee = tx_total_in - tx_total_out;
2115 fee_array.push_back(txfee);
2117 maxfee = std::max(maxfee, txfee);
2118 minfee = std::min(minfee, txfee);
2123 if (do_feerate_percentiles) {
2124 feerate_array.emplace_back(std::make_pair(feerate, weight));
2126 maxfeerate = std::max(maxfeerate, feerate);
2127 minfeerate = std::min(minfeerate, feerate);
2136 feerates_res.
push_back(feerate_percentiles[i]);
2140 ret_all.
pushKV(
"avgfee", (block.
vtx.size() > 1) ? totalfee / (block.
vtx.size() - 1) : 0);
2142 ret_all.
pushKV(
"avgtxsize", (block.
vtx.size() > 1) ? total_size / (block.
vtx.size() - 1) : 0);
2143 ret_all.
pushKV(
"blockhash", pindex->GetBlockHash().GetHex());
2144 ret_all.
pushKV(
"feerate_percentiles", feerates_res);
2145 ret_all.
pushKV(
"height", (int64_t)pindex->nHeight);
2146 ret_all.
pushKV(
"ins", inputs);
2147 ret_all.
pushKV(
"maxfee", maxfee);
2148 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2149 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2151 ret_all.
pushKV(
"mediantime", pindex->GetMedianTimePast());
2154 ret_all.
pushKV(
"minfeerate", (minfeerate ==
MAX_MONEY) ? 0 : minfeerate);
2156 ret_all.
pushKV(
"outs", outputs);
2158 ret_all.
pushKV(
"swtotal_size", swtotal_size);
2159 ret_all.
pushKV(
"swtotal_weight", swtotal_weight);
2160 ret_all.
pushKV(
"swtxs", swtxs);
2161 ret_all.
pushKV(
"time", pindex->GetBlockTime());
2162 ret_all.
pushKV(
"total_out", total_out);
2163 ret_all.
pushKV(
"total_size", total_size);
2164 ret_all.
pushKV(
"total_weight", total_weight);
2165 ret_all.
pushKV(
"totalfee", totalfee);
2166 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
2167 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2168 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2175 for (
const std::string& stat : stats) {
2176 const UniValue& value = ret_all[stat];
2190 "\nDumps the mempool to disk. It will fail until the previous dump is fully loaded.\n",
2216 bool 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)
2220 while (cursor->
Valid()) {
2223 if (!cursor->
GetKey(key) || !cursor->
GetValue(coin))
return false;
2224 if (++
count % 8192 == 0) {
2225 interruption_point();
2231 if (
count % 256 == 0) {
2234 scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
2237 out_results.emplace(key, coin);
2241 scan_progress = 100;
2278 "\nScans the unspent transaction output set for entries that match certain output descriptors.\n" 2279 "Examples of output descriptors are:\n" 2280 " addr(<address>) Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\n" 2281 " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n" 2282 " combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n" 2283 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n" 2284 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n" 2285 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n" 2286 "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n" 2287 "unhardened or hardened child keys.\n" 2288 "In the latter case, a range needs to be specified by below if different from 1000.\n" 2289 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
2292 "\"start\" for starting a scan\n" 2293 "\"abort\" for aborting the current scan (returns true when abort was successful)\n" 2294 "\"status\" for progress report (in %) of the current scan"},
2296 "Every scan object is either a string descriptor or an object:",
2305 "[scanobjects,...]"},
2337 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR});
2340 if (request.params[0].get_str() ==
"status") {
2348 }
else if (request.params[0].get_str() ==
"abort") {
2357 }
else if (request.params[0].get_str() ==
"start") {
2363 if (request.params.size() < 2) {
2367 std::set<CScript> needles;
2368 std::map<CScript, std::string> descriptors;
2375 for (
const auto& script : scripts) {
2377 needles.emplace(script);
2378 descriptors.emplace(std::move(script), std::move(inferred));
2384 std::vector<CTxOut> input_txos;
2385 std::map<COutPoint, Coin> coins;
2388 std::unique_ptr<CCoinsViewCursor> pcursor;
2402 result.
pushKV(
"success", res);
2407 for (
const auto& it : coins) {
2409 const Coin& coin = it.second;
2411 input_txos.push_back(txo);
2416 unspent.
pushKV(
"vout", (int32_t)outpoint.
n);
2424 result.
pushKV(
"unspents", unspents);
2437 "\nRetrieve a BIP 157 content filter for a particular block.\n",
2449 HelpExampleCli(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"") +
2450 HelpExampleRpc(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\", \"basic\"")
2455 std::string filtertype_name =
"basic";
2456 if (!request.params[1].isNull()) {
2457 filtertype_name = request.params[1].get_str();
2471 bool block_was_connected;
2475 block_index = chainman.m_blockman.LookupBlockIndex(block_hash);
2482 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2489 std::string errmsg =
"Filter not found.";
2491 if (!block_was_connected) {
2493 errmsg +=
" Block was not connected to active chain.";
2494 }
else if (!index_ready) {
2496 errmsg +=
" Block filters are still in the process of being indexed.";
2499 errmsg +=
" This error is unexpected and indicates index corruption.";
2522 "\nWrite the serialized UTXO set to disk.\n",
2528 "path to the output file. If relative, will be prefixed by datadir."},
2549 if (fs::exists(path)) {
2552 path.string() +
" already exists. If you are sure this is what you want, " 2553 "move it out of the way first");
2560 fs::rename(temppath, path);
2562 result.
pushKV(
"path", path.string());
2570 std::unique_ptr<CCoinsViewCursor> pcursor;
2606 unsigned int iter{0};
2608 while (pcursor->Valid()) {
2609 if (iter % 5000 == 0)
node.rpc_interruption_point();
2611 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
2622 result.
pushKV(
"coins_written", stats.coins_count);
2670 for (
const auto& c : commands) {
std::shared_ptr< const CTransaction > CTransactionRef
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
static int64_t GetTransactionWeight(const CTransaction &tx)
int min_activation_height
If lock in occurs, delay activation until at least this block height.
void queryHashes(std::vector< uint256 > &vtxid) const
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
static RPCHelpMan syncwithvalidationinterfacequeue()
Display status of an in-progress BIP9 softfork.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
static constexpr int NUM_GETBLOCKSTATS_PERCENTILES
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
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...
static RPCHelpMan getblock()
CTxMemPool & EnsureMemPool(const NodeContext &node)
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
const std::vector< UniValue > & getValues() const
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
static const int WITNESS_SCALE_FACTOR
CChain m_chain
The current chain of blockheaders we consult and build on.
#define LogPrint(category,...)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
FILE * fopen(const fs::path &p, const char *mode)
CBlockIndex * pprev
pointer to the index of the predecessor of this block
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...
uint32_t nStatus
Verification status of this block.
bool IsRPCRunning()
Query whether RPC is running.
CBlockPolicyEstimator & EnsureAnyFeeEstimator(const std::any &context)
Either this tx or a mempool ancestor signals rbf.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
static const CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
An in-memory indexed chain of blocks.
Unconfirmed tx that does not signal rbf and is not in the mempool.
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
size_t DynamicMemoryUsage() const
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
Comparison function for sorting the getchaintips heads.
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ::ChainActive().Tip() will not be pruned.
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
bool MoneyRange(const CAmount &nValue)
CBlockHeader GetBlockHeader() const
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
int Height() const
Return the maximal height in the chain.
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
CTxOut out
unspent transaction output
unsigned long size() const
unsigned int fCoinBase
whether containing transaction was a coinbase
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
Block header to JSON.
CChainState stores and provides an API to update our local knowledge of the current best chain...
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
CTxMemPool & EnsureAnyMemPool(const std::any &context)
bool index_requested
Signals if the coinstatsindex should be used (when available).
std::set< txiter, CompareIteratorByHash > setEntries
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.
const std::string & get_str() const
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
static void entryToJSON(const CTxMemPool &pool, UniValue &info, const CTxMemPoolEntry &e) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
const UniValue & get_array() const
Double ended buffer combining vector and stream-like interfaces.
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index.
static RPCHelpMan scantxoutset()
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
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.
static std::atomic< int > g_scan_progress
RAII object to prevent concurrency issue when scanning the txout set.
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
int threshold
Number of blocks with the version bit set required to activate the softfork.
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
static int ComputeNextBlockAndDepth(const CBlockIndex *tip, const CBlockIndex *blockindex, const CBlockIndex *&next)
bool isSpent(const COutPoint &outpoint) const
const std::vector< CTxIn > vin
Invalid, missing or duplicate parameter.
size_t GetSerializeSize(const T &t, int nVersion=0)
RPCHelpMan getblockchaininfo()
RBFTransactionState
The rbf state of unconfirmed transactions.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
bool DeploymentEnabled(const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is enabled (can ever be active)
CoinStatsHashType ParseHashType(const std::string &hash_type_input)
static RPCHelpMan getchaintxstats()
int64_t CAmount
Amount in satoshis (Can be negative)
static T CalculateTruncatedMedian(std::vector< T > &scores)
virtual bool GetValue(Coin &coin) const =0
uint256 GetBlockHash() const
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
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...
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0...
static RPCHelpMan getblockfilter()
Special type that is a STR with only hex chars.
ChainstateManager & EnsureChainman(const NodeContext &node)
static std::atomic< bool > g_scan_in_progress
const std::vector< unsigned char > & GetEncodedFilter() const
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
UniValue JSONRPCError(int code, const std::string &message)
bool push_back(const UniValue &val)
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
Special string with only hex chars.
NodeContext struct containing references to chain state and connection state.
bool fPruneMode
True if we're running in -prune mode.
virtual bool Valid() const =0
static RPCHelpMan waitfornewblock()
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
void RegisterBlockchainRPCCommands(CRPCTable &t)
Register block chain RPC commands.
Abstract view on the open txout dataset.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
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...
An input of a transaction.
int period
Length of blocks of the BIP9 signalling period.
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
int DeploymentHeight(BuriedDeployment dep) const
const uint256 & GetHash() const
std::string ToString() const
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
static RPCHelpMan getblockheader()
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
static std::condition_variable cond_blockchange
Complete block filter struct as defined in BIP 157.
Special array that has a fixed number of entries.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
static std::vector< RPCResult > MempoolEntryDescription()
int64_t nStartTime
Start MedianTime for version bits miner confirmation.
int64_t nPowTargetSpacing
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
static RPCHelpMan getmempoolancestors()
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
static RPCHelpMan getblockstats()
UniValue CreateUTXOSnapshot(NodeContext &node, CChainState &chainstate, CAutoFile &afile)
Helper to create UTXO snapshots given a chainstate and a file handle.
const std::string CURRENCY_UNIT
General application defined errors.
bool pushKV(const std::string &key, const UniValue &val)
int count
Number of blocks with the version bit set since the beginning of the current period.
#define WAIT_LOCK(cs, name)
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
An output of a transaction.
bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as invalid.
std::string ToString() const
Parameters that influence chain consensus.
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.
An outpoint - a combination of a transaction hash and an index n into its vout.
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
bool IsDeprecatedRPCEnabled(const std::string &method)
Special numeric to denote unix epoch time.
UniValue blockToJSON(const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
static RPCHelpMan getmempoolinfo()
int64_t GetMedianTimePast() const
static RPCHelpMan getdifficulty()
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Optional arg that is a named argument and has a default value of null.
static RPCHelpMan invalidateblock()
virtual bool GetKey(COutPoint &key) const =0
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
static RPCHelpMan getblockcount()
VersionBitsCache g_versionbitscache
Global cache for versionbits deployment status.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Special type that is a NUM or [NUM,NUM].
int32_t nVersion
block header
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
Optional argument with default value omitted because they are implicitly clear.
static std::atomic< bool > g_should_abort_scan
#define EXCLUSIVE_LOCKS_REQUIRED(...)
static RPCHelpMan waitforblock()
std::vector< CTransactionRef > vtx
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
ChainstateManager & EnsureAnyChainman(const std::any &context)
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
static bool SetHasKeys(const std::set< T > &set)
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
Special string to represent a floating point amount.
static RPCHelpMan gettxout()
UniValue MempoolInfoToJSON(const CTxMemPool &pool)
Mempool information to JSON.
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
bool VerifyDB(CChainState &chainstate, const CChainParams &chainparams, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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 ...
static RPCHelpMan verifychain()
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
Undo information for a CBlock.
Serialized script, used inside transaction inputs and outputs.
int RPCSerializationFlags()
static const signed int DEFAULT_CHECKBLOCKS
Undo information for a CTransaction.
const CTransaction & GetTx() const
static RPCHelpMan savemempool()
static const int PROTOCOL_VERSION
network protocol versioning
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
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...
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.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out)
Get a single filter header by block.
static Mutex cs_blockchange
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
static RPCHelpMan preciousblock()
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
std::string GetHex() const
static RPCHelpMan getrawmempool()
static constexpr size_t PER_UTXO_OVERHEAD
std::set< CTxMemPoolEntryRef, CompareIteratorByHash > Children
static RPCHelpMan waitforblockheight()
UniValue ValueFromAmount(const CAmount amount)
static RPCHelpMan gettxoutsetinfo()
const UniValue NullUniValue
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances...
static RPCHelpMan pruneblockchain()
#define AssertLockNotHeld(cs)
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
int elapsed
Number of blocks elapsed since the beginning of the current period.
static RPCHelpMan reconsiderblock()
bool possible
False if there are not enough blocks left in this period to pass activation threshold.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static RPCHelpMan getchaintips()
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
NodeContext & EnsureAnyNodeContext(const std::any &context)
static const unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits) ...
CChainState & ActiveChainstate() const
The most-work chain.
std::string GetHex() const
static CBlockUndo GetUndoChecked(const CBlockIndex *pblockindex)
The basic transaction that is broadcasted on the network and contained in blocks. ...
int nHeight
height of the entry in the chain. The genesis block has height 0
static void SoftForkDescPushBack(const CBlockIndex *active_chain_tip, UniValue &softforks, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
const Consensus::Params & GetConsensus() const
int bit
Bit position to select the particular bit in nVersion.
Special dictionary with keys that are not literals.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange)
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
full block available in blk*.dat
CBlockIndex * ParseHashOrHeight(const UniValue ¶m, ChainstateManager &chainman)
void __pushKV(const std::string &key, const UniValue &val)
static RPCHelpMan getmempoolentry()
std::vector< CTxUndo > vtxundo
static int64_t GetBlockWeight(const CBlock &block)
static RPCHelpMan getmempooldescendants()
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
CCoinsView that brings transactions from a mempool into view.
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
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 CBlock GetBlockChecked(const CBlockIndex *pblockindex)
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
BuriedDeployment
A buried deployment is one where the height of the activation has been hardcoded into the client impl...
unsigned int nTx
Number of transactions in this block.
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function, bool skip_file_commit)
Dump the mempool to disk.
CChain & ActiveChain() const
static const unsigned int DEFAULT_CHECKLEVEL
Non-refcounted RAII wrapper for FILE*.
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex, int serialize_flags, const CTxUndo *txundo)
static RPCHelpMan getblockhash()
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
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...
CBlockPolicyEstimator & EnsureFeeEstimator(const NodeContext &node)
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Special type to denote elision (...)
std::string DeploymentName(Consensus::BuriedDeployment dep)
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Cursor for iterating over CoinsView state.
static RPCHelpMan getbestblockhash()