11#include <chainparams.h>
49#include <condition_variable>
75 const std::function<
void()> &interruption_point = {})
83 const std::function<
void()> &interruption_point = {});
89 int nShift = (blockindex.
nBits >> 24) & 0xff;
90 double dDiff = double(0x0000ffff) / double(blockindex.
nBits & 0x00ffffff);
108 if (next && next->
pprev == &blockindex) {
112 return &blockindex == &tip ? 1 : -1;
121 const int height{param.
getInt<
int>()};
125 strprintf(
"Target block height %d is negative", height));
127 const int current_tip{active_chain.
Height()};
128 if (height > current_tip) {
131 strprintf(
"Target block height %d after current tip %d", height,
135 return active_chain[height];
158 result.
pushKV(
"confirmations", confirmations);
171 if (blockindex.
pprev) {
172 result.
pushKV(
"previousblockhash",
199 ::cs_main,
return !blockman.IsBlockPruned(blockindex))};
200 const bool have_undo{is_not_pruned &&
202 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
205 const CTxUndo *txundo = (have_undo && i > 0)
215 result.
pushKV(
"tx", std::move(txs));
223 "Returns the height of the most-work fully-validated chain.\n"
224 "The genesis block has height 0.\n",
241 "Returns the hash of the best (tip) block in the "
242 "most-work fully-validated chain.\n",
260 latestblock.height = pindex->
nHeight;
268 "Waits for a specific new block and returns useful info about it.\n"
269 "\nReturns the current block on timeout or exit.\n",
272 "Time in milliseconds to wait for a response. 0 indicates no "
287 if (!request.params[0].isNull()) {
288 timeout = request.params[0].
getInt<
int>();
297 lock, std::chrono::milliseconds(timeout),
299 return latestblock.height != block.
height ||
300 latestblock.hash != block.
hash ||
307 return latestblock.height != block.
height ||
308 latestblock.hash != block.
hash ||
325 "Waits for a specific new block and returns useful info about it.\n"
326 "\nReturns the current block on timeout or exit.\n",
329 "Block hash to wait for."},
331 "Time in milliseconds to wait for a response. 0 indicates no "
342 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
343 "ed7b4a8c619eb02596f8862\" 1000") +
345 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
346 "ed7b4a8c619eb02596f8862\", 1000")},
353 if (!request.params[1].isNull()) {
354 timeout = request.params[1].getInt<
int>();
362 lock, std::chrono::milliseconds(timeout),
386 "waitforblockheight",
387 "Waits for (at least) block height and returns the height and "
388 "hash\nof the current tip.\n"
389 "\nReturns the current block on timeout or exit.\n",
392 "Block height to wait for."},
394 "Time in milliseconds to wait for a response. 0 indicates no "
410 int height = request.params[0].
getInt<
int>();
412 if (!request.params[1].isNull()) {
413 timeout = request.params[1].getInt<
int>();
421 lock, std::chrono::milliseconds(timeout),
423 return latestblock.height >= height ||
430 return latestblock.height >= height ||
446 "syncwithvalidationinterfacequeue",
447 "Waits for the validation interface queue to catch up on everything "
448 "that was there when we entered this function.\n",
464 "Returns the proof-of-work difficulty as a multiple of the minimum "
468 "the proof-of-work difficulty as a multiple of the minimum "
484 "Attempt to fetch block from a given peer.\n"
485 "\nWe must have the header for this block, e.g. using submitheader.\n"
486 "The block will not have any undo data which can limit the usage of "
487 "the block data in a context where the undo data is needed.\n"
488 "Subsequent calls for the same block may cause the response from the "
489 "previous peer to be ignored.\n"
490 "Peers generally ignore requests for a stale block that they never "
491 "fully verified, or one that is more than a month old.\n"
492 "When a peer does not respond with a block, we will disconnect.\n"
493 "\nReturns an empty JSON object if the request was successfully "
497 "The block hash to try to fetch"},
499 "The peer to fetch it from (see getpeerinfo for peer IDs)"},
503 "\"00000000c937983704a73af28acdec37b049d214a"
504 "dbda81d7e2a3dd146f6ed09\" 0") +
506 "\"00000000c937983704a73af28acdec37b049d214a"
507 "dbda81d7e2a3dd146f6ed09\" 0")},
516 const NodeId peer_id{request.params[1].getInt<int64_t>()};
530 if (
const auto err{peerman.
FetchBlock(config, peer_id, *index)}) {
541 "Returns hash of block in best-block-chain at height provided.\n",
555 int nHeight = request.params[0].getInt<
int>();
556 if (nHeight < 0 || nHeight > active_chain.
Height()) {
558 "Block height out of range");
570 "If verbose is false, returns a string that is serialized, hex-encoded "
571 "data for blockheader 'hash'.\n"
572 "If verbose is true, returns an Object with information about "
573 "blockheader <hash>.\n",
578 "true for a json object, false for the hex-encoded data"},
582 "for verbose = true",
588 "the block hash (same as provided)"},
590 "The number of confirmations, or -1 if the block is not "
591 "on the main chain"},
593 "The block height or index"},
596 "The block version formatted in hexadecimal"},
606 "Expected number of hashes required to produce the "
609 "The number of transactions in the block"},
612 "The hash of the previous block (if available)"},
615 "The hash of the next block (if available)"},
618 "A string that is serialized, hex-encoded data for block "
622 "\"00000000c937983704a73af28acdec37b049d214a"
623 "dbda81d7e2a3dd146f6ed09\"") +
625 "\"00000000c937983704a73af28acdec37b049d214a"
626 "dbda81d7e2a3dd146f6ed09\"")},
631 bool fVerbose =
true;
632 if (!request.params[1].isNull()) {
633 fVerbose = request.params[1].get_bool();
654 std::string strHex =
HexStr(ssBlock);
668 if (blockman.IsBlockPruned(blockindex)) {
670 "Block not available (pruned data)");
674 if (!blockman.
ReadBlock(block, blockindex)) {
691 if (blockman.IsBlockPruned(blockindex)) {
693 "Undo data not available (pruned data)");
707 "If verbosity is 0 or false, returns a string that is serialized, "
708 "hex-encoded data for block 'hash'.\n"
709 "If verbosity is 1 or true, returns an Object with information about "
711 "If verbosity is 2, returns an Object with information about block "
712 "<hash> and information about each transaction.\n"
713 "If verbosity is 3, returns an Object with information about block "
714 "<hash> and information about each transaction, including prevout "
715 "information for inputs (only for unpruned blocks in the current best "
721 "0 for hex-encoded data, 1 for a json object, and 2 for json "
722 "object with transaction data",
727 "A string that is serialized, hex-encoded data for block "
736 "the block hash (same as provided)"},
738 "The number of confirmations, or -1 if the block is not "
739 "on the main chain"},
742 "The block height or index"},
745 "The block version formatted in hexadecimal"},
749 "The transaction ids",
759 "Expected number of hashes required to produce the chain "
760 "up to this block (in hex)"},
762 "The number of transactions in the block"},
765 "The hash of the previous block (if available)"},
768 "The hash of the next block (if available)"},
776 "Same output as verbosity = 1"},
786 "The transactions in the format of the "
787 "getrawtransaction RPC. Different from "
788 "verbosity = 1 \"tx\" result"},
790 "The transaction fee in " +
792 ", omitted if block undo data is not "
799 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
800 "214adbda81d7e2a3dd146f6ed09\"") +
801 HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
802 "214adbda81d7e2a3dd146f6ed09\"")},
808 if (!request.params[1].isNull()) {
809 if (request.params[1].isNum()) {
810 verbosity = request.params[1].getInt<
int>();
812 verbosity = request.params[1].get_bool() ? 1 : 0;
833 if (verbosity <= 0) {
836 std::string strHex =
HexStr(ssBlock);
841 if (verbosity == 1) {
843 }
else if (verbosity == 2) {
867 if (!first_block || !chain_tip) {
872 if (!(chain_tip->nStatus.hasData() && chain_tip->nStatus.hasUndo())) {
879 blockman.GetFirstBlock(*chain_tip,
881 return status.hasData() && status.hasUndo();
883 if (first_unpruned == first_block) {
899 "The block height to prune up to. May be set to a discrete "
903 " to prune blocks whose block time is at "
904 "least 2 hours older than the provided timestamp."},
915 "Cannot prune blocks because node is not in prune mode.");
922 int heightParam = request.params[0].getInt<
int>();
923 if (heightParam < 0) {
925 "Negative block height.");
931 if (heightParam > 1000000000) {
938 "Could not find block with at least the "
939 "specified timestamp.");
944 unsigned int height = (
unsigned int)heightParam;
945 unsigned int chainHeight = (
unsigned int)active_chain.
Height();
946 if (chainHeight < config.GetChainParams().PruneAfterHeight()) {
948 "Blockchain is too short for pruning.");
949 }
else if (height > chainHeight) {
952 "Blockchain is shorter than the attempted prune height.");
955 "Attempt to prune blocks close to the tip. "
956 "Retaining the minimum number of blocks.\n");
968 if (hash_type_input ==
"hash_serialized") {
969 return CoinStatsHashType::HASH_SERIALIZED;
970 }
else if (hash_type_input ==
"muhash") {
971 return CoinStatsHashType::MUHASH;
972 }
else if (hash_type_input ==
"none") {
977 strprintf(
"%s is not a valid hash_type", hash_type_input));
984 "Returns statistics about the unspent transaction output set.\n"
985 "Note this call may take some time if you are not using "
989 "Which UTXO set hash should be calculated. Options: "
990 "'hash_serialized' (the legacy algorithm), 'muhash', 'none'."},
992 "The block hash or height of the target height (only available "
993 "with coinstatsindex).",
995 .type_str = {
"",
"string or numeric"}}},
997 "Use coinstatsindex, if available."},
1005 "The current block height (index)"},
1007 "The hash of the block at the tip of the chain"},
1009 "The number of unspent transaction outputs"},
1011 "Database-independent, meaningless metric indicating "
1012 "the UTXO set size"},
1015 "The serialized hash (only present if 'hash_serialized' "
1016 "hash_type is chosen)"},
1018 "The serialized hash (only present if 'muhash' "
1019 "hash_type is chosen)"},
1021 "The number of transactions with unspent outputs (not "
1022 "available when coinstatsindex is used)"},
1024 "The estimated size of the chainstate on disk (not "
1025 "available when coinstatsindex is used)"},
1027 "The total amount"},
1029 "The total amount of coins permanently excluded from the UTXO "
1030 "set (only available if coinstatsindex is used)"},
1033 "Info on amounts in the block at this block height (only "
1034 "available if coinstatsindex is used)",
1036 "Total amount of all prevouts spent in this block"},
1038 "Coinbase subsidy amount of this block"},
1040 "Total amount of new outputs created by this block"},
1042 "Total amount of unspendable outputs created in this block"},
1045 "Detailed view of the unspendable categories",
1048 "The unspendable amount of the Genesis block subsidy"},
1050 "Transactions overridden by duplicates (no longer "
1051 "possible with BIP30)"},
1053 "Amounts sent to scripts that are unspendable (for "
1054 "example OP_RETURN outputs)"},
1056 "Fee rewards that miners did not claim in their "
1057 "coinbase transaction"},
1066 R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1072 R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")},
1079 request.params[0].isNull()
1080 ? CoinStatsHashType::HASH_SERIALIZED
1082 bool index_requested =
1083 request.params[2].isNull() || request.params[2].get_bool();
1094 coins_view = &active_chainstate.
CoinsDB();
1099 if (!request.params[1].isNull()) {
1102 "Querying specific block heights "
1103 "requires coinstatsindex");
1106 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1108 "hash_serialized hash type cannot be "
1109 "queried for a specific block");
1123 if (pindex->nHeight > summary.best_block_height) {
1127 "Unable to get data because coinstatsindex is "
1128 "still syncing. Current height: %d",
1129 summary.best_block_height));
1134 const std::optional<CCoinsStats> maybe_stats =
GetUTXOStats(
1135 coins_view, *blockman, hash_type,
node.rpc_interruption_point,
1136 pindex, index_requested);
1137 if (maybe_stats.has_value()) {
1143 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1144 ret.
pushKV(
"hash_serialized",
1147 if (hash_type == CoinStatsHashType::MUHASH) {
1153 ret.
pushKV(
"transactions",
1157 ret.
pushKV(
"total_unspendable_amount",
1161 if (pindex->nHeight > 0) {
1162 const std::optional<CCoinsStats> maybe_prev_stats =
1164 node.rpc_interruption_point,
1165 pindex->pprev, index_requested);
1166 if (!maybe_prev_stats) {
1168 "Unable to read UTXO set");
1170 prev_stats = maybe_prev_stats.value();
1177 prev_stats.total_prevout_spent_amount);
1178 block_info.
pushKV(
"coinbase",
1180 prev_stats.total_coinbase_amount);
1182 "new_outputs_ex_coinbase",
1184 prev_stats.total_new_outputs_ex_coinbase_amount);
1185 block_info.
pushKV(
"unspendable",
1187 prev_stats.total_unspendable_amount);
1193 prev_stats.total_unspendables_genesis_block);
1196 prev_stats.total_unspendables_bip30);
1199 prev_stats.total_unspendables_scripts);
1201 "unclaimed_rewards",
1203 prev_stats.total_unspendables_unclaimed_rewards);
1204 block_info.
pushKV(
"unspendables", std::move(unspendables));
1206 ret.
pushKV(
"block_info", std::move(block_info));
1210 "Unable to read UTXO set");
1220 "Returns details about an unspent transaction output.\n",
1223 "The transaction id"},
1226 "Whether to include the mempool. Note that an unspent output that "
1227 "is spent in the mempool won't appear."},
1239 "The hash of the block at the tip of the chain"},
1241 "The number of confirmations"},
1251 "Number of required signatures"},
1253 "The type, eg pubkeyhash"},
1256 "array of eCash addresses",
1265 "\nAs a JSON-RPC call\n" +
1276 int n = request.params[1].getInt<
int>();
1277 COutPoint
out(txid, n);
1278 bool fMempool =
true;
1279 if (!request.params[2].isNull()) {
1280 fMempool = request.params[2].get_bool();
1286 std::optional<Coin> coin;
1306 ret.
pushKV(
"confirmations", 0);
1308 ret.
pushKV(
"confirmations",
1309 int64_t(pindex->
nHeight - coin->GetHeight() + 1));
1311 ret.
pushKV(
"value", coin->GetTxOut().nValue);
1314 ret.
pushKV(
"scriptPubKey", std::move(o));
1315 ret.
pushKV(
"coinbase", coin->IsCoinBase());
1325 "Verifies blockchain database.\n",
1330 strprintf(
"How thorough the block verification is:\n%s",
1334 "The number of blocks to check."},
1337 "Verification finished successfully. If false, check "
1338 "debug.log for reason."},
1343 const int check_level{request.params[0].
isNull()
1345 : request.params[0].getInt<
int>()};
1346 const int check_depth{request.params[1].isNull()
1348 : request.params[1].getInt<
int>()};
1356 active_chainstate.
CoinsTip(), check_level,
1364 "getblockchaininfo",
1365 "Returns an object containing various state info regarding blockchain "
1374 "current network name (main, test, regtest)"},
1376 "the height of the most-work fully-validated "
1377 "non-parked chain. The genesis block has height 0"},
1379 "the current number of headers we have validated"},
1381 "the hash of the avalanche finalized tip if any, otherwise "
1382 "the genesis block hash"},
1384 "the hash of the currently best block"},
1391 "estimate of verification progress [0..1]"},
1393 "(debug information) estimate of whether this node is in "
1394 "Initial Block Download mode"},
1396 "total amount of work in active chain, in hexadecimal"},
1398 "the estimated size of the block and undo files on disk"},
1400 "if the blocks are subject to pruning"},
1402 "lowest-height complete block stored (only present if pruning "
1405 "whether automatic pruning is enabled (only present if "
1406 "pruning is enabled)"},
1408 "the target size used by pruning (only present if automatic "
1409 "pruning is enabled)"},
1411 "any network and blockchain warnings"},
1417 const CChainParams &chainparams = config.GetChainParams();
1425 const int height{tip.
nHeight};
1429 obj.
pushKV(
"blocks", height);
1430 obj.
pushKV(
"headers", chainman.m_best_header
1431 ? chainman.m_best_header->nHeight
1434 obj.
pushKV(
"finalized_blockhash",
1435 avalanche_finalized_tip
1436 ? avalanche_finalized_tip->GetBlockHash().GetHex()
1443 "verificationprogress",
1445 obj.
pushKV(
"initialblockdownload",
1448 obj.
pushKV(
"size_on_disk",
1455 obj.
pushKV(
"pruneheight",
1456 prune_height ? prune_height.value() + 1 : 0);
1458 const bool automatic_pruning{
1460 BlockManager::PRUNE_TARGET_MANUAL};
1461 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1462 if (automatic_pruning) {
1463 obj.
pushKV(
"prune_target_size",
1490 "Return information about all known tips in the block tree, including "
1491 "the main chain as well as orphaned branches.\n",
1504 "zero for main chain, otherwise length of branch connecting "
1505 "the tip to the main chain"},
1507 "status of the chain, \"active\" for the main chain\n"
1508 "Possible values for status:\n"
1509 "1. \"invalid\" This branch contains at "
1510 "least one invalid block\n"
1511 "2. \"parked\" This branch contains at "
1512 "least one parked block\n"
1513 "3. \"headers-only\" Not all blocks for this "
1514 "branch are available, but the headers are valid\n"
1515 "4. \"valid-headers\" All blocks are available for "
1516 "this branch, but they were never fully validated\n"
1517 "5. \"valid-fork\" This branch is not part of "
1518 "the active chain, but is fully validated\n"
1519 "6. \"active\" This is the tip of the "
1520 "active main chain, which is certainly valid"},
1541 std::set<const CBlockIndex *, CompareBlocksByHeight> setTips;
1542 std::set<const CBlockIndex *> setOrphans;
1543 std::set<const CBlockIndex *> setPrevs;
1545 for (
const auto &[
_, block_index] : chainman.
BlockIndex()) {
1546 if (!active_chain.
Contains(&block_index)) {
1547 setOrphans.insert(&block_index);
1548 setPrevs.insert(block_index.pprev);
1552 for (std::set<const CBlockIndex *>::iterator it =
1554 it != setOrphans.end(); ++it) {
1555 if (setPrevs.erase(*it) == 0) {
1556 setTips.insert(*it);
1561 setTips.insert(active_chain.
Tip());
1567 obj.
pushKV(
"height", block->nHeight);
1568 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1570 const int branchLen =
1572 obj.
pushKV(
"branchlen", branchLen);
1575 if (active_chain.
Contains(block)) {
1578 }
else if (block->nStatus.isInvalid()) {
1581 }
else if (block->nStatus.isOnParkedChain()) {
1584 }
else if (!block->HaveNumChainTxs()) {
1587 status =
"headers-only";
1592 status =
"valid-fork";
1597 status =
"valid-headers";
1602 obj.
pushKV(
"status", status);
1615 "Treats a block as if it were received before others with the same "
1617 "\nA later preciousblock call can override the effect of an earlier "
1619 "\nThe effects of preciousblock are not retained across restarts.\n",
1622 "the hash of the block to mark as precious"},
1645 node.avalanche.get());
1686 "Permanently marks a block as invalid, as if it violated a consensus "
1690 "the hash of the block to mark as invalid"},
1713 "Marks a block as parked.\n",
1716 "the hash of the block to park"},
1723 const std::string strHash = request.params[0].
get_str();
1746 active_chainstate.
ParkBlock(state, pblockindex);
1750 node.avalanche.get());
1777 chainman.RecalculateBestHeader();
1792 "Removes invalidity status of a block, its ancestors and its"
1793 "descendants, reconsider them for activation.\n"
1794 "This can be used to undo the effects of invalidateblock.\n",
1797 "the hash of the block to reconsider"},
1821 "Removes parked status of a block and its descendants, reconsider "
1822 "them for activation.\n"
1823 "This can be used to undo the effects of parkblock.\n",
1826 "the hash of the block to unpark"},
1833 const std::string strHash = request.params[0].
get_str();
1849 if (!pblockindex->nStatus.isOnParkedChain()) {
1871 node.avalanche.get());
1888 "Compute statistics about the total number and rate of transactions "
1892 "Size of the window in number of blocks"},
1895 "The hash of the block that ends the window."},
1903 "The timestamp for the final block in the window, "
1907 "The total number of transactions in the chain up to "
1908 "that point, if known. It may be unknown when using "
1911 "The hash of the final block in the window"},
1913 "The height of the final block in the window."},
1915 "Size of the window in number of blocks"},
1917 "The elapsed time in the window in seconds. Only "
1918 "returned if \"window_block_count\" is > 0"},
1920 "The number of transactions in the window. Only "
1921 "returned if \"window_block_count\" is > 0 and if "
1922 "txcount exists for the start and end of the window."},
1924 "The average rate of transactions per second in the "
1925 "window. Only returned if \"window_interval\" is > 0 "
1926 "and if window_tx_count exists."},
1938 config.GetChainParams().GetConsensus().nPowTargetSpacing;
1940 if (request.params[1].isNull()) {
1953 "Block is not in main chain");
1959 if (request.params[0].isNull()) {
1961 std::max(0, std::min(blockcount, pindex->
nHeight - 1));
1963 blockcount = request.params[0].getInt<
int>();
1965 if (blockcount < 0 ||
1966 (blockcount > 0 && blockcount >= pindex->
nHeight)) {
1968 "Invalid block count: "
1969 "should be between 0 and "
1970 "the block's height - 1");
1977 past_block.GetMedianTimePast()};
1984 ret.
pushKV(
"window_final_block_hash",
1987 ret.
pushKV(
"window_block_count", blockcount);
1988 if (blockcount > 0) {
1989 ret.
pushKV(
"window_interval", nTimeDiff);
1990 if (pindex->
nChainTx != 0 && past_block.nChainTx != 0) {
1991 unsigned int window_tx_count =
1992 pindex->
nChainTx - past_block.nChainTx;
1993 ret.
pushKV(
"window_tx_count", window_tx_count);
1994 if (nTimeDiff > 0) {
1996 double(window_tx_count) / nTimeDiff);
2006template <
typename T>
2008 size_t size = scores.size();
2013 std::sort(scores.begin(), scores.end());
2014 if (size % 2 == 0) {
2015 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
2017 return scores[size / 2];
2021template <
typename T>
static inline bool SetHasKeys(
const std::set<T> &set) {
2024template <
typename T,
typename Tk,
typename... Args>
2025static inline bool SetHasKeys(
const std::set<T> &set,
const Tk &key,
2026 const Args &...args) {
2027 return (set.count(key) != 0) ||
SetHasKeys(set, args...);
2032 sizeof(COutPoint) +
sizeof(uint32_t) +
sizeof(bool);
2038 "Compute per block statistics for a given window. All amounts are "
2042 "It won't work for some heights with pruning.\n",
2045 "The block hash or height of the target block",
2047 .type_str = {
"",
"string or numeric"}}},
2051 "Values to plot (see result below)",
2054 "Selected statistic"},
2056 "Selected statistic"},
2067 "Average feerate (in satoshis per virtual byte)"},
2070 "The block hash (to check for potential reorgs)"},
2073 "The number of inputs (excluding coinbase)"},
2076 "Maximum feerate (in satoshis per virtual byte)"},
2079 "Truncated median fee in the block"},
2081 "Truncated median feerate (in " + ticker +
" per byte)"},
2083 "The block median time past"},
2085 "Truncated median transaction size"},
2088 "Minimum feerate (in satoshis per virtual byte)"},
2094 "Total amount in all outputs (excluding coinbase and thus "
2095 "reward [ie subsidy + totalfee])"},
2097 "Total size of all non-coinbase transactions"},
2100 "The number of transactions (including coinbase)"},
2102 "The increase/decrease in the number of unspent outputs"},
2104 "The increase/decrease in size for the utxo index (not "
2105 "discounting op_return and similar)"},
2110 R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2112 R
"(1000 '["minfeerate","avgfeerate"]')") +
2115 R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2117 R
"(1000, ["minfeerate","avgfeerate"])")},
2124 std::set<std::string> stats;
2125 if (!request.params[1].isNull()) {
2127 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2128 const std::string stat = stats_univalue[i].
get_str();
2138 const bool do_all = stats.size() == 0;
2139 const bool do_mediantxsize =
2140 do_all || stats.count(
"mediantxsize") != 0;
2141 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
2142 const bool do_medianfeerate =
2143 do_all || stats.count(
"medianfeerate") != 0;
2144 const bool loop_inputs =
2145 do_all || do_medianfee || do_medianfeerate ||
2146 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
2147 "avgfeerate",
"minfee",
"maxfee",
"minfeerate",
2149 const bool loop_outputs =
2150 do_all || loop_inputs || stats.count(
"total_out");
2151 const bool do_calculate_size =
2152 do_mediantxsize || loop_inputs ||
2153 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
2156 const int64_t blockMaxSize = config.GetMaxBlockSize();
2164 int64_t maxtxsize = 0;
2165 int64_t mintxsize = blockMaxSize;
2166 int64_t outputs = 0;
2167 int64_t total_size = 0;
2168 int64_t utxo_size_inc = 0;
2169 std::vector<Amount> fee_array;
2170 std::vector<Amount> feerate_array;
2171 std::vector<int64_t> txsize_array;
2173 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2174 const auto &tx = block.
vtx.at(i);
2175 outputs += tx->vout.size();
2179 tx_total_out +=
out.nValue;
2185 if (tx->IsCoinBase()) {
2190 inputs += tx->vin.size();
2192 total_out += tx_total_out;
2194 int64_t tx_size = 0;
2195 if (do_calculate_size) {
2196 tx_size = tx->GetTotalSize();
2197 if (do_mediantxsize) {
2198 txsize_array.push_back(tx_size);
2200 maxtxsize = std::max(maxtxsize, tx_size);
2201 mintxsize = std::min(mintxsize, tx_size);
2202 total_size += tx_size;
2207 const auto &txundo = blockUndo.
vtxundo.at(i - 1);
2208 for (
const Coin &coin : txundo.vprevout) {
2211 tx_total_in += prevoutput.
nValue;
2216 Amount txfee = tx_total_in - tx_total_out;
2219 fee_array.push_back(txfee);
2221 maxfee = std::max(maxfee, txfee);
2222 minfee = std::min(minfee, txfee);
2225 Amount feerate = txfee / tx_size;
2226 if (do_medianfeerate) {
2227 feerate_array.push_back(feerate);
2229 maxfeerate = std::max(maxfeerate, feerate);
2230 minfeerate = std::min(minfeerate, feerate);
2236 block.
vtx.size() > 1
2237 ? (totalfee /
int((block.
vtx.size() - 1)))
2239 ret_all.
pushKV(
"avgfeerate", total_size > 0
2240 ? (totalfee / total_size)
2242 ret_all.
pushKV(
"avgtxsize",
2243 (block.
vtx.size() > 1)
2244 ? total_size / (block.
vtx.size() - 1)
2246 ret_all.
pushKV(
"blockhash", pindex.GetBlockHash().GetHex());
2247 ret_all.
pushKV(
"height", (int64_t)pindex.nHeight);
2248 ret_all.
pushKV(
"ins", inputs);
2249 ret_all.
pushKV(
"maxfee", maxfee);
2250 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2251 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2253 ret_all.
pushKV(
"medianfeerate",
2255 ret_all.
pushKV(
"mediantime", pindex.GetMedianTimePast());
2256 ret_all.
pushKV(
"mediantxsize",
2263 ret_all.
pushKV(
"mintxsize",
2264 mintxsize == blockMaxSize ? 0 : mintxsize);
2265 ret_all.
pushKV(
"outs", outputs);
2268 ret_all.
pushKV(
"time", pindex.GetBlockTime());
2269 ret_all.
pushKV(
"total_out", total_out);
2270 ret_all.
pushKV(
"total_size", total_size);
2271 ret_all.
pushKV(
"totalfee", totalfee);
2272 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
2273 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2274 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2281 for (
const std::string &stat : stats) {
2282 const UniValue &value = ret_all[stat];
2286 strprintf(
"Invalid selected statistic %s", stat));
2297static bool FindScriptPubKey(std::atomic<int> &scan_progress,
2298 const std::atomic<bool> &should_abort,
2300 const std::set<CScript> &needles,
2301 std::map<COutPoint, Coin> &out_results,
2302 std::function<
void()> &interruption_point) {
2305 while (cursor->
Valid()) {
2311 if (++
count % 8192 == 0) {
2312 interruption_point();
2318 if (
count % 256 == 0) {
2320 const TxId &txid = key.GetTxId();
2321 uint32_t high = 0x100 * *txid.
begin() + *(txid.
begin() + 1);
2322 scan_progress = int(high * 100.0 / 65536.0 + 0.5);
2325 out_results.emplace(key, coin);
2329 scan_progress = 100;
2365 "Scans the unspent transaction output set for entries that match "
2366 "certain output descriptors.\n"
2367 "Examples of output descriptors are:\n"
2368 " addr(<address>) Outputs whose scriptPubKey "
2369 "corresponds to the specified address (does not include P2PK)\n"
2370 " raw(<hex script>) Outputs whose scriptPubKey "
2371 "equals the specified hex scripts\n"
2372 " combo(<pubkey>) P2PK and P2PKH outputs for "
2373 "the given pubkey\n"
2374 " pkh(<pubkey>) P2PKH outputs for the given "
2376 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
2377 "the given threshold and pubkeys\n"
2378 "\nIn the above, <pubkey> either refers to a fixed public key in "
2379 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2380 "or more path elements separated by \"/\", and optionally ending in "
2381 "\"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2382 "unhardened or hardened child keys.\n"
2383 "In the latter case, a range needs to be specified by below if "
2384 "different from 1000.\n"
2385 "For more information on output descriptors, see the documentation in "
2386 "the doc/descriptors.md file.\n",
2389 "The action to execute\n"
2390 " \"start\" for starting a "
2392 " \"abort\" for aborting the "
2393 "current scan (returns true when abort was successful)\n"
2395 "progress report (in %) of the current scan"},
2399 "Array of scan objects. Required for \"start\" action\n"
2400 " Every scan object is either a "
2401 "string descriptor or an object:",
2404 "An output descriptor"},
2409 "An object with output descriptor and metadata",
2412 "An output descriptor"},
2414 "The range of HD chain indexes to explore (either "
2415 "end or [begin,end])"},
2423 RPCResult{
"When action=='status' and no scan is in progress",
2426 "When action=='status' and scan is in progress",
2434 "When action=='start'",
2440 "Whether the scan was completed"},
2442 "The number of unspent transaction outputs scanned"},
2444 "The current block height (index)"},
2446 "The hash of the block at the tip of the chain"},
2456 "The transaction id"},
2461 "A specialized descriptor for the matched "
2464 "The total amount in " + ticker +
2465 " of the unspent output"},
2467 "Whether this is a coinbase output"},
2469 "Height of the unspent transaction output"},
2473 "The total amount of all found unspent outputs in " +
2481 const auto action{self.
Arg<std::string>(
"action")};
2482 if (action ==
"status") {
2490 }
else if (action ==
"abort") {
2499 }
else if (action ==
"start") {
2503 "Scan already in progress, use action "
2504 "\"abort\" or \"status\"");
2507 if (request.params.size() < 2) {
2509 "scanobjects argument is required for "
2510 "the start action");
2513 std::set<CScript> needles;
2514 std::map<CScript, std::string> descriptors;
2523 for (CScript &
script : scripts) {
2524 std::string inferred =
2527 descriptors.emplace(std::move(
script),
2528 std::move(inferred));
2534 std::vector<CTxOut> input_txos;
2535 std::map<COutPoint, Coin> coins;
2539 std::unique_ptr<CCoinsViewCursor> pcursor;
2551 bool res = FindScriptPubKey(
2553 needles, coins,
node.rpc_interruption_point);
2554 result.
pushKV(
"success", res);
2559 for (
const auto &it : coins) {
2560 const COutPoint &outpoint = it.first;
2561 const Coin &coin = it.second;
2563 input_txos.push_back(txo);
2567 unspent.
pushKV(
"txid", outpoint.GetTxId().GetHex());
2568 unspent.
pushKV(
"vout", int32_t(outpoint.GetN()));
2577 result.
pushKV(
"unspents", std::move(unspents));
2578 result.
pushKV(
"total_amount", total_in);
2581 strprintf(
"Invalid action '%s'", action));
2591 "Retrieve a BIP 157 content filter for a particular block.\n",
2594 "The hash of the block"},
2596 "The type name of the filter"},
2603 "the hex-encoded filter data"},
2605 "the hex-encoded filter header"},
2609 "\"00000000c937983704a73af28acdec37b049d214a"
2610 "dbda81d7e2a3dd146f6ed09\" \"basic\"") +
2612 "\"00000000c937983704a73af28acdec37b049d214adbda81d7"
2613 "e2a3dd146f6ed09\", \"basic\"")},
2618 std::string filtertype_name =
"basic";
2619 if (!request.params[1].isNull()) {
2620 filtertype_name = request.params[1].get_str();
2626 "Unknown filtertype");
2632 "Index is not enabled for filtertype " +
2637 bool block_was_connected;
2647 block_was_connected =
2651 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2658 std::string errmsg =
"Filter not found.";
2660 if (!block_was_connected) {
2662 errmsg +=
" Block was not connected to active chain.";
2663 }
else if (!index_ready) {
2665 errmsg +=
" Block filters are still in the process of "
2669 errmsg +=
" This error is unexpected and indicates index "
2696 "Network activity could not be suspended.");
2734 "Write the serialized UTXO set to a file. This can be used in "
2735 "loadtxoutset afterwards if this snapshot height is supported in the "
2736 "chainparams as well.\n\n"
2737 "Unless the the \"latest\" type is requested, the node will roll back "
2738 "to the requested height and network activity will be suspended during "
2740 "Because of this it is discouraged to interact with the node in any "
2741 "other way during the execution of this call to avoid inconsistent "
2742 "results and race conditions, particularly RPCs that interact with "
2744 "This call may take several minutes. Make sure to use no RPC timeout "
2745 "(bitcoin-cli -rpcclienttimeout=0)",
2749 "path to the output file. If relative, will be prefixed by "
2752 "The type of snapshot to create. Can be \"latest\" to create a "
2753 "snapshot of the current UTXO set or \"rollback\" to temporarily "
2754 "roll back the state of the node to a historical block before "
2755 "creating the snapshot of a historical UTXO set. This parameter "
2756 "can be omitted if a separate \"rollback\" named parameter is "
2757 "specified indicating the height or hash of a specific historical "
2758 "block. If \"rollback\" is specified and separate \"rollback\" "
2759 "named parameter is not specified, this will roll back to the "
2760 "latest valid snapshot block that can currently be loaded with "
2769 "Height or hash of the block to roll back to before "
2770 "creating the snapshot. Note: The further this number is "
2771 "from the tip, the longer this process will take. "
2772 "Consider setting a higher -rpcclienttimeout value in "
2775 .type_str = {
"",
"string or numeric"}}},
2784 "the number of coins written in the snapshot"},
2786 "the hash of the base of the snapshot"},
2788 "the height of the base of the snapshot"},
2790 "the absolute path that the snapshot was written to"},
2792 "the hash of the UTXO set contents"},
2794 "the number of transactions in the chain up to and "
2795 "including the base block"},
2798 "utxo.dat latest") +
2800 "utxo.dat rollback") +
2802 R
"(utxo.dat rollback=853456)")},
2809 const std::string snapshot_type{self.
Arg<std::string>(
"type")};
2812 : request.params[2]};
2813 if (options.exists(
"rollback")) {
2814 if (!snapshot_type.empty() && snapshot_type !=
"rollback") {
2817 strprintf(
"Invalid snapshot type \"%s\" specified with "
2823 }
else if (snapshot_type ==
"rollback") {
2824 auto snapshot_heights =
2825 node.chainman->GetParams().GetAvailableSnapshotHeights();
2827 auto max_height = std::max_element(snapshot_heights.begin(),
2828 snapshot_heights.end());
2830 }
else if (snapshot_type ==
"latest") {
2835 strprintf(
"Invalid snapshot type \"%s\" specified. Please "
2836 "specify \"rollback\" or \"latest\"",
2842 args.GetDataDirNet(),
fs::u8path(request.params[0].get_str()));
2846 args.GetDataDirNet(),
2847 fs::u8path(request.params[0].get_str() +
".incomplete"));
2852 " already exists. If you are sure this "
2853 "is what you want, "
2854 "move it out of the way first");
2862 std::optional<NetworkDisable> disable_network;
2863 std::optional<TemporaryRollback> temporary_rollback;
2867 if (target_index != tip) {
2870 if (
node.chainman->m_blockman.IsPruneMode()) {
2873 node.chainman->ActiveChain().Tip()};
2875 node.chainman->m_blockman.GetFirstBlock(
2880 if (first_block->nHeight > target_index->nHeight) {
2883 "Could not roll back to requested height since "
2884 "necessary block data is already pruned.");
2898 disable_network.emplace(connman);
2903 return node.chainman->ActiveChain().Next(target_index));
2904 temporary_rollback.emplace(*
node.chainman,
node.avalanche.get(),
2909 std::unique_ptr<CCoinsViewCursor> cursor;
2919 chainstate = &
node.chainman->ActiveChainstate();
2928 if (target_index != chainstate->
m_chain.
Tip()) {
2930 "Failed to roll back to requested height, "
2931 "reverting to tip.\n");
2934 "Could not roll back to requested height.");
2937 *chainstate,
node.rpc_interruption_point);
2943 path, temppath,
node.rpc_interruption_point);
2944 fs::rename(temppath, path);
2953 const std::function<
void()> &interruption_point) {
2954 std::unique_ptr<CCoinsViewCursor> pcursor;
2955 std::optional<CCoinsStats> maybe_stats;
2977 CoinStatsHashType::HASH_SERIALIZED,
2978 interruption_point);
2984 std::unique_ptr<CCoinsViewCursor>(chainstate.
CoinsDB().
Cursor());
2996 const std::function<
void()> &interruption_point) {
2998 strprintf(
"writing UTXO snapshot at height %s (%s) to file %s (via %s)",
3009 unsigned int iter{0};
3010 size_t written_coins_count{0};
3011 std::vector<std::pair<uint32_t, Coin>> coins;
3020 auto write_coins_to_file =
3022 const std::vector<std::pair<uint32_t, Coin>> &coins,
3023 size_t &written_coins_count) {
3026 for (
const auto &[n, coin_] : coins) {
3029 ++written_coins_count;
3034 last_txid = key.GetTxId();
3035 while (pcursor->
Valid()) {
3036 if (iter % 5000 == 0) {
3037 interruption_point();
3041 if (key.GetTxId() != last_txid) {
3042 write_coins_to_file(afile, last_txid, coins,
3043 written_coins_count);
3044 last_txid = key.GetTxId();
3047 coins.emplace_back(key.GetN(), coin);
3052 if (!coins.empty()) {
3053 write_coins_to_file(afile, last_txid, coins, written_coins_count);
3061 result.
pushKV(
"coins_written", written_coins_count);
3077 tmppath,
node.rpc_interruption_point);
3083 "Load the serialized UTXO set from a file.\n"
3084 "Once this snapshot is loaded, its contents will be deserialized into "
3085 "a second chainstate data structure, which is then used to sync to the "
3087 "Meanwhile, the original chainstate will complete the initial block "
3088 "download process in the background, eventually validating up to the "
3089 "block that the snapshot is based upon.\n\n"
3090 "The result is a usable bitcoind instance that is current with the "
3091 "network tip in a matter of minutes rather than hours. UTXO snapshot "
3092 "are typically obtained from third-party sources (HTTP, torrent, etc.) "
3093 "which is reasonable since their contents are always checked by "
3095 "This RPC is incompatible with the -chronik init option, and a node "
3096 "with multiple chainstates may not be restarted with -chronik. After "
3097 "the background validation is finished and the chainstates are merged, "
3098 "the node can be restarted again with Chronik.\n\n"
3099 "You can find more information on this process in the `assumeutxo` "
3100 "design document (https://www.bitcoinabc.org/doc/assumeutxo.html).",
3103 "path to the snapshot file. If relative, will be prefixed by "
3111 "the number of coins loaded from the snapshot"},
3113 "the hash of the base of the snapshot"},
3115 "the height of the base of the snapshot"},
3117 "the absolute path that the snapshot was loaded from"},
3132 "loadtxoutset is not compatible with Chronik.");
3139 "Couldn't open file " + path.
u8string() +
3146 }
catch (
const std::ios_base::failure &e) {
3149 strprintf(
"Unable to parse metadata: %s", e.what()));
3152 auto activation_result{
3154 if (!activation_result) {
3157 strprintf(
"Unable to load UTXO snapshot: %s. (%s)",
3175 result.
pushKV(
"tip_hash", snapshot_index.GetBlockHash().ToString());
3176 result.
pushKV(
"base_height", snapshot_index.nHeight);
3188 "progress towards the network tip"},
3190 "the base block of the snapshot this chainstate is based on, if any"},
3193 "size of the coinstip cache"},
3195 "whether the chainstate is fully validated. True if all blocks in the "
3196 "chainstate were validated, false if the chain is based on a snapshot and "
3197 "the snapshot has not yet been validated."},
3204 "\nReturn information about chainstates.\n",
3211 "the number of headers seen so far"},
3214 "list of the chainstates ordered by work, with the "
3215 "most-work (active) chainstate last",
3229 auto make_chain_data =
3244 "verificationprogress",
3246 data.
pushKV(
"coins_db_cache_bytes",
3248 data.
pushKV(
"coins_tip_cache_bytes",
3252 "snapshot_blockhash",
3255 data.
pushKV(
"validated", validated);
3259 obj.
pushKV(
"headers", chainman.m_best_header
3260 ? chainman.m_best_header->nHeight
3263 const auto &chainstates = chainman.
GetAll();
3266 obj_chainstates.push_back(
3267 make_chain_data(*
cs, !
cs->m_from_snapshot_blockhash ||
3268 chainstates.size() == 1));
3270 obj.
pushKV(
"chainstates", std::move(obj_chainstates));
3313 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.
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)
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex &tip, const CBlockIndex &blockindex, TxVerbosity verbosity)
Block description to JSON.
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.
std::optional< Coin > GetCoin(const COutPoint &outpoint) 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.
std::optional< Coin > GetCoin(const COutPoint &outpoint) 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 ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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.
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
TxVerbosity
Verbose level for block's transaction.
@ SHOW_DETAILS_AND_PREVOUT
The same as previous option with information about prevouts if available.
@ SHOW_TXID
Only TXID for each block's transaction.
@ SHOW_DETAILS
Include TXID, inputs, outputs, and other common block's transaction information.
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS, std::function< bool(const CTxOut &)> is_change_func={})
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.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
#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::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
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)
void WriteCompactSize(SizeComputer &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)
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.
std::optional< Amount > total_amount
The total amount, or nullopt if an overflow occurred calculating it.
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
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...
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.