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 "\nReturns an empty JSON object if the request was successfully "
494 "The block hash to try to fetch"},
496 "The peer to fetch it from (see getpeerinfo for peer IDs)"},
500 "\"00000000c937983704a73af28acdec37b049d214a"
501 "dbda81d7e2a3dd146f6ed09\" 0") +
503 "\"00000000c937983704a73af28acdec37b049d214a"
504 "dbda81d7e2a3dd146f6ed09\" 0")},
513 const NodeId peer_id{request.params[1].getInt<int64_t>()};
527 if (
const auto err{peerman.
FetchBlock(config, peer_id, *index)}) {
538 "Returns hash of block in best-block-chain at height provided.\n",
552 int nHeight = request.params[0].getInt<
int>();
553 if (nHeight < 0 || nHeight > active_chain.
Height()) {
555 "Block height out of range");
567 "If verbose is false, returns a string that is serialized, hex-encoded "
568 "data for blockheader 'hash'.\n"
569 "If verbose is true, returns an Object with information about "
570 "blockheader <hash>.\n",
575 "true for a json object, false for the hex-encoded data"},
579 "for verbose = true",
585 "the block hash (same as provided)"},
587 "The number of confirmations, or -1 if the block is not "
588 "on the main chain"},
590 "The block height or index"},
593 "The block version formatted in hexadecimal"},
603 "Expected number of hashes required to produce the "
606 "The number of transactions in the block"},
609 "The hash of the previous block (if available)"},
612 "The hash of the next block (if available)"},
615 "A string that is serialized, hex-encoded data for block "
619 "\"00000000c937983704a73af28acdec37b049d214a"
620 "dbda81d7e2a3dd146f6ed09\"") +
622 "\"00000000c937983704a73af28acdec37b049d214a"
623 "dbda81d7e2a3dd146f6ed09\"")},
628 bool fVerbose =
true;
629 if (!request.params[1].isNull()) {
630 fVerbose = request.params[1].get_bool();
651 std::string strHex =
HexStr(ssBlock);
665 if (blockman.IsBlockPruned(blockindex)) {
667 "Block not available (pruned data)");
671 if (!blockman.
ReadBlock(block, blockindex)) {
688 if (blockman.IsBlockPruned(blockindex)) {
690 "Undo data not available (pruned data)");
704 "If verbosity is 0 or false, returns a string that is serialized, "
705 "hex-encoded data for block 'hash'.\n"
706 "If verbosity is 1 or true, returns an Object with information about "
708 "If verbosity is 2, returns an Object with information about block "
709 "<hash> and information about each transaction.\n"
710 "If verbosity is 3, returns an Object with information about block "
711 "<hash> and information about each transaction, including prevout "
712 "information for inputs (only for unpruned blocks in the current best "
718 "0 for hex-encoded data, 1 for a json object, and 2 for json "
719 "object with transaction data",
724 "A string that is serialized, hex-encoded data for block "
733 "the block hash (same as provided)"},
735 "The number of confirmations, or -1 if the block is not "
736 "on the main chain"},
739 "The block height or index"},
742 "The block version formatted in hexadecimal"},
746 "The transaction ids",
756 "Expected number of hashes required to produce the chain "
757 "up to this block (in hex)"},
759 "The number of transactions in the block"},
762 "The hash of the previous block (if available)"},
765 "The hash of the next block (if available)"},
773 "Same output as verbosity = 1"},
783 "The transactions in the format of the "
784 "getrawtransaction RPC. Different from "
785 "verbosity = 1 \"tx\" result"},
787 "The transaction fee in " +
789 ", omitted if block undo data is not "
796 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
797 "214adbda81d7e2a3dd146f6ed09\"") +
798 HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
799 "214adbda81d7e2a3dd146f6ed09\"")},
805 if (!request.params[1].isNull()) {
806 if (request.params[1].isNum()) {
807 verbosity = request.params[1].getInt<
int>();
809 verbosity = request.params[1].get_bool() ? 1 : 0;
830 if (verbosity <= 0) {
833 std::string strHex =
HexStr(ssBlock);
838 if (verbosity == 1) {
840 }
else if (verbosity == 2) {
864 if (!first_block || !chain_tip) {
869 if (!(chain_tip->nStatus.hasData() && chain_tip->nStatus.hasUndo())) {
876 blockman.GetFirstBlock(*chain_tip,
878 return status.hasData() && status.hasUndo();
880 if (first_unpruned == first_block) {
896 "The block height to prune up to. May be set to a discrete "
900 " to prune blocks whose block time is at "
901 "least 2 hours older than the provided timestamp."},
912 "Cannot prune blocks because node is not in prune mode.");
919 int heightParam = request.params[0].getInt<
int>();
920 if (heightParam < 0) {
922 "Negative block height.");
928 if (heightParam > 1000000000) {
935 "Could not find block with at least the "
936 "specified timestamp.");
941 unsigned int height = (
unsigned int)heightParam;
942 unsigned int chainHeight = (
unsigned int)active_chain.
Height();
943 if (chainHeight < config.GetChainParams().PruneAfterHeight()) {
945 "Blockchain is too short for pruning.");
946 }
else if (height > chainHeight) {
949 "Blockchain is shorter than the attempted prune height.");
952 "Attempt to prune blocks close to the tip. "
953 "Retaining the minimum number of blocks.\n");
965 if (hash_type_input ==
"hash_serialized") {
966 return CoinStatsHashType::HASH_SERIALIZED;
967 }
else if (hash_type_input ==
"muhash") {
968 return CoinStatsHashType::MUHASH;
969 }
else if (hash_type_input ==
"none") {
974 strprintf(
"%s is not a valid hash_type", hash_type_input));
981 "Returns statistics about the unspent transaction output set.\n"
982 "Note this call may take some time if you are not using "
986 "Which UTXO set hash should be calculated. Options: "
987 "'hash_serialized' (the legacy algorithm), 'muhash', 'none'."},
989 "The block hash or height of the target height (only available "
990 "with coinstatsindex).",
992 .type_str = {
"",
"string or numeric"}}},
994 "Use coinstatsindex, if available."},
1002 "The current block height (index)"},
1004 "The hash of the block at the tip of the chain"},
1006 "The number of unspent transaction outputs"},
1008 "Database-independent, meaningless metric indicating "
1009 "the UTXO set size"},
1012 "The serialized hash (only present if 'hash_serialized' "
1013 "hash_type is chosen)"},
1015 "The serialized hash (only present if 'muhash' "
1016 "hash_type is chosen)"},
1018 "The number of transactions with unspent outputs (not "
1019 "available when coinstatsindex is used)"},
1021 "The estimated size of the chainstate on disk (not "
1022 "available when coinstatsindex is used)"},
1024 "The total amount"},
1026 "The total amount of coins permanently excluded from the UTXO "
1027 "set (only available if coinstatsindex is used)"},
1030 "Info on amounts in the block at this block height (only "
1031 "available if coinstatsindex is used)",
1033 "Total amount of all prevouts spent in this block"},
1035 "Coinbase subsidy amount of this block"},
1037 "Total amount of new outputs created by this block"},
1039 "Total amount of unspendable outputs created in this block"},
1042 "Detailed view of the unspendable categories",
1045 "The unspendable amount of the Genesis block subsidy"},
1047 "Transactions overridden by duplicates (no longer "
1048 "possible with BIP30)"},
1050 "Amounts sent to scripts that are unspendable (for "
1051 "example OP_RETURN outputs)"},
1053 "Fee rewards that miners did not claim in their "
1054 "coinbase transaction"},
1063 R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1069 R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")},
1076 request.params[0].isNull()
1077 ? CoinStatsHashType::HASH_SERIALIZED
1079 bool index_requested =
1080 request.params[2].isNull() || request.params[2].get_bool();
1091 coins_view = &active_chainstate.
CoinsDB();
1096 if (!request.params[1].isNull()) {
1099 "Querying specific block heights "
1100 "requires coinstatsindex");
1103 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1105 "hash_serialized hash type cannot be "
1106 "queried for a specific block");
1120 if (pindex->nHeight > summary.best_block_height) {
1124 "Unable to get data because coinstatsindex is "
1125 "still syncing. Current height: %d",
1126 summary.best_block_height));
1131 const std::optional<CCoinsStats> maybe_stats =
GetUTXOStats(
1132 coins_view, *blockman, hash_type,
node.rpc_interruption_point,
1133 pindex, index_requested);
1134 if (maybe_stats.has_value()) {
1140 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1141 ret.
pushKV(
"hash_serialized",
1144 if (hash_type == CoinStatsHashType::MUHASH) {
1150 ret.
pushKV(
"transactions",
1154 ret.
pushKV(
"total_unspendable_amount",
1158 if (pindex->nHeight > 0) {
1159 const std::optional<CCoinsStats> maybe_prev_stats =
1161 node.rpc_interruption_point,
1162 pindex->pprev, index_requested);
1163 if (!maybe_prev_stats) {
1165 "Unable to read UTXO set");
1167 prev_stats = maybe_prev_stats.value();
1174 prev_stats.total_prevout_spent_amount);
1175 block_info.
pushKV(
"coinbase",
1177 prev_stats.total_coinbase_amount);
1179 "new_outputs_ex_coinbase",
1181 prev_stats.total_new_outputs_ex_coinbase_amount);
1182 block_info.
pushKV(
"unspendable",
1184 prev_stats.total_unspendable_amount);
1190 prev_stats.total_unspendables_genesis_block);
1193 prev_stats.total_unspendables_bip30);
1196 prev_stats.total_unspendables_scripts);
1198 "unclaimed_rewards",
1200 prev_stats.total_unspendables_unclaimed_rewards);
1201 block_info.
pushKV(
"unspendables", std::move(unspendables));
1203 ret.
pushKV(
"block_info", std::move(block_info));
1207 "Unable to read UTXO set");
1217 "Returns details about an unspent transaction output.\n",
1220 "The transaction id"},
1223 "Whether to include the mempool. Note that an unspent output that "
1224 "is spent in the mempool won't appear."},
1236 "The hash of the block at the tip of the chain"},
1238 "The number of confirmations"},
1248 "Number of required signatures"},
1250 "The type, eg pubkeyhash"},
1253 "array of eCash addresses",
1262 "\nAs a JSON-RPC call\n" +
1273 int n = request.params[1].getInt<
int>();
1274 COutPoint out(txid, n);
1275 bool fMempool =
true;
1276 if (!request.params[2].isNull()) {
1277 fMempool = request.params[2].get_bool();
1292 if (!coins_view->
GetCoin(out, coin)) {
1302 ret.
pushKV(
"confirmations", 0);
1304 ret.
pushKV(
"confirmations",
1310 ret.
pushKV(
"scriptPubKey", std::move(o));
1321 "Verifies blockchain database.\n",
1326 strprintf(
"How thorough the block verification is:\n%s",
1330 "The number of blocks to check."},
1333 "Verification finished successfully. If false, check "
1334 "debug.log for reason."},
1339 const int check_level{request.params[0].
isNull()
1341 : request.params[0].getInt<
int>()};
1342 const int check_depth{request.params[1].isNull()
1344 : request.params[1].getInt<
int>()};
1352 active_chainstate.
CoinsTip(), check_level,
1360 "getblockchaininfo",
1361 "Returns an object containing various state info regarding blockchain "
1370 "current network name (main, test, regtest)"},
1372 "the height of the most-work fully-validated "
1373 "non-parked chain. The genesis block has height 0"},
1375 "the current number of headers we have validated"},
1377 "the hash of the avalanche finalized tip if any, otherwise "
1378 "the genesis block hash"},
1380 "the hash of the currently best block"},
1387 "estimate of verification progress [0..1]"},
1389 "(debug information) estimate of whether this node is in "
1390 "Initial Block Download mode"},
1392 "total amount of work in active chain, in hexadecimal"},
1394 "the estimated size of the block and undo files on disk"},
1396 "if the blocks are subject to pruning"},
1398 "lowest-height complete block stored (only present if pruning "
1401 "whether automatic pruning is enabled (only present if "
1402 "pruning is enabled)"},
1404 "the target size used by pruning (only present if automatic "
1405 "pruning is enabled)"},
1407 "any network and blockchain warnings"},
1413 const CChainParams &chainparams = config.GetChainParams();
1421 const int height{tip.
nHeight};
1425 obj.
pushKV(
"blocks", height);
1426 obj.
pushKV(
"headers", chainman.m_best_header
1427 ? chainman.m_best_header->nHeight
1430 obj.
pushKV(
"finalized_blockhash",
1431 avalanche_finalized_tip
1432 ? avalanche_finalized_tip->GetBlockHash().GetHex()
1439 "verificationprogress",
1441 obj.
pushKV(
"initialblockdownload",
1444 obj.
pushKV(
"size_on_disk",
1451 obj.
pushKV(
"pruneheight",
1452 prune_height ? prune_height.value() + 1 : 0);
1454 const bool automatic_pruning{
1456 BlockManager::PRUNE_TARGET_MANUAL};
1457 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1458 if (automatic_pruning) {
1459 obj.
pushKV(
"prune_target_size",
1486 "Return information about all known tips in the block tree, including "
1487 "the main chain as well as orphaned branches.\n",
1500 "zero for main chain, otherwise length of branch connecting "
1501 "the tip to the main chain"},
1503 "status of the chain, \"active\" for the main chain\n"
1504 "Possible values for status:\n"
1505 "1. \"invalid\" This branch contains at "
1506 "least one invalid block\n"
1507 "2. \"parked\" This branch contains at "
1508 "least one parked block\n"
1509 "3. \"headers-only\" Not all blocks for this "
1510 "branch are available, but the headers are valid\n"
1511 "4. \"valid-headers\" All blocks are available for "
1512 "this branch, but they were never fully validated\n"
1513 "5. \"valid-fork\" This branch is not part of "
1514 "the active chain, but is fully validated\n"
1515 "6. \"active\" This is the tip of the "
1516 "active main chain, which is certainly valid"},
1537 std::set<const CBlockIndex *, CompareBlocksByHeight> setTips;
1538 std::set<const CBlockIndex *> setOrphans;
1539 std::set<const CBlockIndex *> setPrevs;
1541 for (
const auto &[
_, block_index] : chainman.
BlockIndex()) {
1542 if (!active_chain.
Contains(&block_index)) {
1543 setOrphans.insert(&block_index);
1544 setPrevs.insert(block_index.pprev);
1548 for (std::set<const CBlockIndex *>::iterator it =
1550 it != setOrphans.end(); ++it) {
1551 if (setPrevs.erase(*it) == 0) {
1552 setTips.insert(*it);
1557 setTips.insert(active_chain.
Tip());
1563 obj.
pushKV(
"height", block->nHeight);
1564 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1566 const int branchLen =
1568 obj.
pushKV(
"branchlen", branchLen);
1571 if (active_chain.
Contains(block)) {
1574 }
else if (block->nStatus.isInvalid()) {
1577 }
else if (block->nStatus.isOnParkedChain()) {
1580 }
else if (!block->HaveNumChainTxs()) {
1583 status =
"headers-only";
1588 status =
"valid-fork";
1593 status =
"valid-headers";
1598 obj.
pushKV(
"status", status);
1611 "Treats a block as if it were received before others with the same "
1613 "\nA later preciousblock call can override the effect of an earlier "
1615 "\nThe effects of preciousblock are not retained across restarts.\n",
1618 "the hash of the block to mark as precious"},
1641 node.avalanche.get());
1682 "Permanently marks a block as invalid, as if it violated a consensus "
1686 "the hash of the block to mark as invalid"},
1709 "Marks a block as parked.\n",
1712 "the hash of the block to park"},
1719 const std::string strHash = request.params[0].
get_str();
1742 active_chainstate.
ParkBlock(state, pblockindex);
1746 node.avalanche.get());
1773 chainman.RecalculateBestHeader();
1788 "Removes invalidity status of a block, its ancestors and its"
1789 "descendants, reconsider them for activation.\n"
1790 "This can be used to undo the effects of invalidateblock.\n",
1793 "the hash of the block to reconsider"},
1817 "Removes parked status of a block and its descendants, reconsider "
1818 "them for activation.\n"
1819 "This can be used to undo the effects of parkblock.\n",
1822 "the hash of the block to unpark"},
1829 const std::string strHash = request.params[0].
get_str();
1845 if (!pblockindex->nStatus.isOnParkedChain()) {
1867 node.avalanche.get());
1884 "Compute statistics about the total number and rate of transactions "
1888 "Size of the window in number of blocks"},
1891 "The hash of the block that ends the window."},
1899 "The timestamp for the final block in the window, "
1903 "The total number of transactions in the chain up to "
1904 "that point, if known. It may be unknown when using "
1907 "The hash of the final block in the window"},
1909 "The height of the final block in the window."},
1911 "Size of the window in number of blocks"},
1913 "The elapsed time in the window in seconds. Only "
1914 "returned if \"window_block_count\" is > 0"},
1916 "The number of transactions in the window. Only "
1917 "returned if \"window_block_count\" is > 0 and if "
1918 "txcount exists for the start and end of the window."},
1920 "The average rate of transactions per second in the "
1921 "window. Only returned if \"window_interval\" is > 0 "
1922 "and if window_tx_count exists."},
1934 config.GetChainParams().GetConsensus().nPowTargetSpacing;
1936 if (request.params[1].isNull()) {
1949 "Block is not in main chain");
1955 if (request.params[0].isNull()) {
1957 std::max(0, std::min(blockcount, pindex->
nHeight - 1));
1959 blockcount = request.params[0].getInt<
int>();
1961 if (blockcount < 0 ||
1962 (blockcount > 0 && blockcount >= pindex->
nHeight)) {
1964 "Invalid block count: "
1965 "should be between 0 and "
1966 "the block's height - 1");
1973 past_block.GetMedianTimePast()};
1980 ret.
pushKV(
"window_final_block_hash",
1983 ret.
pushKV(
"window_block_count", blockcount);
1984 if (blockcount > 0) {
1985 ret.
pushKV(
"window_interval", nTimeDiff);
1986 if (pindex->
nChainTx != 0 && past_block.nChainTx != 0) {
1987 unsigned int window_tx_count =
1988 pindex->
nChainTx - past_block.nChainTx;
1989 ret.
pushKV(
"window_tx_count", window_tx_count);
1990 if (nTimeDiff > 0) {
1992 double(window_tx_count) / nTimeDiff);
2002template <
typename T>
2004 size_t size = scores.size();
2009 std::sort(scores.begin(), scores.end());
2010 if (size % 2 == 0) {
2011 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
2013 return scores[size / 2];
2017template <
typename T>
static inline bool SetHasKeys(
const std::set<T> &set) {
2020template <
typename T,
typename Tk,
typename... Args>
2021static inline bool SetHasKeys(
const std::set<T> &set,
const Tk &key,
2022 const Args &...args) {
2023 return (set.count(key) != 0) ||
SetHasKeys(set, args...);
2028 sizeof(COutPoint) +
sizeof(uint32_t) +
sizeof(bool);
2034 "Compute per block statistics for a given window. All amounts are "
2038 "It won't work for some heights with pruning.\n",
2041 "The block hash or height of the target block",
2043 .type_str = {
"",
"string or numeric"}}},
2047 "Values to plot (see result below)",
2050 "Selected statistic"},
2052 "Selected statistic"},
2063 "Average feerate (in satoshis per virtual byte)"},
2066 "The block hash (to check for potential reorgs)"},
2069 "The number of inputs (excluding coinbase)"},
2072 "Maximum feerate (in satoshis per virtual byte)"},
2075 "Truncated median fee in the block"},
2077 "Truncated median feerate (in " + ticker +
" per byte)"},
2079 "The block median time past"},
2081 "Truncated median transaction size"},
2084 "Minimum feerate (in satoshis per virtual byte)"},
2090 "Total amount in all outputs (excluding coinbase and thus "
2091 "reward [ie subsidy + totalfee])"},
2093 "Total size of all non-coinbase transactions"},
2096 "The number of transactions (including coinbase)"},
2098 "The increase/decrease in the number of unspent outputs"},
2100 "The increase/decrease in size for the utxo index (not "
2101 "discounting op_return and similar)"},
2106 R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2108 R
"(1000 '["minfeerate","avgfeerate"]')") +
2111 R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2113 R
"(1000, ["minfeerate","avgfeerate"])")},
2120 std::set<std::string> stats;
2121 if (!request.params[1].isNull()) {
2123 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2124 const std::string stat = stats_univalue[i].
get_str();
2134 const bool do_all = stats.size() == 0;
2135 const bool do_mediantxsize =
2136 do_all || stats.count(
"mediantxsize") != 0;
2137 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
2138 const bool do_medianfeerate =
2139 do_all || stats.count(
"medianfeerate") != 0;
2140 const bool loop_inputs =
2141 do_all || do_medianfee || do_medianfeerate ||
2142 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
2143 "avgfeerate",
"minfee",
"maxfee",
"minfeerate",
2145 const bool loop_outputs =
2146 do_all || loop_inputs || stats.count(
"total_out");
2147 const bool do_calculate_size =
2148 do_mediantxsize || loop_inputs ||
2149 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
2152 const int64_t blockMaxSize = config.GetMaxBlockSize();
2160 int64_t maxtxsize = 0;
2161 int64_t mintxsize = blockMaxSize;
2162 int64_t outputs = 0;
2163 int64_t total_size = 0;
2164 int64_t utxo_size_inc = 0;
2165 std::vector<Amount> fee_array;
2166 std::vector<Amount> feerate_array;
2167 std::vector<int64_t> txsize_array;
2169 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2170 const auto &tx = block.
vtx.at(i);
2171 outputs += tx->vout.size();
2174 for (
const CTxOut &out : tx->vout) {
2175 tx_total_out += out.
nValue;
2181 if (tx->IsCoinBase()) {
2186 inputs += tx->vin.size();
2188 total_out += tx_total_out;
2190 int64_t tx_size = 0;
2191 if (do_calculate_size) {
2192 tx_size = tx->GetTotalSize();
2193 if (do_mediantxsize) {
2194 txsize_array.push_back(tx_size);
2196 maxtxsize = std::max(maxtxsize, tx_size);
2197 mintxsize = std::min(mintxsize, tx_size);
2198 total_size += tx_size;
2203 const auto &txundo = blockUndo.
vtxundo.at(i - 1);
2204 for (
const Coin &coin : txundo.vprevout) {
2207 tx_total_in += prevoutput.
nValue;
2212 Amount txfee = tx_total_in - tx_total_out;
2215 fee_array.push_back(txfee);
2217 maxfee = std::max(maxfee, txfee);
2218 minfee = std::min(minfee, txfee);
2221 Amount feerate = txfee / tx_size;
2222 if (do_medianfeerate) {
2223 feerate_array.push_back(feerate);
2225 maxfeerate = std::max(maxfeerate, feerate);
2226 minfeerate = std::min(minfeerate, feerate);
2232 block.
vtx.size() > 1
2233 ? (totalfee /
int((block.
vtx.size() - 1)))
2235 ret_all.
pushKV(
"avgfeerate", total_size > 0
2236 ? (totalfee / total_size)
2238 ret_all.
pushKV(
"avgtxsize",
2239 (block.
vtx.size() > 1)
2240 ? total_size / (block.
vtx.size() - 1)
2242 ret_all.
pushKV(
"blockhash", pindex.GetBlockHash().GetHex());
2243 ret_all.
pushKV(
"height", (int64_t)pindex.nHeight);
2244 ret_all.
pushKV(
"ins", inputs);
2245 ret_all.
pushKV(
"maxfee", maxfee);
2246 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2247 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2249 ret_all.
pushKV(
"medianfeerate",
2251 ret_all.
pushKV(
"mediantime", pindex.GetMedianTimePast());
2252 ret_all.
pushKV(
"mediantxsize",
2259 ret_all.
pushKV(
"mintxsize",
2260 mintxsize == blockMaxSize ? 0 : mintxsize);
2261 ret_all.
pushKV(
"outs", outputs);
2264 ret_all.
pushKV(
"time", pindex.GetBlockTime());
2265 ret_all.
pushKV(
"total_out", total_out);
2266 ret_all.
pushKV(
"total_size", total_size);
2267 ret_all.
pushKV(
"totalfee", totalfee);
2268 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
2269 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2270 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2277 for (
const std::string &stat : stats) {
2278 const UniValue &value = ret_all[stat];
2282 strprintf(
"Invalid selected statistic %s", stat));
2293static bool FindScriptPubKey(std::atomic<int> &scan_progress,
2294 const std::atomic<bool> &should_abort,
2296 const std::set<CScript> &needles,
2297 std::map<COutPoint, Coin> &out_results,
2298 std::function<
void()> &interruption_point) {
2301 while (cursor->
Valid()) {
2307 if (++
count % 8192 == 0) {
2308 interruption_point();
2314 if (
count % 256 == 0) {
2316 const TxId &txid = key.GetTxId();
2317 uint32_t high = 0x100 * *txid.
begin() + *(txid.
begin() + 1);
2318 scan_progress = int(high * 100.0 / 65536.0 + 0.5);
2321 out_results.emplace(key, coin);
2325 scan_progress = 100;
2361 "Scans the unspent transaction output set for entries that match "
2362 "certain output descriptors.\n"
2363 "Examples of output descriptors are:\n"
2364 " addr(<address>) Outputs whose scriptPubKey "
2365 "corresponds to the specified address (does not include P2PK)\n"
2366 " raw(<hex script>) Outputs whose scriptPubKey "
2367 "equals the specified hex scripts\n"
2368 " combo(<pubkey>) P2PK and P2PKH outputs for "
2369 "the given pubkey\n"
2370 " pkh(<pubkey>) P2PKH outputs for the given "
2372 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
2373 "the given threshold and pubkeys\n"
2374 "\nIn the above, <pubkey> either refers to a fixed public key in "
2375 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2376 "or more path elements separated by \"/\", and optionally ending in "
2377 "\"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2378 "unhardened or hardened child keys.\n"
2379 "In the latter case, a range needs to be specified by below if "
2380 "different from 1000.\n"
2381 "For more information on output descriptors, see the documentation in "
2382 "the doc/descriptors.md file.\n",
2385 "The action to execute\n"
2386 " \"start\" for starting a "
2388 " \"abort\" for aborting the "
2389 "current scan (returns true when abort was successful)\n"
2391 "progress report (in %) of the current scan"},
2395 "Array of scan objects. Required for \"start\" action\n"
2396 " Every scan object is either a "
2397 "string descriptor or an object:",
2400 "An output descriptor"},
2405 "An object with output descriptor and metadata",
2408 "An output descriptor"},
2410 "The range of HD chain indexes to explore (either "
2411 "end or [begin,end])"},
2419 RPCResult{
"When action=='status' and no scan is in progress",
2422 "When action=='status' and scan is in progress",
2430 "When action=='start'",
2436 "Whether the scan was completed"},
2438 "The number of unspent transaction outputs scanned"},
2440 "The current block height (index)"},
2442 "The hash of the block at the tip of the chain"},
2452 "The transaction id"},
2457 "A specialized descriptor for the matched "
2460 "The total amount in " + ticker +
2461 " of the unspent output"},
2463 "Whether this is a coinbase output"},
2465 "Height of the unspent transaction output"},
2469 "The total amount of all found unspent outputs in " +
2477 const auto action{self.
Arg<std::string>(
"action")};
2478 if (action ==
"status") {
2486 }
else if (action ==
"abort") {
2495 }
else if (action ==
"start") {
2499 "Scan already in progress, use action "
2500 "\"abort\" or \"status\"");
2503 if (request.params.size() < 2) {
2505 "scanobjects argument is required for "
2506 "the start action");
2509 std::set<CScript> needles;
2510 std::map<CScript, std::string> descriptors;
2519 for (CScript &
script : scripts) {
2520 std::string inferred =
2523 descriptors.emplace(std::move(
script),
2524 std::move(inferred));
2530 std::vector<CTxOut> input_txos;
2531 std::map<COutPoint, Coin> coins;
2535 std::unique_ptr<CCoinsViewCursor> pcursor;
2547 bool res = FindScriptPubKey(
2549 needles, coins,
node.rpc_interruption_point);
2550 result.
pushKV(
"success", res);
2555 for (
const auto &it : coins) {
2556 const COutPoint &outpoint = it.first;
2557 const Coin &coin = it.second;
2559 input_txos.push_back(txo);
2563 unspent.
pushKV(
"txid", outpoint.GetTxId().GetHex());
2564 unspent.
pushKV(
"vout", int32_t(outpoint.GetN()));
2573 result.
pushKV(
"unspents", std::move(unspents));
2574 result.
pushKV(
"total_amount", total_in);
2577 strprintf(
"Invalid action '%s'", action));
2587 "Retrieve a BIP 157 content filter for a particular block.\n",
2590 "The hash of the block"},
2592 "The type name of the filter"},
2599 "the hex-encoded filter data"},
2601 "the hex-encoded filter header"},
2605 "\"00000000c937983704a73af28acdec37b049d214a"
2606 "dbda81d7e2a3dd146f6ed09\" \"basic\"") +
2608 "\"00000000c937983704a73af28acdec37b049d214adbda81d7"
2609 "e2a3dd146f6ed09\", \"basic\"")},
2614 std::string filtertype_name =
"basic";
2615 if (!request.params[1].isNull()) {
2616 filtertype_name = request.params[1].get_str();
2622 "Unknown filtertype");
2628 "Index is not enabled for filtertype " +
2633 bool block_was_connected;
2643 block_was_connected =
2647 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2654 std::string errmsg =
"Filter not found.";
2656 if (!block_was_connected) {
2658 errmsg +=
" Block was not connected to active chain.";
2659 }
else if (!index_ready) {
2661 errmsg +=
" Block filters are still in the process of "
2665 errmsg +=
" This error is unexpected and indicates index "
2692 "Network activity could not be suspended.");
2730 "Write the serialized UTXO set to a file. This can be used in "
2731 "loadtxoutset afterwards if this snapshot height is supported in the "
2732 "chainparams as well.\n\n"
2733 "Unless the the \"latest\" type is requested, the node will roll back "
2734 "to the requested height and network activity will be suspended during "
2736 "Because of this it is discouraged to interact with the node in any "
2737 "other way during the execution of this call to avoid inconsistent "
2738 "results and race conditions, particularly RPCs that interact with "
2740 "This call may take several minutes. Make sure to use no RPC timeout "
2741 "(bitcoin-cli -rpcclienttimeout=0)",
2745 "path to the output file. If relative, will be prefixed by "
2748 "The type of snapshot to create. Can be \"latest\" to create a "
2749 "snapshot of the current UTXO set or \"rollback\" to temporarily "
2750 "roll back the state of the node to a historical block before "
2751 "creating the snapshot of a historical UTXO set. This parameter "
2752 "can be omitted if a separate \"rollback\" named parameter is "
2753 "specified indicating the height or hash of a specific historical "
2754 "block. If \"rollback\" is specified and separate \"rollback\" "
2755 "named parameter is not specified, this will roll back to the "
2756 "latest valid snapshot block that can currently be loaded with "
2765 "Height or hash of the block to roll back to before "
2766 "creating the snapshot. Note: The further this number is "
2767 "from the tip, the longer this process will take. "
2768 "Consider setting a higher -rpcclienttimeout value in "
2771 .type_str = {
"",
"string or numeric"}}},
2780 "the number of coins written in the snapshot"},
2782 "the hash of the base of the snapshot"},
2784 "the height of the base of the snapshot"},
2786 "the absolute path that the snapshot was written to"},
2788 "the hash of the UTXO set contents"},
2790 "the number of transactions in the chain up to and "
2791 "including the base block"},
2794 "utxo.dat latest") +
2796 "utxo.dat rollback") +
2798 R
"(utxo.dat rollback=853456)")},
2805 const std::string snapshot_type{self.
Arg<std::string>(
"type")};
2808 : request.params[2]};
2809 if (options.exists(
"rollback")) {
2810 if (!snapshot_type.empty() && snapshot_type !=
"rollback") {
2813 strprintf(
"Invalid snapshot type \"%s\" specified with "
2819 }
else if (snapshot_type ==
"rollback") {
2820 auto snapshot_heights =
2821 node.chainman->GetParams().GetAvailableSnapshotHeights();
2823 auto max_height = std::max_element(snapshot_heights.begin(),
2824 snapshot_heights.end());
2826 }
else if (snapshot_type ==
"latest") {
2831 strprintf(
"Invalid snapshot type \"%s\" specified. Please "
2832 "specify \"rollback\" or \"latest\"",
2838 args.GetDataDirNet(),
fs::u8path(request.params[0].get_str()));
2842 args.GetDataDirNet(),
2843 fs::u8path(request.params[0].get_str() +
".incomplete"));
2848 " already exists. If you are sure this "
2849 "is what you want, "
2850 "move it out of the way first");
2858 std::optional<NetworkDisable> disable_network;
2859 std::optional<TemporaryRollback> temporary_rollback;
2863 if (target_index != tip) {
2866 if (
node.chainman->m_blockman.IsPruneMode()) {
2869 node.chainman->ActiveChain().Tip()};
2871 node.chainman->m_blockman.GetFirstBlock(
2876 if (first_block->nHeight > target_index->nHeight) {
2879 "Could not roll back to requested height since "
2880 "necessary block data is already pruned.");
2894 disable_network.emplace(connman);
2899 return node.chainman->ActiveChain().Next(target_index));
2900 temporary_rollback.emplace(*
node.chainman,
node.avalanche.get(),
2905 std::unique_ptr<CCoinsViewCursor> cursor;
2915 chainstate = &
node.chainman->ActiveChainstate();
2924 if (target_index != chainstate->
m_chain.
Tip()) {
2926 "Failed to roll back to requested height, "
2927 "reverting to tip.\n");
2930 "Could not roll back to requested height.");
2933 *chainstate,
node.rpc_interruption_point);
2939 path, temppath,
node.rpc_interruption_point);
2940 fs::rename(temppath, path);
2949 const std::function<
void()> &interruption_point) {
2950 std::unique_ptr<CCoinsViewCursor> pcursor;
2951 std::optional<CCoinsStats> maybe_stats;
2973 CoinStatsHashType::HASH_SERIALIZED,
2974 interruption_point);
2980 std::unique_ptr<CCoinsViewCursor>(chainstate.
CoinsDB().
Cursor());
2992 const std::function<
void()> &interruption_point) {
2994 strprintf(
"writing UTXO snapshot at height %s (%s) to file %s (via %s)",
3005 unsigned int iter{0};
3006 size_t written_coins_count{0};
3007 std::vector<std::pair<uint32_t, Coin>> coins;
3016 auto write_coins_to_file =
3018 const std::vector<std::pair<uint32_t, Coin>> &coins,
3019 size_t &written_coins_count) {
3022 for (
const auto &[n, coin_] : coins) {
3025 ++written_coins_count;
3030 last_txid = key.GetTxId();
3031 while (pcursor->
Valid()) {
3032 if (iter % 5000 == 0) {
3033 interruption_point();
3037 if (key.GetTxId() != last_txid) {
3038 write_coins_to_file(afile, last_txid, coins,
3039 written_coins_count);
3040 last_txid = key.GetTxId();
3043 coins.emplace_back(key.GetN(), coin);
3048 if (!coins.empty()) {
3049 write_coins_to_file(afile, last_txid, coins, written_coins_count);
3057 result.
pushKV(
"coins_written", written_coins_count);
3073 tmppath,
node.rpc_interruption_point);
3079 "Load the serialized UTXO set from a file.\n"
3080 "Once this snapshot is loaded, its contents will be deserialized into "
3081 "a second chainstate data structure, which is then used to sync to the "
3083 "Meanwhile, the original chainstate will complete the initial block "
3084 "download process in the background, eventually validating up to the "
3085 "block that the snapshot is based upon.\n\n"
3086 "The result is a usable bitcoind instance that is current with the "
3087 "network tip in a matter of minutes rather than hours. UTXO snapshot "
3088 "are typically obtained from third-party sources (HTTP, torrent, etc.) "
3089 "which is reasonable since their contents are always checked by "
3091 "This RPC is incompatible with the -chronik init option, and a node "
3092 "with multiple chainstates may not be restarted with -chronik. After "
3093 "the background validation is finished and the chainstates are merged, "
3094 "the node can be restarted again with Chronik.\n\n"
3095 "You can find more information on this process in the `assumeutxo` "
3096 "design document (https://www.bitcoinabc.org/doc/assumeutxo.html).",
3099 "path to the snapshot file. If relative, will be prefixed by "
3107 "the number of coins loaded from the snapshot"},
3109 "the hash of the base of the snapshot"},
3111 "the height of the base of the snapshot"},
3113 "the absolute path that the snapshot was loaded from"},
3128 "loadtxoutset is not compatible with Chronik.");
3135 "Couldn't open file " + path.
u8string() +
3142 }
catch (
const std::ios_base::failure &e) {
3145 strprintf(
"Unable to parse metadata: %s", e.what()));
3148 auto activation_result{
3150 if (!activation_result) {
3153 strprintf(
"Unable to load UTXO snapshot: %s. (%s)",
3171 result.
pushKV(
"tip_hash", snapshot_index.GetBlockHash().ToString());
3172 result.
pushKV(
"base_height", snapshot_index.nHeight);
3184 "progress towards the network tip"},
3186 "the base block of the snapshot this chainstate is based on, if any"},
3189 "size of the coinstip cache"},
3191 "whether the chainstate is fully validated. True if all blocks in the "
3192 "chainstate were validated, false if the chain is based on a snapshot and "
3193 "the snapshot has not yet been validated."},
3200 "\nReturn information about chainstates.\n",
3207 "the number of headers seen so far"},
3210 "list of the chainstates ordered by work, with the "
3211 "most-work (active) chainstate last",
3225 auto make_chain_data =
3240 "verificationprogress",
3242 data.
pushKV(
"coins_db_cache_bytes",
3244 data.
pushKV(
"coins_tip_cache_bytes",
3248 "snapshot_blockhash",
3251 data.
pushKV(
"validated", validated);
3255 obj.
pushKV(
"headers", chainman.m_best_header
3256 ? chainman.m_best_header->nHeight
3259 const auto &chainstates = chainman.
GetAll();
3262 obj_chainstates.push_back(
3263 make_chain_data(*
cs, !
cs->m_from_snapshot_blockhash ||
3264 chainstates.size() == 1));
3266 obj.
pushKV(
"chainstates", std::move(obj_chainstates));
3309 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.
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 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.