10#include <blockfilter.h>
12#include <chainparams.h>
76#include <versionbits.h>
121 const fs::path& path,
130 const fs::path& path,
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>()};
217 if (blockindex.
pprev)
220 result.
pushKV(
"nextblockhash",
pnext->GetBlockHash().GetHex());
254 txs.reserve(block.
vtx.size());
259 txs.push_back(tx->GetHash().GetHex());
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) {
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)",
353 const int timeout{
self.Arg<
int>(
"timeout")};
367 uint256 tip_hash{request.params[1].isNull()
369 :
ParseHashV(request.params[1],
"current_tip")};
373 std::optional<BlockRef> block = timeout ? block_template_manager.
WaitTipChanged(tip_hash, std::chrono::milliseconds(timeout)) :
391 "Waits for a specific new block and returns useful info about it.\n"
392 "\nReturns the current block on timeout or exit.\n"
393 "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
405 HelpExampleCli(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\" 1000")
406 +
HelpExampleRpc(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
410 const int timeout{
self.Arg<
int>(
"timeout")};
422 const auto deadline{std::chrono::steady_clock::now() + 1
ms * timeout};
424 std::optional<BlockRef> block;
426 auto now{std::chrono::steady_clock::now()};
449 "waitforblockheight",
450 "Waits for (at least) block height and returns the height and hash\n"
451 "of the current tip.\n"
452 "\nReturns the current block on timeout or exit.\n"
453 "\nMake sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
470 const int timeout{
self.Arg<
int>(
"timeout")};
472 int height = request.params[0].
getInt<
int>();
482 const auto deadline{std::chrono::steady_clock::now() + 1
ms * timeout};
485 std::optional<BlockRef> block;
487 auto now{std::chrono::steady_clock::now()};
510 "syncwithvalidationinterfacequeue",
511 "Waits for the validation interface queue to catch up on everything that was there when we entered this function.\n",
531 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
534 RPCResult::Type::NUM,
"",
"the proof-of-work difficulty as a multiple of the minimum difficulty."},
552 "Attempt to fetch block from a given peer.\n\n"
553 "We must have the header for this block, e.g. using submitheader.\n"
554 "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"
555 "Subsequent calls for the same block may cause the response from the previous peer to be ignored.\n"
556 "Peers generally ignore requests for a stale block that they never fully verified, or one that is more than a month old.\n"
557 "When a peer does not respond with a block, we will disconnect.\n"
558 "Note: The block could be re-pruned as soon as it is received.\n\n"
559 "Returns an empty JSON object if the request was successfully scheduled.",
566 HelpExampleCli(
"getblockfrompeer",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 0")
567 +
HelpExampleRpc(
"getblockfrompeer", R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", 0)")
587 throw JSONRPCError(
RPC_MISC_ERROR,
"In prune mode, only blocks that the node has already synced previously can be fetched from a peer");
607 "Returns hash of block in best-block-chain at height provided.\n",
623 int nHeight = request.params[0].getInt<
int>();
637 "If verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
638 "If verbose is true, returns an Object with information about blockheader <hash>.\n",
648 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
668 HelpExampleCli(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
669 +
HelpExampleRpc(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
707 if (!(blockindex.nStatus & flag)) {
708 if (
blockman.IsBlockPruned(blockindex)) {
726 if (!
blockman.ReadBlock(block, blockindex)) {
771 auto fields = std::vector<RPCResult>{
773 {
RPCResult::Type::NUM,
"confirmations",
"The number of confirmations, or -1 if the block is not on the main chain"},
783 {
RPCResult::Type::STR_HEX,
"witness",
true,
"The coinbase input's first (and only) witness stack element, if present"},
794 fields.emplace_back(
RPCResult::Type::STR_HEX,
"bits",
"nBits: compact representation of the block difficulty target");
797 fields.emplace_back(
RPCResult::Type::STR_HEX,
"chainwork",
"Expected number of hashes required to produce the chain up to this block (in hex)");
799 fields.emplace_back(
RPCResult::Type::STR_HEX,
"previousblockhash",
true,
"The hash of the previous block (if available)");
806 for (
const auto&
f : fields) {
807 if (
f.m_key_name ==
"tx") {
831 "If verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
832 "If verbosity is 1, returns an Object with information about block <hash>.\n"
833 "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction.\n"
834 "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",
837 {
"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",
850 .elision_summary =
"The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result",
851 .fee =
true, .hex =
true,
852 .fee_doc =
"The transaction fee in " +
CURRENCY_UNIT +
", omitted if block undo data is not available"})},
853 }},
"Same output as verbosity = 1")},
860 .prevout_optional =
true,
864 .prevout_doc =
"(Only if undo information is available)",
865 .vin_inner_elision =
"The same output as verbosity = 2"})},
866 }},
"Same output as verbosity = 2")},
869 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
870 +
HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
943 "Attempts to delete block and undo data up to a specified height or timestamp, if eligible for pruning.\n"
944 "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",
947 " to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
989 LogDebug(
BCLog::RPC,
"Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
1002 return CoinStatsHashType::HASH_SERIALIZED;
1004 return CoinStatsHashType::MUHASH;
1006 return CoinStatsHashType::NONE;
1046 "Returns statistics about the unspent transaction output set.\n"
1047 "Note this call may take some time if you are not using coinstatsindex.\n",
1049 {
"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'."},
1053 .type_str = {
"",
"string or numeric"},
1063 {
RPCResult::Type::NUM,
"bogosize",
"Database-independent, meaningless metric indicating the UTXO set size"},
1064 {
RPCResult::Type::STR_HEX,
"hash_serialized_3",
true,
"The serialized hash (only present if 'hash_serialized_3' hash_type is chosen)"},
1066 {
RPCResult::Type::NUM,
"transactions",
true,
"The number of transactions with unspent outputs (not available when coinstatsindex is used)"},
1067 {
RPCResult::Type::NUM,
"disk_size",
true,
"The estimated size of the chainstate on disk (not available when coinstatsindex is used)"},
1069 {
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)"},
1070 {
RPCResult::Type::OBJ,
"block_info",
true,
"Info on amounts in the block at this block height (only available if coinstatsindex is used)",
1089 HelpExampleCli("gettxoutsetinfo", R
"("none" 00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09)") +
1090 HelpExampleCli("-named gettxoutsetinfo", R
"(hash_type='muhash' use_index='false')") +
1094 HelpExampleRpc("gettxoutsetinfo", R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")
1112 if (!request.params[1].isNull()) {
1117 if (
hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1146 if (
hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1149 if (
hash_type == CoinStatsHashType::MUHASH) {
1175 prev_stats.total_unspendables_unclaimed_rewards;
1213 "Returns details about an unspent transaction output.\n",
1217 {
"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."},
1230 {
RPCResult::Type::STR,
"address",
true,
"The Bitcoin address (only if a well-defined address exists)"},
1236 "\nGet unspent transactions\n"
1238 "\nView the details\n"
1240 "\nAs a JSON-RPC call\n"
1253 const bool fMempool{
self.Arg<
bool>(
"include_mempool")};
1258 std::optional<Coin> coin;
1263 if (!mempool.
isSpent(out)) coin =
view.GetCoin(out);
1265 coin = coins_view->
GetCoin(out);
1272 ret.pushKV(
"confirmations", 0);
1274 ret.pushKV(
"confirmations", pindex->
nHeight - coin->nHeight + 1);
1279 ret.pushKV(
"scriptPubKey", std::move(
o));
1280 ret.pushKV(
"coinbase", coin->IsCoinBase());
1291 "Verifies blockchain database.\n",
1298 RPCResult::Type::BOOL,
"",
"Verification finished successfully. If false, check debug log for reason."},
1305 const int check_level{
self.Arg<
int>(
"checklevel")};
1325 rv.pushKV(
"type",
"buried");
1337 if (blockindex ==
nullptr)
return;
1344 if (info.stats.has_value()) {
1349 bip9.pushKV(
"min_activation_height",
depparams.min_activation_height);
1352 bip9.pushKV(
"status", info.current_state);
1353 bip9.pushKV(
"since", info.since);
1354 bip9.pushKV(
"status_next", info.next_state);
1357 if (info.stats.has_value()) {
1359 statsUV.pushKV(
"period", info.stats->period);
1360 statsUV.pushKV(
"elapsed", info.stats->elapsed);
1361 statsUV.pushKV(
"count", info.stats->count);
1362 if (info.stats->threshold > 0 || info.stats->possible) {
1363 statsUV.pushKV(
"threshold", info.stats->threshold);
1364 statsUV.pushKV(
"possible", info.stats->possible);
1369 sig.reserve(info.signalling_blocks.size());
1370 for (
const bool s : info.signalling_blocks) {
1371 sig.push_back(s ?
'#' :
'-');
1373 bip9.pushKV(
"signalling", sig);
1377 rv.pushKV(
"type",
"bip9");
1379 if (info.active_since.has_value()) {
1380 rv.pushKV(
"height", *info.active_since);
1392 "Returns an object containing various state info regarding blockchain processing.\n",
1398 {
RPCResult::Type::NUM,
"blocks",
"the height of the most-work fully-validated chain. The genesis block has height 0"},
1407 {
RPCResult::Type::BOOL,
"initialblockdownload",
"(debug information) estimate of whether this node is in Initial Block Download mode"},
1408 {
RPCResult::Type::OBJ,
"backgroundvalidation",
true,
"state info regarding background validation process",
1410 {
RPCResult::Type::NUM,
"snapshotheight",
"the height of the snapshot block. Background validation verifies the chain from genesis up to this height"},
1411 {
RPCResult::Type::NUM,
"blocks",
"the height of the most-work background fully-validated chain. The genesis block has height 0"},
1412 {
RPCResult::Type::STR,
"bestblockhash",
"the hash of the currently best block validated in the background"},
1414 {
RPCResult::Type::NUM,
"verificationprogress",
"estimate of background verification progress [0..1]"},
1418 {
RPCResult::Type::NUM,
"size_on_disk",
"the estimated size of the block and undo files on disk"},
1420 {
RPCResult::Type::NUM,
"pruneheight",
true,
"the first block unpruned, all previous blocks were pruned (only present if pruning is enabled)"},
1421 {
RPCResult::Type::BOOL,
"automatic_pruning",
true,
"whether automatic pruning is enabled (only present if pruning is enabled)"},
1422 {
RPCResult::Type::NUM,
"prune_target_size",
true,
"the target size used by pruning (only present if automatic pruning is enabled)"},
1423 {
RPCResult::Type::STR_HEX,
"signet_challenge",
true,
"the block challenge (aka. block script), in hexadecimal (only present if the current network is a signet)"},
1426 RPCResult{
RPCResult::Type::ARR,
"warnings",
"any network and blockchain warnings (run with `-deprecatedrpc=warnings` to return the latest warning as a single string)",
1447 obj.pushKV(
"blocks", height);
1448 obj.pushKV(
"headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
1449 obj.pushKV(
"bestblockhash",
tip.GetBlockHash().GetHex());
1453 obj.pushKV(
"time",
tip.GetBlockTime());
1454 obj.pushKV(
"mediantime",
tip.GetMedianTimePast());
1470 obj.pushKV(
"chainwork",
tip.nChainWork.GetHex());
1471 obj.pushKV(
"size_on_disk", chainman.
m_blockman.CalculateCurrentUsage());
1484 const std::vector<uint8_t>& signet_challenge =
1486 obj.pushKV(
"signet_challenge",
HexStr(signet_challenge));
1499 {
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)"},
1500 {
RPCResult::Type::BOOL,
"active",
"true if the rules are enforced for the mempool and the next block"},
1503 {
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)"},
1504 {
RPCResult::Type::NUM_TIME,
"start_time",
"the minimum median time past of a block at which the bit gains its meaning"},
1505 {
RPCResult::Type::NUM_TIME,
"timeout",
"the median time past of a block at which the deployment is considered failed if not yet locked in"},
1506 {
RPCResult::Type::NUM,
"min_activation_height",
"minimum height of blocks for which the rules may be enforced"},
1507 {
RPCResult::Type::STR,
"status",
"status of deployment at specified block (one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\")"},
1510 {
RPCResult::Type::OBJ,
"statistics",
true,
"numeric statistics about signalling for a softfork (only for \"started\" and \"locked_in\" status)",
1513 {
RPCResult::Type::NUM,
"threshold",
true,
"the number of blocks with the version bit set required to activate the feature (only for \"started\" status)"},
1514 {
RPCResult::Type::NUM,
"elapsed",
"the number of blocks elapsed since the beginning of the current period"},
1515 {
RPCResult::Type::NUM,
"count",
"the number of blocks with the version bit set in the current period"},
1516 {
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)"},
1518 {
RPCResult::Type::STR,
"signalling",
true,
"indicates blocks that signalled with a # and blocks that did not with a -"},
1538 "Returns an object containing various state info regarding deployments of consensus changes.\n"
1539 "Consensus changes for which the new rules are enforced from genesis are not listed in \"deployments\".",
1563 if (request.params[0].isNull()) {
1606 "Return information about all known tips in the block tree,"
1607 " including the main chain as well as orphaned branches.\n",
1615 {
RPCResult::Type::NUM,
"branchlen",
"zero for main chain, otherwise length of branch connecting the tip to the main chain"},
1617 "Possible values for status:\n"
1618 "1. \"invalid\" This branch contains at least one invalid block\n"
1619 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
1620 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
1621 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
1622 "5. \"active\" This is the tip of the active main chain, which is certainly valid"},
1641 std::set<const CBlockIndex*, CompareBlocksByHeight>
setTips;
1643 std::set<const CBlockIndex*>
setPrevs;
1652 for (std::set<const CBlockIndex*>::iterator it =
setOrphans.begin(); it !=
setOrphans.end(); ++it) {
1666 obj.pushKV(
"height", block->nHeight);
1667 obj.pushKV(
"hash", block->phashBlock->GetHex());
1679 }
else if (!block->HaveNumChainTxs()) {
1681 status =
"headers-only";
1684 status =
"valid-fork";
1687 status =
"valid-headers";
1692 obj.pushKV(
"status", status);
1694 res.push_back(std::move(
obj));
1706 "Treats a block as if it were received before others with the same work.\n"
1707 "\nThis only breaks ties between chains with equal work. If the specified block has the same work as the current tip, "
1708 "the node switches its active chain to it. If the specified block has less work than the current tip (including any "
1709 "ancestor of the tip), the call has no effect. If another chain later gains more work, the node switches to it as usual.\n"
1710 "\nA later preciousblock call can override the effect of an earlier one.\n"
1711 "\nThe effects of preciousblock are not retained across restarts.\n",
1771 "Permanently marks a block as invalid, as if it violated a consensus rule.\n",
1801 chainman.RecalculateBestHeader();
1816 "Removes invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n"
1817 "This can be used to undo the effects of invalidateblock.\n",
1842 "Compute statistics about the total number and rate of transactions in the chain.\n",
1852 "The total number of transactions in the chain up to that point, if known. "
1853 "It may be unknown when using assumeutxo."},
1855 {
RPCResult::Type::NUM,
"window_final_block_height",
"The height of the final block in the window."},
1857 {
RPCResult::Type::NUM,
"window_interval",
true,
"The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0"},
1859 "The number of transactions in the window. "
1860 "Only returned if \"window_block_count\" is > 0 and if txcount exists for the start and end of the window."},
1862 "The average rate of transactions per second in the window. "
1863 "Only returned if \"window_interval\" is > 0 and if window_tx_count exists."},
1875 if (request.params[1].isNull()) {
1892 if (request.params[0].isNull()) {
1895 blockcount = request.params[0].getInt<
int>();
1911 ret.pushKV(
"window_final_block_height", pindex->
nHeight);
1932 size_t size =
scores.size();
1938 if (size % 2 == 0) {
1970 result[i] =
scores.back().first;
1975static inline bool SetHasKeys(
const std::set<T>& set) {
return false;}
1976template<
typename T,
typename Tk,
typename... Args>
1989 "Compute per block statistics for a given window. All amounts are in satoshis.\n"
1990 "It won't work for some heights with pruning.\n",
1995 .type_str = {
"",
"string or numeric"},
2011 {
RPCResult::Type::ARR_FIXED,
"feerate_percentiles",
true,
"Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)",
2036 {
RPCResult::Type::NUM,
"total_out",
true,
"Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])"},
2041 {
RPCResult::Type::NUM,
"utxo_increase",
true,
"The increase/decrease in the number of unspent outputs (not discounting op_return and similar)"},
2042 {
RPCResult::Type::NUM,
"utxo_size_inc",
true,
"The increase/decrease in size for the utxo index (not discounting op_return and similar)"},
2043 {
RPCResult::Type::NUM,
"utxo_increase_actual",
true,
"The increase/decrease in the number of unspent outputs, not counting unspendables"},
2044 {
RPCResult::Type::NUM,
"utxo_size_inc_actual",
true,
"The increase/decrease in size for the utxo index, not counting unspendables"},
2047 HelpExampleCli(
"getblockstats", R
"(00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09 '["minfeerate","avgfeerate"]')") +
2048 HelpExampleCli("getblockstats", R
"(1000 '["minfeerate","avgfeerate"]')") +
2049 HelpExampleRpc("getblockstats", R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2050 HelpExampleRpc("getblockstats", R
"(1000, ["minfeerate","avgfeerate"])")
2057 std::set<std::string> stats;
2058 if (!request.params[1].isNull()) {
2069 const bool do_all = stats.size() == 0;
2074 SetHasKeys(stats,
"utxo_increase",
"utxo_increase_actual",
"utxo_size_inc",
"utxo_size_inc_actual",
"totalfee",
"avgfee",
"avgfeerate",
"minfee",
"maxfee",
"minfeerate",
"maxfeerate");
2077 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
"maxtxsize",
"swtotal_size");
2078 const bool do_calculate_weight =
do_all ||
SetHasKeys(stats,
"total_weight",
"avgfeerate",
"swtotal_weight",
"avgfeerate",
"feerate_percentiles",
"minfeerate",
"maxfeerate");
2103 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2104 const auto& tx = block.
vtx.at(i);
2105 outputs += tx->vout.size();
2109 for (
const CTxOut& out : tx->vout) {
2119 if (out.scriptPubKey.IsUnspendable())
continue;
2126 if (tx->IsCoinBase()) {
2130 inputs += tx->vin.size();
2136 tx_size = tx->ComputeTotalSize();
2203 ret_all.pushKV(
"ins", inputs);
2213 ret_all.pushKV(
"outs", outputs);
2224 ret_all.pushKV(
"utxo_increase", outputs - inputs);
2226 ret_all.pushKV(
"utxo_increase_actual",
utxos - inputs);
2234 for (
const std::string&
stat : stats) {
2252 while (
cursor->Valid()) {
2255 if (!
cursor->GetKey(key) || !
cursor->GetValue(coin))
return false;
2256 if (++
count % 8192 == 0) {
2263 if (
count % 256 == 0) {
2309 "\"start\" for starting a scan\n"
2310 "\"abort\" for aborting the current scan (returns true when abort was successful)\n"
2311 "\"status\" for progress report (in %) of the current scan"
2324 "Every scan object is either a string descriptor or an object:",
2334 "True if scan will be aborted (not necessarily before this RPC returns), or false if there is no scan to abort"
2337 "when action=='status' and no scan is in progress - possibly already completed",
RPCResult::Type::NONE,
"",
""
2348 const std::string
EXAMPLE_DESCRIPTOR_RAW =
"raw(76a91411b366edfc0a8b66feebae5c2e25a7b6a5d1cf3188ac)#fm24fxxy";
2352 "Scans the unspent transaction output set for entries that match certain output descriptors.\n"
2353 "Examples of output descriptors are:\n"
2354 " addr(<address>) Outputs whose output script corresponds to the specified address (does not include P2PK)\n"
2355 " raw(<hex script>) Outputs whose output script equals the specified hex-encoded bytes\n"
2356 " combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n"
2357 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
2358 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
2359 " tr(<pubkey>) P2TR\n"
2360 " tr(<pubkey>,{pk(<pubkey>)}) P2TR with single fallback pubkey in tapscript\n"
2361 " rawtr(<pubkey>) P2TR with the specified key as output key rather than inner\n"
2362 " wsh(and_v(v:pk(<pubkey>),after(2))) P2WSH miniscript with mandatory pubkey and a timelock\n"
2363 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2364 "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2365 "unhardened or hardened child keys.\n"
2366 "In the latter case, a range needs to be specified by below if different from 1000.\n"
2367 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
2390 {
RPCResult::Type::NUM,
"confirmations",
"Number of confirmations of the unspent transaction output when the scan was done"},
2410 const auto action{
self.Arg<std::string_view>(
"action")};
2411 if (
action ==
"status") {
2419 }
else if (
action ==
"abort") {
2428 }
else if (
action ==
"start") {
2457 std::map<COutPoint, Coin> coins;
2460 std::unique_ptr<CCoinsViewCursor> pcursor;
2475 result.
pushKV(
"bestblock",
tip->GetBlockHash().GetHex());
2477 for (
const auto& it : coins) {
2479 const Coin& coin = it.second;
2487 unspent.pushKV(
"vout", outpoint.
n);
2542 for (
const auto& tx : block.vtx) {
2543 if (std::any_of(tx->vout.cbegin(), tx->vout.cend(), [&](
const auto& txout) {
2544 return needles.contains(std::vector<unsigned char>(txout.scriptPubKey.begin(), txout.scriptPubKey.end()));
2551 if (std::any_of(
txundo.vprevout.cbegin(),
txundo.vprevout.cend(), [&](
const auto& coin) {
2552 return needles.contains(std::vector<unsigned char>(coin.out.scriptPubKey.begin(), coin.out.scriptPubKey.end()));
2565 "Return relevant blockhashes for given descriptors (requires blockfilterindex).\n"
2566 "This call may take several minutes. Make sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
2575 {
"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"},
2597 HelpExampleCli(
"scanblocks",
"start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 300000") +
2598 HelpExampleCli(
"scanblocks",
"start '[\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"]' 100 150 basic") +
2600 HelpExampleRpc(
"scanblocks",
"\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 300000") +
2601 HelpExampleRpc(
"scanblocks",
"\"start\", [\"addr(bcrt1q4u4nsgk6ug0sqz7r3rj9tykjxrsl0yy4d0wwte)\"], 100, 150, \"basic\"") +
2607 auto action{
self.Arg<std::string_view>(
"action")};
2608 if (
action ==
"status") {
2617 }
else if (
action ==
"abort") {
2626 }
else if (
action ==
"start") {
2643 bool filter_false_positives{options.exists(
"filter_false_positives") ? options[
"filter_false_positives"].get_bool() :
false};
2664 if (!request.params[3].isNull()) {
2685 std::vector<BlockFilter>
filters;
2696 node.rpc_interruption_point();
2711 if (filter.GetFilter().MatchAny(
needle_set)) {
2721 blocks.push_back(filter.GetBlockHash().GetHex());
2741 ret.pushKV(
"relevant_blocks", std::move(
blocks));
2754 "getdescriptoractivity",
2755 "Get spend and receive activity associated with a set of descriptors for a set of blocks. "
2756 "This command pairs well with the `relevant_blocks` output of `scanblocks()`.\n"
2757 "This call may take several minutes. If you encounter timeouts, try specifying no RPC timeout (bitcoin-cli -rpcclienttimeout=0)",
2795 }, {.skip_type_check=
true}, },
2799 HelpExampleCli(
"getdescriptoractivity",
"'[\"000000000000000000001347062c12fded7c528943c8ce133987e2e2f5a840ee\"]' '[\"addr(bc1qzl6nsgqzu89a66l50cvwapnkw5shh23zarqkw9)\"]'")
2819 for (
const UniValue& blockhash : request.params[0].get_array().getValues()) {
2856 event.pushKV(
"type",
"spend");
2859 event.pushKV(
"blockhash", index->GetBlockHash().ToString());
2860 event.pushKV(
"height", index->nHeight);
2862 event.pushKV(
"spend_txid", tx->GetHash().ToString());
2863 event.pushKV(
"spend_vin", vin);
2864 event.pushKV(
"prevout_txid",
txin.prevout.hash.ToString());
2865 event.pushKV(
"prevout_vout",
txin.prevout.n);
2866 event.pushKV(
"prevout_spk",
spkUv);
2876 event.pushKV(
"type",
"receive");
2879 event.pushKV(
"blockhash", index->GetBlockHash().ToString());
2880 event.pushKV(
"height", index->nHeight);
2882 event.pushKV(
"txid", tx->GetHash().ToString());
2883 event.pushKV(
"vout", vout);
2884 event.pushKV(
"output_spk",
spkUv);
2900 for (
size_t i = 0; i < block.vtx.size(); ++i) {
2901 const auto& tx = block.vtx.at(i);
2903 if (!tx->IsCoinBase()) {
2918 const auto& vout = tx->vout.at(
vout_idx);
2935 const auto& tx =
e.GetSharedTx();
2941 std::optional<Coin> coin = coins_view.
GetCoin(
txin.prevout);
2950 throw std::runtime_error(
"Invalid output index");
2953 scriptPubKey = out.scriptPubKey;
2957 const CTxOut& out = coin->out;
2958 scriptPubKey = out.scriptPubKey;
2965 scriptPubKey, value, tx,
vin_idx,
txin,
nullptr));
2970 const auto& vout = tx->vout.at(
vout_idx);
2988 "Retrieve a BIP 157 content filter for a particular block.\n",
3000 HelpExampleCli(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"") +
3001 HelpExampleRpc(
"getblockfilter",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\", \"basic\"")
3030 bool index_ready = index->BlockUntilSyncedToCurrentChain();
3037 std::string
errmsg =
"Filter not found.";
3041 errmsg +=
" Block was not connected to active chain.";
3044 errmsg +=
" Block filters are still in the process of being indexed.";
3047 errmsg +=
" This error is unexpected and indicates index corruption.";
3067 static constexpr const char*
LOCK_NAME{
"dumptxoutset-rollback"};
3093 "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"
3094 "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"
3095 "For deep rollbacks, make sure to use no RPC timeout (bitcoin-cli -rpcclienttimeout=0) as it may take several minutes.",
3098 {
"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."},
3102 "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.",
3104 {
"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)."},
3116 {
RPCResult::Type::NUM,
"nchaintx",
"the number of transactions in the chain up to and including the base block"},
3120 HelpExampleCli(
"-rpcclienttimeout=0 dumptxoutset",
"utxo.dat latest") +
3121 HelpExampleCli(
"-rpcclienttimeout=0 dumptxoutset",
"utxo.dat rollback") +
3122 HelpExampleCli(
"-rpcclienttimeout=0 -named dumptxoutset", R
"(utxo.dat rollback=853456)") +
3123 HelpExampleCli("-rpcclienttimeout=0 -named dumptxoutset", R
"(utxo.dat rollback=853456 in_memory=true)")
3132 if (options.exists(
"rollback")) {
3158 path.utf8string() +
" already exists. If you are sure this is what you want, "
3159 "move it out of the way first");
3164 if (
afile.IsNull()) {
3167 "Couldn't open file " +
temppath.utf8string() +
" for writing.");
3179 if (
node.chainman->m_blockman.IsPruneMode()) {
3189 const bool in_memory{options.exists(
"in_memory") ? options[
"in_memory"].get_bool() :
false};
3217 fs::create_directories(
m_path);
3221 LogInfo(
"Failed to clean up temporary UTXO database at %s, please remove it manually.",
3232 const fs::path& path,
3245 LogInfo(
"Using in-memory database for UTXO-set rollback (this may require significant RAM).");
3258 std::unique_ptr<CCoinsViewDB>
temp_db = std::make_unique<CCoinsViewDB>(
3264 LogInfo(
"Copying current UTXO set to temporary database.");
3267 std::unique_ptr<CCoinsViewCursor>
cursor;
3276 size_t coins_count = 0;
3277 while (
cursor->Valid()) {
3278 node.rpc_interruption_point();
3283 temp_cache.AddCoin(key, std::move(coin),
false);
3287 if (coins_count % 10'000'000 == 0) {
3288 LogInfo(
"Copying UTXO set: %uM coins copied.", coins_count / 1'000'000);
3292 if (coins_count % 100'000 == 0) {
3300 LogInfo(
"UTXO set copy complete: %u coins total", coins_count);
3303 LogInfo(
"Rolling back from height %d to %d",
tip->nHeight,
target->nHeight);
3314 node.rpc_interruption_point();
3331 LogInfo(
"Rolled back %d%% of blocks.", progress);
3342 LogInfo(
"Rollback complete. Computing UTXO statistics for created txoutset dump.");
3345 CoinStatsHashType::HASH_SERIALIZED,
3346 node.rpc_interruption_point);
3352 std::unique_ptr<CCoinsViewCursor> pcursor{
temp_db->Cursor()};
3354 LogInfo(
"Writing snapshot to disk.");
3362 node.rpc_interruption_point);
3370 std::unique_ptr<CCoinsViewCursor> pcursor;
3409 const fs::path& path,
3414 tip->nHeight,
tip->GetBlockHash().ToString(),
3424 unsigned int iter{0};
3426 std::vector<std::pair<uint32_t, Coin>> coins;
3438 for (
const auto& [n, coin] : coins) {
3447 while (pcursor->
Valid()) {
3456 coins.emplace_back(key.
n, coin);
3461 if (!coins.empty()) {
3467 if (
afile.fclose() != 0) {
3468 throw std::ios_base::failure(
3474 result.
pushKV(
"base_hash",
tip->GetBlockHash().ToString());
3475 result.
pushKV(
"base_height",
tip->nHeight);
3476 result.
pushKV(
"path", path.utf8string());
3478 result.
pushKV(
"nchaintx",
tip->m_chain_tx_count);
3486 const fs::path& path,
3497 node.rpc_interruption_point);
3504 "Load the serialized UTXO set from a file.\n"
3505 "Once this snapshot is loaded, its contents will be "
3506 "deserialized into a second chainstate data structure, which is then used to sync to "
3507 "the network's tip. "
3508 "Meanwhile, the original chainstate will complete the initial block download process in "
3509 "the background, eventually validating up to the block that the snapshot is based upon.\n\n"
3511 "The result is a usable bitcoind instance that is current with the network tip in a "
3512 "matter of minutes rather than hours. UTXO snapshot are typically obtained from "
3513 "third-party sources (HTTP, torrent, etc.) which is reasonable since their "
3514 "contents are always checked by hash.\n\n"
3516 "You can find more information on this process in the `assumeutxo` design "
3517 "document (<https://github.com/bitcoin/bitcoin/blob/master/doc/design/assumeutxo.md>).",
3522 "path to the snapshot file. If relative, will be prefixed by datadir."},
3544 if (
afile.IsNull()) {
3547 "Couldn't open file " + path.utf8string() +
" for reading.");
3553 }
catch (
const std::ios_base::failure&
e) {
3588 {
RPCResult::Type::STR_HEX,
"snapshot_blockhash",
true,
"the base block of the snapshot this chainstate is based on, if any"},
3591 {
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."},
3598 "Return information about chainstates.\n",
3620 if (!
cs.m_chain.Tip()) {
3627 data.pushKV(
"bestblockhash",
tip->GetBlockHash().GetHex());
3632 data.pushKV(
"coins_db_cache_bytes",
cs.m_coinsdb_cache_size_bytes);
3633 data.pushKV(
"coins_tip_cache_bytes",
cs.m_coinstip_cache_size_bytes);
3634 if (
cs.m_from_snapshot_blockhash) {
3635 data.pushKV(
"snapshot_blockhash",
cs.m_from_snapshot_blockhash->ToString());
3641 obj.pushKV(
"headers", chainman.m_best_header ? chainman.m_best_header->nHeight : -1);
3689 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*.
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,...
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.
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.
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.
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/)
CCoinsView that brings transactions from a mempool into view.
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.
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.
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.
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.
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 UniValue & get_array() const
void pushKV(std::string key, UniValue val)
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
std::string GetHex() const
Hex encoding of the number (with the most significant digits first).
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
static constexpr auto PRUNE_TARGET_MANUAL
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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.
Creates block templates, submits solved blocks, and provides tip-waiting helpers for mining code.
std::optional< interfaces::BlockRef > WaitTipChanged(const uint256 ¤t_tip, MillisecondsDouble &timeout, bool &interrupt)
Wait for the tip to differ from current_tip or timeout.
std::optional< interfaces::BlockRef > GetTip()
Locks cs_main.
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.
int64_t NodeId
Identifier of a peer connection.
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)
node::BlockTemplateManager & EnsureBlockTemplateManager(const NodeContext &node)
ArgsManager & EnsureArgsman(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...
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.
#define AssertLockHeld(cs)
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
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
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...