44 #include <condition_variable>
73 int nShift = (blockindex->
nBits >> 24) & 0xff;
74 double dDiff = double(0x0000ffff) / double(blockindex->
nBits & 0x00ffffff);
92 if (next && next->
pprev == blockindex) {
96 return blockindex == tip ? 1 : -1;
105 const int height{param.
get_int()};
109 strprintf(
"Target block height %d is negative", height));
111 const int current_tip{active_chain.
Height()};
112 if (height > current_tip) {
115 strprintf(
"Target block height %d after current tip %d", height,
119 return active_chain[height];
142 result.
pushKV(
"confirmations", confirmations);
153 result.
pushKV(
"nTx", uint64_t(blockindex->
nTx));
155 if (blockindex->
pprev) {
156 result.
pushKV(
"previousblockhash",
174 const bool is_not_pruned{
176 const bool have_undo{is_not_pruned &&
178 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
182 (have_undo && i) ? &blockUndo.
vtxundo.at(i - 1) :
nullptr;
201 "Returns the height of the most-work fully-validated chain.\n"
202 "The genesis block has height 0.\n",
219 "Returns the hash of the best (tip) block in the "
220 "most-work fully-validated chain.\n",
238 latestblock.height = pindex->
nHeight;
246 "Waits for a specific new block and returns useful info about it.\n"
247 "\nReturns the current block on timeout or exit.\n",
250 "Time in milliseconds to wait for a response. 0 indicates no "
265 if (!request.params[0].isNull()) {
266 timeout = request.params[0].
get_int();
275 lock, std::chrono::milliseconds(timeout),
277 return latestblock.height != block.
height ||
278 latestblock.hash != block.
hash ||
285 return latestblock.height != block.
height ||
286 latestblock.hash != block.
hash ||
303 "Waits for a specific new block and returns useful info about it.\n"
304 "\nReturns the current block on timeout or exit.\n",
307 "Block hash to wait for."},
309 "Time in milliseconds to wait for a response. 0 indicates no "
320 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
321 "ed7b4a8c619eb02596f8862\" 1000") +
323 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
324 "ed7b4a8c619eb02596f8862\", 1000")},
331 if (!request.params[1].isNull()) {
332 timeout = request.params[1].get_int();
340 lock, std::chrono::milliseconds(timeout),
364 "waitforblockheight",
365 "Waits for (at least) block height and returns the height and "
366 "hash\nof the current tip.\n"
367 "\nReturns the current block on timeout or exit.\n",
370 "Block height to wait for."},
372 "Time in milliseconds to wait for a response. 0 indicates no "
388 int height = request.params[0].
get_int();
390 if (!request.params[1].isNull()) {
391 timeout = request.params[1].get_int();
399 lock, std::chrono::milliseconds(timeout),
401 return latestblock.height >= height ||
408 return latestblock.height >= height ||
424 "syncwithvalidationinterfacequeue",
425 "Waits for the validation interface queue to catch up on everything "
426 "that was there when we entered this function.\n",
442 "Returns the proof-of-work difficulty as a multiple of the minimum "
446 "the proof-of-work difficulty as a multiple of the minimum "
462 "\nAttempt to fetch block from a given peer.\n"
463 "\nWe must have the header for this block, e.g. using submitheader.\n"
464 "Subsequent calls for the same block and a new peer will cause the "
465 "response from the previous peer to be ignored.\n"
466 "\nReturns an empty JSON object if the request was successfully "
470 "The block hash to try to fetch"},
472 "The peer to fetch it from (see getpeerinfo for peer IDs)"},
476 "\"00000000c937983704a73af28acdec37b049d214a"
477 "dbda81d7e2a3dd146f6ed09\" 0") +
479 "\"00000000c937983704a73af28acdec37b049d214a"
480 "dbda81d7e2a3dd146f6ed09\" 0")},
489 const NodeId peer_id{request.params[1].get_int64()};
503 if (
const auto err{peerman.
FetchBlock(config, peer_id, *index)}) {
514 "Returns hash of block in best-block-chain at height provided.\n",
528 int nHeight = request.params[0].get_int();
529 if (nHeight < 0 || nHeight > active_chain.
Height()) {
531 "Block height out of range");
543 "If verbose is false, returns a string that is serialized, hex-encoded "
544 "data for blockheader 'hash'.\n"
545 "If verbose is true, returns an Object with information about "
546 "blockheader <hash>.\n",
551 "true for a json object, false for the hex-encoded data"},
555 "for verbose = true",
561 "the block hash (same as provided)"},
563 "The number of confirmations, or -1 if the block is not "
564 "on the main chain"},
566 "The block height or index"},
569 "The block version formatted in hexadecimal"},
579 "Expected number of hashes required to produce the "
582 "The number of transactions in the block"},
585 "The hash of the previous block (if available)"},
588 "The hash of the next block (if available)"},
591 "A string that is serialized, hex-encoded data for block "
595 "\"00000000c937983704a73af28acdec37b049d214a"
596 "dbda81d7e2a3dd146f6ed09\"") +
598 "\"00000000c937983704a73af28acdec37b049d214a"
599 "dbda81d7e2a3dd146f6ed09\"")},
604 bool fVerbose =
true;
605 if (!request.params[1].isNull()) {
606 fVerbose = request.params[1].get_bool();
627 std::string strHex =
HexStr(ssBlock);
641 if (blockman.IsBlockPruned(pblockindex)) {
643 "Block not available (pruned data)");
665 if (blockman.IsBlockPruned(pblockindex)) {
667 "Undo data not available (pruned data)");
681 "If verbosity is 0 or false, returns a string that is serialized, "
682 "hex-encoded data for block 'hash'.\n"
683 "If verbosity is 1 or true, returns an Object with information about "
685 "If verbosity is 2, returns an Object with information about block "
686 "<hash> and information about each transaction.\n",
691 "0 for hex-encoded data, 1 for a json object, and 2 for json "
692 "object with transaction data"},
696 "A string that is serialized, hex-encoded data for block "
705 "the block hash (same as provided)"},
707 "The number of confirmations, or -1 if the block is not "
708 "on the main chain"},
711 "The block height or index"},
714 "The block version formatted in hexadecimal"},
718 "The transaction ids",
728 "Expected number of hashes required to produce the chain "
729 "up to this block (in hex)"},
731 "The number of transactions in the block"},
734 "The hash of the previous block (if available)"},
737 "The hash of the next block (if available)"},
745 "Same output as verbosity = 1"},
755 "The transactions in the format of the "
756 "getrawtransaction RPC. Different from "
757 "verbosity = 1 \"tx\" result"},
759 "The transaction fee in " +
761 ", omitted if block undo data is not "
768 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
769 "214adbda81d7e2a3dd146f6ed09\"") +
770 HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
771 "214adbda81d7e2a3dd146f6ed09\"")},
777 if (!request.params[1].isNull()) {
778 if (request.params[1].isNum()) {
779 verbosity = request.params[1].get_int();
781 verbosity = request.params[1].get_bool() ? 1 : 0;
802 if (verbosity <= 0) {
806 std::string strHex =
HexStr(ssBlock);
822 "The block height to prune up to. May be set to a discrete "
826 " to prune blocks whose block time is at "
827 "least 2 hours older than the provided timestamp."},
838 "Cannot prune blocks because node is not in prune mode.");
842 Chainstate &active_chainstate = chainman.ActiveChainstate();
845 int heightParam = request.params[0].get_int();
846 if (heightParam < 0) {
848 "Negative block height.");
854 if (heightParam > 1000000000) {
861 "Could not find block with at least the "
862 "specified timestamp.");
867 unsigned int height = (
unsigned int)heightParam;
868 unsigned int chainHeight = (
unsigned int)active_chain.
Height();
869 if (chainHeight < config.GetChainParams().PruneAfterHeight()) {
871 "Blockchain is too short for pruning.");
872 }
else if (height > chainHeight) {
875 "Blockchain is shorter than the attempted prune height.");
878 "Attempt to prune blocks close to the tip. "
879 "Retaining the minimum number of blocks.\n");
887 return static_cast<uint64_t
>(last_block->
nHeight);
893 if (hash_type_input ==
"hash_serialized") {
894 return CoinStatsHashType::HASH_SERIALIZED;
895 }
else if (hash_type_input ==
"muhash") {
896 return CoinStatsHashType::MUHASH;
897 }
else if (hash_type_input ==
"none") {
902 strprintf(
"%s is not a valid hash_type", hash_type_input));
909 "Returns statistics about the unspent transaction output set.\n"
910 "Note this call may take some time if you are not using "
914 "Which UTXO set hash should be calculated. Options: "
915 "'hash_serialized' (the legacy algorithm), 'muhash', 'none'."},
919 "The block hash or height of the target height (only available "
920 "with coinstatsindex).",
922 {
"",
"string or numeric"}},
924 "Use coinstatsindex, if available."},
932 "The current block height (index)"},
934 "The hash of the block at the tip of the chain"},
936 "The number of unspent transaction outputs"},
938 "Database-independent, meaningless metric indicating "
939 "the UTXO set size"},
942 "The serialized hash (only present if 'hash_serialized' "
943 "hash_type is chosen)"},
945 "The serialized hash (only present if 'muhash' "
946 "hash_type is chosen)"},
948 "The number of transactions with unspent outputs (not "
949 "available when coinstatsindex is used)"},
951 "The estimated size of the chainstate on disk (not "
952 "available when coinstatsindex is used)"},
956 "The total amount of coins permanently excluded from the UTXO "
957 "set (only available if coinstatsindex is used)"},
960 "Info on amounts in the block at this block height (only "
961 "available if coinstatsindex is used)",
963 "Total amount of all prevouts spent in this block"},
965 "Coinbase subsidy amount of this block"},
967 "Total amount of new outputs created by this block"},
969 "Total amount of unspendable outputs created in this block"},
972 "Detailed view of the unspendable categories",
975 "The unspendable amount of the Genesis block subsidy"},
977 "Transactions overridden by duplicates (no longer "
978 "possible with BIP30)"},
980 "Amounts sent to scripts that are unspendable (for "
981 "example OP_RETURN outputs)"},
983 "Fee rewards that miners did not claim in their "
984 "coinbase transaction"},
993 R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
999 R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")},
1006 request.params[0].isNull()
1007 ? CoinStatsHashType::HASH_SERIALIZED
1009 bool index_requested =
1010 request.params[2].isNull() || request.params[2].get_bool();
1014 Chainstate &active_chainstate = chainman.ActiveChainstate();
1021 coins_view = &active_chainstate.
CoinsDB();
1026 if (!request.params[1].isNull()) {
1029 "Querying specific block heights "
1030 "requires coinstatsindex");
1033 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1035 "hash_serialized hash type cannot be "
1036 "queried for a specific block");
1050 if (pindex->nHeight > summary.best_block_height) {
1054 "Unable to get data because coinstatsindex is "
1055 "still syncing. Current height: %d",
1056 summary.best_block_height));
1061 const std::optional<CCoinsStats> maybe_stats =
GetUTXOStats(
1062 coins_view, *blockman, hash_type,
node.rpc_interruption_point,
1063 pindex, index_requested);
1064 if (maybe_stats.has_value()) {
1070 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1071 ret.
pushKV(
"hash_serialized",
1074 if (hash_type == CoinStatsHashType::MUHASH) {
1079 ret.
pushKV(
"transactions",
1083 ret.
pushKV(
"total_unspendable_amount",
1087 if (pindex->nHeight > 0) {
1088 const std::optional<CCoinsStats> maybe_prev_stats =
1090 node.rpc_interruption_point,
1091 pindex->pprev, index_requested);
1092 if (!maybe_prev_stats) {
1094 "Unable to read UTXO set");
1096 prev_stats = maybe_prev_stats.value();
1103 prev_stats.total_prevout_spent_amount);
1104 block_info.
pushKV(
"coinbase",
1106 prev_stats.total_coinbase_amount);
1108 "new_outputs_ex_coinbase",
1110 prev_stats.total_new_outputs_ex_coinbase_amount);
1111 block_info.
pushKV(
"unspendable",
1113 prev_stats.total_unspendable_amount);
1119 prev_stats.total_unspendables_genesis_block);
1122 prev_stats.total_unspendables_bip30);
1125 prev_stats.total_unspendables_scripts);
1127 "unclaimed_rewards",
1129 prev_stats.total_unspendables_unclaimed_rewards);
1130 block_info.
pushKV(
"unspendables", unspendables);
1132 ret.
pushKV(
"block_info", block_info);
1136 "Unable to read UTXO set");
1146 "Returns details about an unspent transaction output.\n",
1149 "The transaction id"},
1152 "Whether to include the mempool. Note that an unspent output that "
1153 "is spent in the mempool won't appear."},
1165 "The hash of the block at the tip of the chain"},
1167 "The number of confirmations"},
1177 "Number of required signatures"},
1179 "The type, eg pubkeyhash"},
1182 "array of eCash addresses",
1191 "\nAs a JSON-RPC call\n" +
1202 int n = request.params[1].get_int();
1204 bool fMempool =
true;
1205 if (!request.params[2].isNull()) {
1206 fMempool = request.params[2].get_bool();
1210 Chainstate &active_chainstate = chainman.ActiveChainstate();
1221 if (!coins_view->
GetCoin(out, coin)) {
1231 ret.
pushKV(
"confirmations", 0);
1233 ret.
pushKV(
"confirmations",
1239 ret.
pushKV(
"scriptPubKey", o);
1250 "Verifies blockchain database.\n",
1255 strprintf(
"How thorough the block verification is:\n - %s",
1259 "The number of blocks to check."},
1262 "Verification finished successfully. If false, check "
1263 "debug.log for reason."},
1268 const int check_level(request.params[0].isNull()
1270 : request.params[0].get_int());
1271 const int check_depth{request.params[1].isNull()
1273 : request.params[1].get_int()};
1278 Chainstate &active_chainstate = chainman.ActiveChainstate();
1280 active_chainstate, active_chainstate.
CoinsTip(),
1288 "getblockchaininfo",
1289 "Returns an object containing various state info regarding blockchain "
1298 "current network name (main, test, regtest)"},
1300 "the height of the most-work fully-validated chain. The "
1301 "genesis block has height 0"},
1303 "the current number of headers we have validated"},
1305 "the hash of the currently best block"},
1312 "estimate of verification progress [0..1]"},
1314 "(debug information) estimate of whether this node is in "
1315 "Initial Block Download mode"},
1317 "total amount of work in active chain, in hexadecimal"},
1319 "the estimated size of the block and undo files on disk"},
1321 "if the blocks are subject to pruning"},
1323 "lowest-height complete block stored (only present if pruning "
1326 "whether automatic pruning is enabled (only present if "
1327 "pruning is enabled)"},
1329 "the target size used by pruning (only present if automatic "
1330 "pruning is enabled)"},
1332 "any network and blockchain warnings"},
1338 const CChainParams &chainparams = config.GetChainParams();
1342 Chainstate &active_chainstate = chainman.ActiveChainstate();
1346 const int height{tip.nHeight};
1350 obj.
pushKV(
"blocks", height);
1351 obj.
pushKV(
"headers", chainman.m_best_header
1352 ? chainman.m_best_header->nHeight
1354 obj.
pushKV(
"bestblockhash", tip.GetBlockHash().GetHex());
1356 obj.
pushKV(
"time", tip.GetBlockTime());
1357 obj.
pushKV(
"mediantime", tip.GetMedianTimePast());
1359 "verificationprogress",
1361 obj.
pushKV(
"initialblockdownload",
1363 obj.
pushKV(
"chainwork", tip.nChainWork.GetHex());
1364 obj.
pushKV(
"size_on_disk",
1369 obj.
pushKV(
"pruneheight",
1372 const bool automatic_pruning{
1374 BlockManager::PRUNE_TARGET_MANUAL};
1375 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1376 if (automatic_pruning) {
1377 obj.
pushKV(
"prune_target_size",
1404 "Return information about all known tips in the block tree, including "
1405 "the main chain as well as orphaned branches.\n",
1418 "zero for main chain, otherwise length of branch connecting "
1419 "the tip to the main chain"},
1421 "status of the chain, \"active\" for the main chain\n"
1422 "Possible values for status:\n"
1423 "1. \"invalid\" This branch contains at "
1424 "least one invalid block\n"
1425 "2. \"parked\" This branch contains at "
1426 "least one parked block\n"
1427 "3. \"headers-only\" Not all blocks for this "
1428 "branch are available, but the headers are valid\n"
1429 "4. \"valid-headers\" All blocks are available for "
1430 "this branch, but they were never fully validated\n"
1431 "5. \"valid-fork\" This branch is not part of "
1432 "the active chain, but is fully validated\n"
1433 "6. \"active\" This is the tip of the "
1434 "active main chain, which is certainly valid"},
1455 std::set<const CBlockIndex *, CompareBlocksByHeight> setTips;
1456 std::set<const CBlockIndex *> setOrphans;
1457 std::set<const CBlockIndex *> setPrevs;
1459 for (
const auto &[
_, block_index] : chainman.
BlockIndex()) {
1460 if (!active_chain.
Contains(&block_index)) {
1461 setOrphans.insert(&block_index);
1462 setPrevs.insert(block_index.pprev);
1466 for (std::set<const CBlockIndex *>::iterator it =
1468 it != setOrphans.end(); ++it) {
1469 if (setPrevs.erase(*it) == 0) {
1470 setTips.insert(*it);
1475 setTips.insert(active_chain.
Tip());
1481 obj.
pushKV(
"height", block->nHeight);
1482 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1484 const int branchLen =
1486 obj.
pushKV(
"branchlen", branchLen);
1489 if (active_chain.
Contains(block)) {
1492 }
else if (block->nStatus.isInvalid()) {
1495 }
else if (block->nStatus.isOnParkedChain()) {
1498 }
else if (!block->HaveTxsDownloaded()) {
1501 status =
"headers-only";
1506 status =
"valid-fork";
1511 status =
"valid-headers";
1516 obj.
pushKV(
"status", status);
1529 "Treats a block as if it were received before others with the same "
1531 "\nA later preciousblock call can override the effect of an earlier "
1533 "\nThe effects of preciousblock are not retained across restarts.\n",
1536 "the hash of the block to mark as precious"},
1557 chainman.ActiveChainstate().PreciousBlock(state, pblockindex);
1574 "Permanently marks a block as invalid, as if it violated a consensus "
1578 "the hash of the block to mark as invalid"},
1598 chainman.ActiveChainstate().InvalidateBlock(state, pblockindex);
1601 chainman.ActiveChainstate().ActivateBestChain(state);
1619 "Marks a block as parked.\n",
1622 "the hash of the block to park"},
1629 const std::string strHash = request.params[0].
get_str();
1634 Chainstate &active_chainstate = chainman.ActiveChainstate();
1651 active_chainstate.
ParkBlock(state, pblockindex);
1672 "Removes invalidity status of a block, its ancestors and its"
1673 "descendants, reconsider them for activation.\n"
1674 "This can be used to undo the effects of invalidateblock.\n",
1677 "the hash of the block to reconsider"},
1696 chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
1700 chainman.ActiveChainstate().ActivateBestChain(state);
1717 "Removes parked status of a block and its descendants, reconsider "
1718 "them for activation.\n"
1719 "This can be used to undo the effects of parkblock.\n",
1722 "the hash of the block to unpark"},
1729 const std::string strHash = request.params[0].
get_str();
1732 Chainstate &active_chainstate = chainman.ActiveChainstate();
1744 if (!pblockindex->nStatus.isOnParkedChain()) {
1782 "Compute statistics about the total number and rate of transactions "
1786 "Size of the window in number of blocks"},
1789 "The hash of the block that ends the window."},
1796 "The timestamp for the final block in the window, "
1800 "The total number of transactions in the chain up to "
1803 "The hash of the final block in the window"},
1805 "The height of the final block in the window."},
1807 "Size of the window in number of blocks"},
1809 "The number of transactions in the window. Only "
1810 "returned if \"window_block_count\" is > 0"},
1812 "The elapsed time in the window in seconds. Only "
1813 "returned if \"window_block_count\" is > 0"},
1815 "The average rate of transactions per second in the "
1816 "window. Only returned if \"window_interval\" is > 0"},
1828 config.GetChainParams().GetConsensus().nPowTargetSpacing;
1830 if (request.params[1].isNull()) {
1843 "Block is not in main chain");
1849 if (request.params[0].isNull()) {
1851 std::max(0, std::min(blockcount, pindex->
nHeight - 1));
1853 blockcount = request.params[0].get_int();
1855 if (blockcount < 0 ||
1856 (blockcount > 0 && blockcount >= pindex->
nHeight)) {
1858 "Invalid block count: "
1859 "should be between 0 and "
1860 "the block's height - 1");
1867 past_block.GetMedianTimePast()};
1874 ret.
pushKV(
"window_final_block_hash",
1877 ret.
pushKV(
"window_block_count", blockcount);
1878 if (blockcount > 0) {
1879 ret.
pushKV(
"window_tx_count", nTxDiff);
1880 ret.
pushKV(
"window_interval", nTimeDiff);
1881 if (nTimeDiff > 0) {
1882 ret.
pushKV(
"txrate",
double(nTxDiff) / nTimeDiff);
1891 template <
typename T>
1893 size_t size = scores.size();
1898 std::sort(scores.begin(), scores.end());
1899 if (size % 2 == 0) {
1900 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1902 return scores[size / 2];
1906 template <
typename T>
static inline bool SetHasKeys(
const std::set<T> &set) {
1909 template <
typename T,
typename Tk,
typename... Args>
1910 static inline bool SetHasKeys(
const std::set<T> &set,
const Tk &key,
1911 const Args &...args) {
1912 return (set.count(key) != 0) ||
SetHasKeys(set, args...);
1917 sizeof(
COutPoint) +
sizeof(uint32_t) +
sizeof(bool);
1923 "Compute per block statistics for a given window. All amounts are "
1927 "It won't work for some heights with pruning.\n",
1932 "The block hash or height of the target block",
1934 {
"",
"string or numeric"}},
1938 "Values to plot (see result below)",
1941 "Selected statistic"},
1943 "Selected statistic"},
1954 "Average feerate (in satoshis per virtual byte)"},
1957 "The block hash (to check for potential reorgs)"},
1960 "The number of inputs (excluding coinbase)"},
1963 "Maximum feerate (in satoshis per virtual byte)"},
1966 "Truncated median fee in the block"},
1968 "Truncated median feerate (in " + ticker +
" per byte)"},
1970 "The block median time past"},
1972 "Truncated median transaction size"},
1975 "Minimum feerate (in satoshis per virtual byte)"},
1981 "Total amount in all outputs (excluding coinbase and thus "
1982 "reward [ie subsidy + totalfee])"},
1984 "Total size of all non-coinbase transactions"},
1987 "The number of transactions (including coinbase)"},
1989 "The increase/decrease in the number of unspent outputs"},
1991 "The increase/decrease in size for the utxo index (not "
1992 "discounting op_return and similar)"},
1997 R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
1999 R
"(1000 '["minfeerate","avgfeerate"]')") +
2002 R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2004 R
"(1000, ["minfeerate","avgfeerate"])")},
2011 std::set<std::string> stats;
2012 if (!request.params[1].isNull()) {
2014 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2015 const std::string stat = stats_univalue[i].
get_str();
2026 const bool do_all = stats.size() == 0;
2027 const bool do_mediantxsize =
2028 do_all || stats.count(
"mediantxsize") != 0;
2029 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
2030 const bool do_medianfeerate =
2031 do_all || stats.count(
"medianfeerate") != 0;
2032 const bool loop_inputs =
2033 do_all || do_medianfee || do_medianfeerate ||
2034 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
2035 "avgfeerate",
"minfee",
"maxfee",
"minfeerate",
2037 const bool loop_outputs =
2038 do_all || loop_inputs || stats.count(
"total_out");
2039 const bool do_calculate_size =
2040 do_mediantxsize || loop_inputs ||
2041 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
2044 const int64_t blockMaxSize = config.GetMaxBlockSize();
2052 int64_t maxtxsize = 0;
2053 int64_t mintxsize = blockMaxSize;
2054 int64_t outputs = 0;
2055 int64_t total_size = 0;
2056 int64_t utxo_size_inc = 0;
2057 std::vector<Amount> fee_array;
2058 std::vector<Amount> feerate_array;
2059 std::vector<int64_t> txsize_array;
2061 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2062 const auto &tx = block.
vtx.at(i);
2063 outputs += tx->vout.size();
2066 for (
const CTxOut &out : tx->vout) {
2067 tx_total_out += out.
nValue;
2074 if (tx->IsCoinBase()) {
2079 inputs += tx->vin.size();
2081 total_out += tx_total_out;
2083 int64_t tx_size = 0;
2084 if (do_calculate_size) {
2085 tx_size = tx->GetTotalSize();
2086 if (do_mediantxsize) {
2087 txsize_array.push_back(tx_size);
2089 maxtxsize = std::max(maxtxsize, tx_size);
2090 mintxsize = std::min(mintxsize, tx_size);
2091 total_size += tx_size;
2096 const auto &txundo = blockUndo.
vtxundo.at(i - 1);
2097 for (
const Coin &coin : txundo.vprevout) {
2100 tx_total_in += prevoutput.
nValue;
2106 Amount txfee = tx_total_in - tx_total_out;
2109 fee_array.push_back(txfee);
2111 maxfee = std::max(maxfee, txfee);
2112 minfee = std::min(minfee, txfee);
2115 Amount feerate = txfee / tx_size;
2116 if (do_medianfeerate) {
2117 feerate_array.push_back(feerate);
2119 maxfeerate = std::max(maxfeerate, feerate);
2120 minfeerate = std::min(minfeerate, feerate);
2126 block.
vtx.size() > 1
2127 ? (totalfee /
int((block.
vtx.size() - 1)))
2129 ret_all.
pushKV(
"avgfeerate", total_size > 0
2130 ? (totalfee / total_size)
2132 ret_all.
pushKV(
"avgtxsize",
2133 (block.
vtx.size() > 1)
2134 ? total_size / (block.
vtx.size() - 1)
2136 ret_all.
pushKV(
"blockhash", pindex.GetBlockHash().GetHex());
2137 ret_all.
pushKV(
"height", (int64_t)pindex.nHeight);
2138 ret_all.
pushKV(
"ins", inputs);
2139 ret_all.
pushKV(
"maxfee", maxfee);
2140 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2141 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2143 ret_all.
pushKV(
"medianfeerate",
2145 ret_all.
pushKV(
"mediantime", pindex.GetMedianTimePast());
2146 ret_all.
pushKV(
"mediantxsize",
2153 ret_all.
pushKV(
"mintxsize",
2154 mintxsize == blockMaxSize ? 0 : mintxsize);
2155 ret_all.
pushKV(
"outs", outputs);
2158 ret_all.
pushKV(
"time", pindex.GetBlockTime());
2159 ret_all.
pushKV(
"total_out", total_out);
2160 ret_all.
pushKV(
"total_size", total_size);
2161 ret_all.
pushKV(
"totalfee", totalfee);
2162 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
2163 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2164 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2171 for (
const std::string &stat : stats) {
2172 const UniValue &value = ret_all[stat];
2176 strprintf(
"Invalid selected statistic %s", stat));
2187 static bool FindScriptPubKey(std::atomic<int> &scan_progress,
2188 const std::atomic<bool> &should_abort,
2190 const std::set<CScript> &needles,
2191 std::map<COutPoint, Coin> &out_results,
2192 std::function<
void()> &interruption_point) {
2195 while (cursor->
Valid()) {
2201 if (++
count % 8192 == 0) {
2202 interruption_point();
2208 if (
count % 256 == 0) {
2211 uint32_t high = 0x100 * *txid.
begin() + *(txid.
begin() + 1);
2212 scan_progress = int(high * 100.0 / 65536.0 + 0.5);
2215 out_results.emplace(key, coin);
2219 scan_progress = 100;
2255 "Scans the unspent transaction output set for entries that match "
2256 "certain output descriptors.\n"
2257 "Examples of output descriptors are:\n"
2258 " addr(<address>) Outputs whose scriptPubKey "
2259 "corresponds to the specified address (does not include P2PK)\n"
2260 " raw(<hex script>) Outputs whose scriptPubKey "
2261 "equals the specified hex scripts\n"
2262 " combo(<pubkey>) P2PK and P2PKH outputs for "
2263 "the given pubkey\n"
2264 " pkh(<pubkey>) P2PKH outputs for the given "
2266 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
2267 "the given threshold and pubkeys\n"
2268 "\nIn the above, <pubkey> either refers to a fixed public key in "
2269 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2270 "or more path elements separated by \"/\", and optionally ending in "
2271 "\"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2272 "unhardened or hardened child keys.\n"
2273 "In the latter case, a range needs to be specified by below if "
2274 "different from 1000.\n"
2275 "For more information on output descriptors, see the documentation in "
2276 "the doc/descriptors.md file.\n",
2279 "The action to execute\n"
2280 " \"start\" for starting a "
2282 " \"abort\" for aborting the "
2283 "current scan (returns true when abort was successful)\n"
2285 "progress report (in %) of the current scan"},
2289 "Array of scan objects. Required for \"start\" action\n"
2290 " Every scan object is either a "
2291 "string descriptor or an object:",
2294 "An output descriptor"},
2299 "An object with output descriptor and metadata",
2302 "An output descriptor"},
2304 "The range of HD chain indexes to explore (either "
2305 "end or [begin,end])"},
2309 "[scanobjects,...]"},
2313 RPCResult{
"When action=='status' and no scan is in progress",
2316 "When action=='status' and scan is in progress",
2324 "When action=='start'",
2330 "Whether the scan was completed"},
2332 "The number of unspent transaction outputs scanned"},
2334 "The current block height (index)"},
2336 "The hash of the block at the tip of the chain"},
2346 "The transaction id"},
2351 "A specialized descriptor for the matched "
2354 "The total amount in " + ticker +
2355 " of the unspent output"},
2357 "Height of the unspent transaction output"},
2361 "The total amount of all found unspent outputs in " +
2368 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR});
2371 if (request.params[0].get_str() ==
"status") {
2379 }
else if (request.params[0].get_str() ==
"abort") {
2388 }
else if (request.params[0].get_str() ==
"start") {
2392 "Scan already in progress, use action "
2393 "\"abort\" or \"status\"");
2396 if (request.params.size() < 2) {
2398 "scanobjects argument is required for "
2399 "the start action");
2402 std::set<CScript> needles;
2403 std::map<CScript, std::string> descriptors;
2412 for (
const auto &script : scripts) {
2413 std::string inferred =
2415 needles.emplace(script);
2416 descriptors.emplace(std::move(script),
2417 std::move(inferred));
2423 std::vector<CTxOut> input_txos;
2424 std::map<COutPoint, Coin> coins;
2428 std::unique_ptr<CCoinsViewCursor> pcursor;
2434 Chainstate &active_chainstate = chainman.ActiveChainstate();
2440 bool res = FindScriptPubKey(
2442 needles, coins,
node.rpc_interruption_point);
2443 result.
pushKV(
"success", res);
2448 for (
const auto &it : coins) {
2450 const Coin &coin = it.second;
2452 input_txos.push_back(txo);
2457 unspent.
pushKV(
"vout", int32_t(outpoint.
GetN()));
2465 result.
pushKV(
"unspents", unspents);
2466 result.
pushKV(
"total_amount", total_in);
2478 "Retrieve a BIP 157 content filter for a particular block.\n",
2481 "The hash of the block"},
2483 "The type name of the filter"},
2490 "the hex-encoded filter data"},
2492 "the hex-encoded filter header"},
2496 "\"00000000c937983704a73af28acdec37b049d214a"
2497 "dbda81d7e2a3dd146f6ed09\" \"basic\"") +
2499 "\"00000000c937983704a73af28acdec37b049d214adbda81d7"
2500 "e2a3dd146f6ed09\", \"basic\"")},
2505 std::string filtertype_name =
"basic";
2506 if (!request.params[1].isNull()) {
2507 filtertype_name = request.params[1].get_str();
2513 "Unknown filtertype");
2519 "Index is not enabled for filtertype " +
2524 bool block_was_connected;
2534 block_was_connected =
2538 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2545 std::string errmsg =
"Filter not found.";
2547 if (!block_was_connected) {
2549 errmsg +=
" Block was not connected to active chain.";
2550 }
else if (!index_ready) {
2552 errmsg +=
" Block filters are still in the process of "
2556 errmsg +=
" This error is unexpected and indicates index "
2579 "Write the serialized UTXO set to disk.\n",
2582 "path to the output file. If relative, will be prefixed by "
2590 "the number of coins written in the snapshot"},
2592 "the hash of the base of the snapshot"},
2594 "the height of the base of the snapshot"},
2596 "the absolute path that the snapshot was written to"},
2598 "the hash of the UTXO set contents"},
2600 "the number of transactions in the chain up to and "
2601 "including the base block"},
2608 args.GetDataDirNet(),
fs::u8path(request.params[0].get_str()));
2612 args.GetDataDirNet(),
2613 fs::u8path(request.params[0].get_str() +
".incomplete"));
2618 " already exists. If you are sure this "
2619 "is what you want, "
2620 "move it out of the way first");
2627 node,
node.chainman->ActiveChainstate(), afile, path, temppath);
2628 fs::rename(temppath, path);
2638 std::unique_ptr<CCoinsViewCursor> pcursor;
2639 std::optional<CCoinsStats> maybe_stats;
2661 CoinStatsHashType::HASH_SERIALIZED,
2662 node.rpc_interruption_point);
2668 std::unique_ptr<CCoinsViewCursor>(chainstate.
CoinsDB().
Cursor());
2674 strprintf(
"writing UTXO snapshot at height %s (%s) to file %s (via %s)",
2685 unsigned int iter{0};
2687 while (pcursor->Valid()) {
2688 if (iter % 5000 == 0) {
2689 node.rpc_interruption_point();
2692 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
2703 result.
pushKV(
"coins_written", maybe_stats->coins_count);
2707 result.
pushKV(
"txoutset_hash", maybe_stats->hashSerialized.ToString());
2750 for (
const auto &c : commands) {
bool MoneyRange(const Amount nValue)
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
static RPCHelpMan getblock()
static int ComputeNextBlockAndDepth(const CBlockIndex *tip, const CBlockIndex *blockindex, const CBlockIndex *&next)
static RPCHelpMan getdifficulty()
static std::atomic< bool > g_scan_in_progress
static bool SetHasKeys(const std::set< T > &set)
static RPCHelpMan reconsiderblock()
static T CalculateTruncatedMedian(std::vector< T > &scores)
static RPCHelpMan invalidateblock()
static RPCHelpMan syncwithvalidationinterfacequeue()
static RPCHelpMan getchaintips()
static RPCHelpMan gettxoutsetinfo()
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 CBlockUndo GetUndoChecked(BlockManager &blockman, const CBlockIndex *pblockindex)
static RPCHelpMan getblockfilter()
static RPCHelpMan getbestblockhash()
RPCHelpMan getblockchaininfo()
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
static RPCHelpMan getchaintxstats()
static RPCHelpMan waitforblock()
static RPCHelpMan getblockfrompeer()
static const CBlockIndex * ParseHashOrHeight(const UniValue ¶m, ChainstateManager &chainman)
static RPCHelpMan getblockhash()
void RegisterBlockchainRPCCommands(CRPCTable &t)
static RPCHelpMan verifychain()
static std::atomic< bool > g_should_abort_scan
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
Block header to JSON.
static RPCHelpMan waitforblockheight()
static RPCHelpMan pruneblockchain()
static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange)
static RPCHelpMan getblockheader()
static CBlock GetBlockChecked(const Config &config, BlockManager &blockman, const CBlockIndex *pblockindex)
UniValue CreateUTXOSnapshot(NodeContext &node, Chainstate &chainstate, AutoFile &afile, const fs::path &path, const fs::path &temppath)
Helper to create UTXO snapshots given a chainstate and a file handle.
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...
#define CHECK_NONFATAL(condition)
Identity function.
Non-refcounted RAII wrapper for FILE*.
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 GetChainTxCount() const
Get the number of transaction in the chain so far.
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 NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
const ChainTxData & TxData() const
const Consensus::Params & GetConsensus() 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
Retrieve the Coin (unspent transaction output) for a given outpoint.
Double ended buffer combining vector and stream-like interfaces.
An outpoint - a combination of a transaction hash and an index n into its vout.
const TxId & GetTxId() const
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.
CChain m_chain
The current chain of blockheaders we consult and build on.
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
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.
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr, bool skip_checkblockindex=false) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Find the best known block, and make it the tip of the block chain.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
void ClearAvalancheFinalizedBlock() EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Clear avalanche finalization.
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...
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const CChainParams & GetParams() const
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const Consensus::Params & GetConsensus() const
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
uint32_t GetHeight() const
virtual const CChainParams & GetChainParams() const =0
Different type to mark Mutex at global scope.
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.
const std::string & get_str() const
const std::vector< UniValue > & getValues() const
bool push_back(const UniValue &val)
const UniValue & get_array() const
bool pushKV(const std::string &key, const 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...
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.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
#define 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.
const CBlockIndex * GetFirstStoredBlock(const CBlockIndex *start_block)
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params ¶ms)
Functions for disk access for blocks.
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
std::optional< CCoinsStats > GetUTXOStats(CCoinsView *view, BlockManager &blockman, CoinStatsHashType hash_type, const std::function< void()> &interruption_point, const CBlockIndex *pindex, bool index_requested)
Calculate statistics about the unspent transaction output set.
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_INVALID_ADDRESS_OR_KEY
Invalid address or key.
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
std::string HelpExampleCli(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 ...
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
size_t GetSerializeSize(const T &t, int nVersion=0)
bool IsRPCRunning()
Query whether RPC is running.
int RPCSerializationFlags()
Retrieves any serialization flags requested in command line argument.
ArgsManager & EnsureAnyArgsman(const std::any &context)
ChainstateManager & EnsureAnyChainman(const std::any &context)
NodeContext & EnsureAnyNodeContext(const std::any &context)
PeerManager & EnsurePeerman(const NodeContext &node)
CTxMemPool & EnsureMemPool(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
static 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.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
@ 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.
@ OBJ_EMPTY
Special type to allow empty OBJ.
A TxId is the identifier of a transaction.
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.
Amount total_unspendables_unclaimed_rewards
Total cumulative amount of coins lost due to unclaimed miner rewards up to and including this block.
Amount total_prevout_spent_amount
Total cumulative amount of prevouts spent up to and including this block.
bool index_used
Signals if the coinstatsindex was used to retrieve the statistics.
Amount total_unspendable_amount
Total cumulative amount of unspendable coins up to and including this block.
Amount total_new_outputs_ex_coinbase_amount
Total cumulative amount of outputs created up to and including this block.
Amount total_unspendables_bip30
The two unspendable coinbase outputs total amount caused by BIP30.
uint64_t nTransactionOutputs
Amount total_unspendables_scripts
Total cumulative amount of outputs sent to unspendable scripts (OP_RETURN for example) up to and incl...
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 const unsigned int DEFAULT_CHECKLEVEL
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
static const signed int DEFAULT_CHECKBLOCKS
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static const int PROTOCOL_VERSION
network protocol versioning
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.