10#include <blockfilter.h>
12#include <chainparams.h>
75#include <versionbits.h>
112 const std::function<
void()>& interruption_point = {})
121 const fs::path& path,
122 const fs::path& temppath,
123 const std::function<
void()>& interruption_point = {});
130 const fs::path& path,
131 const fs::path& tmppath,
138 int nShift = (blockindex.
nBits >> 24) & 0xff;
140 (double)0x0000ffff / (
double)(blockindex.
nBits & 0x00ffffff);
159 if (next && next->
pprev == &blockindex) {
163 return &blockindex == &tip ? 1 : -1;
172 const int height{param.
getInt<
int>()};
176 const int current_tip{active_chain.
Height()};
177 if (height > current_tip) {
181 return active_chain[height];
203 result.
pushKV(
"confirmations", confirmations);
217 if (blockindex.
pprev)
228 const CTxIn& vin_0{coinbase_tx.
vin[0]};
232 coinbase_tx_obj.
pushKV(
"sequence", vin_0.nSequence);
233 coinbase_tx_obj.
pushKV(
"coinbase",
HexStr(vin_0.scriptSig));
234 const auto& witness_stack{vin_0.scriptWitness.stack};
235 if (!witness_stack.empty()) {
237 coinbase_tx_obj.
pushKV(
"witness",
HexStr(witness_stack[0]));
239 return coinbase_tx_obj;
266 const bool is_not_pruned{
WITH_LOCK(
::cs_main,
return !blockman.IsBlockPruned(blockindex))};
268 if (have_undo && !blockman.
ReadBlockUndo(blockUndo, blockindex)) {
269 throw JSONRPCError(
RPC_INTERNAL_ERROR,
"Undo data expected but can't be read. This could be due to disk corruption or a conflict with a pruning event.");
271 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
274 const CTxUndo* txundo = (have_undo && i > 0) ? &blockUndo.
vtxundo.at(i - 1) :
nullptr;
282 result.
pushKV(
"tx", std::move(txs));
291 "Returns the height of the most-work fully-validated chain.\n"
292 "The genesis block has height 0.\n",
313 "Returns the hash of the best (tip) block in the most-work fully-validated chain.\n",
334 "Waits for any new block and returns useful info about it.\n"
335 "\nReturns the current block on timeout or exit.\n"
336 "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
354 if (!request.params[0].isNull())
355 timeout = request.params[0].
getInt<
int>();
369 uint256 tip_hash{request.params[1].isNull()
371 :
ParseHashV(request.params[1],
"current_tip")};
375 std::optional<BlockRef> block = timeout ? miner.
waitTipChanged(tip_hash, std::chrono::milliseconds(timeout)) :
379 if (block) current_block = *block;
382 ret.pushKV(
"hash", current_block.hash.GetHex());
383 ret.pushKV(
"height", current_block.height);
393 "Waits for a specific new block and returns useful info about it.\n"
394 "\nReturns the current block on timeout or exit.\n"
395 "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
407 HelpExampleCli(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\" 1000")
408 +
HelpExampleRpc(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
416 if (!request.params[1].isNull())
417 timeout = request.params[1].getInt<
int>();
426 const auto deadline{std::chrono::steady_clock::now() + 1ms * timeout};
427 while (current_block.hash != hash) {
428 std::optional<BlockRef> block;
430 auto now{std::chrono::steady_clock::now()};
431 if (now >= deadline)
break;
439 current_block = *block;
443 ret.pushKV(
"hash", current_block.hash.GetHex());
444 ret.pushKV(
"height", current_block.height);
453 "waitforblockheight",
454 "Waits for (at least) block height and returns the height and hash\n"
455 "of the current tip.\n"
456 "\nReturns the current block on timeout or exit.\n"
457 "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
476 int height = request.params[0].
getInt<
int>();
478 if (!request.params[1].isNull())
479 timeout = request.params[1].getInt<
int>();
488 const auto deadline{std::chrono::steady_clock::now() + 1ms * timeout};
490 while (current_block.height < height) {
491 std::optional<BlockRef> block;
493 auto now{std::chrono::steady_clock::now()};
494 if (now >= deadline)
break;
502 current_block = *block;
506 ret.pushKV(
"hash", current_block.hash.GetHex());
507 ret.pushKV(
"height", current_block.height);
516 "syncwithvalidationinterfacequeue",
517 "Waits for the validation interface queue to catch up on everything that was there when we entered this function.\n",
537 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
540 RPCResult::Type::NUM,
"",
"the proof-of-work difficulty as a multiple of the minimum difficulty."},
558 "Attempt to fetch block from a given peer.\n\n"
559 "We must have the header for this block, e.g. using submitheader.\n"
560 "The block will not have any undo data which can limit the usage of the block data in a context where the undo data is needed.\n"
561 "Subsequent calls for the same block may cause the response from the previous peer to be ignored.\n"
562 "Peers generally ignore requests for a stale block that they never fully verified, or one that is more than a month old.\n"
563 "When a peer does not respond with a block, we will disconnect.\n"
564 "Note: The block could be re-pruned as soon as it is received.\n\n"
565 "Returns an empty JSON object if the request was successfully scheduled.",
572 HelpExampleCli(
"getblockfrompeer",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
573 +
HelpExampleRpc(
"getblockfrompeer", R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", 0)")
582 const NodeId peer_id{request.params[1].getInt<int64_t>()};
593 throw JSONRPCError(
RPC_MISC_ERROR,
"In prune mode, only blocks that the node has already synced previously can be fetched from a peer");
597 if (block_has_data) {
601 if (
const auto res{peerman.
FetchBlock(peer_id, *index)}; !res) {
613 "Returns hash of block in best-block-chain at height provided.\n",
629 int nHeight = request.params[0].getInt<
int>();
630 if (nHeight < 0 || nHeight > active_chain.
Height())
643 "If verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
644 "If verbose is true, returns an Object with information about blockheader <hash>.\n",
654 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
674 HelpExampleCli(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
675 +
HelpExampleRpc(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
681 bool fVerbose =
true;
682 if (!request.params[1].isNull())
683 fVerbose = request.params[1].get_bool();
702 std::string strHex =
HexStr(ssBlock);
715 if (!(blockindex.nStatus & flag)) {
716 if (blockman.IsBlockPruned(blockindex)) {
719 if (check_for_undo) {
734 if (!blockman.
ReadBlock(block, blockindex)) {
763 if (blockindex.
nHeight == 0)
return blockUndo;
779 auto fields = std::vector<RPCResult>{
781 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
791 {
RPCResult::Type::STR_HEX,
"witness",
true,
"The coinbase input's first (and only) witness stack element, if present"},
798 fields.push_back(std::move(tx_result));
802 fields.emplace_back(
RPCResult::Type::STR_HEX,
"bits",
"nBits: compact representation of the block difficulty target");
805 fields.emplace_back(
RPCResult::Type::STR_HEX,
"chainwork",
"Expected number of hashes required to produce the chain up to this block (in hex)");
807 fields.emplace_back(
RPCResult::Type::STR_HEX,
"previousblockhash",
true,
"The hash of the previous block (if available)");
811 std::vector<RPCResult> new_fields;
812 new_fields.reserve(fields.size());
814 for (
const auto& f : fields) {
815 if (f.m_key_name ==
"tx") {
816 new_fields.push_back(f);
822 new_fields.emplace_back(f, std::move(eopts));
827 new_fields.emplace_back(f, std::move(eopts));
830 fields = std::move(new_fields);
839 "If verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
840 "If verbosity is 1, returns an Object with information about block <hash>.\n"
841 "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction.\n"
842 "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",
845 {
"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",
858 .elision_summary =
"The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result",
859 .fee =
true, .hex =
true,
860 .fee_doc =
"The transaction fee in " +
CURRENCY_UNIT +
", omitted if block undo data is not available"})},
861 }},
"Same output as verbosity = 1")},
868 .prevout_optional =
true,
872 .prevout_doc =
"(Only if undo information is available)",
873 .vin_inner_elision =
"The same output as verbosity = 2"})},
874 }},
"Same output as verbosity = 2")},
877 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
878 +
HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
901 if (verbosity <= 0) {
902 return HexStr(block_data);
909 if (verbosity == 1) {
911 }
else if (verbosity == 2) {
933 if (!first_block || !chain_tip)
return std::nullopt;
938 const auto& first_unpruned{blockman.GetFirstBlock(*chain_tip,
BLOCK_HAVE_MASK, first_block)};
939 if (&first_unpruned == first_block) {
951 "Attempts to delete block and undo data up to a specified height or timestamp, if eligible for pruning.\n"
952 "Requires `-prune` to be enabled at startup. While pruned data may be re-fetched in some cases (e.g., via `getblockfrompeer`), local deletion is irreversible.\n",
955 " to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
974 int heightParam = request.params[0].getInt<
int>();
975 if (heightParam < 0) {
981 if (heightParam > 1000000000) {
990 unsigned int height = (
unsigned int) heightParam;
991 unsigned int chainHeight = (
unsigned int) active_chain.
Height();
994 }
else if (height > chainHeight) {
997 LogDebug(
BCLog::RPC,
"Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
1009 if (hash_type_input ==
"hash_serialized_3") {
1010 return CoinStatsHashType::HASH_SERIALIZED;
1011 }
else if (hash_type_input ==
"muhash") {
1012 return CoinStatsHashType::MUHASH;
1013 }
else if (hash_type_input ==
"none") {
1027 const std::function<
void()>& interruption_point = {},
1029 bool index_requested =
true)
1054 "Returns statistics about the unspent transaction output set.\n"
1055 "Note this call may take some time if you are not using coinstatsindex.\n",
1057 {
"hash_type",
RPCArg::Type::STR,
RPCArg::Default{
"hash_serialized_3"},
"Which UTXO set hash should be calculated. Options: 'hash_serialized_3' (the legacy algorithm), 'muhash', 'none'."},
1061 .type_str = {
"",
"string or numeric"},
1071 {
RPCResult::Type::NUM,
"bogosize",
"Database-independent, meaningless metric indicating the UTXO set size"},
1072 {
RPCResult::Type::STR_HEX,
"hash_serialized_3",
true,
"The serialized hash (only present if 'hash_serialized_3' hash_type is chosen)"},
1074 {
RPCResult::Type::NUM,
"transactions",
true,
"The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
1075 {
RPCResult::Type::NUM,
"disk_size",
true,
"The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
1077 {
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)"},
1078 {
RPCResult::Type::OBJ,
"block_info",
true,
"Info on amounts in the block at this block height (only available if coinstatsindex is used)",
1097 HelpExampleCli("gettxoutsetinfo", R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1098 HelpExampleCli("-named gettxoutsetinfo", R
"(hash_type='muhash' use_index='false')") +
1102 HelpExampleRpc("gettxoutsetinfo", R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")
1109 bool index_requested = request.params[2].isNull() || request.params[2].get_bool();
1120 if (!request.params[1].isNull()) {
1125 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1129 if (!index_requested) {
1141 if (pindex && pindex->
nHeight > summary.best_block_height) {
1147 const std::optional<CCoinsStats> maybe_stats =
GetUTXOStats(coins_view, blockman, hash_type,
node.rpc_interruption_point, pindex, index_requested);
1148 if (maybe_stats.has_value()) {
1154 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1157 if (hash_type == CoinStatsHashType::MUHASH) {
1169 const std::optional<CCoinsStats> maybe_prev_stats =
GetUTXOStats(coins_view, blockman, hash_type,
node.rpc_interruption_point, block_index.
pprev, index_requested);
1170 if (!maybe_prev_stats) {
1173 prev_stats = maybe_prev_stats.value();
1180 CAmount prev_block_total_unspendable_amount = prev_stats.total_unspendables_genesis_block +
1181 prev_stats.total_unspendables_bip30 +
1182 prev_stats.total_unspendables_scripts +
1183 prev_stats.total_unspendables_unclaimed_rewards;
1185 ret.pushKV(
"total_unspendable_amount",
ValueFromAmount(block_total_unspendable_amount));
1198 block_info.
pushKV(
"unspendable",
ValueFromAmount(block_total_unspendable_amount - prev_block_total_unspendable_amount));
1205 block_info.
pushKV(
"unspendables", std::move(unspendables));
1207 ret.pushKV(
"block_info", std::move(block_info));
1221 "Returns details about an unspent transaction output.\n",
1225 {
"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."},
1238 {
RPCResult::Type::STR,
"address",
true,
"The Bitcoin address (only if a well-defined address exists)"},
1244 "\nGet unspent transactions\n"
1246 "\nView the details\n"
1248 "\nAs a JSON-RPC call\n"
1260 COutPoint out{hash, request.params[1].getInt<uint32_t>()};
1261 bool fMempool =
true;
1262 if (!request.params[2].isNull())
1263 fMempool = request.params[2].get_bool();
1268 std::optional<Coin> coin;
1282 ret.pushKV(
"confirmations", 0);
1284 ret.pushKV(
"confirmations", pindex->
nHeight - coin->nHeight + 1);
1289 ret.pushKV(
"scriptPubKey", std::move(o));
1290 ret.pushKV(
"coinbase", coin->IsCoinBase());
1301 "Verifies blockchain database.\n",
1308 RPCResult::Type::BOOL,
"",
"Verification finished successfully. If false, check debug log for reason."},
1316 const int check_depth{request.params[1].isNull() ?
DEFAULT_CHECKBLOCKS : request.params[1].getInt<
int>()};
1335 rv.
pushKV(
"type",
"buried");
1347 if (blockindex ==
nullptr)
return;
1354 if (info.stats.has_value()) {
1355 bip9.
pushKV(
"bit", depparams.bit);
1357 bip9.
pushKV(
"start_time", depparams.nStartTime);
1358 bip9.
pushKV(
"timeout", depparams.nTimeout);
1359 bip9.
pushKV(
"min_activation_height", depparams.min_activation_height);
1362 bip9.
pushKV(
"status", info.current_state);
1363 bip9.
pushKV(
"since", info.since);
1364 bip9.
pushKV(
"status_next", info.next_state);
1367 if (info.stats.has_value()) {
1369 statsUV.
pushKV(
"period", info.stats->period);
1370 statsUV.
pushKV(
"elapsed", info.stats->elapsed);
1371 statsUV.
pushKV(
"count", info.stats->count);
1372 if (info.stats->threshold > 0 || info.stats->possible) {
1373 statsUV.
pushKV(
"threshold", info.stats->threshold);
1374 statsUV.
pushKV(
"possible", info.stats->possible);
1376 bip9.
pushKV(
"statistics", std::move(statsUV));
1379 sig.reserve(info.signalling_blocks.size());
1380 for (
const bool s : info.signalling_blocks) {
1381 sig.push_back(
s ?
'#' :
'-');
1383 bip9.
pushKV(
"signalling", sig);
1387 rv.
pushKV(
"type",
"bip9");
1388 bool is_active =
false;
1389 if (info.active_since.has_value()) {
1390 rv.
pushKV(
"height", *info.active_since);
1391 is_active = (*info.active_since <= blockindex->
nHeight + 1);
1393 rv.
pushKV(
"active", is_active);
1402 "Returns an object containing various state info regarding blockchain processing.\n",
1408 {
RPCResult::Type::NUM,
"blocks",
"the height of the most-work fully-validated chain. The genesis block has height 0"},
1417 {
RPCResult::Type::BOOL,
"initialblockdownload",
"(debug information) estimate of whether this node is in Initial Block Download mode"},
1418 {
RPCResult::Type::OBJ,
"backgroundvalidation",
true,
"state info regarding background validation process",
1420 {
RPCResult::Type::NUM,
"snapshotheight",
"the height of the snapshot block. Background validation verifies the chain from genesis up to this height"},
1421 {
RPCResult::Type::NUM,
"blocks",
"the height of the most-work background fully-validated chain. The genesis block has height 0"},
1422 {
RPCResult::Type::STR,
"bestblockhash",
"the hash of the currently best block validated in the background"},
1424 {
RPCResult::Type::NUM,
"verificationprogress",
"estimate of background verification progress [0..1]"},
1428 {
RPCResult::Type::NUM,
"size_on_disk",
"the estimated size of the block and undo files on disk"},
1430 {
RPCResult::Type::NUM,
"pruneheight",
true,
"the first block unpruned, all previous blocks were pruned (only present if pruning is enabled)"},
1431 {
RPCResult::Type::BOOL,
"automatic_pruning",
true,
"whether automatic pruning is enabled (only present if pruning is enabled)"},
1432 {
RPCResult::Type::NUM,
"prune_target_size",
true,
"the target size used by pruning (only present if automatic pruning is enabled)"},
1433 {
RPCResult::Type::STR_HEX,
"signet_challenge",
true,
"the block challenge (aka. block script), in hexadecimal (only present if the current network is a signet)"},
1436 RPCResult{
RPCResult::Type::ARR,
"warnings",
"any network and blockchain warnings (run with `-deprecatedrpc=warnings` to return the latest warning as a single string)",
1454 const int height{tip.
nHeight};
1457 obj.
pushKV(
"blocks", height);
1458 obj.
pushKV(
"headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
1467 auto historical_blocks{chainman.GetHistoricalBlockRange()};
1468 if (historical_blocks) {
1472 background_validation.
pushKV(
"snapshotheight", btarget.nHeight);
1473 background_validation.
pushKV(
"blocks", btip.nHeight);
1474 background_validation.
pushKV(
"bestblockhash", btip.GetBlockHash().GetHex());
1475 background_validation.
pushKV(
"mediantime", btip.GetMedianTimePast());
1476 background_validation.
pushKV(
"chainwork", btip.nChainWork.GetHex());
1478 obj.
pushKV(
"backgroundvalidation", std::move(background_validation));
1485 obj.
pushKV(
"pruneheight", prune_height ? prune_height.value() + 1 : 0);
1488 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1489 if (automatic_pruning) {
1494 const std::vector<uint8_t>& signet_challenge =
1496 obj.
pushKV(
"signet_challenge",
HexStr(signet_challenge));
1507const std::vector<RPCResult> RPCHelpForDeployment{
1509 {
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)"},
1510 {
RPCResult::Type::BOOL,
"active",
"true if the rules are enforced for the mempool and the next block"},
1513 {
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)"},
1514 {
RPCResult::Type::NUM_TIME,
"start_time",
"the minimum median time past of a block at which the bit gains its meaning"},
1515 {
RPCResult::Type::NUM_TIME,
"timeout",
"the median time past of a block at which the deployment is considered failed if not yet locked in"},
1516 {
RPCResult::Type::NUM,
"min_activation_height",
"minimum height of blocks for which the rules may be enforced"},
1517 {
RPCResult::Type::STR,
"status",
"status of deployment at specified block (one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\")"},
1520 {
RPCResult::Type::OBJ,
"statistics",
true,
"numeric statistics about signalling for a softfork (only for \"started\" and \"locked_in\" status)",
1523 {
RPCResult::Type::NUM,
"threshold",
true,
"the number of blocks with the version bit set required to activate the feature (only for \"started\" status)"},
1524 {
RPCResult::Type::NUM,
"elapsed",
"the number of blocks elapsed since the beginning of the current period"},
1525 {
RPCResult::Type::NUM,
"count",
"the number of blocks with the version bit set in the current period"},
1526 {
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)"},
1528 {
RPCResult::Type::STR,
"signalling",
true,
"indicates blocks that signalled with a # and blocks that did not with a -"},
1548 "Returns an object containing various state info regarding deployments of consensus changes.\n"
1549 "Consensus changes for which the new rules are enforced from genesis are not listed in \"deployments\".",
1573 if (request.params[0].isNull()) {
1589 uv_flagnames.
push_backV(flagnames.begin(), flagnames.end());
1590 deploymentinfo.
pushKV(
"script_flags", uv_flagnames);
1592 deploymentinfo.
pushKV(
"deployments", DeploymentInfo(blockindex, chainman));
1593 return deploymentinfo;
1616 "Return information about all known tips in the block tree,"
1617 " including the main chain as well as orphaned branches.\n",
1625 {
RPCResult::Type::NUM,
"branchlen",
"zero for main chain, otherwise length of branch connecting the tip to the main chain"},
1627 "Possible values for status:\n"
1628 "1. \"invalid\" This branch contains at least one invalid block\n"
1629 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
1630 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
1631 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
1632 "5. \"active\" This is the tip of the active main chain, which is certainly valid"},
1651 std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1652 std::set<const CBlockIndex*> setOrphans;
1653 std::set<const CBlockIndex*> setPrevs;
1655 for (
const auto& [
_, block_index] : chainman.
BlockIndex()) {
1656 if (!active_chain.
Contains(block_index)) {
1657 setOrphans.insert(&block_index);
1658 setPrevs.insert(block_index.pprev);
1662 for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) {
1663 if (setPrevs.erase(*it) == 0) {
1664 setTips.insert(*it);
1669 setTips.insert(active_chain.
Tip());
1676 obj.
pushKV(
"height", block->nHeight);
1677 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1679 const int branchLen = block->nHeight - active_chain.
FindFork(*block)->
nHeight;
1680 obj.
pushKV(
"branchlen", branchLen);
1683 if (active_chain.
Contains(*block)) {
1689 }
else if (!block->HaveNumChainTxs()) {
1691 status =
"headers-only";
1694 status =
"valid-fork";
1697 status =
"valid-headers";
1702 obj.
pushKV(
"status", status);
1716 "Treats a block as if it were received before others with the same work.\n"
1717 "\nA later preciousblock call can override the effect of an earlier one.\n"
1718 "\nThe effects of preciousblock are not retained across restarts.\n",
1778 "Permanently marks a block as invalid, as if it violated a consensus rule.\n",
1808 chainman.RecalculateBestHeader();
1823 "Removes invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n"
1824 "This can be used to undo the effects of invalidateblock.\n",
1849 "Compute statistics about the total number and rate of transactions in the chain.\n",
1859 "The total number of transactions in the chain up to that point, if known. "
1860 "It may be unknown when using assumeutxo."},
1862 {
RPCResult::Type::NUM,
"window_final_block_height",
"The height of the final block in the window."},
1864 {
RPCResult::Type::NUM,
"window_interval",
true,
"The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0"},
1866 "The number of transactions in the window. "
1867 "Only returned if \"window_block_count\" is > 0 and if txcount exists for the start and end of the window."},
1869 "The average rate of transactions per second in the window. "
1870 "Only returned if \"window_interval\" is > 0 and if window_tx_count exists."},
1882 if (request.params[1].isNull()) {
1899 if (request.params[0].isNull()) {
1900 blockcount = std::max(0, std::min(blockcount, pindex->
nHeight - 1));
1902 blockcount = request.params[0].getInt<
int>();
1904 if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->
nHeight)) {
1910 const int64_t nTimeDiff{pindex->
GetMedianTimePast() - past_block.GetMedianTimePast()};
1918 ret.pushKV(
"window_final_block_height", pindex->
nHeight);
1919 ret.pushKV(
"window_block_count", blockcount);
1920 if (blockcount > 0) {
1921 ret.pushKV(
"window_interval", nTimeDiff);
1923 const auto window_tx_count = pindex->
m_chain_tx_count - past_block.m_chain_tx_count;
1924 ret.pushKV(
"window_tx_count", window_tx_count);
1925 if (nTimeDiff > 0) {
1926 ret.pushKV(
"txrate",
double(window_tx_count) / nTimeDiff);
1939 size_t size = scores.size();
1944 std::sort(scores.begin(), scores.end());
1945 if (size % 2 == 0) {
1946 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1948 return scores[size / 2];
1954 if (scores.empty()) {
1958 std::sort(scores.begin(), scores.end());
1962 total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
1965 int64_t next_percentile_index = 0;
1966 int64_t cumulative_weight = 0;
1967 for (
const auto& element : scores) {
1968 cumulative_weight += element.second;
1969 while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
1970 result[next_percentile_index] = element.first;
1971 ++next_percentile_index;
1977 result[i] = scores.back().first;
1982static inline bool SetHasKeys(
const std::set<T>& set) {
return false;}
1983template<
typename T,
typename Tk,
typename... Args>
1984static inline bool SetHasKeys(
const std::set<T>& set,
const Tk& key,
const Args&...
args)
1996 "Compute per block statistics for a given window. All amounts are in satoshis.\n"
1997 "It won't work for some heights with pruning.\n",
2002 .type_str = {
"",
"string or numeric"},
2018 {
RPCResult::Type::ARR_FIXED,
"feerate_percentiles",
true,
"Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
2043 {
RPCResult::Type::NUM,
"total_out",
true,
"Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
2048 {
RPCResult::Type::NUM,
"utxo_increase",
true,
"The increase/decrease in the number of unspent outputs (not discounting op_return and similar)"},
2049 {
RPCResult::Type::NUM,
"utxo_size_inc",
true,
"The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
2050 {
RPCResult::Type::NUM,
"utxo_increase_actual",
true,
"The increase/decrease in the number of unspent outputs, not counting unspendables"},
2051 {
RPCResult::Type::NUM,
"utxo_size_inc_actual",
true,
"The increase/decrease in size for the utxo index, not counting unspendables"},
2054 HelpExampleCli(
"getblockstats", R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2055 HelpExampleCli("getblockstats", R
"(1000 '["minfeerate","avgfeerate"]')") +
2056 HelpExampleRpc("getblockstats", R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2057 HelpExampleRpc("getblockstats", R
"(1000, ["minfeerate","avgfeerate"])")
2064 std::set<std::string> stats;
2065 if (!request.params[1].isNull()) {
2067 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2068 const std::string stat = stats_univalue[i].
get_str();
2076 const bool do_all = stats.size() == 0;
2077 const bool do_mediantxsize = do_all || stats.contains(
"mediantxsize");
2078 const bool do_medianfee = do_all || stats.contains(
"medianfee");
2079 const bool do_feerate_percentiles = do_all || stats.contains(
"feerate_percentiles");
2080 const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
2081 SetHasKeys(stats,
"utxo_increase",
"utxo_increase_actual",
"utxo_size_inc",
"utxo_size_inc_actual",
"totalfee",
"avgfee",
"avgfeerate",
"minfee",
"maxfee",
"minfeerate",
"maxfeerate");
2082 const bool loop_outputs = do_all || loop_inputs || stats.contains(
"total_out");
2083 const bool do_calculate_size = do_mediantxsize ||
2084 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
"maxtxsize",
"swtotal_size");
2085 const bool do_calculate_weight = do_all ||
SetHasKeys(stats,
"total_weight",
"avgfeerate",
"swtotal_weight",
"avgfeerate",
"feerate_percentiles",
"minfeerate",
"maxfeerate");
2086 const bool do_calculate_sw = do_all ||
SetHasKeys(stats,
"swtxs",
"swtotal_size",
"swtotal_weight");
2095 int64_t maxtxsize = 0;
2097 int64_t outputs = 0;
2098 int64_t swtotal_size = 0;
2099 int64_t swtotal_weight = 0;
2101 int64_t total_size = 0;
2102 int64_t total_weight = 0;
2104 int64_t utxo_size_inc = 0;
2105 int64_t utxo_size_inc_actual = 0;
2106 std::vector<CAmount> fee_array;
2107 std::vector<std::pair<CAmount, int64_t>> feerate_array;
2108 std::vector<int64_t> txsize_array;
2110 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2111 const auto& tx = block.
vtx.at(i);
2112 outputs += tx->vout.size();
2117 tx_total_out +=
out.nValue;
2120 utxo_size_inc += out_size;
2126 if (
out.scriptPubKey.IsUnspendable())
continue;
2129 utxo_size_inc_actual += out_size;
2133 if (tx->IsCoinBase()) {
2137 inputs += tx->vin.size();
2138 total_out += tx_total_out;
2140 int64_t tx_size = 0;
2141 if (do_calculate_size) {
2143 tx_size = tx->ComputeTotalSize();
2144 if (do_mediantxsize) {
2145 txsize_array.push_back(tx_size);
2147 maxtxsize = std::max(maxtxsize, tx_size);
2148 mintxsize = std::min(mintxsize, tx_size);
2149 total_size += tx_size;
2153 if (do_calculate_weight) {
2155 total_weight += weight;
2158 if (do_calculate_sw && tx->HasWitness()) {
2160 swtotal_size += tx_size;
2161 swtotal_weight += weight;
2166 const auto& txundo = blockUndo.
vtxundo.at(i - 1);
2167 for (
const Coin& coin: txundo.vprevout) {
2170 tx_total_in += prevoutput.
nValue;
2172 utxo_size_inc -= prevout_size;
2173 utxo_size_inc_actual -= prevout_size;
2176 CAmount txfee = tx_total_in - tx_total_out;
2179 fee_array.push_back(txfee);
2181 maxfee = std::max(maxfee, txfee);
2182 minfee = std::min(minfee, txfee);
2187 if (do_feerate_percentiles) {
2188 feerate_array.emplace_back(feerate, weight);
2190 maxfeerate = std::max(maxfeerate, feerate);
2191 minfeerate = std::min(minfeerate, feerate);
2200 feerates_res.
push_back(feerate_percentiles[i]);
2204 ret_all.
pushKV(
"avgfee", (block.
vtx.size() > 1) ? totalfee / (block.
vtx.size() - 1) : 0);
2206 ret_all.
pushKV(
"avgtxsize", (block.
vtx.size() > 1) ? total_size / (block.
vtx.size() - 1) : 0);
2208 ret_all.
pushKV(
"feerate_percentiles", std::move(feerates_res));
2210 ret_all.
pushKV(
"ins", inputs);
2211 ret_all.
pushKV(
"maxfee", maxfee);
2212 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2213 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2218 ret_all.
pushKV(
"minfeerate", (minfeerate ==
MAX_MONEY) ? 0 : minfeerate);
2220 ret_all.
pushKV(
"outs", outputs);
2222 ret_all.
pushKV(
"swtotal_size", swtotal_size);
2223 ret_all.
pushKV(
"swtotal_weight", swtotal_weight);
2224 ret_all.
pushKV(
"swtxs", swtxs);
2226 ret_all.
pushKV(
"total_out", total_out);
2227 ret_all.
pushKV(
"total_size", total_size);
2228 ret_all.
pushKV(
"total_weight", total_weight);
2229 ret_all.
pushKV(
"totalfee", totalfee);
2230 ret_all.
pushKV(
"txs", block.
vtx.size());
2231 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2232 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2233 ret_all.
pushKV(
"utxo_increase_actual", utxos - inputs);
2234 ret_all.
pushKV(
"utxo_size_inc_actual", utxo_size_inc_actual);
2241 for (
const std::string& stat : stats) {
2242 const UniValue& value = ret_all[stat];
2246 ret.pushKVEnd(stat, value);
2255bool 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)
2259 while (cursor->
Valid()) {
2262 if (!cursor->
GetKey(key) || !cursor->
GetValue(coin))
return false;
2263 if (++
count % 8192 == 0) {
2264 interruption_point();
2270 if (
count % 256 == 0) {
2273 scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
2276 out_results.emplace(key, coin);
2280 scan_progress = 100;
2316 "\"start\" for starting a scan\n"
2317 "\"abort\" for aborting the current scan (returns true when abort was successful)\n"
2318 "\"status\" for progress report (in %) of the current scan"
2331 "Every scan object is either a string descriptor or an object:",
2341 "True if scan will be aborted (not necessarily before this RPC returns), or false if there is no scan to abort"
2344 "when action=='status' and no scan is in progress - possibly already completed",
RPCResult::Type::NONE,
"",
""
2355 const std::string EXAMPLE_DESCRIPTOR_RAW =
"raw(76a91411b366edfc0a8b66feebae5c2e25a7b6a5d1cf3188ac)#fm24fxxy";
2359 "Scans the unspent transaction output set for entries that match certain output descriptors.\n"
2360 "Examples of output descriptors are:\n"
2361 " addr(<address>) Outputs whose output script corresponds to the specified address (does not include P2PK)\n"
2362 " raw(<hex script>) Outputs whose output script equals the specified hex-encoded bytes\n"
2363 " combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n"
2364 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
2365 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
2366 " tr(<pubkey>) P2TR\n"
2367 " tr(<pubkey>,{pk(<pubkey>)}) P2TR with single fallback pubkey in tapscript\n"
2368 " rawtr(<pubkey>) P2TR with the specified key as output key rather than inner\n"
2369 " wsh(and_v(v:pk(<pubkey>),after(2))) P2WSH miniscript with mandatory pubkey and a timelock\n"
2370 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2371 "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2372 "unhardened or hardened child keys.\n"
2373 "In the latter case, a range needs to be specified by below if different from 1000.\n"
2374 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
2397 {
RPCResult::Type::NUM,
"confirmations",
"Number of confirmations of the unspent transaction output when the scan was done"},
2407 HelpExampleCli(
"scantxoutset",
"start \'[\"" + EXAMPLE_DESCRIPTOR_RAW +
"\"]\'") +
2410 HelpExampleRpc(
"scantxoutset",
"\"start\", [\"" + EXAMPLE_DESCRIPTOR_RAW +
"\"]") +
2417 const auto action{self.
Arg<std::string_view>(
"action")};
2418 if (action ==
"status") {
2426 }
else if (action ==
"abort") {
2435 }
else if (action ==
"start") {
2446 std::set<CScript> needles;
2447 std::map<CScript, std::string> descriptors;
2457 descriptors.emplace(std::move(
script), std::move(inferred));
2463 std::vector<CTxOut> input_txos;
2464 std::map<COutPoint, Coin> coins;
2467 std::unique_ptr<CCoinsViewCursor> pcursor;
2479 result.
pushKV(
"success", res);
2484 for (
const auto& it : coins) {
2486 const Coin& coin = it.second;
2489 input_txos.push_back(txo);
2494 unspent.
pushKV(
"vout", outpoint.
n);
2500 unspent.
pushKV(
"blockhash", coinb_block.GetBlockHash().GetHex());
2505 result.
pushKV(
"unspents", std::move(unspents));
2549 for (
const auto& tx : block.vtx) {
2550 if (std::any_of(tx->vout.cbegin(), tx->vout.cend(), [&](
const auto& txout) {
2551 return needles.contains(std::vector<unsigned char>(txout.scriptPubKey.begin(), txout.scriptPubKey.end()));
2557 for (
const auto& txundo : block_undo.vtxundo) {
2558 if (std::any_of(txundo.vprevout.cbegin(), txundo.vprevout.cend(), [&](
const auto& coin) {
2559 return needles.contains(std::vector<unsigned char>(coin.out.scriptPubKey.begin(), coin.out.scriptPubKey.end()));
2572 "Return relevant blockhashes for given descriptors (requires blockfilterindex).\n"
2573 "This call may take several minutes. Make sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
2582 {
"filter_false_positives",
RPCArg::Type::BOOL,
RPCArg::Default{
false},
"Filter false positives (slower and may fail on pruned nodes). Otherwise they may occur at a rate of 1/M"},
2604 HelpExampleCli(
"scanblocks",
"start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 300000") +
2605 HelpExampleCli(
"scanblocks",
"start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 100 150 basic") +
2607 HelpExampleRpc(
"scanblocks",
"\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 300000") +
2608 HelpExampleRpc(
"scanblocks",
"\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 100, 150, \"basic\"") +
2614 auto action{self.
Arg<std::string_view>(
"action")};
2615 if (action ==
"status") {
2624 }
else if (action ==
"abort") {
2633 }
else if (action ==
"start") {
2642 auto filtertype_name{self.
Arg<std::string_view>(
"filtertype")};
2650 bool filter_false_positives{options.exists(
"filter_false_positives") ? options[
"filter_false_positives"].get_bool() :
false};
2666 start_index = active_chain.
Genesis();
2667 stop_block = active_chain.
Tip();
2668 if (!request.params[2].isNull()) {
2669 start_index = active_chain[request.params[2].getInt<
int>()];
2674 if (!request.params[3].isNull()) {
2675 stop_block = active_chain[request.params[3].getInt<
int>()];
2694 const int amount_per_chunk = 10000;
2695 std::vector<BlockFilter> filters;
2696 int start_block_height = start_index->
nHeight;
2697 const int total_blocks_to_process = stop_block->
nHeight - start_block_height;
2702 bool completed =
true;
2706 node.rpc_interruption_point();
2713 int start_block = !end_range ? start_index->
nHeight : start_index->
nHeight + 1;
2714 end_range = (start_block + amount_per_chunk < stop_block->
nHeight) ?
2721 if (filter.GetFilter().MatchAny(needle_set)) {
2722 if (filter_false_positives) {
2731 blocks.
push_back(filter.GetBlockHash().GetHex());
2735 start_index = end_range;
2738 int blocks_processed = end_range->
nHeight - start_block_height;
2739 if (total_blocks_to_process > 0) {
2747 }
while (start_index != stop_block);
2749 ret.pushKV(
"from_height", start_block_height);
2750 ret.pushKV(
"to_height", start_index->
nHeight);
2751 ret.pushKV(
"relevant_blocks", std::move(blocks));
2752 ret.pushKV(
"completed", completed);
2764 "getdescriptoractivity",
2765 "Get spend and receive activity associated with a set of descriptors for a set of blocks. "
2766 "This command pairs well with the `relevant_blocks` output of `scanblocks()`.\n"
2767 "This call may take several minutes. If you encounter timeouts, try specifying no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
2805 }, {.skip_type_check=
true}, },
2809 HelpExampleCli(
"getdescriptoractivity",
"'[\"000000000000000000001347062c12fded7c528943c8ce133987e2e2f5a840ee\"]' '[\"addr(bc1qzl6nsgqzu89a66l50cvwapnkw5shh23zarqkw9)\"]'")
2818 struct CompareByHeightAscending {
2824 std::set<const CBlockIndex*, CompareByHeightAscending> blockindexes_sorted;
2838 blockindexes_sorted.insert(pindex);
2842 std::set<CScript> scripts_to_watch;
2850 scripts_to_watch.insert(
script);
2854 const auto AddSpend = [&](
2866 event.pushKV(
"type",
"spend");
2869 event.pushKV(
"blockhash", index->GetBlockHash().ToString());
2870 event.pushKV(
"height", index->nHeight);
2872 event.pushKV(
"spend_txid", tx->GetHash().ToString());
2873 event.pushKV(
"spend_vin", vin);
2874 event.pushKV(
"prevout_txid", txin.prevout.hash.ToString());
2875 event.pushKV(
"prevout_vout", txin.prevout.n);
2876 event.pushKV(
"prevout_spk", spkUv);
2886 event.pushKV(
"type",
"receive");
2889 event.pushKV(
"blockhash", index->GetBlockHash().ToString());
2890 event.pushKV(
"height", index->nHeight);
2892 event.pushKV(
"txid", tx->GetHash().ToString());
2893 event.pushKV(
"vout", vout);
2894 event.pushKV(
"output_spk", spkUv);
2906 for (
const CBlockIndex* blockindex : blockindexes_sorted) {
2910 for (
size_t i = 0; i < block.vtx.size(); ++i) {
2911 const auto& tx = block.vtx.at(i);
2913 if (!tx->IsCoinBase()) {
2915 const auto& txundo = block_undo.
vtxundo.at(i - 1);
2917 for (
size_t vin_idx = 0; vin_idx < tx->vin.size(); ++vin_idx) {
2918 const auto& coin = txundo.vprevout.at(vin_idx);
2919 const auto& txin = tx->vin.at(vin_idx);
2927 for (
size_t vout_idx = 0; vout_idx < tx->vout.size(); ++vout_idx) {
2928 const auto& vout = tx->vout.at(vout_idx);
2929 if (scripts_to_watch.contains(vout.scriptPubKey)) {
2930 activity.
push_back(AddReceive(vout, blockindex, vout_idx, tx));
2936 bool search_mempool =
true;
2937 if (!request.params[2].isNull()) {
2938 search_mempool = request.params[2].get_bool();
2941 if (search_mempool) {
2948 const auto& tx = e.GetSharedTx();
2950 for (
size_t vin_idx = 0; vin_idx < tx->vin.size(); ++vin_idx) {
2953 const auto& txin = tx->vin.at(vin_idx);
2954 std::optional<Coin> coin = coins_view.
GetCoin(txin.prevout);
2962 if (txin.prevout.n >= prev_tx->vout.size()) {
2963 throw std::runtime_error(
"Invalid output index");
2965 const CTxOut&
out = prev_tx->vout[txin.prevout.n];
2966 scriptPubKey =
out.scriptPubKey;
2971 scriptPubKey =
out.scriptPubKey;
2975 if (scripts_to_watch.contains(scriptPubKey)) {
2978 scriptPubKey, value, tx, vin_idx, txin,
nullptr));
2982 for (
size_t vout_idx = 0; vout_idx < tx->vout.size(); ++vout_idx) {
2983 const auto& vout = tx->vout.at(vout_idx);
2984 if (scripts_to_watch.contains(vout.scriptPubKey)) {
2985 activity.
push_back(AddReceive(vout,
nullptr, vout_idx, tx));
2991 ret.pushKV(
"activity", activity);
3001 "Retrieve a BIP 157 content filter for a particular block.\n",
3013 HelpExampleCli(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"") +
3014 HelpExampleRpc(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\", \"basic\"")
3019 auto filtertype_name{self.
Arg<std::string_view>(
"filtertype")};
3032 bool block_was_connected;
3043 bool index_ready = index->BlockUntilSyncedToCurrentChain();
3050 std::string errmsg =
"Filter not found.";
3052 if (!block_was_connected) {
3054 errmsg +=
" Block was not connected to active chain.";
3055 }
else if (!index_ready) {
3057 errmsg +=
" Block filters are still in the process of being indexed.";
3060 errmsg +=
" This error is unexpected and indicates index corruption.";
3068 ret.pushKV(
"header", filter_header.
GetHex());
3080 static constexpr const char*
LOCK_NAME{
"dumptxoutset-rollback"};
3106 "Write the serialized UTXO set to a file. This can be used in loadtxoutset afterwards if this snapshot height is supported in the chainparams as well.\n"
3107 "This creates a temporary UTXO database when rolling back, keeping the main chain intact. Should the node experience an unclean shutdown the temporary database may need to be removed from the datadir manually.\n"
3108 "For deep rollbacks, make sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0) as it may take several minutes.",
3111 {
"type",
RPCArg::Type::STR,
RPCArg::Default(
""),
"The type of snapshot to create. Can be \"latest\" to create a snapshot of the current UTXO set or \"rollback\" to temporarily roll back the state of the node to a historical block before creating the snapshot of a historical UTXO set. This parameter can be omitted if a separate \"rollback\" named parameter is specified indicating the height or hash of a specific historical block. If \"rollback\" is specified and separate \"rollback\" named parameter is not specified, this will roll back to the latest valid snapshot block that can currently be loaded with loadtxoutset."},
3115 "Height or hash of the block to roll back to before creating the snapshot. Note: The further this number is from the tip, the longer this process will take. Consider setting a higher -rpcclienttimeout value in this case.",
3117 {
"in_memory",
RPCArg::Type::BOOL,
RPCArg::Default{
false},
"If true, the temporary UTXO-set database used during rollback is kept entirely in memory. This can significantly speed up the process but requires sufficient free RAM (over 10 GB on mainnet)."},
3129 {
RPCResult::Type::NUM,
"nchaintx",
"the number of transactions in the chain up to and including the base block"},
3133 HelpExampleCli(
"-rpcclienttimeout=0 dumptxoutset",
"utxo.dat latest") +
3134 HelpExampleCli(
"-rpcclienttimeout=0 dumptxoutset",
"utxo.dat rollback") +
3135 HelpExampleCli(
"-rpcclienttimeout=0 -named dumptxoutset", R
"(utxo.dat rollback=853456)") +
3136 HelpExampleCli("-rpcclienttimeout=0 -named dumptxoutset", R
"(utxo.dat rollback=853456 in_memory=true)")
3143 const auto snapshot_type{self.
Arg<std::string_view>(
"type")};
3145 if (options.exists(
"rollback")) {
3146 if (!snapshot_type.empty() && snapshot_type !=
"rollback") {
3150 }
else if (snapshot_type ==
"rollback") {
3151 auto snapshot_heights =
node.chainman->GetParams().GetAvailableSnapshotHeights();
3153 auto max_height = std::max_element(snapshot_heights.begin(), snapshot_heights.end());
3155 }
else if (snapshot_type ==
"latest") {
3163 const auto path_info{fs::status(path)};
3166 const fs::path temppath = fs::is_fifo(path_info) ? path : path +
".incomplete";
3168 if (
fs::exists(path_info) && !fs::is_fifo(path_info)) {
3171 path.utf8string() +
" already exists. If you are sure this is what you want, "
3172 "move it out of the way first");
3177 if (afile.IsNull()) {
3180 "Couldn't open file " + temppath.utf8string() +
" for writing.");
3185 if (target_index == tip) {
3191 std::optional<TemporaryPruneLock> temp_prune_lock;
3192 if (
node.chainman->m_blockman.IsPruneMode()) {
3196 if (first_block.nHeight > target_index->nHeight) {
3199 temp_prune_lock.emplace(
node.chainman->m_blockman, target_index->nHeight);
3202 const bool in_memory{options.exists(
"in_memory") ? options[
"in_memory"].get_bool() :
false};
3212 if (!fs::is_fifo(path_info)) {
3213 fs::rename(temppath, path);
3230 fs::create_directories(
m_path);
3234 LogInfo(
"Failed to clean up temporary UTXO database at %s, please remove it manually.",
3245 const fs::path& path,
3246 const fs::path& tmppath,
3247 const bool in_memory)
3254 std::optional<TemporaryUTXODatabase> temp_db_cleaner;
3256 temp_db_cleaner.emplace(temp_db_path);
3258 LogInfo(
"Using in-memory database for UTXO-set rollback (this may require significant RAM).");
3263 .
path = temp_db_path,
3265 .memory_only = in_memory,
3271 std::unique_ptr<CCoinsViewDB> temp_db = std::make_unique<CCoinsViewDB>(
3272 std::move(db_params),
3277 LogInfo(
"Copying current UTXO set to temporary database.");
3280 std::unique_ptr<CCoinsViewCursor> cursor;
3289 size_t coins_count = 0;
3290 while (cursor->Valid()) {
3291 node.rpc_interruption_point();
3295 if (cursor->GetKey(key) && cursor->GetValue(coin)) {
3296 temp_cache.
AddCoin(key, std::move(coin),
false);
3300 if (coins_count % 10'000'000 == 0) {
3301 LogInfo(
"Copying UTXO set: %uM coins copied.", coins_count / 1'000'000);
3305 if (coins_count % 100'000 == 0) {
3313 LogInfo(
"UTXO set copy complete: %u coins total", coins_count);
3316 LogInfo(
"Rolling back from height %d to %d", tip->nHeight, target->
nHeight);
3319 const size_t total_blocks{
static_cast<size_t>(block_index->nHeight - target->
nHeight)};
3321 rollback_cache.
SetBestBlock(block_index->GetBlockHash());
3322 size_t blocks_processed = 0;
3323 int last_progress{0};
3326 while (block_index->nHeight > target->
nHeight) {
3327 node.rpc_interruption_point();
3330 if (!
node.chainman->m_blockman.ReadBlock(block, *block_index)) {
3332 strprintf(
"Failed to read block at height %d", block_index->nHeight));
3335 WITH_LOCK(
::cs_main, res = chainstate.DisconnectBlock(block, block_index, rollback_cache));
3338 strprintf(
"Failed to roll back block at height %d", block_index->nHeight));
3342 int progress{
static_cast<int>(blocks_processed * 100 / total_blocks)};
3343 if (progress >= last_progress + 5) {
3344 LogInfo(
"Rolled back %d%% of blocks.", progress);
3345 last_progress = progress;
3346 rollback_cache.
Flush();
3349 block_index = block_index->pprev;
3353 rollback_cache.
Flush();
3355 LogInfo(
"Rollback complete. Computing UTXO statistics for created txoutset dump.");
3356 std::optional<CCoinsStats> maybe_stats =
GetUTXOStats(*temp_db,
3358 CoinStatsHashType::HASH_SERIALIZED,
3359 node.rpc_interruption_point);
3365 std::unique_ptr<CCoinsViewCursor> pcursor{temp_db->Cursor()};
3367 LogInfo(
"Writing snapshot to disk.");
3375 node.rpc_interruption_point);
3381 const std::function<
void()>& interruption_point)
3383 std::unique_ptr<CCoinsViewCursor> pcursor;
3384 std::optional<CCoinsStats> maybe_stats;
3422 const fs::path& path,
3423 const fs::path& temppath,
3424 const std::function<
void()>& interruption_point)
3437 unsigned int iter{0};
3438 size_t written_coins_count{0};
3439 std::vector<std::pair<uint32_t, Coin>> coins;
3448 auto write_coins_to_file = [&](
AutoFile& afile,
const Txid& last_hash,
const std::vector<std::pair<uint32_t, Coin>>& coins,
size_t& written_coins_count) {
3451 for (
const auto& [n, coin] : coins) {
3454 ++written_coins_count;
3459 last_hash = key.
hash;
3460 while (pcursor->
Valid()) {
3461 if (iter % 5000 == 0) interruption_point();
3464 if (key.
hash != last_hash) {
3465 write_coins_to_file(afile, last_hash, coins, written_coins_count);
3466 last_hash = key.
hash;
3469 coins.emplace_back(key.
n, coin);
3474 if (!coins.empty()) {
3475 write_coins_to_file(afile, last_hash, coins, written_coins_count);
3480 if (afile.
fclose() != 0) {
3481 throw std::ios_base::failure(
3486 result.
pushKV(
"coins_written", written_coins_count);
3489 result.
pushKV(
"path", path.utf8string());
3499 const fs::path& path,
3500 const fs::path& tmppath)
3510 node.rpc_interruption_point);
3517 "Load the serialized UTXO set from a file.\n"
3518 "Once this snapshot is loaded, its contents will be "
3519 "deserialized into a second chainstate data structure, which is then used to sync to "
3520 "the network's tip. "
3521 "Meanwhile, the original chainstate will complete the initial block download process in "
3522 "the background, eventually validating up to the block that the snapshot is based upon.\n\n"
3524 "The result is a usable bitcoind instance that is current with the network tip in a "
3525 "matter of minutes rather than hours. UTXO snapshot are typically obtained from "
3526 "third-party sources (HTTP, torrent, etc.) which is reasonable since their "
3527 "contents are always checked by hash.\n\n"
3529 "You can find more information on this process in the `assumeutxo` design "
3530 "document (<https://github.com/bitcoin/bitcoin/blob/master/doc/design/assumeutxo.md>).",
3535 "path to the snapshot file. If relative, will be prefixed by datadir."},
3557 if (afile.IsNull()) {
3560 "Couldn't open file " + path.utf8string() +
" for reading.");
3566 }
catch (
const std::ios_base::failure& e) {
3571 if (!activation_result) {
3585 result.
pushKV(
"coins_loaded", metadata.m_coins_count);
3586 result.
pushKV(
"tip_hash", snapshot_index.GetBlockHash().ToString());
3587 result.
pushKV(
"base_height", snapshot_index.nHeight);
3601 {
RPCResult::Type::STR_HEX,
"snapshot_blockhash",
true,
"the base block of the snapshot this chainstate is based on, if any"},
3604 {
RPCResult::Type::BOOL,
"validated",
"whether the chainstate is fully validated. True if all blocks in the chainstate were validated, false if the chain is based on a snapshot and the snapshot has not yet been validated."},
3611 "Return information about chainstates.\n",
3633 if (!
cs.m_chain.Tip()) {
3645 data.pushKV(
"coins_db_cache_bytes",
cs.m_coinsdb_cache_size_bytes);
3646 data.pushKV(
"coins_tip_cache_bytes",
cs.m_coinstip_cache_size_bytes);
3647 if (
cs.m_from_snapshot_blockhash) {
3648 data.pushKV(
"snapshot_blockhash",
cs.m_from_snapshot_blockhash->ToString());
3654 obj.
pushKV(
"headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
3657 obj_chainstates.push_back(make_chain_data(*
cs));
3660 obj.
pushKV(
"chainstates", std::move(obj_chainstates));
3701 for (
const auto& c : commands) {
3702 t.appendCommand(c.name, &c);
constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
bool MoneyRange(const CAmount &nValue)
int64_t CAmount
Amount in satoshis (Can be negative)
fs::path AbsPathForConfigVal(const ArgsManager &args, const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
static std::vector< RPCResult > GetBlockFields(RPCResult tx_result, std::optional< std::string > elision_msg=std::nullopt)
static const auto scan_result_abort
static std::atomic< bool > g_scan_in_progress
static bool SetHasKeys(const std::set< T > &set)
static T CalculateTruncatedMedian(std::vector< T > &scores)
static int ComputeNextBlockAndDepth(const CBlockIndex &tip, const CBlockIndex &blockindex, const CBlockIndex *&next)
CoinStatsHashType ParseHashType(std::string_view hash_type_input)
static RPCMethod getdifficulty()
static CBlockUndo GetUndoChecked(BlockManager &blockman, const CBlockIndex &blockindex)
static std::vector< std::byte > GetRawBlockChecked(BlockManager &blockman, const CBlockIndex &blockindex)
static RPCMethod getblockheader()
std::tuple< std::unique_ptr< CCoinsViewCursor >, CCoinsStats, const CBlockIndex * > PrepareUTXOSnapshot(Chainstate &chainstate, const std::function< void()> &interruption_point={}) EXCLUSIVE_LOCKS_REQUIRED(UniValue WriteUTXOSnapshot(Chainstate &chainstate, CCoinsViewCursor *pcursor, CCoinsStats *maybe_stats, const CBlockIndex *tip, AutoFile &&afile, const fs::path &path, const fs::path &temppath, const std::function< void()> &interruption_point={})
static RPCMethod reconsiderblock()
static RPCMethod getblockfilter()
static RPCMethod pruneblockchain()
static RPCMethod scanblocks()
std::tuple< std::unique_ptr< CCoinsViewCursor >, CCoinsStats, const CBlockIndex * > PrepareUTXOSnapshot(Chainstate &chainstate, const std::function< void()> &interruption_point)
static std::atomic< int > g_scanfilter_progress_height
static const auto output_descriptor_obj
static RPCMethod getbestblockhash()
void CheckBlockDataAvailability(BlockManager &blockman, const CBlockIndex &blockindex, bool check_for_undo)
static std::atomic< bool > g_scanfilter_should_abort_scan
static std::atomic< int > g_scanfilter_progress
RAII object to prevent concurrency issue when scanning blockfilters.
static RPCMethod preciousblock()
static RPCMethod getdescriptoractivity()
static void SoftForkDescPushBack(const CBlockIndex *blockindex, UniValue &softforks, const ChainstateManager &chainman, Consensus::BuriedDeployment dep)
UniValue coinbaseTxToJSON(const CTransaction &coinbase_tx)
Serialize coinbase transaction metadata.
static constexpr size_t PER_UTXO_OVERHEAD
static RPCMethod getblockcount()
double GetDifficulty(const CBlockIndex &blockindex)
Get the difficulty of the net wrt to the given block index.
static const auto scan_objects_arg_desc
static RPCMethod scantxoutset()
static RPCMethod waitforblock()
static bool CheckBlockFilterMatches(BlockManager &blockman, const CBlockIndex &blockindex, const GCSFilter::ElementSet &needles)
void InvalidateBlock(ChainstateManager &chainman, const uint256 block_hash)
static RPCMethod getblockfrompeer()
static RPCMethod invalidateblock()
UniValue CreateUTXOSnapshot(node::NodeContext &node, Chainstate &chainstate, AutoFile &&afile, const fs::path &path, const fs::path &tmppath)
Helper to create UTXO snapshots given a chainstate and a file handle.
static RPCMethod waitfornewblock()
static std::atomic< int > g_scan_progress
RAII object to prevent concurrency issue when scanning the txout set.
static CBlock GetBlockChecked(BlockManager &blockman, const CBlockIndex &blockindex)
std::optional< int > GetPruneHeight(const BlockManager &blockman, const CChain &chain)
Return height of highest block that has been pruned, or std::nullopt if no blocks have been pruned.
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex &tip, const CBlockIndex &blockindex, TxVerbosity verbosity, const uint256 pow_limit)
Block description to JSON.
static RPCMethod getchainstates()
static RPCMethod verifychain()
static RPCMethod gettxout()
static RPCMethod syncwithvalidationinterfacequeue()
static RPCMethod getblockhash()
void ReconsiderBlock(ChainstateManager &chainman, uint256 block_hash)
static RPCMethod getchaintips()
UniValue blockheaderToJSON(const CBlockIndex &tip, const CBlockIndex &blockindex, const uint256 pow_limit)
Block header to JSON.
static RPCMethod getchaintxstats()
static const auto scan_result_status_some
static RPCMethod getblockstats()
static std::optional< kernel::CCoinsStats > GetUTXOStats(const CCoinsViewDB &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.
void RegisterBlockchainRPCCommands(CRPCTable &t)
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
static std::atomic< bool > g_should_abort_scan
const std::vector< RPCResult > RPCHelpForChainstate
static const auto scan_action_arg_desc
static const CBlockIndex * ParseHashOrHeight(const UniValue ¶m, ChainstateManager &chainman)
RPCMethod getblockchaininfo()
static RPCMethod waitforblockheight()
static RPCMethod dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
RPCMethod getdeploymentinfo()
static RPCMethod loadtxoutset()
static std::atomic< bool > g_scanfilter_in_progress
UniValue CreateRolledBackUTXOSnapshot(NodeContext &node, Chainstate &chainstate, const CBlockIndex *target, AutoFile &&afile, const fs::path &path, const fs::path &tmppath, bool in_memory)
static RPCMethod getblock()
static const auto scan_result_status_none
static RPCMethod gettxoutsetinfo()
constexpr int NUM_GETBLOCKSTATS_PERCENTILES
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
bool BlockFilterTypeByName(std::string_view 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.
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous.
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
@ BLOCK_HAVE_DATA
full block available in blk*.dat
@ BLOCK_FAILED_VALID
stage after last reached validness failed
constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
#define LIST_CHAIN_NAMES
List of possible chain / network names
#define CHECK_NONFATAL(condition)
Identity function.
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
Non-refcounted RAII wrapper for FILE*.
int64_t size()
Return the size of the file.
Complete block filter struct as defined in BIP 157.
const std::vector< unsigned char > & GetEncodedFilter() const LIFETIMEBOUND
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilterRange(int start_height, const CBlockIndex *stop_index, std::vector< BlockFilter > &filters_out) const
Get a range of filters between two heights on a chain.
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.
BlockFiltersScanReserver()=default
~BlockFiltersScanReserver()
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
bool IsValid(enum BlockStatus nUpTo) 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
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including 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 ...
uint256 GetBlockHash() const
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.
int nHeight
height of the entry in the chain. The genesis block has height 0
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Undo information for a CBlock.
std::vector< CTxUndo > vtxundo
An in-memory indexed chain of blocks.
bool Contains(const CBlockIndex &index) const
Efficiently check whether a block is present in this chain.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
const CBlockIndex * FindFork(const CBlockIndex &index) const
Find the last common block between this chain and a block index entry.
CBlockIndex * Genesis() const
Returns the index entry for the genesis block 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.
std::string GetChainTypeString() const
Return the chain type string.
const MessageStartChars & MessageStart() const
const Consensus::Params & GetConsensus() const
uint64_t PruneAfterHeight() const
ChainType GetChainType() const
Return the chain type.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
virtual void Flush(bool reallocate_cache=true)
Push the modifications applied to this cache to its base and wipe local state.
void SetBestBlock(const uint256 &block_hash)
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Cursor for iterating over CoinsView state.
virtual bool Valid() const =0
virtual bool GetKey(COutPoint &key) const =0
virtual bool GetValue(Coin &coin) const =0
CCoinsView backed by the coin database (chainstate/)
std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
CCoinsView that brings transactions from a mempool into view.
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
GetCoin, returning whether it exists and is not spent.
An outpoint - a combination of a transaction hash and an index n into its vout.
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxIn > vin
An input of a transaction.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
CTransactionRef get(const Txid &hash) const
Return a mempool transaction with a given hash.
std::vector< CTxMemPoolEntryRef > entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool isSpent(const COutPoint &outpoint) const
An output of a transaction.
Undo information for a CTransaction.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, 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.
CChain m_chain
The current chain of blockheaders we consult and build on.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(void SetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
void ForceFlushStateToDisk(bool wipe_cache=true)
Flush all changes to disk.
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
double GetBackgroundVerificationProgress(const CBlockIndex &pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Guess background verification progress in case assume-utxo was used (as a fraction between 0....
double GuessVerificationProgress(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
bool IsInitialBlockDownload() const noexcept
Check whether we are doing an initial block download (synchronizing from disk or network)
kernel::Notifications & GetNotifications() const
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the sna...
VersionBitsCache m_versionbitscache
Track versionbit status.
const CChainParams & GetParams() const
const Consensus::Params & GetConsensus() const
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(util::Result< CBlockIndex * ActivateSnapshot)(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Instantiate a new chainstate.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
CTxOut out
unspent transaction output
uint32_t nHeight
at which height this containing transaction was included in the active block chain
CoinsViewScanReserver()=default
Double ended buffer combining vector and stream-like interfaces.
std::unordered_set< Element, ByteVectorHash > ElementSet
virtual util::Expected< void, std::string > FetchBlock(NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
auto Arg(std::string_view key) const
Helper to get a required or default-valued request argument.
Minimal stream for reading from an existing byte array by std::span.
RAII class that registers a prune lock in its constructor to prevent block data from being pruned,...
BlockManager & m_blockman
static constexpr const char * LOCK_NAME
TemporaryPruneLock(BlockManager &blockman, int height)
RAII class that creates a temporary database directory in its constructor and removes it in its destr...
TemporaryUTXODatabase(const fs::path &path)
void push_back(UniValue val)
const std::string & get_str() const
const std::vector< UniValue > & getValues() const
const UniValue & get_array() const
void reserve(size_t new_cap)
void pushKV(std::string key, UniValue val)
void push_backV(const std::vector< UniValue > &vec)
std::string ToString() const
BIP9Info Info(const CBlockIndex &block_index, const Consensus::Params ¶ms, Consensus::DeploymentPos id) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
256-bit unsigned big integer.
std::string ToString() const
std::string GetHex() const
uint64_t GetLow64() const
std::string GetHex() const
Hex encoding of the number (with the most significant digits first).
Interface giving clients (RPC, Stratum v2 Template Provider in the future) ability to create block te...
virtual std::optional< BlockRef > waitTipChanged(uint256 current_tip, MillisecondsDouble timeout=MillisecondsDouble::max())=0
Waits for the connected tip to change.
virtual std::optional< BlockRef > getTip()=0
Returns the hash and height for the tip of this chain.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
CBlockFileInfo *GetBlockFileInfo(size_t n) EXCLUSIVE_LOCKS_REQUIRED(bool WriteBlockUndo(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos WriteBlock(const CBlock &block, int nHeight) EXCLUSIVE_LOCKS_REQUIRED(void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(bool IsPruneMode() const
Get block file info entry for one block file.
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
ReadRawBlockResult ReadRawBlock(const FlatFilePos &pos, std::optional< std::pair< size_t, size_t > > block_part=std::nullopt) const
bool ReadBlock(CBlock &block, const FlatFilePos &pos, const std::optional< uint256 > &expected_hash) const
Functions for disk access for blocks.
constexpr const std::byte * begin() const
std::string GetHex() const
static transaction_identifier FromUint256(const uint256 &id)
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static int64_t GetBlockWeight(const CBlock &block)
static int32_t GetTransactionWeight(const CTransaction &tx)
constexpr unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
constexpr int WITNESS_SCALE_FACTOR
void ScriptToUniv(const CScript &script, UniValue &out, bool include_hex, bool include_address, const SigningProvider *provider)
void TxToUniv(const CTransaction &tx, const uint256 &block_hash, UniValue &entry, bool include_hex, const CTxUndo *txundo, TxVerbosity verbosity, std::function< bool(const CTxOut &)> is_change_func)
UniValue ValueFromAmount(const CAmount amount)
TxVerbosity
Verbose level for block's transaction.
@ SHOW_DETAILS_AND_PREVOUT
The same as previous option with information about prevouts if available.
@ SHOW_TXID
Only TXID for each block's transaction.
@ SHOW_DETAILS
Include TXID, inputs, outputs, and other common block's transaction information.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
bool DestroyDB(const std::string &path_str)
std::string DeploymentName(Consensus::BuriedDeployment dep)
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::BuriedDeployment dep, VersionBitsCache &versionbitscache)
Determine if a deployment is active for the next block.
bool DeploymentEnabled(const Consensus::Params ¶ms, Consensus::BuriedDeployment dep)
Determine if a deployment is enabled (can ever be active)
const std::string CURRENCY_UNIT
static path u8path(std::string_view utf8_str)
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to a byte string.
#define T(expected, seed, data)
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::vector< std::string > GetScriptFlagNames(script_verify_flags flags)
#define LogDebug(category,...)
BuriedDeployment
A buried deployment is one where the height of the activation has been hardcoded into the client impl...
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.
static std::optional< CCoinsStats > ComputeUTXOStats(T hash_obj, const CCoinsViewDB &view, node::BlockManager &blockman, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
UniValue GetWarningsForRpc(const Warnings &warnings, bool use_deprecated)
RPC helper function that wraps warnings.GetMessages().
bilingual_str ErrorString(const Result< T > &result)
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
constexpr TransactionSerParams TX_NO_WITNESS
constexpr TransactionSerParams TX_WITH_WITNESS
std::shared_ptr< const CTransaction > CTransactionRef
std::vector< RPCResult > TxDoc(const TxDocOptions &opts)
Explain the UniValue "decoded" transaction object, may include extra fields if processed by wallet.
@ WithSummary
first field carries elision_summary as "...", rest skipped
@ Silent
all top-level fields skipped silently (no "..." line)
UniValue JSONRPCError(int code, const std::string &message)
@ RPC_MISC_ERROR
General application defined errors.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_DATABASE_ERROR
Database error.
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider, const bool expand_priv)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
uint256 GetTarget(const CBlockIndex &blockindex, const uint256 pow_limit)
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.
int ParseVerbosity(const UniValue &arg, int default_verbosity, bool allow_bool)
Parses verbosity from provided UniValue.
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
std::vector< RPCResult > ScriptPubKeyDoc()
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
uint64_t GetSerializeSize(const T &t)
bool IsDeprecatedRPCEnabled(const std::string &method)
ChainstateManager & EnsureAnyChainman(const std::any &context)
NodeContext & EnsureAnyNodeContext(const std::any &context)
CTxMemPool & EnsureMemPool(const NodeContext &node)
PeerManager & EnsurePeerman(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
ArgsManager & EnsureArgsman(const NodeContext &node)
interfaces::Mining & EnsureMining(const NodeContext &node)
ArgsManager & EnsureAnyArgsman(const std::any &context)
unsigned char * UCharCast(char *c)
Detailed status of an enabled BIP9 deployment.
User-controlled performance and debug options.
Comparison function for sorting the getchaintips heads.
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
std::vector< uint8_t > signet_challenge
uint256 powLimit
Proof of work parameters.
int DeploymentHeight(BuriedDeployment dep) const
std::array< BIP9Deployment, MAX_VERSION_BITS_DEPLOYMENTS > vDeployments
int64_t nPowTargetSpacing
User-controlled performance and debug options.
Application-specific storage settings.
fs::path path
Location in the filesystem where leveldb data will be stored.
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ OBJ_NAMED_PARAMS
Special type that behaves almost exactly like OBJ, defining an options object with a list of pre-defi...
std::string DefaultHint
Hint for default value.
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
UniValue Default
Default constant value.
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
@ NUM_TIME
Special numeric to denote unix epoch time.
@ ARR_FIXED
Special array that has a fixed number of entries.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
HelpElision print_elision
Hash/height pair to help track and identify blocks.
arith_uint256 total_prevout_spent_amount
Total cumulative amount of prevouts spent up to and including this block.
std::optional< CAmount > total_amount
The total amount, or nullopt if an overflow occurred calculating it.
CAmount total_unspendables_scripts
Total cumulative amount of outputs sent to unspendable scripts (OP_RETURN for example) up to and incl...
uint64_t coins_count
The number of coins contained.
arith_uint256 total_coinbase_amount
Total cumulative amount of coinbase outputs up to and including this block.
uint64_t nTransactionOutputs
bool index_used
Signals if the coinstatsindex was used to retrieve the statistics.
CAmount total_unspendables_bip30
The two unspendable coinbase outputs total amount caused by BIP30.
CAmount total_unspendables_genesis_block
The unspendable coinbase amount from the genesis block.
arith_uint256 total_new_outputs_ex_coinbase_amount
Total cumulative amount of outputs created up to and including this block.
CAmount total_unspendables_unclaimed_rewards
Total cumulative amount of coins lost due to unclaimed miner rewards up to and including this block.
NodeContext struct containing references to chain state and connection state.
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
std::string SysErrorString(int err)
Return system error string from errno value.
FuzzedDataProvider provider
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOG_TIME_SECONDS(end_msg)
consteval auto _(util::TranslatedLiteral str)
constexpr uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
const UniValue NullUniValue
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
script_verify_flags GetBlockScriptFlags(const CBlockIndex &block_index, const ChainstateManager &chainman)
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
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.
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30)
constexpr signed int DEFAULT_CHECKBLOCKS
constexpr int DEFAULT_CHECKLEVEL
@ VALIDATED
Every block in the chain has been validated.
constexpr unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...