8 #include <blockfilter.h> 51 #include <condition_variable> 80 int nShift = (blockindex->
nBits >> 24) & 0xff;
82 (double)0x0000ffff / (
double)(blockindex->
nBits & 0x00ffffff);
101 if (next && next->
pprev == blockindex) {
105 return blockindex == tip ? 1 : -1;
114 const int height{param.
getInt<
int>()};
118 const int current_tip{active_chain.
Height()};
119 if (height > current_tip) {
123 return active_chain[height];
145 result.
pushKV(
"confirmations", confirmations);
156 result.
pushKV(
"nTx", (uint64_t)blockindex->
nTx);
158 if (blockindex->
pprev)
186 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
189 const CTxUndo* txundo = (have_undo && i > 0) ? &blockUndo.
vtxundo.at(i - 1) :
nullptr;
205 "\nReturns the height of the most-work fully-validated chain.\n" 206 "The genesis block has height 0.\n",
226 "\nReturns the hash of the best (tip) block in the most-work fully-validated chain.\n",
248 latestblock.height = pindex->
nHeight;
256 "\nWaits for a specific new block and returns useful info about it.\n" 257 "\nReturns the current block on timeout or exit.\n",
274 if (!request.params[0].isNull())
275 timeout = request.params[0].
getInt<
int>();
298 "\nWaits for a specific new block and returns useful info about it.\n" 299 "\nReturns the current block on timeout or exit.\n",
311 HelpExampleCli(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\" 1000")
312 +
HelpExampleRpc(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
320 if (!request.params[1].isNull())
321 timeout = request.params[1].getInt<
int>();
344 "\nWaits for (at least) block height and returns the height and hash\n" 345 "of the current tip.\n" 346 "\nReturns the current block on timeout or exit.\n",
365 int height = request.params[0].
getInt<
int>();
367 if (!request.params[1].isNull())
368 timeout = request.params[1].getInt<
int>();
389 return RPCHelpMan{
"syncwithvalidationinterfacequeue",
390 "\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n",
408 "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
411 RPCResult::Type::NUM,
"",
"the proof-of-work difficulty as a multiple of the minimum difficulty."},
429 "Attempt to fetch block from a given peer.\n\n" 430 "We must have the header for this block, e.g. using submitheader.\n" 431 "Subsequent calls for the same block and a new peer will cause the response from the previous peer to be ignored.\n\n" 432 "Returns an empty JSON object if the request was successfully scheduled.",
439 HelpExampleCli(
"getblockfrompeer",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
440 +
HelpExampleRpc(
"getblockfrompeer",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
454 const NodeId peer_id{request.params[1].getInt<int64_t>()};
463 if (block_has_data) {
467 if (
const auto err{peerman.
FetchBlock(peer_id, *index)}) {
478 "\nReturns hash of block in best-block-chain at height provided.\n",
494 int nHeight = request.params[0].getInt<
int>();
495 if (nHeight < 0 || nHeight > active_chain.
Height())
507 "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" 508 "If verbose is true, returns an Object with information about blockheader <hash>.\n",
518 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
537 HelpExampleCli(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
538 +
HelpExampleRpc(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
544 bool fVerbose =
true;
545 if (!request.params[1].isNull())
546 fVerbose = request.params[1].get_bool();
565 std::string strHex =
HexStr(ssBlock);
578 if (blockman.IsBlockPruned(pblockindex)) {
596 if (blockman.IsBlockPruned(pblockindex)) {
623 {
RPCResult::Type::STR,
"address",
true,
"The Bitcoin address (only if a well-defined address exists)"},
634 "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n" 635 "If verbosity is 1, returns an Object with information about block <hash>.\n" 636 "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction.\n" 637 "If verbosity is 3, returns an Object with information about block <hash> and information about each transaction, including prevout information for inputs (only for unpruned blocks in the current best chain).\n",
640 {
"verbosity|verbose",
RPCArg::Type::NUM,
RPCArg::Default{1},
"0 for hex-encoded data, 1 for a JSON object, 2 for JSON object with transaction data, and 3 for JSON object with transaction data including prevout information for inputs"},
649 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
664 {
RPCResult::Type::STR_HEX,
"chainwork",
"Expected number of hashes required to produce the chain up to this block (in hex)"},
677 {
RPCResult::Type::ELISION,
"",
"The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result"},
696 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
697 +
HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
704 if (!request.params[1].isNull()) {
705 if (request.params[1].isBool()) {
706 verbosity = request.params[1].get_bool() ? 1 : 0;
708 verbosity = request.params[1].getInt<
int>();
732 std::string strHex =
HexStr(ssBlock);
737 if (verbosity == 1) {
739 }
else if (verbosity == 2) {
755 " to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
773 int heightParam = request.params[0].getInt<
int>();
774 if (heightParam < 0) {
780 if (heightParam > 1000000000) {
789 unsigned int height = (
unsigned int) heightParam;
790 unsigned int chainHeight = (
unsigned int) active_chain.
Height();
793 }
else if (height > chainHeight) {
796 LogPrint(
BCLog::RPC,
"Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
804 return static_cast<int64_t
>(last_block->nHeight - 1);
811 if (hash_type_input ==
"hash_serialized_2") {
812 return CoinStatsHashType::HASH_SERIALIZED;
813 }
else if (hash_type_input ==
"muhash") {
814 return CoinStatsHashType::MUHASH;
815 }
else if (hash_type_input ==
"none") {
829 const std::function<
void()>& interruption_point = {},
831 bool index_requested =
true)
855 "\nReturns statistics about the unspent transaction output set.\n" 856 "Note this call may take some time if you are not using coinstatsindex.\n",
858 {
"hash_type",
RPCArg::Type::STR,
RPCArg::Default{
"hash_serialized_2"},
"Which UTXO set hash should be calculated. Options: 'hash_serialized_2' (the legacy algorithm), 'muhash', 'none'."},
859 {
"hash_or_height",
RPCArg::Type::NUM,
RPCArg::DefaultHint{
"the current best block"},
"The block hash or height of the target height (only available with coinstatsindex).",
"", {
"",
"string or numeric"}},
868 {
RPCResult::Type::NUM,
"bogosize",
"Database-independent, meaningless metric indicating the UTXO set size"},
869 {
RPCResult::Type::STR_HEX,
"hash_serialized_2",
true,
"The serialized hash (only present if 'hash_serialized_2' hash_type is chosen)"},
871 {
RPCResult::Type::NUM,
"transactions",
true,
"The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
872 {
RPCResult::Type::NUM,
"disk_size",
true,
"The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
874 {
RPCResult::Type::STR_AMOUNT,
"total_unspendable_amount",
true,
"The total amount of coins permanently excluded from the UTXO set (only available if coinstatsindex is used)"},
875 {
RPCResult::Type::OBJ,
"block_info",
true,
"Info on amounts in the block at this block height (only available if coinstatsindex is used)",
894 HelpExampleCli("gettxoutsetinfo", R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") + 895 HelpExampleCli("-named gettxoutsetinfo", R
"(hash_type='muhash' use_index='false')") + 899 HelpExampleRpc("gettxoutsetinfo", R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")") 907 bool index_requested = request.params[2].isNull() || request.params[2].get_bool();
918 coins_view = &active_chainstate.
CoinsDB();
923 if (!request.params[1].isNull()) {
928 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
932 if (!index_requested) {
944 if (pindex->
nHeight > summary.best_block_height) {
950 const std::optional<CCoinsStats> maybe_stats =
GetUTXOStats(coins_view, *blockman, hash_type,
node.rpc_interruption_point, pindex, index_requested);
951 if (maybe_stats.has_value()) {
957 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
960 if (hash_type == CoinStatsHashType::MUHASH) {
973 const std::optional<CCoinsStats> maybe_prev_stats =
GetUTXOStats(coins_view, *blockman, hash_type,
node.rpc_interruption_point, pindex->
pprev, index_requested);
974 if (!maybe_prev_stats) {
977 prev_stats = maybe_prev_stats.value();
991 block_info.
pushKV(
"unspendables", unspendables);
993 ret.pushKV(
"block_info", block_info);
1006 "\nReturns details about an unspent transaction output.\n",
1010 {
"include_mempool",
RPCArg::Type::BOOL,
RPCArg::Default{
true},
"Whether to include the mempool. Note that an unspent output that is spent in the mempool won't appear."},
1023 {
RPCResult::Type::STR,
"address",
true,
"The Bitcoin address (only if a well-defined address exists)"},
1029 "\nGet unspent transactions\n" 1031 "\nView the details\n" 1033 "\nAs a JSON-RPC call\n" 1045 COutPoint out{hash, request.params[1].getInt<uint32_t>()};
1046 bool fMempool =
true;
1047 if (!request.params[2].isNull())
1048 fMempool = request.params[2].get_bool();
1062 if (!coins_view->
GetCoin(out, coin)) {
1070 ret.pushKV(
"confirmations", 0);
1077 ret.pushKV(
"scriptPubKey", o);
1088 "\nVerifies blockchain database.\n",
1103 const int check_depth{request.params[1].isNull() ?
DEFAULT_CHECKBLOCKS : request.params[1].getInt<
int>()};
1122 rv.
pushKV(
"type",
"buried");
1135 if (blockindex ==
nullptr)
return;
1137 auto get_state_name = [](
const ThresholdState state) -> std::string {
1164 bip9.
pushKV(
"status", get_state_name(current_state));
1166 bip9.
pushKV(
"status_next", get_state_name(next_state));
1171 std::vector<bool> signals;
1180 bip9.
pushKV(
"statistics", statsUV);
1183 sig.reserve(signals.size());
1184 for (
const bool s : signals) {
1185 sig.push_back(s ?
'#' :
'-');
1187 bip9.
pushKV(
"signalling", sig);
1191 rv.
pushKV(
"type",
"bip9");
1205 "Returns an object containing various state info regarding blockchain processing.\n",
1211 {
RPCResult::Type::NUM,
"blocks",
"the height of the most-work fully-validated chain. The genesis block has height 0"},
1218 {
RPCResult::Type::BOOL,
"initialblockdownload",
"(debug information) estimate of whether this node is in Initial Block Download mode"},
1220 {
RPCResult::Type::NUM,
"size_on_disk",
"the estimated size of the block and undo files on disk"},
1222 {
RPCResult::Type::NUM,
"pruneheight",
true,
"height of the last block pruned, plus one (only present if pruning is enabled)"},
1223 {
RPCResult::Type::BOOL,
"automatic_pruning",
true,
"whether automatic pruning is enabled (only present if pruning is enabled)"},
1224 {
RPCResult::Type::NUM,
"prune_target_size",
true,
"the target size used by pruning (only present if automatic pruning is enabled)"},
1239 const int height{tip.nHeight};
1242 obj.
pushKV(
"blocks", height);
1244 obj.
pushKV(
"bestblockhash", tip.GetBlockHash().GetHex());
1246 obj.
pushKV(
"time", tip.GetBlockTime());
1247 obj.
pushKV(
"mediantime", tip.GetMedianTimePast());
1249 obj.
pushKV(
"initialblockdownload", active_chainstate.IsInitialBlockDownload());
1250 obj.
pushKV(
"chainwork", tip.nChainWork.GetHex());
1254 obj.
pushKV(
"pruneheight", chainman.
m_blockman.GetFirstStoredBlock(tip)->nHeight);
1258 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1259 if (automatic_pruning) {
1271 const std::vector<RPCResult> RPCHelpForDeployment{
1273 {
RPCResult::Type::NUM,
"height",
true,
"height of the first block which the rules are or will be enforced (only for \"buried\" type, or \"bip9\" type with \"active\" status)"},
1274 {
RPCResult::Type::BOOL,
"active",
"true if the rules are enforced for the mempool and the next block"},
1277 {
RPCResult::Type::NUM,
"bit",
true,
"the bit (0-28) in the block version field used to signal this softfork (only for \"started\" and \"locked_in\" status)"},
1278 {
RPCResult::Type::NUM_TIME,
"start_time",
"the minimum median time past of a block at which the bit gains its meaning"},
1279 {
RPCResult::Type::NUM_TIME,
"timeout",
"the median time past of a block at which the deployment is considered failed if not yet locked in"},
1280 {
RPCResult::Type::NUM,
"min_activation_height",
"minimum height of blocks for which the rules may be enforced"},
1281 {
RPCResult::Type::STR,
"status",
"status of deployment at specified block (one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\")"},
1284 {
RPCResult::Type::OBJ,
"statistics",
true,
"numeric statistics about signalling for a softfork (only for \"started\" and \"locked_in\" status)",
1287 {
RPCResult::Type::NUM,
"threshold",
true,
"the number of blocks with the version bit set required to activate the feature (only for \"started\" status)"},
1288 {
RPCResult::Type::NUM,
"elapsed",
"the number of blocks elapsed since the beginning of the current period"},
1289 {
RPCResult::Type::NUM,
"count",
"the number of blocks with the version bit set in the current period"},
1290 {
RPCResult::Type::BOOL,
"possible",
true,
"returns false if there are not enough blocks left in this period to pass activation threshold (only for \"started\" status)"},
1292 {
RPCResult::Type::STR,
"signalling",
true,
"indicates blocks that signalled with a # and blocks that did not with a -"},
1313 "Returns an object containing various state info regarding deployments of consensus changes.",
1334 if (request.params[0].isNull()) {
1347 deploymentinfo.
pushKV(
"deployments", DeploymentInfo(blockindex, chainman));
1348 return deploymentinfo;
1371 "Return information about all known tips in the block tree," 1372 " including the main chain as well as orphaned branches.\n",
1380 {
RPCResult::Type::NUM,
"branchlen",
"zero for main chain, otherwise length of branch connecting the tip to the main chain"},
1382 "Possible values for status:\n" 1383 "1. \"invalid\" This branch contains at least one invalid block\n" 1384 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" 1385 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" 1386 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" 1387 "5. \"active\" This is the tip of the active main chain, which is certainly valid"},
1406 std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1407 std::set<const CBlockIndex*> setOrphans;
1408 std::set<const CBlockIndex*> setPrevs;
1410 for (
const auto& [
_, block_index] : chainman.
BlockIndex()) {
1411 if (!active_chain.
Contains(&block_index)) {
1412 setOrphans.insert(&block_index);
1413 setPrevs.insert(block_index.
pprev);
1417 for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) {
1418 if (setPrevs.erase(*it) == 0) {
1419 setTips.insert(*it);
1424 setTips.insert(active_chain.
Tip());
1430 obj.
pushKV(
"height", block->nHeight);
1431 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1433 const int branchLen = block->nHeight - active_chain.
FindFork(block)->
nHeight;
1434 obj.
pushKV(
"branchlen", branchLen);
1437 if (active_chain.
Contains(block)) {
1443 }
else if (!block->HaveTxsDownloaded()) {
1445 status =
"headers-only";
1448 status =
"valid-fork";
1451 status =
"valid-headers";
1456 obj.
pushKV(
"status", status);
1469 "\nTreats a block as if it were received before others with the same work.\n" 1470 "\nA later preciousblock call can override the effect of an earlier one.\n" 1471 "\nThe effects of preciousblock are not retained across restarts.\n",
1509 "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n",
1550 "\nRemoves invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n" 1551 "This can be used to undo the effects of invalidateblock.\n",
1590 "\nCompute statistics about the total number and rate of transactions in the chain.\n",
1599 {
RPCResult::Type::NUM,
"txcount",
"The total number of transactions in the chain up to that point"},
1601 {
RPCResult::Type::NUM,
"window_final_block_height",
"The height of the final block in the window."},
1603 {
RPCResult::Type::NUM,
"window_tx_count",
true,
"The number of transactions in the window. Only returned if \"window_block_count\" is > 0"},
1604 {
RPCResult::Type::NUM,
"window_interval",
true,
"The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0"},
1605 {
RPCResult::Type::NUM,
"txrate",
true,
"The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0"},
1617 if (request.params[1].isNull()) {
1634 if (request.params[0].isNull()) {
1635 blockcount = std::max(0, std::min(blockcount, pindex->
nHeight - 1));
1637 blockcount = request.params[0].getInt<
int>();
1639 if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->
nHeight)) {
1645 const int64_t nTimeDiff{pindex->
GetMedianTimePast() - past_block.GetMedianTimePast()};
1646 const int nTxDiff = pindex->
nChainTx - past_block.nChainTx;
1649 ret.pushKV(
"time", (int64_t)pindex->
nTime);
1652 ret.pushKV(
"window_final_block_height", pindex->
nHeight);
1653 ret.pushKV(
"window_block_count", blockcount);
1654 if (blockcount > 0) {
1655 ret.pushKV(
"window_tx_count", nTxDiff);
1656 ret.pushKV(
"window_interval", nTimeDiff);
1657 if (nTimeDiff > 0) {
1658 ret.pushKV(
"txrate", ((
double)nTxDiff) / nTimeDiff);
1667 template<
typename T>
1670 size_t size = scores.size();
1675 std::sort(scores.begin(), scores.end());
1676 if (size % 2 == 0) {
1677 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1679 return scores[size / 2];
1685 if (scores.empty()) {
1689 std::sort(scores.begin(), scores.end());
1693 total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
1696 int64_t next_percentile_index = 0;
1697 int64_t cumulative_weight = 0;
1698 for (
const auto& element : scores) {
1699 cumulative_weight += element.second;
1700 while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
1701 result[next_percentile_index] = element.first;
1702 ++next_percentile_index;
1708 result[i] = scores.back().first;
1712 template<
typename T>
1713 static inline bool SetHasKeys(
const std::set<T>&
set) {
return false;}
1714 template<
typename T,
typename Tk,
typename... Args>
1715 static inline bool SetHasKeys(
const std::set<T>&
set,
const Tk& key,
const Args&...
args)
1726 "\nCompute per block statistics for a given window. All amounts are in satoshis.\n" 1727 "It won't work for some heights with pruning.\n",
1744 {
RPCResult::Type::ARR_FIXED,
"feerate_percentiles",
true,
"Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
1769 {
RPCResult::Type::NUM,
"total_out",
true,
"Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
1774 {
RPCResult::Type::NUM,
"utxo_increase",
true,
"The increase/decrease in the number of unspent outputs"},
1775 {
RPCResult::Type::NUM,
"utxo_size_inc",
true,
"The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
1778 HelpExampleCli(
"getblockstats", R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") + 1779 HelpExampleCli("getblockstats", R
"(1000 '["minfeerate","avgfeerate"]')") + 1780 HelpExampleRpc("getblockstats", R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") + 1781 HelpExampleRpc("getblockstats", R
"(1000, ["minfeerate","avgfeerate"])") 1789 std::set<std::string> stats;
1790 if (!request.params[1].isNull()) {
1792 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
1793 const std::string stat = stats_univalue[i].
get_str();
1801 const bool do_all = stats.size() == 0;
1802 const bool do_mediantxsize = do_all || stats.count(
"mediantxsize") != 0;
1803 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
1804 const bool do_feerate_percentiles = do_all || stats.count(
"feerate_percentiles") != 0;
1805 const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
1806 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
"avgfeerate",
"minfee",
"maxfee",
"minfeerate",
"maxfeerate");
1807 const bool loop_outputs = do_all || loop_inputs || stats.count(
"total_out");
1808 const bool do_calculate_size = do_mediantxsize ||
1809 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
"maxtxsize",
"swtotal_size");
1810 const bool do_calculate_weight = do_all ||
SetHasKeys(stats,
"total_weight",
"avgfeerate",
"swtotal_weight",
"avgfeerate",
"feerate_percentiles",
"minfeerate",
"maxfeerate");
1811 const bool do_calculate_sw = do_all ||
SetHasKeys(stats,
"swtxs",
"swtotal_size",
"swtotal_weight");
1820 int64_t maxtxsize = 0;
1822 int64_t outputs = 0;
1823 int64_t swtotal_size = 0;
1824 int64_t swtotal_weight = 0;
1826 int64_t total_size = 0;
1827 int64_t total_weight = 0;
1828 int64_t utxo_size_inc = 0;
1829 std::vector<CAmount> fee_array;
1830 std::vector<std::pair<CAmount, int64_t>> feerate_array;
1831 std::vector<int64_t> txsize_array;
1833 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
1834 const auto& tx = block.
vtx.at(i);
1835 outputs += tx->vout.size();
1839 for (
const CTxOut& out : tx->vout) {
1840 tx_total_out += out.
nValue;
1845 if (tx->IsCoinBase()) {
1849 inputs += tx->vin.size();
1850 total_out += tx_total_out;
1852 int64_t tx_size = 0;
1853 if (do_calculate_size) {
1855 tx_size = tx->GetTotalSize();
1856 if (do_mediantxsize) {
1857 txsize_array.push_back(tx_size);
1859 maxtxsize = std::max(maxtxsize, tx_size);
1860 mintxsize = std::min(mintxsize, tx_size);
1861 total_size += tx_size;
1865 if (do_calculate_weight) {
1867 total_weight += weight;
1870 if (do_calculate_sw && tx->HasWitness()) {
1872 swtotal_size += tx_size;
1873 swtotal_weight += weight;
1878 const auto& txundo = blockUndo.
vtxundo.at(i - 1);
1879 for (
const Coin& coin: txundo.vprevout) {
1882 tx_total_in += prevoutput.
nValue;
1886 CAmount txfee = tx_total_in - tx_total_out;
1889 fee_array.push_back(txfee);
1891 maxfee = std::max(maxfee, txfee);
1892 minfee = std::min(minfee, txfee);
1897 if (do_feerate_percentiles) {
1898 feerate_array.emplace_back(std::make_pair(feerate, weight));
1900 maxfeerate = std::max(maxfeerate, feerate);
1901 minfeerate = std::min(minfeerate, feerate);
1910 feerates_res.
push_back(feerate_percentiles[i]);
1914 ret_all.
pushKV(
"avgfee", (block.
vtx.size() > 1) ? totalfee / (block.
vtx.size() - 1) : 0);
1916 ret_all.
pushKV(
"avgtxsize", (block.
vtx.size() > 1) ? total_size / (block.
vtx.size() - 1) : 0);
1918 ret_all.
pushKV(
"feerate_percentiles", feerates_res);
1920 ret_all.
pushKV(
"ins", inputs);
1921 ret_all.
pushKV(
"maxfee", maxfee);
1922 ret_all.
pushKV(
"maxfeerate", maxfeerate);
1923 ret_all.
pushKV(
"maxtxsize", maxtxsize);
1928 ret_all.
pushKV(
"minfeerate", (minfeerate ==
MAX_MONEY) ? 0 : minfeerate);
1930 ret_all.
pushKV(
"outs", outputs);
1932 ret_all.
pushKV(
"swtotal_size", swtotal_size);
1933 ret_all.
pushKV(
"swtotal_weight", swtotal_weight);
1934 ret_all.
pushKV(
"swtxs", swtxs);
1936 ret_all.
pushKV(
"total_out", total_out);
1937 ret_all.
pushKV(
"total_size", total_size);
1938 ret_all.
pushKV(
"total_weight", total_weight);
1939 ret_all.
pushKV(
"totalfee", totalfee);
1940 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
1941 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
1942 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
1949 for (
const std::string& stat : stats) {
1950 const UniValue& value = ret_all[stat];
1954 ret.pushKV(stat, value);
1963 bool FindScriptPubKey(std::atomic<int>& scan_progress,
const std::atomic<bool>& should_abort, int64_t&
count,
CCoinsViewCursor* cursor,
const std::set<CScript>& needles, std::map<COutPoint, Coin>& out_results, std::function<
void()>& interruption_point)
1967 while (cursor->
Valid()) {
1970 if (!cursor->
GetKey(key) || !cursor->
GetValue(coin))
return false;
1971 if (++
count % 8192 == 0) {
1972 interruption_point();
1978 if (
count % 256 == 0) {
1981 scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
1984 out_results.emplace(key, coin);
1988 scan_progress = 100;
2025 const std::string EXAMPLE_DESCRIPTOR_RAW =
"raw(76a91411b366edfc0a8b66feebae5c2e25a7b6a5d1cf3188ac)#fm24fxxy";
2028 "\nScans the unspent transaction output set for entries that match certain output descriptors.\n" 2029 "Examples of output descriptors are:\n" 2030 " addr(<address>) Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\n" 2031 " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n" 2032 " combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n" 2033 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n" 2034 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n" 2035 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n" 2036 "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n" 2037 "unhardened or hardened child keys.\n" 2038 "In the latter case, a range needs to be specified by below if different from 1000.\n" 2039 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
2042 "\"start\" for starting a scan\n" 2043 "\"abort\" for aborting the current scan (returns true when abort was successful)\n" 2044 "\"status\" for progress report (in %) of the current scan"},
2046 "Every scan object is either a string descriptor or an object:",
2055 "[scanobjects,...]"},
2077 RPCResult{
"when action=='abort'",
RPCResult::Type::BOOL,
"success",
"True if scan will be aborted (not necessarily before this RPC returns), or false if there is no scan to abort"},
2085 HelpExampleCli(
"scantxoutset",
"start \'[\"" + EXAMPLE_DESCRIPTOR_RAW +
"\"]\'") +
2088 HelpExampleRpc(
"scantxoutset",
"\"start\", [\"" + EXAMPLE_DESCRIPTOR_RAW +
"\"]") +
2094 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR});
2097 if (request.params[0].get_str() ==
"status") {
2105 }
else if (request.params[0].get_str() ==
"abort") {
2114 }
else if (request.params[0].get_str() ==
"start") {
2120 if (request.params.size() < 2) {
2124 std::set<CScript> needles;
2125 std::map<CScript, std::string> descriptors;
2132 for (
CScript& script : scripts) {
2134 needles.emplace(script);
2135 descriptors.emplace(std::move(script), std::move(inferred));
2141 std::vector<CTxOut> input_txos;
2142 std::map<COutPoint, Coin> coins;
2145 std::unique_ptr<CCoinsViewCursor> pcursor;
2157 result.
pushKV(
"success", res);
2162 for (
const auto& it : coins) {
2164 const Coin& coin = it.second;
2166 input_txos.push_back(txo);
2171 unspent.
pushKV(
"vout", (int32_t)outpoint.
n);
2179 result.
pushKV(
"unspents", unspents);
2192 "\nRetrieve a BIP 157 content filter for a particular block.\n",
2204 HelpExampleCli(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"") +
2205 HelpExampleRpc(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\", \"basic\"")
2211 if (!request.params[1].isNull()) {
2212 filtertype_name = request.params[1].get_str();
2226 bool block_was_connected;
2237 bool index_ready = index->BlockUntilSyncedToCurrentChain();
2244 std::string errmsg =
"Filter not found.";
2246 if (!block_was_connected) {
2248 errmsg +=
" Block was not connected to active chain.";
2249 }
else if (!index_ready) {
2251 errmsg +=
" Block filters are still in the process of being indexed.";
2254 errmsg +=
" This error is unexpected and indicates index corruption.";
2262 ret.pushKV(
"header", filter_header.
GetHex());
2277 "Write the serialized UTXO set to disk.",
2289 {
RPCResult::Type::NUM,
"nchaintx",
"the number of transactions in the chain up to and including the base block"},
2306 path.
u8string() +
" already exists. If you are sure this is what you want, " 2307 "move it out of the way first");
2312 if (afile.IsNull()) {
2315 "Couldn't open file " + temppath.
u8string() +
" for writing.");
2320 node,
node.chainman->ActiveChainstate(), afile, path, temppath);
2321 fs::rename(temppath, path);
2323 result.
pushKV(
"path", path.u8string());
2336 std::unique_ptr<CCoinsViewCursor> pcursor;
2337 std::optional<CCoinsStats> maybe_stats;
2376 unsigned int iter{0};
2378 while (pcursor->Valid()) {
2379 if (iter % 5000 == 0)
node.rpc_interruption_point();
2381 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
2392 result.
pushKV(
"coins_written", maybe_stats->coins_count);
2396 result.
pushKV(
"txoutset_hash", maybe_stats->hashSerialized.ToString());
2433 for (
const auto& c : commands) {
2434 t.appendCommand(c.name, &c);
std::shared_ptr< const CTransaction > CTransactionRef
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 ...
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
static int64_t GetTransactionWeight(const CTransaction &tx)
int min_activation_height
If lock in occurs, delay activation until at least this block height.
std::string NetworkIDString() const
Return the network string.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
static RPCHelpMan syncwithvalidationinterfacequeue()
Display status of an in-progress BIP9 softfork.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
void push_back(UniValue val)
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
static constexpr int NUM_GETBLOCKSTATS_PERCENTILES
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static const int SERIALIZE_TRANSACTION_NO_WITNESS
A flag that is ORed into the protocol version to designate that a transaction should be (un)serialize...
static RPCHelpMan getblock()
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
The same as previous option with information about prevouts if available.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
const std::vector< UniValue > & getValues() const
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
static const int WITNESS_SCALE_FACTOR
CBlockIndex * m_best_header
Best header we've seen so far (used for getheaders queries' starting points).
#define LogPrint(category,...)
int64_t GetBlockTime() const
FILE * fopen(const fs::path &p, const char *mode)
CBlockIndex * pprev
pointer to the index of the predecessor of this block
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool IsRPCRunning()
Query whether RPC is running.
static RPCHelpMan getblockfrompeer()
static CBlock GetBlockChecked(BlockManager &blockman, const CBlockIndex *pblockindex) EXCLUSIVE_LOCKS_REQUIRED(
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, TxVerbosity verbosity)
Block description to JSON.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances...
CTxMemPool & EnsureMemPool(const NodeContext &node)
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
TxVerbosity
Verbose level for block's transaction.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
An in-memory indexed chain of blocks.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
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.
CAmount total_new_outputs_ex_coinbase_amount
Total cumulative amount of outputs created up to and including this block.
bool index_used
Signals if the coinstatsindex was used to retrieve the statistics.
Comparison function for sorting the getchaintips heads.
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...
int StateSinceHeight(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Get the block height at which the BIP9 deployment switched into the state for the block after pindexP...
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
static GlobalMutex cs_blockchange
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
static constexpr int DEFAULT_CHECKLEVEL
bool MoneyRange(const CAmount &nValue)
CBlockHeader GetBlockHeader() const
#define CHECK_NONFATAL(condition)
Identity function.
int Height() const
Return the maximal height in the chain.
CTxOut out
unspent transaction output
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep, [[maybe_unused]] VersionBitsCache &versionbitscache)
Determine if a deployment is active for the next block.
std::optional< CAmount > total_amount
The total amount, or nullopt if an overflow occurred calculating it.
unsigned int fCoinBase
whether containing transaction was a coinbase
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
Block header to JSON.
#define LOG_TIME_SECONDS(end_msg)
const std::string & get_str() const
const UniValue & get_array() const
Double ended buffer combining vector and stream-like interfaces.
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index.
static RPCHelpMan scantxoutset()
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
CChain m_chain
The current chain of blockheaders we consult and build on.
static BIP9Stats Statistics(const CBlockIndex *pindex, const Consensus::Params ¶ms, Consensus::DeploymentPos pos, std::vector< bool > *signalling_blocks=nullptr)
Get the numerical statistics for a given deployment for the signalling period that includes pindex...
static std::atomic< int > g_scan_progress
RAII object to prevent concurrency issue when scanning the txout set.
Non-refcounted RAII wrapper for FILE*.
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
int threshold
Number of blocks with the version bit set required to activate the softfork.
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
CAmount total_unspendables_scripts
Total cumulative amount of outputs sent to unspendable scripts (OP_RETURN for example) up to and incl...
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
static int ComputeNextBlockAndDepth(const CBlockIndex *tip, const CBlockIndex *blockindex, const CBlockIndex *&next)
bool isSpent(const COutPoint &outpoint) const
Invalid, missing or duplicate parameter.
CAmount total_coinbase_amount
Total cumulative amount of coinbase outputs up to and including this block.
size_t GetSerializeSize(const T &t, int nVersion=0)
RPCHelpMan getblockchaininfo()
VersionBitsCache m_versionbitscache
Track versionbit status.
bool DeploymentEnabled(const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is enabled (can ever be active)
CoinStatsHashType ParseHashType(const std::string &hash_type_input)
CoinsViewScanReserver()=default
static RPCHelpMan getchaintxstats()
ThresholdState State(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Get the BIP9 state for a given deployment for the block after pindexPrev.
const RPCResult getblock_vin
int64_t CAmount
Amount in satoshis (Can be negative)
CAmount total_unspendables_unclaimed_rewards
Total cumulative amount of coins lost due to unclaimed miner rewards up to and including this block...
CAmount total_unspendables_bip30
The two unspendable coinbase outputs total amount caused by BIP30.
static T CalculateTruncatedMedian(std::vector< T > &scores)
std::string GetAllOutputTypes()
Gets all existing output types formatted for RPC help sections.
virtual bool GetValue(Coin &coin) const =0
uint256 GetBlockHash() const
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
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...
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0...
static RPCHelpMan getblockfilter()
uint64_t PruneAfterHeight() const
Special type that is a STR with only hex chars.
NodeContext struct containing references to chain state and connection state.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
static std::atomic< bool > g_scan_in_progress
UniValue JSONRPCError(int code, const std::string &message)
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
Special string with only hex chars.
static std::string PathToString(const path &path)
Convert path object to a byte string.
static CBlockUndo GetUndoChecked(BlockManager &blockman, const CBlockIndex *pblockindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
uint64_t nPruneTarget
Number of bytes of block files that we're trying to stay below.
virtual bool Valid() const =0
Chainstate stores and provides an API to update our local knowledge of the current best chain...
static RPCHelpMan waitfornewblock()
Include TXID, inputs, outputs, and other common block's transaction information.
static void SoftForkDescPushBack(const CBlockIndex *blockindex, UniValue &softforks, const ChainstateManager &chainman, Consensus::BuriedDeployment dep)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
static const CBlockIndex * ParseHashOrHeight(const UniValue ¶m, ChainstateManager &chainman)
void RegisterBlockchainRPCCommands(CRPCTable &t)
Abstract view on the open txout dataset.
int period
Length of blocks of the BIP9 signalling period.
int DeploymentHeight(BuriedDeployment dep) const
std::string ToString() const
bilingual_str _(const char *psz)
Translation function.
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
static RPCHelpMan getblockheader()
static std::condition_variable cond_blockchange
Complete block filter struct as defined in BIP 157.
CAmount total_prevout_spent_amount
Total cumulative amount of prevouts spent up to and including this block.
Special array that has a fixed number of entries.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
int64_t nStartTime
Start MedianTime for version bits miner confirmation.
int64_t nPowTargetSpacing
bool VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
static RPCHelpMan getblockstats()
const Consensus::Params & GetConsensus() const
const std::string CURRENCY_UNIT
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
General application defined errors.
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
int count
Number of blocks with the version bit set since the beginning of the current period.
#define WAIT_LOCK(cs, name)
An output of a transaction.
CAmount total_unspendable_amount
Total cumulative amount of unspendable coins up to and including this block.
std::string ToString() const
virtual std::optional< std::string > FetchBlock(NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
An outpoint - a combination of a transaction hash and an index n into its vout.
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Special numeric to denote unix epoch time.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
int64_t GetMedianTimePast() const
static RPCHelpMan getdifficulty()
static RPCHelpMan invalidateblock()
virtual bool GetKey(COutPoint &key) const =0
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
static RPCHelpMan getblockcount()
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Special type that is a NUM or [NUM,NUM].
bool fPruneMode
Pruning-related variables and constants.
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
int32_t nVersion
block header
static bool ComputeUTXOStats(CCoinsView *view, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
const CChainParams & GetParams() const
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
Optional argument with default value omitted because they are implicitly clear.
static std::atomic< bool > g_should_abort_scan
#define EXCLUSIVE_LOCKS_REQUIRED(...)
static RPCHelpMan waitforblock()
std::vector< CTransactionRef > vtx
const ChainTxData & TxData() const
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
static bool SetHasKeys(const std::set< T > &set)
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
static std::optional< kernel::CCoinsStats > GetUTXOStats(CCoinsView *view, node::BlockManager &blockman, kernel::CoinStatsHashType hash_type, const std::function< void()> &interruption_point={}, const CBlockIndex *pindex=nullptr, bool index_requested=true)
Calculate statistics about the unspent transaction output set.
Only TXID for each block's transaction.
Special string to represent a floating point amount.
static RPCHelpMan gettxout()
static RPCHelpMan verifychain()
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
void pushKV(std::string key, UniValue val)
Undo information for a CBlock.
Serialized script, used inside transaction inputs and outputs.
int RPCSerializationFlags()
static const signed int DEFAULT_CHECKBLOCKS
Undo information for a CTransaction.
ChainstateManager & EnsureChainman(const NodeContext &node)
static const int PROTOCOL_VERSION
network protocol versioning
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
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...
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
static RPCHelpMan preciousblock()
std::string GetHex() const
std::string u8string() const
static constexpr size_t PER_UTXO_OVERHEAD
static RPCHelpMan waitforblockheight()
UniValue ValueFromAmount(const CAmount amount)
static RPCHelpMan gettxoutsetinfo()
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
ArgsManager & EnsureAnyArgsman(const std::any &context)
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
static RPCHelpMan pruneblockchain()
#define AssertLockNotHeld(cs)
int elapsed
Number of blocks elapsed since the beginning of the current period.
static RPCHelpMan reconsiderblock()
bool possible
False if there are not enough blocks left in this period to pass activation threshold.
PeerManager & EnsurePeerman(const NodeContext &node)
static RPCHelpMan getchaintips()
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static const unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits) ...
static RPCHelpMan getdeploymentinfo()
void ScriptToUniv(const CScript &script, UniValue &out, bool include_hex=true, bool include_address=false)
std::string GetHex() const
CAmount total_unspendables_genesis_block
The unspendable coinbase amount from the genesis block.
Different type to mark Mutex at global scope.
int nHeight
height of the entry in the chain. The genesis block has height 0
const std::vector< unsigned char > & GetEncodedFilter() const LIFETIMEBOUND
const Consensus::Params & GetConsensus() const
int bit
Bit position to select the particular bit in nVersion.
Chainstate & ActiveChainstate() const
The most-work chain.
Special dictionary with keys that are not literals.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange)
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
full block available in blk*.dat
static bool exists(const path &p)
ChainstateManager & EnsureAnyChainman(const std::any &context)
static path u8path(const std::string &utf8_str)
std::vector< CTxUndo > vtxundo
static int64_t GetBlockWeight(const CBlock &block)
uint64_t nTransactionOutputs
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
CCoinsView that brings transactions from a mempool into view.
void TxToUniv(const CTransaction &tx, const uint256 &block_hash, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS)
void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector< std::pair< CAmount, int64_t >> &scores, int64_t total_weight)
Used by getblockstats to get feerates at different percentiles by weight.
#define T(expected, seed, data)
BuriedDeployment
A buried deployment is one where the height of the activation has been hardcoded into the client impl...
unsigned int nTx
Number of transactions in this block.
NodeContext & EnsureAnyNodeContext(const std::any &context)
static RPCHelpMan getblockhash()
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Special type to denote elision (...)
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
std::string DeploymentName(Consensus::BuriedDeployment dep)
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Cursor for iterating over CoinsView state.
static RPCHelpMan getbestblockhash()