 |
Bitcoin Core
22.99.0
P2P Digital Currency
|
Go to the documentation of this file.
8 #include <blockfilter.h>
55 #include <condition_variable>
85 int nShift = (blockindex->
nBits >> 24) & 0xff;
87 (double)0x0000ffff / (
double)(blockindex->
nBits & 0x00ffffff);
106 if (next && next->
pprev == blockindex) {
110 return blockindex == tip ? 1 : -1;
118 const int height{param.
get_int()};
122 const int current_tip{active_chain.
Height()};
123 if (height > current_tip) {
127 return active_chain[height];
149 result.
pushKV(
"confirmations", confirmations);
160 result.
pushKV(
"nTx", (uint64_t)blockindex->
nTx);
162 if (blockindex->
pprev)
190 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
193 const CTxUndo* txundo = (have_undo && i > 0) ? &blockUndo.
vtxundo.at(i - 1) :
nullptr;
209 "\nReturns the height of the most-work fully-validated chain.\n"
210 "The genesis block has height 0.\n",
230 "\nReturns the hash of the best (tip) block in the most-work fully-validated chain.\n",
252 latestblock.height = pindex->
nHeight;
260 "\nWaits for a specific new block and returns useful info about it.\n"
261 "\nReturns the current block on timeout or exit.\n",
278 if (!request.params[0].isNull())
279 timeout = request.params[0].
get_int();
302 "\nWaits for a specific new block and returns useful info about it.\n"
303 "\nReturns the current block on timeout or exit.\n",
315 HelpExampleCli(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\" 1000")
316 +
HelpExampleRpc(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
324 if (!request.params[1].isNull())
325 timeout = request.params[1].get_int();
348 "\nWaits for (at least) block height and returns the height and hash\n"
349 "of the current tip.\n"
350 "\nReturns the current block on timeout or exit.\n",
369 int height = request.params[0].
get_int();
371 if (!request.params[1].isNull())
372 timeout = request.params[1].get_int();
393 return RPCHelpMan{
"syncwithvalidationinterfacequeue",
394 "\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n",
412 "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
415 RPCResult::Type::NUM,
"",
"the proof-of-work difficulty as a multiple of the minimum difficulty."},
430 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."},
433 "transaction fee, denominated in " +
CURRENCY_UNIT +
" (DEPRECATED, returned only if config option -deprecatedrpc=fees is passed)"},
435 "transaction fee with fee deltas used for mining priority, denominated in " +
CURRENCY_UNIT +
436 " (DEPRECATED, returned only if config option -deprecatedrpc=fees is passed)"},
442 "transaction fees of in-mempool descendants (including this one) with fee deltas used for mining priority, denominated in " +
443 CURRENCY_ATOM +
"s (DEPRECATED, returned only if config option -deprecatedrpc=fees is passed)"},
447 "transaction fees of in-mempool ancestors (including this one) with fee deltas used for mining priority, denominated in " +
448 CURRENCY_ATOM +
"s (DEPRECATED, returned only if config option -deprecatedrpc=fees is passed)"},
462 RPCResult{
RPCResult::Type::BOOL,
"unbroadcast",
"Whether this transaction is currently unbroadcast (initial broadcast not yet acknowledged by any peers)"},
469 info.pushKV(
"vsize", (
int)e.GetTxSize());
470 info.pushKV(
"weight", (
int)e.GetTxWeight());
473 if (deprecated_fee_fields_enabled) {
478 info.pushKV(
"height", (
int)e.GetHeight());
479 info.pushKV(
"descendantcount", e.GetCountWithDescendants());
480 info.pushKV(
"descendantsize", e.GetSizeWithDescendants());
481 if (deprecated_fee_fields_enabled) {
482 info.pushKV(
"descendantfees", e.GetModFeesWithDescendants());
484 info.pushKV(
"ancestorcount", e.GetCountWithAncestors());
485 info.pushKV(
"ancestorsize", e.GetSizeWithAncestors());
486 if (deprecated_fee_fields_enabled) {
487 info.pushKV(
"ancestorfees", e.GetModFeesWithAncestors());
489 info.pushKV(
"wtxid", pool.vTxHashes[e.vTxHashesIdx].first.ToString());
496 info.pushKV(
"fees", fees);
499 std::set<std::string> setDepends;
507 for (
const std::string& dep : setDepends)
512 info.pushKV(
"depends", depends);
518 spent.
push_back(child.GetTx().GetHash().ToString());
521 info.pushKV(
"spentby", spent);
524 bool rbfStatus =
false;
532 info.pushKV(
"bip125-replaceable", rbfStatus);
533 info.pushKV(
"unbroadcast", pool.IsUnbroadcastTx(tx.
GetHash()));
539 if (include_mempool_sequence) {
555 uint64_t mempool_sequence;
556 std::vector<uint256> vtxid;
563 for (
const uint256& hash : vtxid)
566 if (!include_mempool_sequence) {
571 o.
pushKV(
"mempool_sequence", mempool_sequence);
580 "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
581 "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n",
584 {
"mempool_sequence",
RPCArg::Type::BOOL,
RPCArg::Default{
false},
"If verbose=false, returns a json object with transaction list and mempool sequence number attached."},
597 RPCResult{
"for verbose = false and mempool_sequence = true",
613 bool fVerbose =
false;
614 if (!request.params[0].isNull())
615 fVerbose = request.params[0].
get_bool();
617 bool include_mempool_sequence =
false;
618 if (!request.params[1].isNull()) {
619 include_mempool_sequence = request.params[1].get_bool();
630 "\nIf txid is in the mempool, returns all in-mempool ancestors.\n",
651 bool fVerbose =
false;
652 if (!request.params[1].isNull())
653 fVerbose = request.params[1].
get_bool();
661 if (it == mempool.mapTx.end()) {
666 uint64_t noLimit = std::numeric_limits<uint64_t>::max();
673 o.
push_back(ancestorIt->GetTx().GetHash().ToString());
694 "\nIf txid is in the mempool, returns all in-mempool descendants.\n",
715 bool fVerbose =
false;
716 if (!request.params[1].isNull())
717 fVerbose = request.params[1].
get_bool();
725 if (it == mempool.mapTx.end()) {
732 setDescendants.erase(it);
737 o.
push_back(descendantIt->GetTx().GetHash().ToString());
759 "\nReturns mempool data for given transaction\n",
777 if (it == mempool.mapTx.end()) {
793 "Attempt to fetch block from a given peer.\n\n"
794 "We must have the header for this block, e.g. using submitheader.\n"
795 "Subsequent calls for the same block and a new peer will cause the response from the previous peer to be ignored.\n\n"
796 "Returns an empty JSON object if the request was successfully scheduled.",
803 HelpExampleCli(
"getblockfrompeer",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
804 +
HelpExampleRpc(
"getblockfrompeer",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
813 const NodeId peer_id{request.params[1].get_int64()};
822 if (block_has_data) {
826 if (
const auto err{peerman.
FetchBlock(peer_id, *index)}) {
837 "\nReturns hash of block in best-block-chain at height provided.\n",
853 int nHeight = request.params[0].get_int();
854 if (nHeight < 0 || nHeight > active_chain.
Height())
866 "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
867 "If verbose is true, returns an Object with information about blockheader <hash>.\n",
877 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
896 HelpExampleCli(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
897 +
HelpExampleRpc(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
903 bool fVerbose =
true;
904 if (!request.params[1].isNull())
905 fVerbose = request.params[1].get_bool();
924 std::string strHex =
HexStr(ssBlock);
969 "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
970 "If verbosity is 1, returns an Object with information about block <hash>.\n"
971 "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction.\n"
972 "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",
975 {
"verbosity|verbose",
RPCArg::Type::NUM,
RPCArg::Default{1},
"0 for hex-encoded data, 1 for a JSON object, 2 for JSON object with transaction data, and 3 for JSON object with transaction data including prevout information for inputs"},
984 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
999 {
RPCResult::Type::STR_HEX,
"chainwork",
"Expected number of hashes required to produce the chain up to this block (in hex)"},
1012 {
RPCResult::Type::ELISION,
"",
"The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result"},
1039 {
RPCResult::Type::STR,
"address",
true,
"The Bitcoin address (only if a well-defined address exists)"},
1050 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
1051 +
HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
1058 if (!request.params[1].isNull()) {
1059 if (request.params[1].isBool()) {
1060 verbosity = request.params[1].get_bool() ? 1 : 0;
1062 verbosity = request.params[1].get_int();
1086 std::string strHex =
HexStr(ssBlock);
1091 if (verbosity == 1) {
1093 }
else if (verbosity == 2) {
1099 return blockToJSON(block, tip, pblockindex, tx_verbosity);
1109 " to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
1127 int heightParam = request.params[0].get_int();
1128 if (heightParam < 0)
1133 if (heightParam > 1000000000) {
1139 heightParam = pindex->
nHeight;
1142 unsigned int height = (
unsigned int) heightParam;
1143 unsigned int chainHeight = (
unsigned int) active_chain.
Height();
1146 else if (height > chainHeight)
1149 LogPrint(
BCLog::RPC,
"Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
1157 block = block->
pprev;
1159 return uint64_t(block->
nHeight);
1166 if (hash_type_input ==
"hash_serialized_2") {
1167 return CoinStatsHashType::HASH_SERIALIZED;
1168 }
else if (hash_type_input ==
"muhash") {
1169 return CoinStatsHashType::MUHASH;
1170 }
else if (hash_type_input ==
"none") {
1180 "\nReturns statistics about the unspent transaction output set.\n"
1181 "Note this call may take some time if you are not using coinstatsindex.\n",
1183 {
"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'."},
1193 {
RPCResult::Type::NUM,
"bogosize",
"Database-independent, meaningless metric indicating the UTXO set size"},
1194 {
RPCResult::Type::STR_HEX,
"hash_serialized_2",
true,
"The serialized hash (only present if 'hash_serialized_2' hash_type is chosen)"},
1196 {
RPCResult::Type::NUM,
"transactions",
true,
"The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
1197 {
RPCResult::Type::NUM,
"disk_size",
true,
"The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
1199 {
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)"},
1200 {
RPCResult::Type::OBJ,
"block_info",
true,
"Info on amounts in the block at this block height (only available if coinstatsindex is used)",
1219 HelpExampleCli("gettxoutsetinfo", R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1223 HelpExampleRpc("gettxoutsetinfo", R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")
1232 stats.
index_requested = request.params[2].isNull() || request.params[2].get_bool();
1243 coins_view = &active_chainstate.
CoinsDB();
1248 if (!request.params[1].isNull()) {
1253 if (stats.m_hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1266 if (pindex->nHeight > summary.best_block_height) {
1272 if (
GetUTXOStats(coins_view, *blockman, stats,
node.rpc_interruption_point, pindex)) {
1273 ret.
pushKV(
"height", (int64_t)stats.nHeight);
1274 ret.
pushKV(
"bestblock", stats.hashBlock.GetHex());
1275 ret.
pushKV(
"txouts", (int64_t)stats.nTransactionOutputs);
1276 ret.
pushKV(
"bogosize", (int64_t)stats.nBogoSize);
1277 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1278 ret.
pushKV(
"hash_serialized_2", stats.hashSerialized.GetHex());
1280 if (hash_type == CoinStatsHashType::MUHASH) {
1281 ret.
pushKV(
"muhash", stats.hashSerialized.GetHex());
1285 if (!stats.index_used) {
1286 ret.
pushKV(
"transactions",
static_cast<int64_t
>(stats.nTransactions));
1287 ret.
pushKV(
"disk_size", stats.nDiskSize);
1293 if (pindex->nHeight > 0) {
1294 GetUTXOStats(coins_view, *blockman, prev_stats,
node.rpc_interruption_point, pindex->pprev);
1298 block_info.
pushKV(
"prevout_spent",
ValueFromAmount(stats.total_prevout_spent_amount - prev_stats.total_prevout_spent_amount));
1299 block_info.
pushKV(
"coinbase",
ValueFromAmount(stats.total_coinbase_amount - prev_stats.total_coinbase_amount));
1300 block_info.
pushKV(
"new_outputs_ex_coinbase",
ValueFromAmount(stats.total_new_outputs_ex_coinbase_amount - prev_stats.total_new_outputs_ex_coinbase_amount));
1301 block_info.
pushKV(
"unspendable",
ValueFromAmount(stats.total_unspendable_amount - prev_stats.total_unspendable_amount));
1304 unspendables.
pushKV(
"genesis_block",
ValueFromAmount(stats.total_unspendables_genesis_block - prev_stats.total_unspendables_genesis_block));
1305 unspendables.
pushKV(
"bip30",
ValueFromAmount(stats.total_unspendables_bip30 - prev_stats.total_unspendables_bip30));
1306 unspendables.
pushKV(
"scripts",
ValueFromAmount(stats.total_unspendables_scripts - prev_stats.total_unspendables_scripts));
1307 unspendables.
pushKV(
"unclaimed_rewards",
ValueFromAmount(stats.total_unspendables_unclaimed_rewards - prev_stats.total_unspendables_unclaimed_rewards));
1308 block_info.
pushKV(
"unspendables", unspendables);
1310 ret.
pushKV(
"block_info", block_info);
1323 "\nReturns details about an unspent transaction output.\n",
1327 {
"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."},
1340 {
RPCResult::Type::STR,
"address",
true,
"The Bitcoin address (only if a well-defined address exists)"},
1346 "\nGet unspent transactions\n"
1348 "\nView the details\n"
1350 "\nAs a JSON-RPC call\n"
1362 int n = request.params[1].get_int();
1364 bool fMempool =
true;
1365 if (!request.params[2].isNull())
1366 fMempool = request.params[2].get_bool();
1380 if (!coins_view->
GetCoin(out, coin)) {
1388 ret.
pushKV(
"confirmations", 0);
1395 ret.
pushKV(
"scriptPubKey", o);
1406 "\nVerifies blockchain database.\n",
1420 const int check_level(request.params[0].isNull() ?
DEFAULT_CHECKLEVEL : request.params[0].get_int());
1421 const int check_depth{request.params[1].isNull() ?
DEFAULT_CHECKBLOCKS : request.params[1].get_int()};
1428 active_chainstate,
Params().GetConsensus(), active_chainstate.
CoinsTip(), check_level, check_depth);
1440 rv.
pushKV(
"type",
"buried");
1453 if (blockindex ==
nullptr)
return;
1455 auto get_state_name = [](
const ThresholdState state) -> std::string {
1482 bip9.
pushKV(
"status", get_state_name(current_state));
1484 bip9.
pushKV(
"status-next", get_state_name(next_state));
1489 std::vector<bool> signals;
1498 bip9.
pushKV(
"statistics", statsUV);
1501 sig.reserve(signals.size());
1502 for (
const bool s : signals) {
1503 sig.push_back(s ?
'#' :
'-');
1505 bip9.
pushKV(
"signalling", sig);
1509 rv.
pushKV(
"type",
"bip9");
1522 extern const std::vector<RPCResult> RPCHelpForDeployment;
1530 "Returns an object containing various state info regarding blockchain processing.\n",
1536 {
RPCResult::Type::NUM,
"blocks",
"the height of the most-work fully-validated chain. The genesis block has height 0"},
1543 {
RPCResult::Type::BOOL,
"initialblockdownload",
"(debug information) estimate of whether this node is in Initial Block Download mode"},
1545 {
RPCResult::Type::NUM,
"size_on_disk",
"the estimated size of the block and undo files on disk"},
1547 {
RPCResult::Type::NUM,
"pruneheight",
true,
"lowest-height complete block stored (only present if pruning is enabled)"},
1548 {
RPCResult::Type::BOOL,
"automatic_pruning",
true,
"whether automatic pruning is enabled (only present if pruning is enabled)"},
1549 {
RPCResult::Type::NUM,
"prune_target_size",
true,
"the target size used by pruning (only present if automatic pruning is enabled)"},
1550 {
RPCResult::Type::OBJ_DYN,
"softforks",
"(DEPRECATED, returned only if config option -deprecatedrpc=softforks is passed) status of softforks",
1553 RPCHelpForDeployment
1571 const int height = tip->
nHeight;
1574 obj.
pushKV(
"blocks", height);
1581 obj.
pushKV(
"initialblockdownload", active_chainstate.IsInitialBlockDownload());
1589 block = block->
pprev;
1596 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1597 if (automatic_pruning) {
1604 obj.
pushKV(
"softforks", DeploymentInfo(tip, consensusParams));
1614 const std::vector<RPCResult> RPCHelpForDeployment{
1616 {
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)"},
1617 {
RPCResult::Type::BOOL,
"active",
"true if the rules are enforced for the mempool and the next block"},
1620 {
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)"},
1621 {
RPCResult::Type::NUM_TIME,
"start_time",
"the minimum median time past of a block at which the bit gains its meaning"},
1622 {
RPCResult::Type::NUM_TIME,
"timeout",
"the median time past of a block at which the deployment is considered failed if not yet locked in"},
1623 {
RPCResult::Type::NUM,
"min_activation_height",
"minimum height of blocks for which the rules may be enforced"},
1624 {
RPCResult::Type::STR,
"status",
"status of deployment at specified block (one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\")"},
1627 {
RPCResult::Type::OBJ,
"statistics",
true,
"numeric statistics about signalling for a softfork (only for \"started\" and \"locked_in\" status)",
1630 {
RPCResult::Type::NUM,
"threshold",
true,
"the number of blocks with the version bit set required to activate the feature (only for \"started\" status)"},
1631 {
RPCResult::Type::NUM,
"elapsed",
"the number of blocks elapsed since the beginning of the current period"},
1632 {
RPCResult::Type::NUM,
"count",
"the number of blocks with the version bit set in the current period"},
1633 {
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)"},
1635 {
RPCResult::Type::STR,
"signalling",
"indicates blocks that signalled with a # and blocks that did not with a -"},
1656 "Returns an object containing various state info regarding deployments of consensus changes.",
1677 if (request.params[0].isNull()) {
1678 blockindex = active_chainstate.
m_chain.
Tip();
1693 deploymentinfo.
pushKV(
"deployments", DeploymentInfo(blockindex, consensusParams));
1694 return deploymentinfo;
1717 "Return information about all known tips in the block tree,"
1718 " including the main chain as well as orphaned branches.\n",
1726 {
RPCResult::Type::NUM,
"branchlen",
"zero for main chain, otherwise length of branch connecting the tip to the main chain"},
1728 "Possible values for status:\n"
1729 "1. \"invalid\" This branch contains at least one invalid block\n"
1730 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
1731 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
1732 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
1733 "5. \"active\" This is the tip of the active main chain, which is certainly valid"},
1752 std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1753 std::set<const CBlockIndex*> setOrphans;
1754 std::set<const CBlockIndex*> setPrevs;
1756 for (
const std::pair<const uint256, CBlockIndex*>& item : chainman.
BlockIndex()) {
1757 if (!active_chain.
Contains(item.second)) {
1758 setOrphans.insert(item.second);
1759 setPrevs.insert(item.second->pprev);
1763 for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) {
1764 if (setPrevs.erase(*it) == 0) {
1765 setTips.insert(*it);
1770 setTips.insert(active_chain.
Tip());
1776 obj.
pushKV(
"height", block->nHeight);
1777 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1779 const int branchLen = block->nHeight - active_chain.
FindFork(block)->
nHeight;
1780 obj.
pushKV(
"branchlen", branchLen);
1783 if (active_chain.
Contains(block)) {
1789 }
else if (!block->HaveTxsDownloaded()) {
1791 status =
"headers-only";
1794 status =
"valid-fork";
1797 status =
"valid-headers";
1802 obj.
pushKV(
"status", status);
1823 ret.
pushKV(
"maxmempool", (int64_t) maxmempool);
1833 "\nReturns details on the active state of the TX memory pool.\n",
1840 {
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"},
1846 {
RPCResult::Type::NUM,
"unbroadcastcount",
"Current number of transactions that haven't passed initial broadcast yet"}
1862 "\nTreats a block as if it were received before others with the same work.\n"
1863 "\nA later preciousblock call can override the effect of an earlier one.\n"
1864 "\nThe effects of preciousblock are not retained across restarts.\n",
1902 "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n",
1943 "\nRemoves invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n"
1944 "This can be used to undo the effects of invalidateblock.\n",
1983 "\nCompute statistics about the total number and rate of transactions in the chain.\n",
1992 {
RPCResult::Type::NUM,
"txcount",
"The total number of transactions in the chain up to that point"},
1994 {
RPCResult::Type::NUM,
"window_final_block_height",
"The height of the final block in the window."},
1996 {
RPCResult::Type::NUM,
"window_tx_count",
true,
"The number of transactions in the window. Only returned if \"window_block_count\" is > 0"},
1997 {
RPCResult::Type::NUM,
"window_interval",
true,
"The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0"},
1998 {
RPCResult::Type::NUM,
"txrate",
true,
"The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0"},
2010 if (request.params[1].isNull()) {
2027 if (request.params[0].isNull()) {
2028 blockcount = std::max(0, std::min(blockcount, pindex->
nHeight - 1));
2030 blockcount = request.params[0].get_int();
2032 if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->
nHeight)) {
2046 ret.
pushKV(
"window_block_count", blockcount);
2047 if (blockcount > 0) {
2048 ret.
pushKV(
"window_tx_count", nTxDiff);
2049 ret.
pushKV(
"window_interval", nTimeDiff);
2050 if (nTimeDiff > 0) {
2051 ret.
pushKV(
"txrate", ((
double)nTxDiff) / nTimeDiff);
2060 template<
typename T>
2063 size_t size = scores.size();
2068 std::sort(scores.begin(), scores.end());
2069 if (size % 2 == 0) {
2070 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
2072 return scores[size / 2];
2078 if (scores.empty()) {
2082 std::sort(scores.begin(), scores.end());
2086 total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
2089 int64_t next_percentile_index = 0;
2090 int64_t cumulative_weight = 0;
2091 for (
const auto& element : scores) {
2092 cumulative_weight += element.second;
2093 while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
2094 result[next_percentile_index] = element.first;
2095 ++next_percentile_index;
2101 result[i] = scores.back().first;
2105 template<
typename T>
2106 static inline bool SetHasKeys(
const std::set<T>& set) {
return false;}
2107 template<
typename T,
typename Tk,
typename... Args>
2108 static inline bool SetHasKeys(
const std::set<T>& set,
const Tk& key,
const Args&...
args)
2119 "\nCompute per block statistics for a given window. All amounts are in satoshis.\n"
2120 "It won't work for some heights with pruning.\n",
2137 {
RPCResult::Type::ARR_FIXED,
"feerate_percentiles",
true,
"Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
2162 {
RPCResult::Type::NUM,
"total_out",
true,
"Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
2167 {
RPCResult::Type::NUM,
"utxo_increase",
true,
"The increase/decrease in the number of unspent outputs"},
2168 {
RPCResult::Type::NUM,
"utxo_size_inc",
true,
"The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
2171 HelpExampleCli(
"getblockstats", R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2172 HelpExampleCli("getblockstats", R
"(1000 '["minfeerate","avgfeerate"]')") +
2173 HelpExampleRpc("getblockstats", R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2174 HelpExampleRpc("getblockstats", R
"(1000, ["minfeerate","avgfeerate"])")
2183 std::set<std::string> stats;
2184 if (!request.params[1].isNull()) {
2186 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2187 const std::string stat = stats_univalue[i].
get_str();
2195 const bool do_all = stats.size() == 0;
2196 const bool do_mediantxsize = do_all || stats.count(
"mediantxsize") != 0;
2197 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
2198 const bool do_feerate_percentiles = do_all || stats.count(
"feerate_percentiles") != 0;
2199 const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
2200 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
"avgfeerate",
"minfee",
"maxfee",
"minfeerate",
"maxfeerate");
2201 const bool loop_outputs = do_all || loop_inputs || stats.count(
"total_out");
2202 const bool do_calculate_size = do_mediantxsize ||
2203 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
"maxtxsize",
"swtotal_size");
2204 const bool do_calculate_weight = do_all ||
SetHasKeys(stats,
"total_weight",
"avgfeerate",
"swtotal_weight",
"avgfeerate",
"feerate_percentiles",
"minfeerate",
"maxfeerate");
2205 const bool do_calculate_sw = do_all ||
SetHasKeys(stats,
"swtxs",
"swtotal_size",
"swtotal_weight");
2214 int64_t maxtxsize = 0;
2216 int64_t outputs = 0;
2217 int64_t swtotal_size = 0;
2218 int64_t swtotal_weight = 0;
2220 int64_t total_size = 0;
2221 int64_t total_weight = 0;
2222 int64_t utxo_size_inc = 0;
2223 std::vector<CAmount> fee_array;
2224 std::vector<std::pair<CAmount, int64_t>> feerate_array;
2225 std::vector<int64_t> txsize_array;
2227 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2228 const auto& tx = block.
vtx.at(i);
2229 outputs += tx->vout.size();
2233 for (
const CTxOut& out : tx->vout) {
2234 tx_total_out += out.
nValue;
2239 if (tx->IsCoinBase()) {
2243 inputs += tx->vin.size();
2244 total_out += tx_total_out;
2246 int64_t tx_size = 0;
2247 if (do_calculate_size) {
2249 tx_size = tx->GetTotalSize();
2250 if (do_mediantxsize) {
2251 txsize_array.push_back(tx_size);
2253 maxtxsize = std::max(maxtxsize, tx_size);
2254 mintxsize = std::min(mintxsize, tx_size);
2255 total_size += tx_size;
2259 if (do_calculate_weight) {
2261 total_weight += weight;
2264 if (do_calculate_sw && tx->HasWitness()) {
2266 swtotal_size += tx_size;
2267 swtotal_weight += weight;
2272 const auto& txundo = blockUndo.
vtxundo.at(i - 1);
2273 for (
const Coin& coin: txundo.vprevout) {
2276 tx_total_in += prevoutput.
nValue;
2280 CAmount txfee = tx_total_in - tx_total_out;
2283 fee_array.push_back(txfee);
2285 maxfee = std::max(maxfee, txfee);
2286 minfee = std::min(minfee, txfee);
2291 if (do_feerate_percentiles) {
2292 feerate_array.emplace_back(std::make_pair(feerate, weight));
2294 maxfeerate = std::max(maxfeerate, feerate);
2295 minfeerate = std::min(minfeerate, feerate);
2304 feerates_res.
push_back(feerate_percentiles[i]);
2308 ret_all.
pushKV(
"avgfee", (block.
vtx.size() > 1) ? totalfee / (block.
vtx.size() - 1) : 0);
2310 ret_all.
pushKV(
"avgtxsize", (block.
vtx.size() > 1) ? total_size / (block.
vtx.size() - 1) : 0);
2311 ret_all.
pushKV(
"blockhash", pindex->GetBlockHash().GetHex());
2312 ret_all.
pushKV(
"feerate_percentiles", feerates_res);
2313 ret_all.
pushKV(
"height", (int64_t)pindex->nHeight);
2314 ret_all.
pushKV(
"ins", inputs);
2315 ret_all.
pushKV(
"maxfee", maxfee);
2316 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2317 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2319 ret_all.
pushKV(
"mediantime", pindex->GetMedianTimePast());
2322 ret_all.
pushKV(
"minfeerate", (minfeerate ==
MAX_MONEY) ? 0 : minfeerate);
2324 ret_all.
pushKV(
"outs", outputs);
2326 ret_all.
pushKV(
"swtotal_size", swtotal_size);
2327 ret_all.
pushKV(
"swtotal_weight", swtotal_weight);
2328 ret_all.
pushKV(
"swtxs", swtxs);
2329 ret_all.
pushKV(
"time", pindex->GetBlockTime());
2330 ret_all.
pushKV(
"total_out", total_out);
2331 ret_all.
pushKV(
"total_size", total_size);
2332 ret_all.
pushKV(
"total_weight", total_weight);
2333 ret_all.
pushKV(
"totalfee", totalfee);
2334 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
2335 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2336 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2343 for (
const std::string& stat : stats) {
2344 const UniValue& value = ret_all[stat];
2358 "\nDumps the mempool to disk. It will fail until the previous dump is fully loaded.\n",
2392 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)
2396 while (cursor->
Valid()) {
2399 if (!cursor->
GetKey(key) || !cursor->
GetValue(coin))
return false;
2400 if (++
count % 8192 == 0) {
2401 interruption_point();
2407 if (
count % 256 == 0) {
2410 scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
2413 out_results.emplace(key, coin);
2417 scan_progress = 100;
2454 const std::string EXAMPLE_DESCRIPTOR_RAW =
"raw(76a91411b366edfc0a8b66feebae5c2e25a7b6a5d1cf3188ac)#fm24fxxy";
2457 "\nScans the unspent transaction output set for entries that match certain output descriptors.\n"
2458 "Examples of output descriptors are:\n"
2459 " addr(<address>) Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\n"
2460 " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
2461 " combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n"
2462 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
2463 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
2464 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2465 "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2466 "unhardened or hardened child keys.\n"
2467 "In the latter case, a range needs to be specified by below if different from 1000.\n"
2468 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
2471 "\"start\" for starting a scan\n"
2472 "\"abort\" for aborting the current scan (returns true when abort was successful)\n"
2473 "\"status\" for progress report (in %) of the current scan"},
2475 "Every scan object is either a string descriptor or an object:",
2484 "[scanobjects,...]"},
2514 HelpExampleCli(
"scantxoutset",
"start \'[\"" + EXAMPLE_DESCRIPTOR_RAW +
"\"]\'") +
2517 HelpExampleRpc(
"scantxoutset",
"\"start\", [\"" + EXAMPLE_DESCRIPTOR_RAW +
"\"]") +
2523 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR});
2526 if (request.params[0].get_str() ==
"status") {
2534 }
else if (request.params[0].get_str() ==
"abort") {
2543 }
else if (request.params[0].get_str() ==
"start") {
2549 if (request.params.size() < 2) {
2553 std::set<CScript> needles;
2554 std::map<CScript, std::string> descriptors;
2561 for (
const auto& script : scripts) {
2563 needles.emplace(script);
2564 descriptors.emplace(std::move(script), std::move(inferred));
2570 std::vector<CTxOut> input_txos;
2571 std::map<COutPoint, Coin> coins;
2574 std::unique_ptr<CCoinsViewCursor> pcursor;
2588 result.
pushKV(
"success", res);
2593 for (
const auto& it : coins) {
2595 const Coin& coin = it.second;
2597 input_txos.push_back(txo);
2602 unspent.
pushKV(
"vout", (int32_t)outpoint.
n);
2610 result.
pushKV(
"unspents", unspents);
2623 "\nRetrieve a BIP 157 content filter for a particular block.\n",
2635 HelpExampleCli(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"") +
2636 HelpExampleRpc(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\", \"basic\"")
2641 std::string filtertype_name =
"basic";
2642 if (!request.params[1].isNull()) {
2643 filtertype_name = request.params[1].get_str();
2657 bool block_was_connected;
2668 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2675 std::string errmsg =
"Filter not found.";
2677 if (!block_was_connected) {
2679 errmsg +=
" Block was not connected to active chain.";
2680 }
else if (!index_ready) {
2682 errmsg +=
" Block filters are still in the process of being indexed.";
2685 errmsg +=
" This error is unexpected and indicates index corruption.";
2708 "Write the serialized UTXO set to disk.",
2720 {
RPCResult::Type::NUM,
"nchaintx",
"the number of transactions in the chain up to and including the base block"},
2737 path.u8string() +
" already exists. If you are sure this is what you want, "
2738 "move it out of the way first");
2745 node,
node.chainman->ActiveChainstate(), afile, path, temppath);
2746 fs::rename(temppath, path);
2748 result.
pushKV(
"path", path.u8string());
2761 std::unique_ptr<CCoinsViewCursor> pcursor;
2762 CCoinsStats stats{CoinStatsHashType::HASH_SERIALIZED};
2801 unsigned int iter{0};
2803 while (pcursor->Valid()) {
2804 if (iter % 5000 == 0)
node.rpc_interruption_point();
2806 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
2817 result.
pushKV(
"coins_written", stats.coins_count);
2820 result.
pushKV(
"path", path.u8string());
2821 result.
pushKV(
"txoutset_hash", stats.hashSerialized.ToString());
2871 for (
const auto& c : commands) {
2872 t.appendCommand(c.name, &c);
int64_t nStartTime
Start MedianTime for version bits miner confirmation.
size_t GetSerializeSize(const T &t, int nVersion=0)
An input of a transaction.
@ RPC_MISC_ERROR
General application defined errors.
bool fPruneMode
True if we're running in -prune mode.
std::set< txiter, CompareIteratorByHash > setEntries
static T CalculateTruncatedMedian(std::vector< T > &scores)
const std::vector< CTxIn > vin
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
@ ELISION
Special type to denote elision (...)
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
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.
static std::atomic< bool > g_should_abort_scan
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
static bool exists(const path &p)
static RPCHelpMan preciousblock()
static constexpr size_t PER_UTXO_OVERHEAD
static RPCHelpMan getblockfilter()
static const unsigned int DEFAULT_CHECKLEVEL
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
static RPCHelpMan verifychain()
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::set< CTxMemPoolEntryRef, CompareIteratorByHash > Children
int bit
Bit position to select the particular bit in nVersion.
#define LOG_TIME_SECONDS(end_msg)
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
static RPCHelpMan getdeploymentinfo()
void RegisterBlockchainRPCCommands(CRPCTable &t)
Register block chain RPC commands.
FILE * fopen(const fs::path &p, const char *mode)
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Undo information for a CTransaction.
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool include_hex, bool include_address=true)
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool index_requested
Signals if the coinstatsindex should be used (when available).
std::string GetHex() const
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
unsigned int nTx
Number of transactions in this block.
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
static std::condition_variable cond_blockchange
static std::atomic< int > g_scan_progress
RAII object to prevent concurrency issue when scanning the txout set.
const std::vector< unsigned char > & GetEncodedFilter() const
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
static RPCHelpMan waitforblockheight()
const UniValue NullUniValue
PeerManager & EnsurePeerman(const NodeContext &node)
RBFTransactionState
The rbf state of unconfirmed transactions.
static constexpr int NUM_GETBLOCKSTATS_PERCENTILES
static RPCHelpMan getmempoolinfo()
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
static RPCHelpMan getblockstats()
CBlockIndex * pprev
pointer to the index of the predecessor of this block
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
UniValue MempoolInfoToJSON(const CTxMemPool &pool)
Mempool information to JSON.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
static int ComputeNextBlockAndDepth(const CBlockIndex *tip, const CBlockIndex *blockindex, const CBlockIndex *&next)
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
int nHeight
height of the entry in the chain. The genesis block has height 0
NodeContext struct containing references to chain state and connection state.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
Comparison function for sorting the getchaintips heads.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
static RPCHelpMan getchaintxstats()
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
bool MoneyRange(const CAmount &nValue)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
const Consensus::Params & GetConsensus() const
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
ArgsManager & EnsureAnyArgsman(const std::any &context)
ChainstateManager & EnsureChainman(const NodeContext &node)
static CBlock GetBlockChecked(const CBlockIndex *pblockindex) EXCLUSIVE_LOCKS_REQUIRED(
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
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.
static RPCHelpMan pruneblockchain()
unsigned int fCoinBase
whether containing transaction was a coinbase
static std::string PathToString(const path &path)
Convert path object to a byte string.
static RPCHelpMan getblockfrompeer()
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 GenTxid Txid(const uint256 &hash)
CChainState & ActiveChainstate() const
The most-work chain.
std::shared_ptr< const CTransaction > CTransactionRef
static RPCHelpMan syncwithvalidationinterfacequeue()
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
std::vector< CTxUndo > vtxundo
bool pushKV(const std::string &key, const UniValue &val)
UniValue ValueFromAmount(const CAmount amount)
bool IsRPCRunning()
Query whether RPC is running.
static RPCHelpMan getblockhash()
static RPCHelpMan getblock()
void queryHashes(std::vector< uint256 > &vtxid) const
bool IsBlockPruned(const CBlockIndex *pblockindex)
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
The basic transaction that is broadcasted on the network and contained in blocks.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static const unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange)
std::string ToString() const
CChain & ActiveChain() const
int64_t nPowTargetSpacing
uint64_t PruneAfterHeight() const
Abstract view on the open txout dataset.
@ ARR_FIXED
Special array that has a fixed number of entries.
NodeContext & EnsureAnyNodeContext(const std::any &context)
CTxOut out
unspent transaction output
static RPCHelpMan getmempoolentry()
Non-refcounted RAII wrapper for FILE*.
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
const std::string & get_str() const
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...
Cursor for iterating over CoinsView state.
CBlockHeader GetBlockHeader() const
Parameters that influence chain consensus.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
Block header to JSON.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
VersionBitsCache g_versionbitscache
Global cache for versionbits deployment status.
const std::string CURRENCY_UNIT
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
virtual bool GetValue(Coin &coin) const =0
#define AssertLockNotHeld(cs)
@ SHOW_TXID
Only TXID for each block's transaction.
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
An output of a transaction.
static BIP9Stats Statistics(const CBlockIndex *pindex, const Consensus::Params ¶ms, Consensus::DeploymentPos pos, std::vector< bool > *signalling_blocks=nullptr)
Get the numerical statistics for a given deployment for the signalling period that includes pindex.
@ STR_HEX
Special type that is a STR with only hex chars.
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index.
int64_t GetMedianTimePast() const
uint32_t nHeight
at which height this containing transaction was included in the active block chain
static RPCHelpMan getdifficulty()
UniValue CreateUTXOSnapshot(NodeContext &node, CChainState &chainstate, CAutoFile &afile, const fs::path &path, const fs::path &temppath)
Helper to create UTXO snapshots given a chainstate and a file handle.
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
int32_t nVersion
block header
ChainstateManager & EnsureAnyChainman(const std::any &context)
bool DeploymentEnabled(const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is enabled (can ever be active)
int count
Number of blocks with the version bit set since the beginning of the current period.
static RPCHelpMan getchaintips()
static RPCHelpMan gettxout()
@ RPC_DATABASE_ERROR
Database error.
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
const std::string CURRENCY_ATOM
bool VerifyDB(CChainState &chainstate, const Consensus::Params &consensus_params, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
@ STR_HEX
Special string with only hex chars.
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
static void entryToJSON(const CTxMemPool &pool, UniValue &info, const CTxMemPoolEntry &e) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
int64_t CAmount
Amount in satoshis (Can be negative)
std::string GetHex() const
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
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...
void __pushKV(const std::string &key, const UniValue &val)
int threshold
Number of blocks with the version bit set required to activate the softfork.
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 ...
@ SHOW_DETAILS_AND_PREVOUT
The same as previous option with information about prevouts if available.
static RPCHelpMan getbestblockhash()
std::string ToString() const
virtual bool Valid() const =0
@ NUM_TIME
Special numeric to denote unix epoch time.
@ SHOW_DETAILS
Include TXID, inputs, outputs, and other common block's transaction information.
CChainState stores and provides an API to update our local knowledge of the current best chain.
#define LogPrint(category,...)
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
static int64_t GetBlockWeight(const CBlock &block)
@ RANGE
Special type that is a NUM or [NUM,NUM].
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
static Mutex cs_blockchange
uint256 GetBlockHash() const
int Height() const
Return the maximal height in the chain.
static RPCHelpMan gettxoutsetinfo()
static RPCHelpMan getrawmempool()
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
CBlockIndex * ParseHashOrHeight(const UniValue ¶m, ChainstateManager &chainman)
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
static RPCHelpMan getblockheader()
int min_activation_height
If lock in occurs, delay activation until at least this block height.
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
Display status of an in-progress BIP9 softfork.
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...
static RPCHelpMan reconsiderblock()
static RPCHelpMan getmempooldescendants()
int elapsed
Number of blocks elapsed since the beginning of the current period.
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
UniValue blockToJSON(const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, TxVerbosity verbosity)
Block description to JSON.
static std::atomic< bool > g_scan_in_progress
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
An in-memory indexed chain of blocks.
static int64_t GetTransactionWeight(const CTransaction &tx)
std::vector< CTransactionRef > vtx
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
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 operator()(const CBlockIndex *a, const CBlockIndex *b) const
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
CoinStatsHashType ParseHashType(const std::string &hash_type_input)
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
UniValue JSONRPCError(int code, const std::string &message)
int DeploymentHeight(BuriedDeployment dep) const
int RPCSerializationFlags()
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
BuriedDeployment
A buried deployment is one where the height of the activation has been hardcoded into the client impl...
static CBlockUndo GetUndoChecked(const CBlockIndex *pblockindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CCoinsView that brings transactions from a mempool into view.
unsigned long size() const
bool push_back(const UniValue &val)
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
const CChainParams & Params()
Return the currently selected parameters.
CTxMemPool & EnsureMemPool(const NodeContext &node)
virtual bool GetKey(COutPoint &key) const =0
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function, bool skip_file_commit)
Dump the mempool to disk.
static RPCHelpMan invalidateblock()
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
static RPCHelpMan scantxoutset()
const std::vector< UniValue > & getValues() const
Double ended buffer combining vector and stream-like interfaces.
@ UNKNOWN
Unconfirmed tx that does not signal rbf and is not in the mempool.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
bool possible
False if there are not enough blocks left in this period to pass activation threshold.
@ OBJ_DYN
Special dictionary with keys that are not literals.
size_t DynamicMemoryUsage() const
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
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)
const uint256 & GetHash() const
std::string DeploymentName(Consensus::BuriedDeployment dep)
An outpoint - a combination of a transaction hash and an index n into its vout.
bool IsDeprecatedRPCEnabled(const std::string &method)
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...
static RPCHelpMan getmempoolancestors()
@ STR_AMOUNT
Special string to represent a floating point amount.
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
@ BLOCK_HAVE_DATA
full block available in blk*.dat
const UniValue & get_array() const
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
int period
Length of blocks of the BIP9 signalling period.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
#define T(expected, seed, data)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
The block chain is a tree shaped structure starting with the genesis block at the root,...
static RPCHelpMan savemempool()
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
RPCHelpMan getblockchaininfo()
bool isSpent(const COutPoint &outpoint) const
static void SoftForkDescPushBack(const CBlockIndex *blockindex, UniValue &softforks, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
virtual std::optional< std::string > FetchBlock(NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
CTxMemPool & EnsureAnyMemPool(const std::any &context)
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
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...
@ REPLACEABLE_BIP125
Either this tx or a mempool ancestor signals rbf.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out)
Get a single filter header by block.
static const int WITNESS_SCALE_FACTOR
static std::vector< RPCResult > MempoolEntryDescription()
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Undo information for a CBlock.
#define WAIT_LOCK(cs, name)
CChain m_chain
The current chain of blockheaders we consult and build on.
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
static RPCHelpMan waitforblock()
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
static bool SetHasKeys(const std::set< T > &set)
TxVerbosity
Verbose level for block's transaction.
static const signed int DEFAULT_CHECKBLOCKS
static const int PROTOCOL_VERSION
network protocol versioning
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
static RPCHelpMan getblockcount()
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
static RPCHelpMan waitfornewblock()
const CTransaction & GetTx() const
Complete block filter struct as defined in BIP 157.