11#include <chainparams.h>
49#include <condition_variable>
74 const std::function<
void()> &interruption_point = {})
82 const std::function<
void()> &interruption_point = {});
88 int nShift = (blockindex.
nBits >> 24) & 0xff;
89 double dDiff = double(0x0000ffff) / double(blockindex.
nBits & 0x00ffffff);
107 if (next && next->
pprev == &blockindex) {
111 return &blockindex == &tip ? 1 : -1;
120 const int height{param.
getInt<
int>()};
124 strprintf(
"Target block height %d is negative", height));
126 const int current_tip{active_chain.
Height()};
127 if (height > current_tip) {
130 strprintf(
"Target block height %d after current tip %d", height,
134 return active_chain[height];
157 result.
pushKV(
"confirmations", confirmations);
170 if (blockindex.
pprev) {
171 result.
pushKV(
"previousblockhash",
189 const bool is_not_pruned{
191 const bool have_undo{is_not_pruned &&
193 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
197 (have_undo && i) ? &blockUndo.
vtxundo.at(i - 1) :
nullptr;
215 "Returns the height of the most-work fully-validated chain.\n"
216 "The genesis block has height 0.\n",
233 "Returns the hash of the best (tip) block in the "
234 "most-work fully-validated chain.\n",
252 latestblock.height = pindex->
nHeight;
260 "Waits for a specific new block and returns useful info about it.\n"
261 "\nReturns the current block on timeout or exit.\n",
264 "Time in milliseconds to wait for a response. 0 indicates no "
279 if (!request.params[0].isNull()) {
280 timeout = request.params[0].
getInt<
int>();
289 lock, std::chrono::milliseconds(timeout),
291 return latestblock.height != block.
height ||
292 latestblock.hash != block.
hash ||
299 return latestblock.height != block.
height ||
300 latestblock.hash != block.
hash ||
317 "Waits for a specific new block and returns useful info about it.\n"
318 "\nReturns the current block on timeout or exit.\n",
321 "Block hash to wait for."},
323 "Time in milliseconds to wait for a response. 0 indicates no "
334 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
335 "ed7b4a8c619eb02596f8862\" 1000") +
337 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
338 "ed7b4a8c619eb02596f8862\", 1000")},
345 if (!request.params[1].isNull()) {
346 timeout = request.params[1].getInt<
int>();
354 lock, std::chrono::milliseconds(timeout),
378 "waitforblockheight",
379 "Waits for (at least) block height and returns the height and "
380 "hash\nof the current tip.\n"
381 "\nReturns the current block on timeout or exit.\n",
384 "Block height to wait for."},
386 "Time in milliseconds to wait for a response. 0 indicates no "
402 int height = request.params[0].
getInt<
int>();
404 if (!request.params[1].isNull()) {
405 timeout = request.params[1].getInt<
int>();
413 lock, std::chrono::milliseconds(timeout),
415 return latestblock.height >= height ||
422 return latestblock.height >= height ||
438 "syncwithvalidationinterfacequeue",
439 "Waits for the validation interface queue to catch up on everything "
440 "that was there when we entered this function.\n",
456 "Returns the proof-of-work difficulty as a multiple of the minimum "
460 "the proof-of-work difficulty as a multiple of the minimum "
476 "Attempt to fetch block from a given peer.\n"
477 "\nWe must have the header for this block, e.g. using submitheader.\n"
478 "The block will not have any undo data which can limit the usage of "
479 "the block data in a context where the undo data is needed.\n"
480 "Subsequent calls for the same block may cause the response from the "
481 "previous peer to be ignored.\n"
482 "\nReturns an empty JSON object if the request was successfully "
486 "The block hash to try to fetch"},
488 "The peer to fetch it from (see getpeerinfo for peer IDs)"},
492 "\"00000000c937983704a73af28acdec37b049d214a"
493 "dbda81d7e2a3dd146f6ed09\" 0") +
495 "\"00000000c937983704a73af28acdec37b049d214a"
496 "dbda81d7e2a3dd146f6ed09\" 0")},
505 const NodeId peer_id{request.params[1].getInt<int64_t>()};
519 if (
const auto err{peerman.
FetchBlock(config, peer_id, *index)}) {
530 "Returns hash of block in best-block-chain at height provided.\n",
544 int nHeight = request.params[0].getInt<
int>();
545 if (nHeight < 0 || nHeight > active_chain.
Height()) {
547 "Block height out of range");
559 "If verbose is false, returns a string that is serialized, hex-encoded "
560 "data for blockheader 'hash'.\n"
561 "If verbose is true, returns an Object with information about "
562 "blockheader <hash>.\n",
567 "true for a json object, false for the hex-encoded data"},
571 "for verbose = true",
577 "the block hash (same as provided)"},
579 "The number of confirmations, or -1 if the block is not "
580 "on the main chain"},
582 "The block height or index"},
585 "The block version formatted in hexadecimal"},
595 "Expected number of hashes required to produce the "
598 "The number of transactions in the block"},
601 "The hash of the previous block (if available)"},
604 "The hash of the next block (if available)"},
607 "A string that is serialized, hex-encoded data for block "
611 "\"00000000c937983704a73af28acdec37b049d214a"
612 "dbda81d7e2a3dd146f6ed09\"") +
614 "\"00000000c937983704a73af28acdec37b049d214a"
615 "dbda81d7e2a3dd146f6ed09\"")},
620 bool fVerbose =
true;
621 if (!request.params[1].isNull()) {
622 fVerbose = request.params[1].get_bool();
643 std::string strHex =
HexStr(ssBlock);
657 if (blockman.IsBlockPruned(blockindex)) {
659 "Block not available (pruned data)");
680 if (blockman.IsBlockPruned(blockindex)) {
682 "Undo data not available (pruned data)");
696 "If verbosity is 0 or false, returns a string that is serialized, "
697 "hex-encoded data for block 'hash'.\n"
698 "If verbosity is 1 or true, returns an Object with information about "
700 "If verbosity is 2, returns an Object with information about block "
701 "<hash> and information about each transaction.\n",
706 "0 for hex-encoded data, 1 for a json object, and 2 for json "
707 "object with transaction data",
712 "A string that is serialized, hex-encoded data for block "
721 "the block hash (same as provided)"},
723 "The number of confirmations, or -1 if the block is not "
724 "on the main chain"},
727 "The block height or index"},
730 "The block version formatted in hexadecimal"},
734 "The transaction ids",
744 "Expected number of hashes required to produce the chain "
745 "up to this block (in hex)"},
747 "The number of transactions in the block"},
750 "The hash of the previous block (if available)"},
753 "The hash of the next block (if available)"},
761 "Same output as verbosity = 1"},
771 "The transactions in the format of the "
772 "getrawtransaction RPC. Different from "
773 "verbosity = 1 \"tx\" result"},
775 "The transaction fee in " +
777 ", omitted if block undo data is not "
784 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
785 "214adbda81d7e2a3dd146f6ed09\"") +
786 HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
787 "214adbda81d7e2a3dd146f6ed09\"")},
793 if (!request.params[1].isNull()) {
794 if (request.params[1].isNum()) {
795 verbosity = request.params[1].getInt<
int>();
797 verbosity = request.params[1].get_bool() ? 1 : 0;
818 if (verbosity <= 0) {
821 std::string strHex =
HexStr(ssBlock);
843 if (!first_block || !chain_tip) {
848 if (!(chain_tip->nStatus.hasData() && chain_tip->nStatus.hasUndo())) {
855 blockman.GetFirstBlock(*chain_tip,
857 return status.hasData() && status.hasUndo();
859 if (first_unpruned == first_block) {
875 "The block height to prune up to. May be set to a discrete "
879 " to prune blocks whose block time is at "
880 "least 2 hours older than the provided timestamp."},
891 "Cannot prune blocks because node is not in prune mode.");
898 int heightParam = request.params[0].getInt<
int>();
899 if (heightParam < 0) {
901 "Negative block height.");
907 if (heightParam > 1000000000) {
914 "Could not find block with at least the "
915 "specified timestamp.");
920 unsigned int height = (
unsigned int)heightParam;
921 unsigned int chainHeight = (
unsigned int)active_chain.
Height();
922 if (chainHeight < config.GetChainParams().PruneAfterHeight()) {
924 "Blockchain is too short for pruning.");
925 }
else if (height > chainHeight) {
928 "Blockchain is shorter than the attempted prune height.");
931 "Attempt to prune blocks close to the tip. "
932 "Retaining the minimum number of blocks.\n");
944 if (hash_type_input ==
"hash_serialized") {
945 return CoinStatsHashType::HASH_SERIALIZED;
946 }
else if (hash_type_input ==
"muhash") {
947 return CoinStatsHashType::MUHASH;
948 }
else if (hash_type_input ==
"none") {
953 strprintf(
"%s is not a valid hash_type", hash_type_input));
960 "Returns statistics about the unspent transaction output set.\n"
961 "Note this call may take some time if you are not using "
965 "Which UTXO set hash should be calculated. Options: "
966 "'hash_serialized' (the legacy algorithm), 'muhash', 'none'."},
968 "The block hash or height of the target height (only available "
969 "with coinstatsindex).",
971 .type_str = {
"",
"string or numeric"}}},
973 "Use coinstatsindex, if available."},
981 "The current block height (index)"},
983 "The hash of the block at the tip of the chain"},
985 "The number of unspent transaction outputs"},
987 "Database-independent, meaningless metric indicating "
988 "the UTXO set size"},
991 "The serialized hash (only present if 'hash_serialized' "
992 "hash_type is chosen)"},
994 "The serialized hash (only present if 'muhash' "
995 "hash_type is chosen)"},
997 "The number of transactions with unspent outputs (not "
998 "available when coinstatsindex is used)"},
1000 "The estimated size of the chainstate on disk (not "
1001 "available when coinstatsindex is used)"},
1003 "The total amount"},
1005 "The total amount of coins permanently excluded from the UTXO "
1006 "set (only available if coinstatsindex is used)"},
1009 "Info on amounts in the block at this block height (only "
1010 "available if coinstatsindex is used)",
1012 "Total amount of all prevouts spent in this block"},
1014 "Coinbase subsidy amount of this block"},
1016 "Total amount of new outputs created by this block"},
1018 "Total amount of unspendable outputs created in this block"},
1021 "Detailed view of the unspendable categories",
1024 "The unspendable amount of the Genesis block subsidy"},
1026 "Transactions overridden by duplicates (no longer "
1027 "possible with BIP30)"},
1029 "Amounts sent to scripts that are unspendable (for "
1030 "example OP_RETURN outputs)"},
1032 "Fee rewards that miners did not claim in their "
1033 "coinbase transaction"},
1042 R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1048 R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")},
1055 request.params[0].isNull()
1056 ? CoinStatsHashType::HASH_SERIALIZED
1058 bool index_requested =
1059 request.params[2].isNull() || request.params[2].get_bool();
1070 coins_view = &active_chainstate.
CoinsDB();
1075 if (!request.params[1].isNull()) {
1078 "Querying specific block heights "
1079 "requires coinstatsindex");
1082 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1084 "hash_serialized hash type cannot be "
1085 "queried for a specific block");
1099 if (pindex->nHeight > summary.best_block_height) {
1103 "Unable to get data because coinstatsindex is "
1104 "still syncing. Current height: %d",
1105 summary.best_block_height));
1110 const std::optional<CCoinsStats> maybe_stats =
GetUTXOStats(
1111 coins_view, *blockman, hash_type,
node.rpc_interruption_point,
1112 pindex, index_requested);
1113 if (maybe_stats.has_value()) {
1119 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1120 ret.
pushKV(
"hash_serialized",
1123 if (hash_type == CoinStatsHashType::MUHASH) {
1128 ret.
pushKV(
"transactions",
1132 ret.
pushKV(
"total_unspendable_amount",
1136 if (pindex->nHeight > 0) {
1137 const std::optional<CCoinsStats> maybe_prev_stats =
1139 node.rpc_interruption_point,
1140 pindex->pprev, index_requested);
1141 if (!maybe_prev_stats) {
1143 "Unable to read UTXO set");
1145 prev_stats = maybe_prev_stats.value();
1152 prev_stats.total_prevout_spent_amount);
1153 block_info.
pushKV(
"coinbase",
1155 prev_stats.total_coinbase_amount);
1157 "new_outputs_ex_coinbase",
1159 prev_stats.total_new_outputs_ex_coinbase_amount);
1160 block_info.
pushKV(
"unspendable",
1162 prev_stats.total_unspendable_amount);
1168 prev_stats.total_unspendables_genesis_block);
1171 prev_stats.total_unspendables_bip30);
1174 prev_stats.total_unspendables_scripts);
1176 "unclaimed_rewards",
1178 prev_stats.total_unspendables_unclaimed_rewards);
1179 block_info.
pushKV(
"unspendables", unspendables);
1181 ret.
pushKV(
"block_info", block_info);
1185 "Unable to read UTXO set");
1195 "Returns details about an unspent transaction output.\n",
1198 "The transaction id"},
1201 "Whether to include the mempool. Note that an unspent output that "
1202 "is spent in the mempool won't appear."},
1214 "The hash of the block at the tip of the chain"},
1216 "The number of confirmations"},
1226 "Number of required signatures"},
1228 "The type, eg pubkeyhash"},
1231 "array of eCash addresses",
1240 "\nAs a JSON-RPC call\n" +
1251 int n = request.params[1].getInt<
int>();
1252 COutPoint out(txid, n);
1253 bool fMempool =
true;
1254 if (!request.params[2].isNull()) {
1255 fMempool = request.params[2].get_bool();
1270 if (!coins_view->
GetCoin(out, coin)) {
1280 ret.
pushKV(
"confirmations", 0);
1282 ret.
pushKV(
"confirmations",
1288 ret.
pushKV(
"scriptPubKey", o);
1299 "Verifies blockchain database.\n",
1304 strprintf(
"How thorough the block verification is:\n%s",
1308 "The number of blocks to check."},
1311 "Verification finished successfully. If false, check "
1312 "debug.log for reason."},
1317 const int check_level{request.params[0].
isNull()
1319 : request.params[0].getInt<
int>()};
1320 const int check_depth{request.params[1].isNull()
1322 : request.params[1].getInt<
int>()};
1330 active_chainstate.
CoinsTip(), check_level,
1338 "getblockchaininfo",
1339 "Returns an object containing various state info regarding blockchain "
1348 "current network name (main, test, regtest)"},
1350 "the height of the most-work fully-validated "
1351 "non-parked chain. The genesis block has height 0"},
1353 "the current number of headers we have validated"},
1355 "the hash of the avalanche finalized tip if any, otherwise "
1356 "the genesis block hash"},
1358 "the hash of the currently best block"},
1365 "estimate of verification progress [0..1]"},
1367 "(debug information) estimate of whether this node is in "
1368 "Initial Block Download mode"},
1370 "total amount of work in active chain, in hexadecimal"},
1372 "the estimated size of the block and undo files on disk"},
1374 "if the blocks are subject to pruning"},
1376 "lowest-height complete block stored (only present if pruning "
1379 "whether automatic pruning is enabled (only present if "
1380 "pruning is enabled)"},
1382 "the target size used by pruning (only present if automatic "
1383 "pruning is enabled)"},
1385 "any network and blockchain warnings"},
1391 const CChainParams &chainparams = config.GetChainParams();
1399 const int height{tip.
nHeight};
1403 obj.
pushKV(
"blocks", height);
1404 obj.
pushKV(
"headers", chainman.m_best_header
1405 ? chainman.m_best_header->nHeight
1408 obj.
pushKV(
"finalized_blockhash",
1409 avalanche_finalized_tip
1410 ? avalanche_finalized_tip->GetBlockHash().GetHex()
1417 "verificationprogress",
1419 obj.
pushKV(
"initialblockdownload",
1422 obj.
pushKV(
"size_on_disk",
1429 obj.
pushKV(
"pruneheight",
1430 prune_height ? prune_height.value() + 1 : 0);
1432 const bool automatic_pruning{
1434 BlockManager::PRUNE_TARGET_MANUAL};
1435 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1436 if (automatic_pruning) {
1437 obj.
pushKV(
"prune_target_size",
1464 "Return information about all known tips in the block tree, including "
1465 "the main chain as well as orphaned branches.\n",
1478 "zero for main chain, otherwise length of branch connecting "
1479 "the tip to the main chain"},
1481 "status of the chain, \"active\" for the main chain\n"
1482 "Possible values for status:\n"
1483 "1. \"invalid\" This branch contains at "
1484 "least one invalid block\n"
1485 "2. \"parked\" This branch contains at "
1486 "least one parked block\n"
1487 "3. \"headers-only\" Not all blocks for this "
1488 "branch are available, but the headers are valid\n"
1489 "4. \"valid-headers\" All blocks are available for "
1490 "this branch, but they were never fully validated\n"
1491 "5. \"valid-fork\" This branch is not part of "
1492 "the active chain, but is fully validated\n"
1493 "6. \"active\" This is the tip of the "
1494 "active main chain, which is certainly valid"},
1515 std::set<const CBlockIndex *, CompareBlocksByHeight> setTips;
1516 std::set<const CBlockIndex *> setOrphans;
1517 std::set<const CBlockIndex *> setPrevs;
1519 for (
const auto &[
_, block_index] : chainman.
BlockIndex()) {
1520 if (!active_chain.
Contains(&block_index)) {
1521 setOrphans.insert(&block_index);
1522 setPrevs.insert(block_index.pprev);
1526 for (std::set<const CBlockIndex *>::iterator it =
1528 it != setOrphans.end(); ++it) {
1529 if (setPrevs.erase(*it) == 0) {
1530 setTips.insert(*it);
1535 setTips.insert(active_chain.
Tip());
1541 obj.
pushKV(
"height", block->nHeight);
1542 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1544 const int branchLen =
1546 obj.
pushKV(
"branchlen", branchLen);
1549 if (active_chain.
Contains(block)) {
1552 }
else if (block->nStatus.isInvalid()) {
1555 }
else if (block->nStatus.isOnParkedChain()) {
1558 }
else if (!block->HaveNumChainTxs()) {
1561 status =
"headers-only";
1566 status =
"valid-fork";
1571 status =
"valid-headers";
1576 obj.
pushKV(
"status", status);
1589 "Treats a block as if it were received before others with the same "
1591 "\nA later preciousblock call can override the effect of an earlier "
1593 "\nThe effects of preciousblock are not retained across restarts.\n",
1596 "the hash of the block to mark as precious"},
1619 node.avalanche.get());
1660 "Permanently marks a block as invalid, as if it violated a consensus "
1664 "the hash of the block to mark as invalid"},
1687 "Marks a block as parked.\n",
1690 "the hash of the block to park"},
1697 const std::string strHash = request.params[0].
get_str();
1720 active_chainstate.
ParkBlock(state, pblockindex);
1724 node.avalanche.get());
1751 chainman.RecalculateBestHeader();
1766 "Removes invalidity status of a block, its ancestors and its"
1767 "descendants, reconsider them for activation.\n"
1768 "This can be used to undo the effects of invalidateblock.\n",
1771 "the hash of the block to reconsider"},
1795 "Removes parked status of a block and its descendants, reconsider "
1796 "them for activation.\n"
1797 "This can be used to undo the effects of parkblock.\n",
1800 "the hash of the block to unpark"},
1807 const std::string strHash = request.params[0].
get_str();
1823 if (!pblockindex->nStatus.isOnParkedChain()) {
1845 node.avalanche.get());
1862 "Compute statistics about the total number and rate of transactions "
1866 "Size of the window in number of blocks"},
1869 "The hash of the block that ends the window."},
1877 "The timestamp for the final block in the window, "
1881 "The total number of transactions in the chain up to "
1882 "that point, if known. It may be unknown when using "
1885 "The hash of the final block in the window"},
1887 "The height of the final block in the window."},
1889 "Size of the window in number of blocks"},
1891 "The elapsed time in the window in seconds. Only "
1892 "returned if \"window_block_count\" is > 0"},
1894 "The number of transactions in the window. Only "
1895 "returned if \"window_block_count\" is > 0 and if "
1896 "txcount exists for the start and end of the window."},
1898 "The average rate of transactions per second in the "
1899 "window. Only returned if \"window_interval\" is > 0 "
1900 "and if window_tx_count exists."},
1912 config.GetChainParams().GetConsensus().nPowTargetSpacing;
1914 if (request.params[1].isNull()) {
1927 "Block is not in main chain");
1933 if (request.params[0].isNull()) {
1935 std::max(0, std::min(blockcount, pindex->
nHeight - 1));
1937 blockcount = request.params[0].getInt<
int>();
1939 if (blockcount < 0 ||
1940 (blockcount > 0 && blockcount >= pindex->
nHeight)) {
1942 "Invalid block count: "
1943 "should be between 0 and "
1944 "the block's height - 1");
1951 past_block.GetMedianTimePast()};
1958 ret.
pushKV(
"window_final_block_hash",
1961 ret.
pushKV(
"window_block_count", blockcount);
1962 if (blockcount > 0) {
1963 ret.
pushKV(
"window_interval", nTimeDiff);
1964 if (pindex->
nChainTx != 0 && past_block.nChainTx != 0) {
1965 unsigned int window_tx_count =
1966 pindex->
nChainTx - past_block.nChainTx;
1967 ret.
pushKV(
"window_tx_count", window_tx_count);
1968 if (nTimeDiff > 0) {
1970 double(window_tx_count) / nTimeDiff);
1980template <
typename T>
1982 size_t size = scores.size();
1987 std::sort(scores.begin(), scores.end());
1988 if (size % 2 == 0) {
1989 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1991 return scores[size / 2];
1995template <
typename T>
static inline bool SetHasKeys(
const std::set<T> &set) {
1998template <
typename T,
typename Tk,
typename... Args>
1999static inline bool SetHasKeys(
const std::set<T> &set,
const Tk &key,
2000 const Args &...args) {
2001 return (set.count(key) != 0) ||
SetHasKeys(set, args...);
2006 sizeof(COutPoint) +
sizeof(uint32_t) +
sizeof(bool);
2012 "Compute per block statistics for a given window. All amounts are "
2016 "It won't work for some heights with pruning.\n",
2019 "The block hash or height of the target block",
2021 .type_str = {
"",
"string or numeric"}}},
2025 "Values to plot (see result below)",
2028 "Selected statistic"},
2030 "Selected statistic"},
2041 "Average feerate (in satoshis per virtual byte)"},
2044 "The block hash (to check for potential reorgs)"},
2047 "The number of inputs (excluding coinbase)"},
2050 "Maximum feerate (in satoshis per virtual byte)"},
2053 "Truncated median fee in the block"},
2055 "Truncated median feerate (in " + ticker +
" per byte)"},
2057 "The block median time past"},
2059 "Truncated median transaction size"},
2062 "Minimum feerate (in satoshis per virtual byte)"},
2068 "Total amount in all outputs (excluding coinbase and thus "
2069 "reward [ie subsidy + totalfee])"},
2071 "Total size of all non-coinbase transactions"},
2074 "The number of transactions (including coinbase)"},
2076 "The increase/decrease in the number of unspent outputs"},
2078 "The increase/decrease in size for the utxo index (not "
2079 "discounting op_return and similar)"},
2084 R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2086 R
"(1000 '["minfeerate","avgfeerate"]')") +
2089 R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2091 R
"(1000, ["minfeerate","avgfeerate"])")},
2098 std::set<std::string> stats;
2099 if (!request.params[1].isNull()) {
2101 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2102 const std::string stat = stats_univalue[i].
get_str();
2112 const bool do_all = stats.size() == 0;
2113 const bool do_mediantxsize =
2114 do_all || stats.count(
"mediantxsize") != 0;
2115 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
2116 const bool do_medianfeerate =
2117 do_all || stats.count(
"medianfeerate") != 0;
2118 const bool loop_inputs =
2119 do_all || do_medianfee || do_medianfeerate ||
2120 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
2121 "avgfeerate",
"minfee",
"maxfee",
"minfeerate",
2123 const bool loop_outputs =
2124 do_all || loop_inputs || stats.count(
"total_out");
2125 const bool do_calculate_size =
2126 do_mediantxsize || loop_inputs ||
2127 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
2130 const int64_t blockMaxSize = config.GetMaxBlockSize();
2138 int64_t maxtxsize = 0;
2139 int64_t mintxsize = blockMaxSize;
2140 int64_t outputs = 0;
2141 int64_t total_size = 0;
2142 int64_t utxo_size_inc = 0;
2143 std::vector<Amount> fee_array;
2144 std::vector<Amount> feerate_array;
2145 std::vector<int64_t> txsize_array;
2147 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2148 const auto &tx = block.
vtx.at(i);
2149 outputs += tx->vout.size();
2152 for (
const CTxOut &out : tx->vout) {
2153 tx_total_out += out.
nValue;
2160 if (tx->IsCoinBase()) {
2165 inputs += tx->vin.size();
2167 total_out += tx_total_out;
2169 int64_t tx_size = 0;
2170 if (do_calculate_size) {
2171 tx_size = tx->GetTotalSize();
2172 if (do_mediantxsize) {
2173 txsize_array.push_back(tx_size);
2175 maxtxsize = std::max(maxtxsize, tx_size);
2176 mintxsize = std::min(mintxsize, tx_size);
2177 total_size += tx_size;
2182 const auto &txundo = blockUndo.
vtxundo.at(i - 1);
2183 for (
const Coin &coin : txundo.vprevout) {
2186 tx_total_in += prevoutput.
nValue;
2192 Amount txfee = tx_total_in - tx_total_out;
2195 fee_array.push_back(txfee);
2197 maxfee = std::max(maxfee, txfee);
2198 minfee = std::min(minfee, txfee);
2201 Amount feerate = txfee / tx_size;
2202 if (do_medianfeerate) {
2203 feerate_array.push_back(feerate);
2205 maxfeerate = std::max(maxfeerate, feerate);
2206 minfeerate = std::min(minfeerate, feerate);
2212 block.
vtx.size() > 1
2213 ? (totalfee /
int((block.
vtx.size() - 1)))
2215 ret_all.
pushKV(
"avgfeerate", total_size > 0
2216 ? (totalfee / total_size)
2218 ret_all.
pushKV(
"avgtxsize",
2219 (block.
vtx.size() > 1)
2220 ? total_size / (block.
vtx.size() - 1)
2222 ret_all.
pushKV(
"blockhash", pindex.GetBlockHash().GetHex());
2223 ret_all.
pushKV(
"height", (int64_t)pindex.nHeight);
2224 ret_all.
pushKV(
"ins", inputs);
2225 ret_all.
pushKV(
"maxfee", maxfee);
2226 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2227 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2229 ret_all.
pushKV(
"medianfeerate",
2231 ret_all.
pushKV(
"mediantime", pindex.GetMedianTimePast());
2232 ret_all.
pushKV(
"mediantxsize",
2239 ret_all.
pushKV(
"mintxsize",
2240 mintxsize == blockMaxSize ? 0 : mintxsize);
2241 ret_all.
pushKV(
"outs", outputs);
2244 ret_all.
pushKV(
"time", pindex.GetBlockTime());
2245 ret_all.
pushKV(
"total_out", total_out);
2246 ret_all.
pushKV(
"total_size", total_size);
2247 ret_all.
pushKV(
"totalfee", totalfee);
2248 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
2249 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2250 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2257 for (
const std::string &stat : stats) {
2258 const UniValue &value = ret_all[stat];
2262 strprintf(
"Invalid selected statistic %s", stat));
2273static bool FindScriptPubKey(std::atomic<int> &scan_progress,
2274 const std::atomic<bool> &should_abort,
2276 const std::set<CScript> &needles,
2277 std::map<COutPoint, Coin> &out_results,
2278 std::function<
void()> &interruption_point) {
2281 while (cursor->
Valid()) {
2287 if (++
count % 8192 == 0) {
2288 interruption_point();
2294 if (
count % 256 == 0) {
2296 const TxId &txid = key.GetTxId();
2297 uint32_t high = 0x100 * *txid.
begin() + *(txid.
begin() + 1);
2298 scan_progress = int(high * 100.0 / 65536.0 + 0.5);
2301 out_results.emplace(key, coin);
2305 scan_progress = 100;
2341 "Scans the unspent transaction output set for entries that match "
2342 "certain output descriptors.\n"
2343 "Examples of output descriptors are:\n"
2344 " addr(<address>) Outputs whose scriptPubKey "
2345 "corresponds to the specified address (does not include P2PK)\n"
2346 " raw(<hex script>) Outputs whose scriptPubKey "
2347 "equals the specified hex scripts\n"
2348 " combo(<pubkey>) P2PK and P2PKH outputs for "
2349 "the given pubkey\n"
2350 " pkh(<pubkey>) P2PKH outputs for the given "
2352 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
2353 "the given threshold and pubkeys\n"
2354 "\nIn the above, <pubkey> either refers to a fixed public key in "
2355 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2356 "or more path elements separated by \"/\", and optionally ending in "
2357 "\"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2358 "unhardened or hardened child keys.\n"
2359 "In the latter case, a range needs to be specified by below if "
2360 "different from 1000.\n"
2361 "For more information on output descriptors, see the documentation in "
2362 "the doc/descriptors.md file.\n",
2365 "The action to execute\n"
2366 " \"start\" for starting a "
2368 " \"abort\" for aborting the "
2369 "current scan (returns true when abort was successful)\n"
2371 "progress report (in %) of the current scan"},
2375 "Array of scan objects. Required for \"start\" action\n"
2376 " Every scan object is either a "
2377 "string descriptor or an object:",
2380 "An output descriptor"},
2385 "An object with output descriptor and metadata",
2388 "An output descriptor"},
2390 "The range of HD chain indexes to explore (either "
2391 "end or [begin,end])"},
2399 RPCResult{
"When action=='status' and no scan is in progress",
2402 "When action=='status' and scan is in progress",
2410 "When action=='start'",
2416 "Whether the scan was completed"},
2418 "The number of unspent transaction outputs scanned"},
2420 "The current block height (index)"},
2422 "The hash of the block at the tip of the chain"},
2432 "The transaction id"},
2437 "A specialized descriptor for the matched "
2440 "The total amount in " + ticker +
2441 " of the unspent output"},
2443 "Whether this is a coinbase output"},
2445 "Height of the unspent transaction output"},
2449 "The total amount of all found unspent outputs in " +
2457 const auto action{self.
Arg<std::string>(
"action")};
2458 if (action ==
"status") {
2466 }
else if (action ==
"abort") {
2475 }
else if (action ==
"start") {
2479 "Scan already in progress, use action "
2480 "\"abort\" or \"status\"");
2483 if (request.params.size() < 2) {
2485 "scanobjects argument is required for "
2486 "the start action");
2489 std::set<CScript> needles;
2490 std::map<CScript, std::string> descriptors;
2499 for (CScript &script : scripts) {
2500 std::string inferred =
2502 needles.emplace(script);
2503 descriptors.emplace(std::move(script),
2504 std::move(inferred));
2510 std::vector<CTxOut> input_txos;
2511 std::map<COutPoint, Coin> coins;
2515 std::unique_ptr<CCoinsViewCursor> pcursor;
2527 bool res = FindScriptPubKey(
2529 needles, coins,
node.rpc_interruption_point);
2530 result.
pushKV(
"success", res);
2535 for (
const auto &it : coins) {
2536 const COutPoint &outpoint = it.first;
2537 const Coin &coin = it.second;
2539 input_txos.push_back(txo);
2543 unspent.
pushKV(
"txid", outpoint.GetTxId().GetHex());
2544 unspent.
pushKV(
"vout", int32_t(outpoint.GetN()));
2553 result.
pushKV(
"unspents", unspents);
2554 result.
pushKV(
"total_amount", total_in);
2557 strprintf(
"Invalid action '%s'", action));
2567 "Retrieve a BIP 157 content filter for a particular block.\n",
2570 "The hash of the block"},
2572 "The type name of the filter"},
2579 "the hex-encoded filter data"},
2581 "the hex-encoded filter header"},
2585 "\"00000000c937983704a73af28acdec37b049d214a"
2586 "dbda81d7e2a3dd146f6ed09\" \"basic\"") +
2588 "\"00000000c937983704a73af28acdec37b049d214adbda81d7"
2589 "e2a3dd146f6ed09\", \"basic\"")},
2594 std::string filtertype_name =
"basic";
2595 if (!request.params[1].isNull()) {
2596 filtertype_name = request.params[1].get_str();
2602 "Unknown filtertype");
2608 "Index is not enabled for filtertype " +
2613 bool block_was_connected;
2623 block_was_connected =
2627 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2634 std::string errmsg =
"Filter not found.";
2636 if (!block_was_connected) {
2638 errmsg +=
" Block was not connected to active chain.";
2639 }
else if (!index_ready) {
2641 errmsg +=
" Block filters are still in the process of "
2645 errmsg +=
" This error is unexpected and indicates index "
2672 "Network activity could not be suspended.");
2710 "Write the serialized UTXO set to a file. This can be used in "
2711 "loadtxoutset afterwards if this snapshot height is supported in the "
2712 "chainparams as well.\n\n"
2713 "Unless the the \"latest\" type is requested, the node will roll back "
2714 "to the requested height and network activity will be suspended during "
2716 "Because of this it is discouraged to interact with the node in any "
2717 "other way during the execution of this call to avoid inconsistent "
2718 "results and race conditions, particularly RPCs that interact with "
2720 "This call may take several minutes. Make sure to use no RPC timeout "
2721 "(bitcoin-cli -rpcclienttimeout=0)",
2725 "path to the output file. If relative, will be prefixed by "
2728 "The type of snapshot to create. Can be \"latest\" to create a "
2729 "snapshot of the current UTXO set or \"rollback\" to temporarily "
2730 "roll back the state of the node to a historical block before "
2731 "creating the snapshot of a historical UTXO set. This parameter "
2732 "can be omitted if a separate \"rollback\" named parameter is "
2733 "specified indicating the height or hash of a specific historical "
2734 "block. If \"rollback\" is specified and separate \"rollback\" "
2735 "named parameter is not specified, this will roll back to the "
2736 "latest valid snapshot block that can currently be loaded with "
2745 "Height or hash of the block to roll back to before "
2746 "creating the snapshot. Note: The further this number is "
2747 "from the tip, the longer this process will take. "
2748 "Consider setting a higher -rpcclienttimeout value in "
2751 .type_str = {
"",
"string or numeric"}}},
2760 "the number of coins written in the snapshot"},
2762 "the hash of the base of the snapshot"},
2764 "the height of the base of the snapshot"},
2766 "the absolute path that the snapshot was written to"},
2768 "the hash of the UTXO set contents"},
2770 "the number of transactions in the chain up to and "
2771 "including the base block"},
2774 "utxo.dat latest") +
2776 "utxo.dat rollback") +
2778 R
"(utxo.dat rollback=853456)")},
2785 const std::string snapshot_type{self.
Arg<std::string>(
"type")};
2788 : request.params[2]};
2789 if (options.exists(
"rollback")) {
2790 if (!snapshot_type.empty() && snapshot_type !=
"rollback") {
2793 strprintf(
"Invalid snapshot type \"%s\" specified with "
2799 }
else if (snapshot_type ==
"rollback") {
2800 auto snapshot_heights =
2801 node.chainman->GetParams().GetAvailableSnapshotHeights();
2803 auto max_height = std::max_element(snapshot_heights.begin(),
2804 snapshot_heights.end());
2806 }
else if (snapshot_type ==
"latest") {
2811 strprintf(
"Invalid snapshot type \"%s\" specified. Please "
2812 "specify \"rollback\" or \"latest\"",
2818 args.GetDataDirNet(),
fs::u8path(request.params[0].get_str()));
2822 args.GetDataDirNet(),
2823 fs::u8path(request.params[0].get_str() +
".incomplete"));
2828 " already exists. If you are sure this "
2829 "is what you want, "
2830 "move it out of the way first");
2838 std::optional<NetworkDisable> disable_network;
2839 std::optional<TemporaryRollback> temporary_rollback;
2843 if (target_index != tip) {
2846 if (
node.chainman->m_blockman.IsPruneMode()) {
2849 node.chainman->ActiveChain().Tip()};
2851 node.chainman->m_blockman.GetFirstBlock(
2856 if (first_block->nHeight > target_index->nHeight) {
2859 "Could not roll back to requested height since "
2860 "necessary block data is already pruned.");
2874 disable_network.emplace(connman);
2879 return node.chainman->ActiveChain().Next(target_index));
2880 temporary_rollback.emplace(*
node.chainman,
node.avalanche.get(),
2885 std::unique_ptr<CCoinsViewCursor> cursor;
2895 chainstate = &
node.chainman->ActiveChainstate();
2904 if (target_index != chainstate->
m_chain.
Tip()) {
2906 "Failed to roll back to requested height, "
2907 "reverting to tip.\n");
2910 "Could not roll back to requested height.");
2913 *chainstate,
node.rpc_interruption_point);
2919 path, temppath,
node.rpc_interruption_point);
2920 fs::rename(temppath, path);
2929 const std::function<
void()> &interruption_point) {
2930 std::unique_ptr<CCoinsViewCursor> pcursor;
2931 std::optional<CCoinsStats> maybe_stats;
2953 CoinStatsHashType::HASH_SERIALIZED,
2954 interruption_point);
2960 std::unique_ptr<CCoinsViewCursor>(chainstate.
CoinsDB().
Cursor());
2972 const std::function<
void()> &interruption_point) {
2974 strprintf(
"writing UTXO snapshot at height %s (%s) to file %s (via %s)",
2985 unsigned int iter{0};
2986 size_t written_coins_count{0};
2987 std::vector<std::pair<uint32_t, Coin>> coins;
2996 auto write_coins_to_file =
2998 const std::vector<std::pair<uint32_t, Coin>> &coins,
2999 size_t &written_coins_count) {
3002 for (
const auto &[n, coin_] : coins) {
3005 ++written_coins_count;
3010 last_txid = key.GetTxId();
3011 while (pcursor->
Valid()) {
3012 if (iter % 5000 == 0) {
3013 interruption_point();
3017 if (key.GetTxId() != last_txid) {
3018 write_coins_to_file(afile, last_txid, coins,
3019 written_coins_count);
3020 last_txid = key.GetTxId();
3023 coins.emplace_back(key.GetN(), coin);
3028 if (!coins.empty()) {
3029 write_coins_to_file(afile, last_txid, coins, written_coins_count);
3037 result.
pushKV(
"coins_written", written_coins_count);
3053 tmppath,
node.rpc_interruption_point);
3059 "Load the serialized UTXO set from a file.\n"
3060 "Once this snapshot is loaded, its contents will be deserialized into "
3061 "a second chainstate data structure, which is then used to sync to the "
3063 "Meanwhile, the original chainstate will complete the initial block "
3064 "download process in the background, eventually validating up to the "
3065 "block that the snapshot is based upon.\n\n"
3066 "The result is a usable bitcoind instance that is current with the "
3067 "network tip in a matter of minutes rather than hours. UTXO snapshot "
3068 "are typically obtained from third-party sources (HTTP, torrent, etc.) "
3069 "which is reasonable since their contents are always checked by "
3071 "This RPC is incompatible with the -chronik init option, and a node "
3072 "with multiple chainstates may not be restarted with -chronik. After "
3073 "the background validation is finished and the chainstates are merged, "
3074 "the node can be restarted again with Chronik.\n\n"
3075 "You can find more information on this process in the `assumeutxo` "
3076 "design document (https://www.bitcoinabc.org/doc/assumeutxo.html).",
3079 "path to the snapshot file. If relative, will be prefixed by "
3087 "the number of coins loaded from the snapshot"},
3089 "the hash of the base of the snapshot"},
3091 "the height of the base of the snapshot"},
3093 "the absolute path that the snapshot was loaded from"},
3108 "loadtxoutset is not compatible with Chronik.");
3115 "Couldn't open file " + path.
u8string() +
3122 }
catch (
const std::ios_base::failure &e) {
3125 strprintf(
"Unable to parse metadata: %s", e.what()));
3128 auto activation_result{
3130 if (!activation_result) {
3133 strprintf(
"Unable to load UTXO snapshot: %s. (%s)",
3151 result.
pushKV(
"tip_hash", snapshot_index.GetBlockHash().ToString());
3152 result.
pushKV(
"base_height", snapshot_index.nHeight);
3164 "progress towards the network tip"},
3166 "the base block of the snapshot this chainstate is based on, if any"},
3169 "size of the coinstip cache"},
3171 "whether the chainstate is fully validated. True if all blocks in the "
3172 "chainstate were validated, false if the chain is based on a snapshot and "
3173 "the snapshot has not yet been validated."},
3180 "\nReturn information about chainstates.\n",
3187 "the number of headers seen so far"},
3190 "list of the chainstates ordered by work, with the "
3191 "most-work (active) chainstate last",
3205 auto make_chain_data =
3220 "verificationprogress",
3222 data.
pushKV(
"coins_db_cache_bytes",
3224 data.
pushKV(
"coins_tip_cache_bytes",
3228 "snapshot_blockhash",
3231 data.
pushKV(
"validated", validated);
3235 obj.
pushKV(
"headers", chainman.m_best_header
3236 ? chainman.m_best_header->nHeight
3239 const auto &chainstates = chainman.
GetAll();
3242 obj_chainstates.push_back(
3243 make_chain_data(*
cs, !
cs->m_from_snapshot_blockhash ||
3244 chainstates.size() == 1));
3246 obj.
pushKV(
"chainstates", std::move(obj_chainstates));
3289 for (
const auto &c : commands) {
bool MoneyRange(const Amount nValue)
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
fs::path AbsPathForConfigVal(const ArgsManager &args, const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
static RPCHelpMan getblock()
static RPCHelpMan getdifficulty()
static std::atomic< bool > g_scan_in_progress
static bool SetHasKeys(const std::set< T > &set)
static RPCHelpMan reconsiderblock()
static void InvalidateBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, const BlockHash &block_hash)
static T CalculateTruncatedMedian(std::vector< T > &scores)
static RPCHelpMan invalidateblock()
static int ComputeNextBlockAndDepth(const CBlockIndex &tip, const CBlockIndex &blockindex, const CBlockIndex *&next)
static RPCHelpMan syncwithvalidationinterfacequeue()
static CBlockUndo GetUndoChecked(BlockManager &blockman, const CBlockIndex &blockindex)
static RPCHelpMan getchaintips()
static RPCHelpMan loadtxoutset()
static RPCHelpMan gettxoutsetinfo()
static RPCHelpMan getchainstates()
std::tuple< std::unique_ptr< CCoinsViewCursor >, CCoinsStats, const CBlockIndex * > PrepareUTXOSnapshot(Chainstate &chainstate, const std::function< void()> &interruption_point)
static RPCHelpMan getblockstats()
static CoinStatsHashType ParseHashType(const std::string &hash_type_input)
static RPCHelpMan preciousblock()
static constexpr size_t PER_UTXO_OVERHEAD
double GetDifficulty(const CBlockIndex &blockindex)
Calculate the difficulty for a given block index.
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex &tip, const CBlockIndex &blockindex, bool txDetails)
Block description to JSON.
static RPCHelpMan scantxoutset()
static std::condition_variable cond_blockchange
static std::atomic< int > g_scan_progress
RAII object to prevent concurrency issue when scanning the txout set.
static CBlock GetBlockChecked(BlockManager &blockman, const CBlockIndex &blockindex)
std::optional< int > GetPruneHeight(const BlockManager &blockman, const CChain &chain)
static void ReconsiderBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, const BlockHash &block_hash)
static RPCHelpMan getblockfilter()
static RPCHelpMan getbestblockhash()
RPCHelpMan getblockchaininfo()
static RPCHelpMan getchaintxstats()
UniValue CreateUTXOSnapshot(node::NodeContext &node, Chainstate &chainstate, AutoFile &afile, const fs::path &path, const fs::path &tmppath)
Test-only helper to create UTXO snapshots given a chainstate and a file handle.
static RPCHelpMan waitforblock()
std::tuple< std::unique_ptr< CCoinsViewCursor >, CCoinsStats, const CBlockIndex * > PrepareUTXOSnapshot(Chainstate &chainstate, const std::function< void()> &interruption_point={}) EXCLUSIVE_LOCKS_REQUIRED(UniValue WriteUTXOSnapshot(Chainstate &chainstate, CCoinsViewCursor *pcursor, CCoinsStats *maybe_stats, const CBlockIndex *tip, AutoFile &afile, const fs::path &path, const fs::path &temppath, const std::function< void()> &interruption_point={})
static RPCHelpMan getblockfrompeer()
static RPCHelpMan getblockhash()
void RegisterBlockchainRPCCommands(CRPCTable &t)
static RPCHelpMan verifychain()
static std::atomic< bool > g_should_abort_scan
const std::vector< RPCResult > RPCHelpForChainstate
UniValue blockheaderToJSON(const CBlockIndex &tip, const CBlockIndex &blockindex)
Block header to JSON.
static RPCHelpMan waitforblockheight()
static const CBlockIndex * ParseHashOrHeight(const UniValue ¶m, ChainstateManager &chainman)
static RPCHelpMan pruneblockchain()
static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange)
static RPCHelpMan getblockheader()
static GlobalMutex cs_blockchange
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
static RPCHelpMan getblockcount()
static RPCHelpMan waitfornewblock()
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
const CChainParams & Params()
Return the currently selected parameters.
#define CHECK_NONFATAL(condition)
Identity function.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Non-refcounted RAII wrapper for FILE*.
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Complete block filter struct as defined in BIP 157.
const std::vector< uint8_t > & GetEncodedFilter() const
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
CBlockIndex * pprev
pointer to the index of the predecessor of this block
CBlockHeader GetBlockHeader() const
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
int64_t GetBlockTime() const
int64_t GetMedianTimePast() const
unsigned int nTx
Number of transactions in this block.
int32_t nVersion
block header
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Undo information for a CBlock.
std::vector< CTxUndo > vtxundo
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
CBlockIndex * FindEarliestAtLeast(int64_t nTime, int height) const
Find the earliest block with timestamp equal or greater than the given time and height equal or great...
int Height() const
Return the maximal height in the chain.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
std::string GetChainTypeString() const
Return the chain type string.
const CBlock & GenesisBlock() const
const ChainTxData & TxData() const
CCoinsView that adds a memory cache for transactions to another CCoinsView.
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Cursor for iterating over CoinsView state.
virtual bool Valid() const =0
virtual bool GetKey(COutPoint &key) const =0
virtual bool GetValue(Coin &coin) const =0
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Abstract view on the open txout dataset.
virtual BlockHash GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
CCoinsView that brings transactions from a mempool into view.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
GetCoin, returning whether it exists and is not spent.
bool GetNetworkActive() const
void SetNetworkActive(bool active)
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
bool isSpent(const COutPoint &outpoint) const
An output of a transaction.
Restore the UTXO in a Coin at a given COutPoint.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Checks if a block is finalized by avalanche voting.
const std::optional< BlockHash > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Find the best known block, and make it the tip of the block chain.
CChain m_chain
The current chain of blockheaders we consult and build on.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
bool AvalancheFinalizeBlock(CBlockIndex *pindex, avalanche::Processor &avalanche) EXCLUSIVE_LOCKS_REQUIRED(voi ClearAvalancheFinalizedBlock)() EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Mark a block as finalized by avalanche.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Park a block.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
kernel::Notifications & GetNotifications() const
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const CChainParams & GetParams() const
const Consensus::Params & GetConsensus() const
const CBlockIndex * GetAvalancheFinalizedTip() const
util::Result< CBlockIndex * > ActivateSnapshot(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Construct and activate a Chainstate on the basis of UTXO snapshot data.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
uint32_t GetHeight() const
CoinsViewScanReserver()=default
Double ended buffer combining vector and stream-like interfaces.
Different type to mark Mutex at global scope.
RAII class that disables the network in its constructor and enables it in its destructor.
NetworkDisable(CConnman &connman)
virtual std::optional< std::string > FetchBlock(const Config &config, NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
auto Arg(size_t i) const
Helper to get a required or default-valued request argument.
RAII class that temporarily rolls back the local chain in it's constructor and rolls it forward again...
avalanche::Processor *const m_avalanche
const CBlockIndex & m_invalidate_index
TemporaryRollback(ChainstateManager &chainman, avalanche::Processor *const avalanche, const CBlockIndex &index)
ChainstateManager & m_chainman
void push_back(UniValue val)
const std::string & get_str() const
const std::vector< UniValue > & getValues() const
const UniValue & get_array() const
void pushKV(std::string key, UniValue val)
std::string GetRejectReason() const
std::string ToString() const
std::string ToString() const
std::string GetHex() const
std::string GetHex() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
std::string u8string() const
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex &index) const
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool IsPruneMode() const
Whether running in -prune mode.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, const CTxUndo *txundo=nullptr)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
#define LogPrintLevel(category, level,...)
#define LogPrint(category,...)
static path u8path(const std::string &utf8_str)
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to byte string.
FILE * fopen(const fs::path &p, const char *mode)
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
std::optional< kernel::CCoinsStats > GetUTXOStats(CCoinsView *view, BlockManager &blockman, kernel::CoinStatsHashType hash_type, const std::function< void()> &interruption_point, const CBlockIndex *pindex, bool index_requested)
Calculate statistics about the unspent transaction output set.
bilingual_str ErrorString(const Result< T > &result)
std::shared_ptr< const CTransaction > CTransactionRef
UniValue JSONRPCError(int code, const std::string &message)
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_DATABASE_ERROR
Database error.
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
size_t GetSerializeSize(const T &t, int nVersion=0)
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
bool IsRPCRunning()
Query whether RPC is running.
ChainstateManager & EnsureAnyChainman(const std::any &context)
NodeContext & EnsureAnyNodeContext(const std::any &context)
CTxMemPool & EnsureMemPool(const NodeContext &node)
PeerManager & EnsurePeerman(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
ArgsManager & EnsureArgsman(const NodeContext &node)
CConnman & EnsureConnman(const NodeContext &node)
ArgsManager & EnsureAnyArgsman(const std::any &context)
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
static constexpr Amount zero() noexcept
A BlockHash is a unqiue identifier for a block.
Comparison function for sorting the getchaintips heads.
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
static const Currency & get()
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ OBJ_NAMED_PARAMS
Special type that behaves almost exactly like OBJ, defining an options object with a list of pre-defi...
std::string DefaultHint
Hint for default value.
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
UniValue Default
Default constant value.
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
A TxId is the identifier of a transaction.
Amount total_unspendables_scripts
Total cumulative amount of outputs sent to unspendable scripts (OP_RETURN for example) up to and incl...
Amount total_coinbase_amount
Total cumulative amount of coinbase outputs up to and including this block.
Amount total_unspendables_genesis_block
The unspendable coinbase amount from the genesis block.
uint64_t coins_count
The number of coins contained.
uint64_t nTransactionOutputs
bool index_used
Signals if the coinstatsindex was used to retrieve the statistics.
Amount total_unspendables_bip30
The two unspendable coinbase outputs total amount caused by BIP30.
Amount total_prevout_spent_amount
Total cumulative amount of prevouts spent up to and including this block.
Amount total_unspendables_unclaimed_rewards
Total cumulative amount of coins lost due to unclaimed miner rewards up to and including this block.
Amount total_new_outputs_ex_coinbase_amount
Total cumulative amount of outputs created up to and including this block.
Amount total_unspendable_amount
Total cumulative amount of unspendable coins up to and including this block.
NodeContext struct containing references to chain state and connection state.
#define WAIT_LOCK(cs, name)
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOG_TIME_SECONDS(end_msg)
bilingual_str _(const char *psz)
Translation function.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
uint256 uint256S(const char *str)
uint256 from const char *.
const UniValue NullUniValue
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
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...
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static constexpr int DEFAULT_CHECKLEVEL
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
static const signed int DEFAULT_CHECKBLOCKS
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static const int PROTOCOL_VERSION
network protocol versioning
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.